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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -0,0 +1,120 @@
1
+ // The JSON serializer: the ONLY thing the TS SDK does with an app value (docs/APP-API.md: "every value the app
2
+ // gives is passed to Core UNCHANGED as JSON"). It writes exactly null, booleans, finite numbers, strings, dense arrays
3
+ // and plain objects, and never drops a key or rewrites a value. A value with no JSON form (undefined at any depth, a
4
+ // cycle, NaN/Infinity, a function, a bigint, a symbol, a non-plain object) is NOT refused here: the SDK chooses no
5
+ // code. It hands Core a non-JSON text in that argument's slot, and Core's refusal for the slot supplies the code
6
+ // (Keel's unencodable-value ruling, 2026-10-30). Value policy (e.g. integers outside ±(2^53-1)) is Core's too.
7
+ /** Thrown inside the writer only; it carries the non-JSON text that names the value. */
8
+ class Unencodable {
9
+ text;
10
+ constructor(text) {
11
+ this.text = text;
12
+ }
13
+ }
14
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
15
+ function member(path, key) {
16
+ return IDENT.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
17
+ }
18
+ function isPlainObject(value) {
19
+ if (Object.prototype.toString.call(value) !== '[object Object]')
20
+ return false;
21
+ const proto = Object.getPrototypeOf(value);
22
+ // null-prototype, or this realm's / another realm's Object.prototype (whose own prototype is null).
23
+ return proto === null || Object.getPrototypeOf(proto) === null;
24
+ }
25
+ function encode(value, path) {
26
+ // The text starts with `$`, so it is never JSON; it names the first value with no JSON form and its path.
27
+ const fail = (at, what) => {
28
+ throw new Unencodable(`${at}: ${what} is not JSON`);
29
+ };
30
+ const ancestors = new Set();
31
+ const write = (v, at) => {
32
+ switch (typeof v) {
33
+ case 'string': return JSON.stringify(v);
34
+ case 'boolean': return v ? 'true' : 'false';
35
+ case 'number':
36
+ if (!Number.isFinite(v))
37
+ return fail(at, String(v));
38
+ return JSON.stringify(v);
39
+ case 'undefined': return fail(at, 'undefined (use null, or leave the key out)');
40
+ case 'function': return fail(at, 'a function');
41
+ case 'bigint': return fail(at, 'a bigint (pass it as a string)');
42
+ case 'symbol': return fail(at, 'a symbol');
43
+ }
44
+ if (v === null)
45
+ return 'null';
46
+ const obj = v;
47
+ if (ancestors.has(obj))
48
+ return fail(at, 'a cycle');
49
+ ancestors.add(obj);
50
+ let out;
51
+ if (Array.isArray(obj)) {
52
+ const parts = [];
53
+ for (let i = 0; i < obj.length; i++) {
54
+ if (!(i in obj))
55
+ fail(`${at}[${i}]`, 'an array hole');
56
+ parts.push(write(obj[i], `${at}[${i}]`));
57
+ }
58
+ out = `[${parts.join(',')}]`;
59
+ }
60
+ else {
61
+ if (!isPlainObject(obj))
62
+ fail(at, `a ${obj.constructor?.name ?? 'non-plain'} object`);
63
+ if (Object.getOwnPropertySymbols(obj).length > 0)
64
+ fail(at, 'a symbol-keyed property');
65
+ const parts = [];
66
+ for (const key of Object.keys(obj)) {
67
+ parts.push(`${JSON.stringify(key)}:${write(obj[key], member(at, key))}`);
68
+ }
69
+ out = `{${parts.join(',')}}`;
70
+ }
71
+ ancestors.delete(obj);
72
+ return out;
73
+ };
74
+ return write(value, path);
75
+ }
76
+ /**
77
+ * `value` as JSON text; when it has no JSON form, a non-JSON text naming the value and its path, which Core
78
+ * refuses with the code of the slot it is handed in.
79
+ */
80
+ export function jsonText(value, path = '$') {
81
+ try {
82
+ return encode(value, path);
83
+ }
84
+ catch (error) {
85
+ if (error instanceof Unencodable)
86
+ return error.text;
87
+ throw error;
88
+ }
89
+ }
90
+ /** `value` as JSON text, or undefined when it has no JSON form (a tool result: the bridge hands Core the fact). */
91
+ export function encodable(value) {
92
+ try {
93
+ return encode(value, '$');
94
+ }
95
+ catch (error) {
96
+ if (error instanceof Unencodable)
97
+ return undefined;
98
+ throw error;
99
+ }
100
+ }
101
+ /**
102
+ * Serializes a method's options object. The ONE relaxation: a top-level option whose value is `undefined` is
103
+ * omitted (it is a TS optional). Everything below the top level goes through `jsonText`, so
104
+ * `{tools: [{tool: 'x', bind: undefined}]}` reaches Core as non-JSON text. `undefined` options = no options.
105
+ */
106
+ export function optionsText(options) {
107
+ if (options === undefined)
108
+ return undefined;
109
+ if (options === null || typeof options !== 'object' || Array.isArray(options) || !isPlainObject(options)
110
+ || Object.getOwnPropertySymbols(options).length > 0) {
111
+ return jsonText(options); // not a plain options object: Core judges it
112
+ }
113
+ const kept = Object.create(null);
114
+ for (const key of Object.keys(options)) {
115
+ const v = options[key];
116
+ if (v !== undefined)
117
+ kept[key] = v;
118
+ }
119
+ return jsonText(kept);
120
+ }
@@ -0,0 +1,3 @@
1
+ import type { Platform } from '../../runtime/src/pal/platform.js';
2
+ export declare const coreModule: () => import("./core/port.js").CoreModule;
3
+ export declare const nativePlatform: Platform;
@@ -0,0 +1,24 @@
1
+ // Compiled at the canonical facade source root; it imports the RN adapter, not
2
+ // another facade or the web/WASM loader. Every source file stays single-owned.
3
+ import { createNativeCore } from '../../react-native/src/core-native.js';
4
+ import { nativeWire, nativeCall, nativeSync, nativeHTTP, nativeStorageCall } from '../../react-native/src/native-module.js';
5
+ const storage = {
6
+ read: key => nativeStorageCall('read', [key]), write: (key, value) => nativeStorageCall('write', [key, value]),
7
+ remove: key => nativeStorageCall('remove', [key]), list: prefix => nativeStorageCall('list', [prefix]),
8
+ lock: name => nativeStorageCall('lock', [name]), unlock: name => nativeStorageCall('unlock', [name]),
9
+ secrets: { read: key => nativeStorageCall('readSecret', [key]), write: (key, value) => nativeStorageCall('writeSecret', [key, value]), remove: key => nativeStorageCall('removeSecret', [key]) },
10
+ };
11
+ const module = createNativeCore(nativeWire, storage);
12
+ export const coreModule = () => module;
13
+ const bytes = async (method, args) => new Uint8Array(await nativeCall(method, args));
14
+ export const nativePlatform = {
15
+ defaultStorage: () => storage,
16
+ platformFacts: () => nativeSync('platformFacts'),
17
+ readAsset: async (path) => { const value = await nativeCall('readAsset', [path]); return value === null ? null : new Uint8Array(value); },
18
+ readImage: (uri, maxBytes) => bytes('readImage', [uri, maxBytes]),
19
+ resolve: (host) => nativeCall('resolve', [host]),
20
+ http: nativeHTTP,
21
+ codec: () => ({ available: () => nativeSync('codecAvailable'),
22
+ decode: (input) => nativeCall('decode', [Array.from(input)]),
23
+ render: request => bytes('render', [request]), release: handle => { nativeSync('release', [handle]); } }),
24
+ };
@@ -0,0 +1,15 @@
1
+ import type { CoreCancel, DecodedImage, ImageDecodeOptions } from '../core/port.js';
2
+ export interface Codec {
3
+ available(): boolean;
4
+ decode(bytes: Uint8Array, options: ImageDecodeOptions, cancel: CoreCancel): Promise<DecodedImage>;
5
+ render(request: {
6
+ handle: string;
7
+ width: number;
8
+ height: number;
9
+ format: 'png' | 'jpeg';
10
+ quality?: number;
11
+ }, cancel: CoreCancel): Promise<Uint8Array>;
12
+ release(handle: string): void;
13
+ }
14
+ export declare const noCodec: Codec;
15
+ export declare function browserCodec(): Codec;
@@ -0,0 +1,52 @@
1
+ import { HostError } from '../errors.js';
2
+ export const noCodec = {
3
+ available: () => false,
4
+ decode: () => Promise.reject(new HostError('image_unsupported', 'This platform has no image codec.')),
5
+ render: () => Promise.reject(new HostError('image_unsupported', 'This platform has no image codec.')),
6
+ release: () => { },
7
+ };
8
+ export function browserCodec() {
9
+ if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas !== 'function')
10
+ return noCodec;
11
+ const bitmaps = new Map();
12
+ const opened = (handle) => {
13
+ const bitmap = bitmaps.get(handle);
14
+ if (!bitmap)
15
+ throw new HostError('image_unsupported', 'The image handle was released.');
16
+ return bitmap;
17
+ };
18
+ return {
19
+ available: () => true,
20
+ async decode(bytes, { frame, applyOrientation }) {
21
+ // createImageBitmap decodes only the first frame (a GIF's frame 0); another frame is not this codec's.
22
+ if (frame !== 0)
23
+ throw new HostError('image_unsupported', 'This codec decodes only the first frame.');
24
+ // 'from-image' applies EXIF orientation when Core asks for it.
25
+ const bitmap = await createImageBitmap(new Blob([bytes]), { imageOrientation: applyOrientation ? 'from-image' : 'none' });
26
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
27
+ const context = canvas.getContext('2d');
28
+ if (!context) {
29
+ bitmap.close();
30
+ throw new HostError('image_unsupported', 'No 2D canvas.');
31
+ }
32
+ context.drawImage(bitmap, 0, 0);
33
+ const pixels = context.getImageData(0, 0, bitmap.width, bitmap.height).data;
34
+ let hasAlpha = false;
35
+ for (let i = 3; i < pixels.length && !hasAlpha; i += 4)
36
+ hasAlpha = pixels[i] < 255;
37
+ const handle = crypto.randomUUID();
38
+ bitmaps.set(handle, bitmap);
39
+ return { handle, width: bitmap.width, height: bitmap.height, hasAlpha };
40
+ },
41
+ async render({ handle, width, height, format, quality }) {
42
+ const canvas = new OffscreenCanvas(width, height);
43
+ canvas.getContext('2d').drawImage(opened(handle), 0, 0, width, height);
44
+ const blob = await canvas.convertToBlob({ type: `image/${format}`, quality });
45
+ return new Uint8Array(await blob.arrayBuffer());
46
+ },
47
+ release(handle) {
48
+ bitmaps.get(handle)?.close();
49
+ bitmaps.delete(handle);
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,5 @@
1
+ import type { PlatformHandle, StoragePal } from '../app-api.js';
2
+ import type { CoreHost, CoreStoragePal } from '../core/port.js';
3
+ /** The app's storage, unchanged, or the platform default (Core has no default of its own). */
4
+ export declare function storageFor(storage: StoragePal | undefined): CoreStoragePal;
5
+ export declare function createHost(handle: PlatformHandle | undefined): CoreHost;
@@ -0,0 +1,35 @@
1
+ import { platform } from './platform.js';
2
+ /** The app's storage, unchanged, or the platform default (Core has no default of its own). */
3
+ export function storageFor(storage) {
4
+ return storage ?? platform().defaultStorage();
5
+ }
6
+ export function createHost(handle) {
7
+ const pal = platform();
8
+ const codec = pal.codec();
9
+ let timer;
10
+ return {
11
+ readAsset: path => pal.readAsset(path),
12
+ http: (request, sink, cancel) => pal.http(request, sink, cancel),
13
+ resolve: (host, cancel) => pal.resolve(host, cancel),
14
+ nowMs: () => Date.now(),
15
+ utcOffsetMinutes: atMs => -new Date(atMs).getTimezoneOffset(),
16
+ // Unref'd: an idle Croche never holds a Node process open.
17
+ sleep: ms => new Promise(resolve => { setTimeout(resolve, ms).unref?.(); }),
18
+ wake(atMs, onWake) {
19
+ clearTimeout(timer);
20
+ timer = undefined;
21
+ if (atMs === null || typeof onWake !== 'function')
22
+ return;
23
+ timer = setTimeout(() => { timer = undefined; onWake(); }, Math.max(0, atMs - Date.now()));
24
+ timer.unref?.();
25
+ },
26
+ random: () => crypto.randomUUID(),
27
+ platformFacts: () => pal.platformFacts(), // the platform's own facts, locale included (absent, never defaulted)
28
+ platform: handle,
29
+ readImage: (request, cancel) => pal.readImage(request.source.uri, request.maxBytes, cancel),
30
+ imageCodecAvailable: () => codec.available(),
31
+ decodeImage: (bytes, options, cancel) => codec.decode(bytes, options, cancel),
32
+ renderImage: (request, cancel) => codec.render(request, cancel),
33
+ releaseDecodedImage: handle => codec.release(handle),
34
+ };
35
+ }
@@ -0,0 +1,16 @@
1
+ import type { StoragePal } from '../app-api.js';
2
+ import type { CoreBodySink, CoreCancel, CoreHttpRequest, PlatformFacts } from '../core/port.js';
3
+ import type { Codec } from './codec.js';
4
+ export interface Platform {
5
+ /** The §2a storage this platform ships, used when the app passes none. */
6
+ defaultStorage(): StoragePal;
7
+ http(request: CoreHttpRequest, sink: CoreBodySink, cancel: CoreCancel): Promise<void>;
8
+ resolve(host: string, cancel: CoreCancel): Promise<string[]>;
9
+ readAsset(path: string): Promise<Uint8Array | null>;
10
+ readImage(uri: string, maxBytes: number, cancel: CoreCancel): Promise<Uint8Array>;
11
+ codec(): Codec;
12
+ /** Build facts the platform knows natively (RN Android: a release build). Never inferred; web and Node know none. */
13
+ platformFacts(): PlatformFacts;
14
+ }
15
+ export declare function usePlatform(platform: Platform): void;
16
+ export declare function platform(): Platform;
@@ -0,0 +1,7 @@
1
+ let current;
2
+ export function usePlatform(platform) { current = platform; }
3
+ export function platform() {
4
+ if (!current)
5
+ throw new Error('No platform PAL selected.');
6
+ return current;
7
+ }
@@ -0,0 +1 @@
1
+ export * from './index.native.js';
@@ -0,0 +1,4 @@
1
+ export * from './index.native.js';
2
+ import { usePlatform } from './pal/platform.js';
3
+ import { nativePlatform } from './native-adapter.js';
4
+ usePlatform(nativePlatform);
@@ -0,0 +1,33 @@
1
+ import type { Json } from './app-api.js';
2
+ import type { ErrorCategory } from './errors.js';
3
+ import type { Attachment } from './generated/app-stream.js';
4
+ /** One envelope for every opened Core plugin; output is the plugin's JSON. */
5
+ export type RunToolResult = {
6
+ id: string;
7
+ status: 'ok';
8
+ output: Json;
9
+ attachments: Attachment[];
10
+ cost: number | null;
11
+ costStatus: 'reported' | 'unknown' | 'none' | (string & {});
12
+ } | {
13
+ id: string;
14
+ status: 'failed';
15
+ code: string;
16
+ category: ErrorCategory;
17
+ message: string;
18
+ cost: number | null;
19
+ costStatus: 'reported' | 'unknown' | 'none' | (string & {});
20
+ } | {
21
+ id: string;
22
+ status: 'lost';
23
+ code: 'outcome_unknown';
24
+ category: 'closed';
25
+ message: string;
26
+ } | {
27
+ id: string;
28
+ status: 'unknown';
29
+ originalStatus: string;
30
+ fields: Json;
31
+ };
32
+ /** Readers preserve a future status and its complete payload, as AgentEvent does. */
33
+ export declare function runToolResult(json: string): RunToolResult;
@@ -0,0 +1,7 @@
1
+ /** Readers preserve a future status and its complete payload, as AgentEvent does. */
2
+ export function runToolResult(json) {
3
+ const value = JSON.parse(json);
4
+ return ['ok', 'failed', 'lost'].includes(value.status)
5
+ ? value
6
+ : { id: value.id, status: 'unknown', originalStatus: value.status, fields: value };
7
+ }
@@ -0,0 +1,19 @@
1
+ import type { Json, ToolManifest, ToolContent, ToolDefinition, ToolExecute, ToolResult } from './app-api.js';
2
+ import type { CoreExecute, CoreToolDefinition } from './core/port.js';
3
+ /** Its message reaches the model verbatim. */
4
+ export declare class ToolError extends Error {
5
+ constructor(message?: string, options?: ErrorOptions);
6
+ }
7
+ /** The ONLY way to make a ToolResult: any other object a tool returns is Json, even one with `json` or `content`. */
8
+ export declare function toolResult(value: string | Json | ToolContent[]): ToolResult;
9
+ /** Core's handle for a definition made by defineTool/tools, or undefined for anything else. */
10
+ export declare function coreDefinition(value: unknown): CoreToolDefinition | undefined;
11
+ /** `manifest` is typed as ToolManifest (a JSON module import or a const with mixed commands fits it); the SDK still
12
+ * serializes it unchanged (undefined throws, json.ts) and Core validates it. */
13
+ export declare function defineTool(manifest: ToolManifest, execute: ToolExecute): ToolDefinition;
14
+ /** Croche tools: they run in Core through Egress and are billed. */
15
+ export declare const tools: {
16
+ readonly webSearch: ToolDefinition;
17
+ };
18
+ /** The callback Core holds for one definition. */
19
+ export declare function bridge(execute: ToolExecute): CoreExecute;
@@ -0,0 +1,70 @@
1
+ import { signalFor } from './cancel.js';
2
+ import { coreModule } from './core/wasm.js';
3
+ import { encodable, jsonText } from './json.js';
4
+ import { thrownError } from './errors.js';
5
+ /** Its message reaches the model verbatim. */
6
+ export class ToolError extends Error {
7
+ constructor(message, options) {
8
+ super(message, options);
9
+ this.name = 'ToolError';
10
+ }
11
+ }
12
+ const BRAND = Symbol('croche.toolResult');
13
+ /** The ONLY way to make a ToolResult: any other object a tool returns is Json, even one with `json` or `content`. */
14
+ export function toolResult(value) {
15
+ return Object.freeze({ [BRAND]: value });
16
+ }
17
+ function branded(value) {
18
+ return typeof value === 'object' && value !== null && Object.hasOwn(value, BRAND);
19
+ }
20
+ // Definitions made here, mapped to Core's handle. A WeakMap, not a property: the app's object stays `{name}`.
21
+ const handles = new WeakMap();
22
+ function wrap(handle) {
23
+ const definition = Object.freeze({ get name() { return handle.name; } });
24
+ handles.set(definition, handle);
25
+ return definition;
26
+ }
27
+ /** Core's handle for a definition made by defineTool/tools, or undefined for anything else. */
28
+ export function coreDefinition(value) {
29
+ return typeof value === 'object' && value !== null ? handles.get(value) : undefined;
30
+ }
31
+ /** `manifest` is typed as ToolManifest (a JSON module import or a const with mixed commands fits it); the SDK still
32
+ * serializes it unchanged (undefined throws, json.ts) and Core validates it. */
33
+ export function defineTool(manifest, execute) {
34
+ const core = coreModule();
35
+ return wrap(core.defineTool(jsonText(manifest), bridge(execute)));
36
+ }
37
+ let webSearch;
38
+ /** Croche tools: they run in Core through Egress and are billed. */
39
+ export const tools = Object.freeze({
40
+ get webSearch() { return webSearch ??= wrap(coreModule().webSearch()); },
41
+ });
42
+ // A ToolCompletion as JSON text. The app's value is spliced in as the strict serializer wrote it, never re-encoded.
43
+ const fact = (completion) => JSON.stringify(completion);
44
+ function completion(value) {
45
+ // A value with no JSON form is the invalid_result fact; Core gives it its code (invalid_tool_result).
46
+ if (value === undefined)
47
+ return fact({ type: 'empty' });
48
+ const brand = branded(value);
49
+ const json = encodable(brand ? value[BRAND] : value);
50
+ if (json === undefined)
51
+ return fact({ type: 'invalid_result' });
52
+ return brand ? `{"type":"result","content":${json}}` : `{"type":"json","value":${json}}`;
53
+ }
54
+ /** The callback Core holds for one definition. */
55
+ export function bridge(execute) {
56
+ return async (callJson, contextJson, cancel) => {
57
+ const signal = signalFor(cancel);
58
+ const ctx = { ...JSON.parse(contextJson), signal };
59
+ let outcome;
60
+ try {
61
+ outcome = completion(await execute(JSON.parse(callJson), ctx));
62
+ }
63
+ catch (error) {
64
+ outcome = fact(error instanceof ToolError
65
+ ? { type: 'tool_error', message: error.message }
66
+ : { type: 'handler_error', error: thrownError(error) });
67
+ }
68
+ return cancel.isCancelled() ? fact({ type: 'cancelled' }) : outcome;
69
+ };
70
+ }
@@ -0,0 +1,14 @@
1
+ import Foundation
2
+
3
+ /// Owned bytes travel BESIDE input JSON. No image is serialized/base64-encoded,
4
+ /// sniffed or resized by the RN bridge. Core owns every acquisition decision.
5
+ struct RNCoreAgentTransport: Sendable {
6
+ let core: any CoreAgentProtocol
7
+
8
+ func send(inputJson: String, images: [CoreImageInput], optionsJson: String?, cancel: CancelToken?) throws -> String {
9
+ try core.send(inputJson: inputJson, images: images, optionsJson: optionsJson, cancel: cancel)
10
+ }
11
+ func request(inputJson: String, images: [CoreImageInput], optionsJson: String?, cancel: CancelToken?) throws -> String {
12
+ try core.request(inputJson: inputJson, images: images, optionsJson: optionsJson, cancel: cancel)
13
+ }
14
+ }
@@ -0,0 +1,58 @@
1
+ import Foundation
2
+
3
+ /// Owns only the native references needed to cross the RN event emitter. Core
4
+ /// decides entry, ordering and duplicate completion; this keeps no event queue.
5
+ final class RNCoreDeliveries: @unchecked Sendable {
6
+ private let lock = NSLock()
7
+ private var entries: [String: any CoreDeliveryProtocol] = [:]
8
+
9
+ func hold(_ delivery: any CoreDeliveryProtocol) -> String {
10
+ let handle = UUID().uuidString
11
+ lock.withLock { entries[handle] = delivery }
12
+ return handle
13
+ }
14
+ /// Called synchronously by the JS native binding ON the invocation stack.
15
+ /// nil means an unknown transport handle, not an SDK decision about entry.
16
+ func tryEnter(_ handle: String) -> Bool? {
17
+ guard let delivery = lock.withLock({ entries[handle] }) else { return nil }
18
+ let entered = delivery.tryEnter()
19
+ if !entered { lock.withLock { _ = entries.removeValue(forKey: handle) } }
20
+ return entered
21
+ }
22
+ @discardableResult func complete(_ handle: String, _ outcomeJson: String) -> Bool {
23
+ guard let delivery = lock.withLock({ entries.removeValue(forKey: handle) }) else { return false }
24
+ delivery.complete(outcomeJson: outcomeJson)
25
+ return true
26
+ }
27
+ }
28
+
29
+ /// The emitter only posts to JavaScript. It MUST NOT enter the delivery here:
30
+ /// the JS shared event sink calls tryEnter synchronously just before app code.
31
+ final class RNCoreEventSink: CoreEventSink, @unchecked Sendable {
32
+ typealias Emit = @Sendable (String) throws -> Void
33
+ private let sink: String
34
+ private let deliveries: RNCoreDeliveries
35
+ private let emit: Emit
36
+ init(sink: String, deliveries: RNCoreDeliveries, emit: @escaping Emit) {
37
+ self.sink = sink; self.deliveries = deliveries; self.emit = emit
38
+ }
39
+ deinit {
40
+ if let json = try? rnJSON(["type":"retired", "sinks":[sink], "hosts":[], "storages":[], "executors":[], "tokens":[]]) { try? emit(json) }
41
+ }
42
+ func deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) throws {
43
+ try post(deliveryId: deliveryId, eventJson: eventJson, delivery: delivery)
44
+ }
45
+ // The generated protocol lets the same transport run against a no-FFI double.
46
+ func post(deliveryId: String, eventJson: String, delivery: any CoreDeliveryProtocol) throws {
47
+ let handle = deliveries.hold(delivery)
48
+ do {
49
+ let packet: [String: String] = ["type": "event", "sink": sink, "id": deliveryId,
50
+ "eventJson": eventJson, "delivery": handle]
51
+ let data = try JSONSerialization.data(withJSONObject: packet, options: [.sortedKeys])
52
+ try emit(String(decoding: data, as: UTF8.self))
53
+ } catch {
54
+ deliveries.complete(handle, #"{"outcome":"unavailable"}"#)
55
+ throw error
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,93 @@
1
+ import Foundation
2
+
3
+ // RN's default primitives are the same iOS PAL as the public Swift SDK.
4
+ // No key rewriting, URL policy, retry loop or storage error code map.
5
+ final class RNDefaultPal: @unchecked Sendable {
6
+ private let guardLock = NSLock()
7
+ private var cached: PlatformPal?
8
+ private var httpTokens: [String: CancelToken] = [:]
9
+ private var cancelledBeforeStart: Set<String> = []
10
+ var emit: (@Sendable (String) -> Void)?
11
+ func host() throws -> PlatformPal {
12
+ guardLock.lock(); defer { guardLock.unlock() }
13
+ if let cached { return cached }
14
+ let host = try PlatformPal.standard(); host.streamPlatformFact = .reactNative
15
+ cached = host; return host
16
+ }
17
+ func call(_ method: String, _ args: [Any]) throws -> Any {
18
+ let host = try host()
19
+ switch method {
20
+ case "read": return try host.read(key: rnString(args, 0)) as Any? ?? NSNull()
21
+ case "write": try host.write(key: rnString(args, 0), value: rnString(args, 1)); return NSNull()
22
+ case "remove": try host.remove(key: rnString(args, 0)); return NSNull()
23
+ case "list": return try host.list(prefix: rnString(args, 0))
24
+ case "lock": return try host.lock(key: rnString(args, 0)) == .acquired ? "acquired" : "held"
25
+ case "unlock": try host.unlock(key: rnString(args, 0)); return NSNull()
26
+ case "readSecret": return try host.readSecret(key: rnString(args, 0)) as Any? ?? NSNull()
27
+ case "writeSecret": try host.writeSecret(key: rnString(args, 0), value: rnString(args, 1)); return NSNull()
28
+ case "removeSecret": try host.removeSecret(key: rnString(args, 0)); return NSNull()
29
+ case "platformFacts":
30
+ let facts = host.platformFacts(); var json: [String: Any] = [:]
31
+ switch facts.targetKind {
32
+ case .iosDevice: json["targetKind"] = "ios-device"
33
+ case .iosSimulator: json["targetKind"] = "ios-simulator"
34
+ case .android: json["targetKind"] = "android"
35
+ case .other: json["targetKind"] = "other"
36
+ }
37
+ if let value = facts.debuggable { json["debuggable"] = value }
38
+ if let value = facts.locale { json["locale"] = value }
39
+ if let value = facts.attestationPlatform { json["attestationPlatform"] = value }
40
+ if let value = facts.browserFetch { json["browserFetch"] = value }
41
+ return json
42
+ case "readAsset": return try host.readAsset(path: rnString(args, 0)).map { Array($0) } as Any? ?? NSNull()
43
+ case "resolve": return try host.resolve(host: rnString(args, 0), cancel: CancelToken())
44
+ case "readImage":
45
+ let max = (args[1] as! NSNumber).uint64Value
46
+ return Array(try host.readImage(request: PalImageReadRequest(source: .local(uri: rnString(args, 0)), maxBytes: max), cancel: CancelToken()))
47
+ case "codecAvailable": return host.imageCodecAvailable()
48
+ case "decode":
49
+ let data = Data((args[0] as! [NSNumber]).map { $0.uint8Value })
50
+ let image = try host.decodeImage(bytes: data, options: PalImageDecodeOptions(frame: 0, applyOrientation: true), cancel: CancelToken())
51
+ return ["handle":image.handle, "width":image.width, "height":image.height, "hasAlpha":image.hasAlpha as Any? ?? NSNull()]
52
+ case "render":
53
+ let p = args[0] as! [String: Any]
54
+ let request = PalImageRenderRequest(handle: p["handle"] as! String, width: (p["width"] as! NSNumber).uint32Value,
55
+ height: (p["height"] as! NSNumber).uint32Value, format: p["format"] as! String == "png" ? .png : .jpeg, quality: p["quality"] as? Double)
56
+ return Array(try host.renderImage(request: request, cancel: CancelToken()))
57
+ case "release": host.releaseDecodedImage(handle: try rnString(args, 0)); return NSNull()
58
+ case "cancelHttp":
59
+ let id = try rnString(args, 0)
60
+ guardLock.lock(); let token = httpTokens[id]; if token == nil { cancelledBeforeStart.insert(id) }; guardLock.unlock()
61
+ token?.cancel(); return NSNull()
62
+ case "http":
63
+ let id = try rnString(args, 0), p = args[1] as! [String: Any]
64
+ let token = CancelToken()
65
+ guardLock.lock(); httpTokens[id] = token; let cancelled = cancelledBeforeStart.remove(id) != nil; guardLock.unlock()
66
+ if cancelled { token.cancel() }
67
+ defer { guardLock.lock(); httpTokens.removeValue(forKey: id); guardLock.unlock() }
68
+ let headers = (p["headers"] as! [[String]]).map { PalHeader(name: $0[0], value: $0[1]) }
69
+ let request = PalHttpRequest(connectTo: p["connectTo"] as? String, url: p["url"] as! String, method: p["method"] as! String,
70
+ headers: headers, body: p["body"] as? String, timeoutMs: (p["timeoutMs"] as! NSNumber).uint64Value,
71
+ responseMode: p["responseMode"] as! String, maxResponseBytes: (p["maxResponseBytes"] as! NSNumber).uint64Value)
72
+ let sink = RNHttpSink(id, self)
73
+ try effect {
74
+ if try PlatformHTTP.direct(request, sink: sink, cancel: token) { return }
75
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: token) { signal -> Bool in
76
+ try await host.session.stream(request, into: sink, cancellation: signal)
77
+ return true
78
+ }
79
+ }
80
+ return NSNull()
81
+ default: throw RNWireError.badPacket
82
+ }
83
+ }
84
+ fileprivate func post(_ packet: [String: Any]) {
85
+ if let json = try? rnJSON(packet) { emit?(json) }
86
+ }
87
+ }
88
+ private final class RNHttpSink: HttpSinkProtocol, @unchecked Sendable {
89
+ let id: String; let pal: RNDefaultPal
90
+ init(_ id: String, _ pal: RNDefaultPal) { self.id = id; self.pal = pal }
91
+ func head(status: UInt16, headers: [PalHeader]) { pal.post(["id":id, "type":"head", "status":status, "headers":headers.map { [$0.name, $0.value] }]) }
92
+ func chunk(bytes: Data) -> Bool { pal.post(["id":id, "type":"chunk", "bytes":Array(bytes)]); return true }
93
+ }
@@ -0,0 +1,44 @@
1
+ import Foundation
2
+
3
+ /// Native capabilities travel separately from app JSON. The factory selects the
4
+ /// app storage OR platform default first; this carrier can never hold nil.
5
+ struct RNCorePlatform: @unchecked Sendable {
6
+ let host: any HostPal
7
+ let storage: any CoreStoragePal
8
+ let platformStorage: any CoreStoragePal
9
+
10
+ init(host: PlatformPal, storage: any CoreStoragePal) {
11
+ host.streamPlatformFact = .reactNative
12
+ self.host = RNProjectPal(host); self.storage = storage
13
+ self.platformStorage = PlatformStorageAdapter(host)
14
+ }
15
+
16
+ static func standard(storage: any CoreStoragePal) throws -> RNCorePlatform {
17
+ RNCorePlatform(host: try PlatformPal.standard(), storage: storage)
18
+ }
19
+
20
+ /// The bridge's own binding facts: sdk "react-native" (BindingFacts, from the SDK sources it builds).
21
+ static let bindingFacts = BindingFacts.json(sdk: "react-native")
22
+ func open(_ json: String, registrations: [CoreToolRegistration], recoveryJson: String? = nil,
23
+ invoke: (String, [CoreToolRegistration], (any CoreStoragePal)?, any HostPal, String, String?) throws -> CoreCroche = CoreCroche.open) throws -> CoreCroche {
24
+ try invoke(json, registrations, storage, host, Self.bindingFacts, recoveryJson)
25
+ }
26
+ func registerBackground(_ json: String, sink: (any CoreEventSink)?, platformStorage: (any CoreStoragePal)?,
27
+ invoke: (String, (any CoreEventSink)?, (any CoreStoragePal)?, (any CoreStoragePal)?, any HostPal, String) throws -> Void = coreRegisterBackground) throws {
28
+ try invoke(json, sink, storage, platformStorage, host, Self.bindingFacts)
29
+ }
30
+ }
31
+
32
+ /// A native Core error envelope: detail is Core's message. No regex, fallback
33
+ /// code, category inference, or SDK policy is applied to a CoreApiError.
34
+ func rnCoreErrorEnvelope(_ error: CoreApiError) throws -> String {
35
+ let fields: [String: Any]
36
+ switch error {
37
+ case let .Failure(code, detail, category, path, retryAfter):
38
+ var value: [String: Any] = ["code": code, "message": detail, "category": category]
39
+ if let path { value["path"] = path }
40
+ if let retryAfter { value["retryAfter"] = retryAfter }
41
+ fields = value
42
+ }
43
+ return String(decoding: try JSONSerialization.data(withJSONObject: ["error": fields], options: [.sortedKeys]), as: UTF8.self)
44
+ }