expo-modules-core 58.0.23 → 58.0.26

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 (27) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/android/build.gradle +2 -2
  3. package/android/prebuilt/metadata.json +1 -1
  4. package/android/prebuilt/native-libs.tar.xz +0 -0
  5. package/android/src/main/java/expo/modules/kotlin/sharedobjects/SharedObject.kt +5 -0
  6. package/android/src/main/java/expo/modules/kotlin/sharedobjects/SharedObjectRegistry.kt +14 -0
  7. package/ios/Benchmarks/FunctionBenchmarks.swift +28 -0
  8. package/ios/Benchmarks/SharedObjectBenchmarks.swift +97 -3
  9. package/ios/Core/AppContext.swift +4 -9
  10. package/ios/Core/ArrayBuffers/ArrayBuffer.swift +44 -6
  11. package/ios/Core/Classes/ClassDefinition.swift +4 -3
  12. package/ios/Core/DynamicTypes/DynamicSharedObjectType.swift +3 -4
  13. package/ios/Core/ExpoModulesMacros.swift +14 -1
  14. package/ios/Core/ExpoRuntime.swift +19 -9
  15. package/ios/Core/SharedObjects/SharedObject.swift +30 -0
  16. package/ios/Core/SharedObjects/SharedObjectNativeState.swift +51 -9
  17. package/ios/Core/SharedObjects/SharedObjectRegistry.swift +59 -33
  18. package/ios/Core/SharedObjects/SharedRef.swift +4 -0
  19. package/ios/Core/Views/SwiftUI/SwiftUIHostingView.swift +38 -0
  20. package/ios/Core/Views/SwiftUI/SwiftUIViewHost.swift +8 -0
  21. package/ios/Utilities/Mutex.swift +15 -3
  22. package/package.json +4 -4
  23. package/prebuilds/output/debug/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  24. package/prebuilds/output/debug/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  25. package/prebuilds/output/headers/xcframeworks/ExpoModulesCoreHeaders.tar.gz +0 -0
  26. package/prebuilds/output/release/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  27. package/prebuilds/output/release/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 58.0.26
4
+
5
+ ### Patch Changes
6
+
7
+ - [iOS] Reduce the overhead of creating shared objects in JavaScript and of returning them from native functions. ([#52096](https://github.com/expo/expo/pull/52096) by [@tsapeta](https://github.com/tsapeta))
8
+ - Updated dependencies. ([#52095](https://github.com/expo/expo/pull/52095))
9
+ - expo-modules-jsi@58.0.19
10
+
11
+ ## 58.0.25
12
+
13
+ ### Patch Changes
14
+
15
+ - [iOS] Support `static` and `class` `@JS` members on `@SharedObject` classes. They are bound onto the JavaScript class itself, for example `Cache.open(name)`. ([#51966](https://github.com/expo/expo/pull/51966) by [@tsapeta](https://github.com/tsapeta))
16
+ - [Android] Fix "Cannot use shared object that was already released" errors when a view with a shared object prop, such as the `@expo/ui` `TextInput`, is remounted right after its first render. ([#51934](https://github.com/expo/expo/pull/51934) by [@expo-tuft](https://github.com/apps/expo-tuft))
17
+ - [iOS] Fix apps running out of memory when native functions return many new `ArrayBuffer` values to JavaScript, because the garbage collector did not count their memory. ([#52124](https://github.com/expo/expo/pull/52124) by [@tsapeta](https://github.com/tsapeta))
18
+ - [iOS] Fix `ArrayBuffer.wrap(dataWithoutCopy:)` keeping the bytes of released buffers alive until the current autorelease pool drains, which could make apps run out of memory when JavaScript calls a native function in a loop. ([#52123](https://github.com/expo/expo/pull/52123) by [@tsapeta](https://github.com/tsapeta))
19
+ - Updated dependencies. ([#52125](https://github.com/expo/expo/pull/52125), [#52031](https://github.com/expo/expo/pull/52031), [#52133](https://github.com/expo/expo/pull/52133), [#52122](https://github.com/expo/expo/pull/52122), [#52055](https://github.com/expo/expo/pull/52055))
20
+ - expo-modules-jsi@58.0.18
21
+
22
+ ## 58.0.24
23
+
24
+ ### Patch Changes
25
+
26
+ - [iOS] Reduce the overhead of creating shared objects in JavaScript and of returning them from native functions. ([#51730](https://github.com/expo/expo/pull/51730) by [@tsapeta](https://github.com/tsapeta))
27
+ - [iOS] Fix shared objects that native code returns to JavaScript again after their earlier JavaScript object was garbage-collected. Their members could throw "Unable to find the native shared object associated with given JavaScript object", or the returned object could belong to another shared object. ([#51854](https://github.com/expo/expo/pull/51854) by [@tsapeta](https://github.com/tsapeta))
28
+ - [iOS] Update `expo-modules-macros` to 0.22.0. `@Record` types now read and write their JavaScript properties with less overhead. The new `@JS` option `.withAsync("name")` also binds a synchronous function under that name, as a function that returns a promise and runs on the concurrent thread pool. A `@Record` can now be a `final class`, and a class that isn't `final` or has an inheritance clause gets a build error that says how to fix it. A `@JS init` now reports an argument type that can't be converted from JavaScript at the initializer. ([#51905](https://github.com/expo/expo/pull/51905) by [@tsapeta](https://github.com/tsapeta))
29
+ - [iOS] Fix a SwiftUI `Host` that mounts during a repeated modal presentation having no safe area. ([#51923](https://github.com/expo/expo/pull/51923) by [@expo-tuft](https://github.com/apps/expo-tuft))
30
+ - [iOS] Fix hosted React Native content going blank or keeping a stale size after its child view is remounted, for example by a `key` change in an `RNHostView`. ([#51906](https://github.com/expo/expo/pull/51906) by [@expo-tuft](https://github.com/apps/expo-tuft))
31
+ - Updated dependencies. ([#51588](https://github.com/expo/expo/pull/51588), [#51835](https://github.com/expo/expo/pull/51835), [#51905](https://github.com/expo/expo/pull/51905))
32
+ - expo-modules-jsi@58.0.17
33
+
3
34
  ## 58.0.23
4
35
 
5
36
  ### Patch Changes
@@ -46,7 +46,7 @@ if (shouldIncludeCompose) {
46
46
  }
47
47
 
48
48
  group = 'host.exp.exponent'
49
- version = '58.0.23'
49
+ version = '58.0.26'
50
50
 
51
51
  def isExpoModulesCoreTests = {
52
52
  Gradle gradle = getGradle()
@@ -175,7 +175,7 @@ android {
175
175
  defaultConfig {
176
176
  consumerProguardFiles 'proguard-rules.pro'
177
177
  versionCode 1
178
- versionName "58.0.23"
178
+ versionName "58.0.26"
179
179
  buildConfigField "String", "EXPO_MODULES_CORE_VERSION", "\"${versionName}\""
180
180
  buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", "true"
181
181
 
@@ -16,5 +16,5 @@
16
16
  "libexpo-modules-jsi.so"
17
17
  ],
18
18
  "stripped": true,
19
- "createdAt": "2026-10-19T12:37:31.850362445Z"
19
+ "createdAt": "2026-10-23T23:08:09.663847375Z"
20
20
  }
Binary file
@@ -80,6 +80,11 @@ open class SharedObject(runtime: Runtime? = null) {
80
80
  }
81
81
  }
82
82
 
83
+ /**
84
+ * Delays the release until the queued view updates are applied. Use it for objects passed as view props.
85
+ */
86
+ open val releasesAfterPendingViewUpdates: Boolean = false
87
+
83
88
  open fun onStartListeningToEvent(eventName: String) = Unit
84
89
 
85
90
  open fun onStopListeningToEvent(eventName: String) = Unit
@@ -1,5 +1,6 @@
1
1
  package expo.modules.kotlin.sharedobjects
2
2
 
3
+ import com.facebook.react.modules.core.ReactChoreographer
3
4
  import expo.modules.kotlin.runtime.Runtime
4
5
  import expo.modules.kotlin.exception.Exceptions
5
6
  import expo.modules.kotlin.exception.InvalidSharedObjectIdException
@@ -85,6 +86,19 @@ class SharedObjectRegistry(runtime: Runtime) {
85
86
  }
86
87
 
87
88
  internal fun delete(id: SharedObjectId) {
89
+ val native = synchronized(this) { pairs[id]?.first } ?: return
90
+ if (native.releasesAfterPendingViewUpdates) {
91
+ val choreographer = runCatching { ReactChoreographer.getInstance() }.getOrNull()
92
+ if (choreographer != null) {
93
+ // Runs after Fabric's `DISPATCH_UI` callback, which applies the queued view updates.
94
+ choreographer.postFrameCallback(ReactChoreographer.CallbackType.IDLE_EVENT) { remove(id) }
95
+ return
96
+ }
97
+ }
98
+ remove(id)
99
+ }
100
+
101
+ private fun remove(id: SharedObjectId) {
88
102
  synchronized(this) {
89
103
  pairs.remove(id)
90
104
  }?.let { (native, _) ->
@@ -93,6 +93,34 @@ extension Benchmarks {
93
93
  }
94
94
  }
95
95
 
96
+ /// Benchmarks for encoding an array of records in Swift, with no JavaScript call around it.
97
+ extension Benchmarks {
98
+ @Test(arguments: [10, 1000])
99
+ func `encode an array of records`(count: Int) async throws {
100
+ try await recordBenchmarkCase { runtime in
101
+ let points = (0..<count).map { BenchmarkPoint(x: Double($0), y: Double($0)) }
102
+ try benchmark("[Record].encode: \(count) records", runtime: runtime) { iterations in
103
+ for _ in 0..<iterations {
104
+ _ = try [BenchmarkPoint].encode(points, in: runtime)
105
+ }
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ /// Runs one case with the runtime of a new app context.
112
+ private func recordBenchmarkCase(
113
+ _ measure: @escaping @JavaScriptActor (JavaScriptRuntime) throws -> Void
114
+ ) async throws {
115
+ try await benchmarkCase {
116
+ let appContext = AppContext.create()
117
+ let runtime = try appContext.runtime
118
+ try withExtendedLifetime(appContext) {
119
+ try measure(runtime)
120
+ }
121
+ }
122
+ }
123
+
96
124
  @Record
97
125
  private struct BenchmarkPoint {
98
126
  var x: Double = 0
@@ -5,9 +5,18 @@ import Testing
5
5
 
6
6
  @testable import ExpoModulesCore
7
7
 
8
- /// Benchmarks for JavaScript using a `@SharedObject` class: creating instances, getting them from a `@JS`
9
- /// function and calling their `@JS` members. A JavaScript driver runs the measured loop. Read every result
10
- /// against `JS: empty driver loop`.
8
+ /// Benchmarks for JavaScript using a `@SharedObject` class: creating, releasing and collecting instances,
9
+ /// reading their IDs, passing them to and getting them from `@JS` functions, and calling their `@JS` members.
10
+ /// A JavaScript driver runs the measured loop, so read these results against `JS: empty driver loop`.
11
+ ///
12
+ /// Notes on reading the results:
13
+ /// - `new instance and garbage collection` adds one full collection to each sample and spreads its cost over
14
+ /// the instances created in the sample. It shows whether collecting shared objects got cheaper, not the
15
+ /// exact cost of finalizing one instance.
16
+ /// - `existing instance returned from a function` includes decoding the argument, which
17
+ /// `instance passed as an argument` measures alone.
18
+ /// - `emit: Int payload from a @SharedObject` emits from Swift in a loop, without the JavaScript driver.
19
+ /// Read it against `emit: Int payload`, which emits the same payload from a module.
11
20
  extension Benchmarks {
12
21
  @Test
13
22
  func `@SharedObject: new instance`() async throws {
@@ -18,6 +27,25 @@ extension Benchmarks {
18
27
  }
19
28
  }
20
29
 
30
+ @Test
31
+ func `@SharedObject: new instance and release`() async throws {
32
+ try await sharedObjectBenchmarkCase(body: "new Counter(i).release();") { run, runtime in
33
+ try benchmark("@SharedObject: new instance and release", runtime: runtime) { iterations in
34
+ _ = try run.call(arguments: iterations)
35
+ }
36
+ }
37
+ }
38
+
39
+ @Test
40
+ func `@SharedObject: new instance and garbage collection`() async throws {
41
+ try await sharedObjectBenchmarkCase(body: "new Counter(i);") { run, runtime in
42
+ try benchmark("@SharedObject: new instance and garbage collection", runtime: runtime) { iterations in
43
+ _ = try run.call(arguments: iterations)
44
+ runtime.collectGarbage()
45
+ }
46
+ }
47
+ }
48
+
21
49
  @Test
22
50
  func `@SharedObject: instance returned from a function`() async throws {
23
51
  try await sharedObjectBenchmarkCase(body: "m.makeCounter(i);") { run, runtime in
@@ -36,6 +64,62 @@ extension Benchmarks {
36
64
  }
37
65
  }
38
66
 
67
+ @Test
68
+ func `@SharedObject: new instance and ID read`() async throws {
69
+ try await sharedObjectBenchmarkCase(body: "new Counter(i).__expo_shared_object_id__;") { run, runtime in
70
+ try benchmark("@SharedObject: new instance and ID read", runtime: runtime) { iterations in
71
+ _ = try run.call(arguments: iterations)
72
+ }
73
+ }
74
+ }
75
+
76
+ @Test
77
+ func `@SharedObject: ID read`() async throws {
78
+ try await sharedObjectBenchmarkCase(body: "counter.__expo_shared_object_id__;") { run, runtime in
79
+ try benchmark("@SharedObject: ID read", runtime: runtime) { iterations in
80
+ _ = try run.call(arguments: iterations)
81
+ }
82
+ }
83
+ }
84
+
85
+ @Test
86
+ func `@SharedObject: instance passed as an argument`() async throws {
87
+ try await sharedObjectBenchmarkCase(body: "m.readCounter(counter);") { run, runtime in
88
+ try benchmark("@SharedObject: instance passed as an argument", runtime: runtime) { iterations in
89
+ _ = try run.call(arguments: iterations)
90
+ }
91
+ }
92
+ }
93
+
94
+ @Test
95
+ func `@SharedObject: existing instance returned from a function`() async throws {
96
+ try await sharedObjectBenchmarkCase(body: "m.echoCounter(counter);") { run, runtime in
97
+ try benchmark("@SharedObject: existing instance returned from a function", runtime: runtime) { iterations in
98
+ _ = try run.call(arguments: iterations)
99
+ }
100
+ }
101
+ }
102
+
103
+ @Test
104
+ func `emit: Int payload from a @SharedObject`() async throws {
105
+ try await moduleBenchmarkCase { appContext in
106
+ return SharedObjectBenchmarkModule(appContext: appContext)
107
+ } _: { _, runtime in
108
+ let counterObject = try runtime.eval([
109
+ "var counter = new expo.modules.SharedObjectBenchmarkModule.BenchmarkCounter(0)",
110
+ "counter.addListener('count', () => {})",
111
+ "counter"
112
+ ]).asObject()
113
+ let counter = try SharedObject.native(from: counterObject)
114
+
115
+ try benchmark("emit: Int payload from a @SharedObject", runtime: runtime) { iterations in
116
+ for index in 0..<iterations {
117
+ counter.emit(event: "count", payload: index)
118
+ }
119
+ }
120
+ }
121
+ }
122
+
39
123
  @Test
40
124
  func `@SharedObject: method call`() async throws {
41
125
  try await sharedObjectBenchmarkCase(body: "counter.increment(1);") { run, runtime in
@@ -87,6 +171,16 @@ private final class SharedObjectBenchmarkModule: Module {
87
171
  func makeRef(value: Int) -> SharedRef<Int> {
88
172
  return SharedRef(value)
89
173
  }
174
+
175
+ @JS
176
+ func readCounter(counter: BenchmarkCounter) -> Int {
177
+ return counter.current
178
+ }
179
+
180
+ @JS
181
+ func echoCounter(counter: BenchmarkCounter) -> BenchmarkCounter {
182
+ return counter
183
+ }
90
184
  }
91
185
 
92
186
  /// Runs one case with `SharedObjectBenchmarkModule` registered and a JavaScript driver that runs `body`
@@ -235,19 +235,14 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
235
235
  /// Perhaps it should be kept by the `ModuleHolder`.
236
236
  internal let classRegistry = ClassRegistry()
237
237
 
238
- /**
239
- Creates a new JavaScript object with the class prototype associated with the given native class.
240
- - ToDo: Move this to `ModuleHolder` along the `classRegistry` property.
241
- */
238
+ /// Creates a new JavaScript object with the class prototype associated with the given native class.
239
+ /// Returns `nil` when no JavaScript class is registered for the native class.
240
+ /// - ToDo: Move this to `ModuleHolder` along the `classRegistry` property.
242
241
  internal func newObject(nativeClassId: ObjectIdentifier) throws -> JavaScriptObject? {
243
242
  let runtime = try self.runtime
244
- let object = classRegistry.withPrototype(nativeClassId: nativeClassId) { (prototype: borrowing JavaScriptObject) in
243
+ return classRegistry.withPrototype(nativeClassId: nativeClassId) { (prototype: borrowing JavaScriptObject) in
245
244
  return runtime.createObject(prototype: prototype)
246
245
  }
247
- guard let object else {
248
- throw JavaScriptClassNotFoundException()
249
- }
250
- return object
251
246
  }
252
247
 
253
248
  // MARK: - Legacy modules
@@ -9,6 +9,9 @@ import ExpoModulesJSI
9
9
  public final class ArrayBuffer: AnyArrayBuffer, Sendable {
10
10
  private let storage: ArrayBufferStorage
11
11
 
12
+ /// Whether a live JavaScript array buffer reports this buffer's memory to the garbage collector.
13
+ private let isMemoryReported = Mutex(false)
14
+
12
15
  private var rawPointer: UnsafeMutableRawPointer {
13
16
  return storage.rawPointer
14
17
  }
@@ -86,14 +89,34 @@ public final class ArrayBuffer: AnyArrayBuffer, Sendable {
86
89
  /// The native buffer is retained for the lifetime of the `JavaScriptArrayBuffer`.
87
90
  @usableFromInline
88
91
  func asJavaScriptArrayBuffer(runtime: JavaScriptRuntime) -> JavaScriptArrayBuffer {
89
- return runtime.createArrayBuffer(
92
+ // The garbage collector does not see native memory, so one live JavaScript array buffer reports it.
93
+ // Reporting it for every wrapper would add the full size each time the same buffer is returned.
94
+ // Borrowed memory belongs to another JavaScript array buffer, which accounts for it.
95
+ let reportsMemory =
96
+ storage.ownsMemory && byteLength > 0
97
+ && isMemoryReported.withLock { isReported in
98
+ if isReported {
99
+ return false
100
+ }
101
+ isReported = true
102
+ return true
103
+ }
104
+ let jsArrayBuffer = runtime.createArrayBuffer(
90
105
  data: rawPointer.assumingMemoryBound(to: UInt8.self),
91
106
  size: byteLength
92
107
  ) { [self] in
93
108
  // Retain `self` until the JS engine releases the ArrayBuffer. When this
94
109
  // closure is dropped, the buffer deinits and deallocates its memory.
95
- _ = self
110
+ if reportsMemory {
111
+ isMemoryReported.withLock { isReported in
112
+ isReported = false
113
+ }
114
+ }
96
115
  }
116
+ if reportsMemory {
117
+ jsArrayBuffer.asValue().getObject().setExternalMemoryPressure(byteLength)
118
+ }
119
+ return jsArrayBuffer
97
120
  }
98
121
 
99
122
  // MARK: - Copy
@@ -147,10 +170,16 @@ public final class ArrayBuffer: AnyArrayBuffer, Sendable {
147
170
  /// - Warning: This bypasses Data's copy-on-write capabilities, effectively allowing
148
171
  /// mutation of the Data from JavaScript code.
149
172
  public static func wrap(dataWithoutCopy data: Data) -> ArrayBuffer {
150
- let retained = Unmanaged.passRetained(data as NSData)
151
- let pointer = UnsafeMutableRawPointer(mutating: retained.takeUnretainedValue().bytes)
152
- return ArrayBuffer(owning: pointer, count: data.count) {
153
- retained.release()
173
+ // `NSData.bytes` returns an inner pointer, so the call retains and autoreleases the `NSData`, which
174
+ // owns the bytes. Without this pool, the bytes stay alive until the caller's pool drains, which never
175
+ // happens while a caller such as a JavaScript loop does not return to its run loop. `retained` keeps
176
+ // the `NSData` alive after this pool drains.
177
+ return autoreleasepool {
178
+ let retained = Unmanaged.passRetained(data as NSData)
179
+ let pointer = UnsafeMutableRawPointer(mutating: retained.takeUnretainedValue().bytes)
180
+ return ArrayBuffer(owning: pointer, count: data.count) {
181
+ retained.release()
182
+ }
154
183
  }
155
184
  }
156
185
 
@@ -305,6 +334,15 @@ private enum ArrayBufferStorage: Sendable {
305
334
  }
306
335
  }
307
336
 
337
+ var ownsMemory: Bool {
338
+ switch self {
339
+ case .ownedNative:
340
+ return true
341
+ case .nativeBacked:
342
+ return false
343
+ }
344
+ }
345
+
308
346
  func cleanup() {
309
347
  switch self {
310
348
  case .ownedNative(let storage), .nativeBacked(let storage):
@@ -67,12 +67,12 @@ public final class ClassDefinition: ObjectDefinition {
67
67
  // the prototype chain `new` set up). Prefer the macro-synthesized `_constructSharedObject`,
68
68
  // falling back to the DSL `Constructor` body.
69
69
  if let sharedObject = try sharedObjectType?._constructSharedObject(this: this, arguments: arguments, in: appContext.runtime) {
70
- appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: this.getObject())
70
+ appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: this.getObject(), inheritsBaseClass: true)
71
71
  } else if let constructor {
72
72
  let result = try constructor.runBody(appContext, in: appContext.runtime, this: this, arguments: arguments)
73
73
 
74
74
  if let sharedObject = result as? SharedObject {
75
- appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: this.getObject())
75
+ appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: this.getObject(), inheritsBaseClass: true)
76
76
  }
77
77
  } else if sharedObjectType != nil {
78
78
  // Nothing built a native instance, so the object would reach JavaScript with no backing
@@ -89,9 +89,10 @@ public final class ClassDefinition: ObjectDefinition {
89
89
 
90
90
  let prototype = klass.getProperty("prototype").getObject()
91
91
 
92
- // Bind the macro's `@JS` members onto the prototype.
92
+ // Bind the macro's `@JS` members: instance members onto the prototype, static members onto the constructor.
93
93
  if let sharedObjectType {
94
94
  try sharedObjectType._decorateSharedObject(prototype: prototype, in: appContext.runtime)
95
+ try sharedObjectType._decorateSharedObject(constructor: klass, in: appContext.runtime)
95
96
  }
96
97
 
97
98
  // Register the prototype of the JS class for its associated native type.
@@ -71,14 +71,14 @@ internal struct DynamicSharedObjectType: AnyDynamicType {
71
71
  if let jsObject = sharedObject.getJavaScriptObject() {
72
72
  return jsObject.asValue()
73
73
  }
74
- guard let jsObject = (try? appContext.newObject(nativeClassId: typeIdentifier)) ?? (try? newBaseSharedObject(appContext, nativeType: innerType)) else {
74
+ guard let jsObject = (try? appContext.newObject(nativeClassId: typeIdentifier)) ?? (try? newBaseSharedObject(appContext, isSharedRef: sharedObject.sharedRefType != nil)) else {
75
75
  // Throwing is not possible here due to swift-objC interop.
76
76
  log.warn("Unable to create a JS object for \(description)")
77
77
  return JavaScriptValue.undefined()
78
78
  }
79
79
 
80
80
  // Add newly created objects to the registry.
81
- appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: jsObject)
81
+ appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: jsObject, inheritsBaseClass: true)
82
82
 
83
83
  return jsObject.asValue()
84
84
  }
@@ -86,8 +86,7 @@ internal struct DynamicSharedObjectType: AnyDynamicType {
86
86
  }
87
87
  }
88
88
 
89
- private func newBaseSharedObject(_ appContext: AppContext, nativeType: AnySharedObject.Type) throws -> JavaScriptObject? {
90
- let isSharedRef = nativeType is AnySharedRef.Type
89
+ private func newBaseSharedObject(_ appContext: AppContext, isSharedRef: Bool) throws -> JavaScriptObject? {
91
90
  return try JavaScriptActor.assumeIsolated {
92
91
  return try appContext.runtime.createBaseSharedObject(isSharedRef: isSharedRef)
93
92
  }
@@ -36,6 +36,16 @@ public enum JSOptions {
36
36
  /// The call sends the module or shared object off the JavaScript thread, so in Swift 6 language
37
37
  /// mode the enclosing class must be `Sendable`.
38
38
  case concurrent
39
+
40
+ /// Binds a synchronous function a second time under the given JavaScript name, as a function that
41
+ /// returns a promise and runs the body on the concurrent thread pool, for example
42
+ /// `@JS("textSync", .withAsync("text"))`. The body must be safe to run on any thread, since the
43
+ /// variant isn't isolated to the JavaScript thread. Only valid on a synchronous function that isn't
44
+ /// isolated to a global actor, and the name must be a string literal.
45
+ ///
46
+ /// The variant sends the module or shared object off the JavaScript thread, so in Swift 6 language
47
+ /// mode the enclosing class must be `Sendable`.
48
+ case withAsync(String)
39
49
  }
40
50
 
41
51
  /// Marker macro applied to module / shared-object members that should be exposed to JavaScript.
@@ -59,6 +69,9 @@ public enum JSOptions {
59
69
  /// @JS("doWork", .concurrent)
60
70
  /// func performHeavyWork() async throws { ... }
61
71
  ///
72
+ /// @JS("textSync", .withAsync("text"))
73
+ /// func text(path: String) throws -> String { ... }
74
+ ///
62
75
  /// Also emits a never-called `_assertTypesConformance_<member>` peer that statically asserts every
63
76
  /// type crossing the JS boundary conforms to the JS-convertible protocol, so a non-conforming type
64
77
  /// fails to compile on the user's declaration. The peer name embeds the member name, hence
@@ -183,7 +196,7 @@ public macro SharedObject(_ name: String? = nil) =
183
196
  @attached(
184
197
  member,
185
198
  names: named(init), named(from), named(toDictionary), named(toObject), named(decode), named(encode),
186
- named(_assertTypesConformance))
199
+ named(_assertTypesConformance), named(_PropNames))
187
200
  @attached(extension, conformances: Record)
188
201
  public macro Record() =
189
202
  #externalMacro(module: "ExpoModulesMacros", type: "RecordMacro")
@@ -26,14 +26,13 @@ public class ExpoRuntime: JavaScriptRuntime, @unchecked Sendable {
26
26
  /// The prototypes of both classes are looked up once per runtime and cached.
27
27
  @JavaScriptActor
28
28
  internal func createBaseSharedObject(isSharedRef: Bool) throws -> JavaScriptObject {
29
- let key = isSharedRef ? sharedRefPrototypeKey : sharedObjectPrototypeKey
30
- let makePrototype = {
31
- let baseClass = try isSharedRef ? self.getSharedRefClass() : self.getSharedObjectClass()
32
- return try baseClass.asObject().getPropertyAsObject("prototype")
29
+ let prototypes = try cached(baseSharedObjectPrototypesKey) {
30
+ return try BaseSharedObjectPrototypes(in: self)
33
31
  }
34
- return try withCached(key, makePrototype) { (prototype: borrowing JavaScriptObject) in
35
- return createObject(prototype: prototype)
32
+ if isSharedRef {
33
+ return createObject(prototype: prototypes.sharedRef)
36
34
  }
35
+ return createObject(prototype: prototypes.sharedObject)
37
36
  }
38
37
 
39
38
  @JavaScriptActor
@@ -57,6 +56,17 @@ public class ExpoRuntime: JavaScriptRuntime, @unchecked Sendable {
57
56
  }
58
57
  }
59
58
 
60
- /// Keys of the base `SharedObject` and `SharedRef` prototypes in each runtime's cache.
61
- private let sharedObjectPrototypeKey = JavaScriptRuntime.Cache.Key<JavaScriptObject.Ref>()
62
- private let sharedRefPrototypeKey = JavaScriptRuntime.Cache.Key<JavaScriptObject.Ref>()
59
+ /// The prototypes of the base `SharedObject` and `SharedRef` classes.
60
+ private final class BaseSharedObjectPrototypes {
61
+ let sharedObject: JavaScriptObject
62
+ let sharedRef: JavaScriptObject
63
+
64
+ @JavaScriptActor
65
+ init(in runtime: ExpoRuntime) throws {
66
+ sharedObject = try runtime.getSharedObjectClass().asObject().getPropertyAsObject("prototype")
67
+ sharedRef = try runtime.getSharedRefClass().asObject().getPropertyAsObject("prototype")
68
+ }
69
+ }
70
+
71
+ /// Key of the base shared object prototypes in each runtime's cache.
72
+ private let baseSharedObjectPrototypesKey = JavaScriptRuntime.Cache.Key<BaseSharedObjectPrototypes>()
@@ -36,6 +36,31 @@ open class SharedObject: AnySharedObject {
36
36
  */
37
37
  public init() {}
38
38
 
39
+ /// The value of `nativeRefType` on the JavaScript object, or `nil` when the object does not conform to
40
+ /// `AnySharedRef`.
41
+ internal var sharedRefType: String? {
42
+ guard Self.conformsToAnySharedRef(Swift.type(of: self)) else {
43
+ return nil
44
+ }
45
+ return (self as? AnySharedRef)?.nativeRefType
46
+ }
47
+
48
+ /// Whether each `SharedObject` class conforms to `AnySharedRef`. A failing `as? AnySharedRef` walks the
49
+ /// whole class hierarchy on every call, so the result is looked up once per class.
50
+ private static let anySharedRefConformances = Mutex([ObjectIdentifier: Bool]())
51
+
52
+ private static func conformsToAnySharedRef(_ type: SharedObject.Type) -> Bool {
53
+ let key = ObjectIdentifier(type)
54
+ return anySharedRefConformances.withLock { conformances in
55
+ if let conforms = conformances[key] {
56
+ return conforms
57
+ }
58
+ let conforms = type is AnySharedRef.Type
59
+ conformances[key] = conforms
60
+ return conforms
61
+ }
62
+ }
63
+
39
64
  /**
40
65
  A function that will be called before the object is removed from the registry.
41
66
  */
@@ -91,6 +116,11 @@ open class SharedObject: AnySharedObject {
91
116
  @JavaScriptActor
92
117
  open class func _decorateSharedObject(prototype: borrowing JavaScriptObject, in runtime: JavaScriptRuntime) throws {}
93
118
 
119
+ /// Binds the class's `static` and `class` `@JS` members onto its JavaScript constructor. Overridden by
120
+ /// the `@SharedObject` macro.
121
+ @JavaScriptActor
122
+ open class func _decorateSharedObject(constructor: borrowing JavaScriptObject, in runtime: JavaScriptRuntime) throws {}
123
+
94
124
  /// Builds a native instance from the JS constructor arguments, or `nil` to use the DSL `Constructor`
95
125
  /// path. Overridden by the `@SharedObject` macro from the class's `@JS init`.
96
126
  @JavaScriptActor
@@ -17,9 +17,14 @@ internal final class SharedObjectNativeState: JavaScriptNativeState {
17
17
  /// (for example a frozen one, whose native state can't be reset), so lookups check this flag.
18
18
  internal private(set) var isReleased = false
19
19
 
20
- /// The JS object paired with the native object in each runtime, keyed by runtime identity and held
21
- /// weakly. One native object can be exposed to several runtimes (e.g. the main and UI runtimes, or
22
- /// worklet contexts), each with its own JS counterpart.
20
+ /// The JS object paired with the native object in the first runtime it was paired in, held weakly.
21
+ /// Most native objects are only exposed to one runtime, so that pairing skips the dictionary below.
22
+ private var firstRuntimeId: JavaScriptRuntime.ID?
23
+ private var firstPairedObject: JavaScriptWeakObject?
24
+
25
+ /// The JS object paired with the native object in each other runtime, keyed by runtime identity and
26
+ /// held weakly. One native object can be exposed to several runtimes (e.g. the main and UI runtimes,
27
+ /// or worklet contexts), each with its own JS counterpart.
23
28
  private var pairedObjects: [JavaScriptRuntime.ID: JavaScriptWeakObject.Ref] = [:]
24
29
 
25
30
  internal init(native: SharedObject, factory: @escaping JavaScriptNativeState.Factory) {
@@ -35,27 +40,64 @@ internal final class SharedObjectNativeState: JavaScriptNativeState {
35
40
  /// for having attached this native state to `jsObject` (`jsObject.setNativeState(self)`), which reuses
36
41
  /// the shared C++ pointee across runtimes.
37
42
  internal func setJavaScriptObject(_ jsObject: borrowing JavaScriptObject, in runtime: JavaScriptRuntime) {
43
+ let runtimeId = runtime.id
44
+
45
+ // Take the first slot when it's free, already belongs to this runtime, or its JS object is gone.
46
+ if firstRuntimeId == nil || firstRuntimeId == runtimeId || !isFirstPairedObjectAlive() {
47
+ firstRuntimeId = runtimeId
48
+ firstPairedObject = jsObject.createWeak()
49
+ if !pairedObjects.isEmpty {
50
+ pairedObjects[runtimeId] = nil
51
+ }
52
+ return
53
+ }
38
54
  // Drop entries whose runtime or JS object has gone away before inserting, so the map doesn't
39
55
  // accumulate dead keys for runtimes that paired once and were torn down.
40
56
  pruneExpired()
41
- pairedObjects[runtime.id] = jsObject.createWeak().ref()
57
+ pairedObjects[runtimeId] = jsObject.createWeak().ref()
42
58
  }
43
59
 
44
60
  /// Returns the JS object paired with the native object in `runtime`, or `nil` if there is no live
45
61
  /// pairing there (none was created, or the JS object has been garbage-collected).
46
62
  internal func javaScriptObject(in runtime: JavaScriptRuntime) -> JavaScriptObject? {
47
- // Unwrap the ref first so the dictionary subscript's optional doesn't nest with `withValue`'s,
48
- // which would form a `JavaScriptObject??` that the non-`Copyable` element can't be wrapped in.
49
- guard let ref = pairedObjects[runtime.id] else {
63
+ let runtimeId = runtime.id
64
+
65
+ // Unwrap the ref first so the optional doesn't nest with `withValue`'s, which would form a
66
+ // `JavaScriptObject??` that the non-`Copyable` element can't be wrapped in.
67
+ if runtimeId == firstRuntimeId {
68
+ switch firstPairedObject {
69
+ case .some(let weakObject):
70
+ return weakObject.lock()
71
+ case .none:
72
+ return nil
73
+ }
74
+ }
75
+ guard !pairedObjects.isEmpty, let ref = pairedObjects[runtimeId] else {
50
76
  return nil
51
77
  }
52
78
  return ref.withValue { $0?.lock() }
53
79
  }
54
80
 
55
81
  private func pruneExpired() {
82
+ guard !pairedObjects.isEmpty else {
83
+ return
84
+ }
56
85
  pairedObjects = pairedObjects.filter { _, ref in
57
- // Keep the entry only while its weak JS object still resolves; an empty ref is dropped.
58
- return ref.withValue { $0?.lock() != nil } ?? false
86
+ return Self.isAlive(ref)
59
87
  }
60
88
  }
89
+
90
+ private func isFirstPairedObjectAlive() -> Bool {
91
+ switch firstPairedObject {
92
+ case .some(let weakObject):
93
+ return weakObject.lock() != nil
94
+ case .none:
95
+ return false
96
+ }
97
+ }
98
+
99
+ /// Whether the weak ref still resolves to a JS object; an empty or missing ref doesn't.
100
+ private static func isAlive(_ ref: JavaScriptWeakObject.Ref?) -> Bool {
101
+ return ref?.withValue { $0?.lock() != nil } ?? false
102
+ }
61
103
  }
@@ -23,7 +23,9 @@ public final class SharedObjectRegistry: Sendable {
23
23
 
24
24
  // `@unchecked` because `SharedObjectNativeState` isn't `Sendable` (its JSI base class isn't), yet a
25
25
  // value escapes `withLock` whenever `get`/the lookups return it. Access is always serialized through
26
- // `state`'s `Mutex` and the callers run on `JavaScriptActor`, so the unchecked assertion is sound.
26
+ // `state`'s `Mutex`. `delete(_:)` can run on the thread that destroys a C++ native state, such as a
27
+ // garbage collector thread, so it and `add` change the native object's ID and native state only under
28
+ // the lock.
27
29
  internal struct State: @unchecked Sendable {
28
30
  /**
29
31
  Maps each shared object id to the native object's `SharedObjectNativeState`, which carries the
@@ -90,26 +92,39 @@ public final class SharedObjectRegistry: Sendable {
90
92
 
91
93
  /**
92
94
  Adds a pair of native and JS shared object to the registry. Assigns a new shared object ID to these objects.
95
+ Pass `inheritsBaseClass: true` when `jsObject` inherits from `expo.SharedObject.prototype`, whose getter
96
+ already reads the ID from the native state. A plain object gets the ID as its own property instead.
93
97
  */
94
98
  @discardableResult
95
- internal func add(native nativeObject: SharedObject, javaScript jsObject: borrowing JavaScriptObject) -> SharedObjectId {
96
- // A native object that already carries a native state was paired in an earlier runtime. Reuse its
97
- // id rather than minting a new one: the C++ `NativeState.objectId` is immutable and drives the
98
- // releaser/`delete`, so a fresh id would disagree with it and leak this object's registry entry.
99
- let existingNativeState = unreleasedNativeState(of: nativeObject)
99
+ internal func add(
100
+ native nativeObject: SharedObject,
101
+ javaScript jsObject: borrowing JavaScriptObject,
102
+ inheritsBaseClass: Bool = false
103
+ ) -> SharedObjectId {
104
+ // Reuse the native state, and with it the ID, only while a live JS object in this runtime holds it.
105
+ // That JS object keeps the C++ native state alive until `setNativeState` attaches it to `jsObject`.
106
+ // Otherwise the C++ native state can be in destruction on another thread, and its release must not
107
+ // apply to `jsObject`, so the native object gets a new native state and ID.
108
+ // Loaded once: each read of the weak reference to the app context costs an atomic operation.
109
+ let appContext = self.appContext
110
+ let runtime = try? appContext?.runtime
111
+ let pairedObject = pairedObjectHoldingNativeState(of: nativeObject, in: runtime)
112
+ let existingNativeState = pairedObject != nil ? nativeObject.nativeState : nil
100
113
  let id = existingNativeState != nil ? nativeObject.sharedObjectId : pullNextId()
101
114
 
102
- // Assign the ID and the app context to the object.
103
- nativeObject.sharedObjectId = id
115
+ // Assign the app context to the object.
104
116
  nativeObject.appContext = appContext
105
117
 
106
118
  // This property should be deprecated, but it's still used when passing as a view prop.
107
- // It's already defined in the JS base SharedObject class prototype,
108
- // but with the current implementation it's possible to use a raw object for registration.
109
- jsObject.defineProperty(sharedObjectIdPropertyName, value: id, options: [.writable])
119
+ // The base class prototype defines it as a getter, so only a plain object needs its own property.
120
+ // Defining it calls `Object.defineProperty` in JS, a large part of the cost of pairing.
121
+ // No option set literals here: they build the set through a generic initializer on every call.
122
+ if !inheritsBaseClass {
123
+ jsObject.defineProperty(sharedObjectIdPropertyName, value: id, options: .writable)
124
+ }
110
125
 
111
- if let sharedRef = nativeObject as? AnySharedRef {
112
- jsObject.defineProperty("nativeRefType", value: sharedRef.nativeRefType, options: [])
126
+ if let sharedRefType = nativeObject.sharedRefType {
127
+ jsObject.defineProperty("nativeRefType", value: sharedRefType, options: JavaScriptObject.PropertyOptions())
113
128
  }
114
129
 
115
130
  let memoryPressure = nativeObject.getAdditionalMemoryPressure()
@@ -120,11 +135,6 @@ public final class SharedObjectRegistry: Sendable {
120
135
  // Attach the C++ shared-object native state. Because `expo::SharedObject::NativeState`
121
136
  // inherits from `expo::EventEmitter::NativeState`, later `addListener` calls see an
122
137
  // existing native state (via the inheritance check) and don't overwrite it.
123
- //
124
- // A native object may already carry a native state from a previous pairing in another runtime.
125
- // Reuse it so all runtimes share one native state (and one underlying C++ pointee, via
126
- // `acquireShared`); a fresh state per runtime would leave `nativeObject.nativeState` pointing at
127
- // whichever ran last and lose the earlier runtimes' pairings.
128
138
  let nativeState = existingNativeState ?? {
129
139
  let releaser: ObjectReleaser = { [weak self] id in
130
140
  self?.delete(id)
@@ -137,26 +147,29 @@ public final class SharedObjectRegistry: Sendable {
137
147
  contextDeallocator: deallocator
138
148
  )
139
149
  }
140
- nativeObject.nativeState = state
141
150
  return state
142
151
  }()
143
152
 
144
- // Index the native state by id. One entry per native object: re-pairing in another runtime stores
145
- // the same state under the same id (idempotent); the per-runtime JS counterparts live on the state.
153
+ // Index the native state by ID. `delete(_:)` reads the native object's ID and native state on any
154
+ // thread, so they change under the same lock.
146
155
  state.withLock { state in
147
156
  state.pairs[id] = nativeState
157
+ nativeObject.sharedObjectId = id
158
+ nativeObject.nativeState = nativeState
148
159
  }
149
160
 
150
161
  // setNativeState calls acquireShared() synchronously, which retains `nativeState`
151
162
  // via Unmanaged.passRetained. That's the wrapper's only strong reference — once
152
163
  // the C++ pointee dies, the contextDeallocator releases it. Reattaching the same
153
164
  // native state to another runtime's JS object reuses that same C++ pointee.
154
- jsObject.setNativeState(nativeState)
165
+ withExtendedLifetime(pairedObject) {
166
+ jsObject.setNativeState(nativeState)
167
+ }
155
168
 
156
169
  // The registry is scoped to its app context, so the JS object being paired here lives in that
157
170
  // context's runtime. Record the pairing under that runtime so the native object can recover this
158
171
  // JS counterpart via `native.nativeState?.javaScriptObject(in:)`.
159
- if let runtime = try? appContext?.runtime {
172
+ if let runtime {
160
173
  nativeState.setJavaScriptObject(jsObject, in: runtime)
161
174
  }
162
175
 
@@ -171,12 +184,18 @@ public final class SharedObjectRegistry: Sendable {
171
184
  if let nativeState = state.pairs[id] {
172
185
  let native = nativeState.native
173
186
  nativeState.markReleased()
174
- native.sharedObjectWillRelease()
175
- // Reset an ID on the object.
176
- native.sharedObjectId = 0
177
187
 
178
188
  // Delete the entry from the dictionary.
179
189
  state.pairs[id] = nil
190
+
191
+ // A native object that was paired again after its JS object died has a new native state and ID,
192
+ // and stays paired.
193
+ guard native.nativeState === nativeState else {
194
+ return
195
+ }
196
+ native.sharedObjectWillRelease()
197
+ // Reset an ID on the object.
198
+ native.sharedObjectId = 0
180
199
  native.sharedObjectDidRelease()
181
200
  }
182
201
  }
@@ -229,13 +248,7 @@ public final class SharedObjectRegistry: Sendable {
229
248
  guard let runtime = try? appContext?.runtime else {
230
249
  return nil
231
250
  }
232
- // The id table and the native object both resolve to the same `SharedObjectNativeState`, which
233
- // owns the per-runtime JS counterparts, so a single lookup serves both. Prefer the native object's
234
- // own back-pointer and fall back to the id table for objects whose back-pointer was cleared.
235
- let nativeState = unreleasedNativeState(of: nativeObject) ?? state.withLock { state in
236
- return state.pairs[nativeObject.sharedObjectId]
237
- }
238
- return nativeState?.javaScriptObject(in: runtime)
251
+ return unreleasedNativeState(of: nativeObject)?.javaScriptObject(in: runtime)
239
252
  }
240
253
 
241
254
  /// Returns the native object's native state, or `nil` if it was released. A released native state can
@@ -247,6 +260,19 @@ public final class SharedObjectRegistry: Sendable {
247
260
  return nativeState
248
261
  }
249
262
 
263
+ /// Returns the JS object paired with the native object in this registry's runtime, if it is alive and
264
+ /// still holds the native object's native state.
265
+ private func pairedObjectHoldingNativeState(of nativeObject: SharedObject, in runtime: JavaScriptRuntime?) -> JavaScriptObject? {
266
+ guard let runtime,
267
+ let nativeState = unreleasedNativeState(of: nativeObject),
268
+ let pairedObject = nativeState.javaScriptObject(in: runtime),
269
+ pairedObject.getNativeState(as: SharedObjectNativeState.self) === nativeState
270
+ else {
271
+ return nil
272
+ }
273
+ return pairedObject
274
+ }
275
+
250
276
  /**
251
277
  Creates a plain JS object and pairs it with a given native object.
252
278
  */
@@ -16,6 +16,10 @@ open class SharedRef<RefType>: SharedObject, AnySharedRef {
16
16
  "unknown"
17
17
  }
18
18
 
19
+ internal override var sharedRefType: String? {
20
+ return nativeRefType
21
+ }
22
+
19
23
  @available(*, deprecated, renamed: "ref", message: "it has been renamed to 'ref' in Expo SDK 52")
20
24
  public var pointer: RefType {
21
25
  return ref
@@ -67,7 +67,11 @@ extension ExpoSwiftUI {
67
67
  self.contentView = ContentView(props: props)
68
68
  let rootView = AnyView(contentView)
69
69
  self.props = props
70
+ #if os(iOS) || os(tvOS)
71
+ let controller: UIHostingController<AnyView> = AppearanceTrackingHostingController(rootView: rootView)
72
+ #else
70
73
  let controller = UIHostingController(rootView: rootView)
74
+ #endif
71
75
 
72
76
  if #available(iOS 16.0, tvOS 16.0, macOS 13.0, *) {
73
77
  controller.sizingOptions = [.intrinsicContentSize]
@@ -259,10 +263,27 @@ extension ExpoSwiftUI {
259
263
  addSubview(hostingController.view)
260
264
  #if os(iOS) || os(tvOS)
261
265
  hostingController.didMove(toParent: parentController)
266
+ forwardAppearanceIfMissed(parentController: parentController)
262
267
  #endif
263
268
  setupHostingViewConstraints()
264
269
  }
265
270
 
271
+ #if os(iOS) || os(tvOS)
272
+ // A child added during a transition after its parent appeared never appears, so it gets no safe area (#51288).
273
+ // TODO: Workaround for https://github.com/software-mansion/react-native-screens/pull/4997, remove once it ships.
274
+ private func forwardAppearanceIfMissed(parentController: UIViewController) {
275
+ guard
276
+ parentController.transitionCoordinator != nil,
277
+ let controller = hostingController as? AppearanceTrackingHostingController,
278
+ !controller.isAppearing
279
+ else {
280
+ return
281
+ }
282
+ controller.beginAppearanceTransition(true, animated: false)
283
+ controller.endAppearanceTransition()
284
+ }
285
+ #endif
286
+
266
287
  #if os(macOS)
267
288
  public override func reactViewController() -> NSViewController? {
268
289
  var currentView: NSView? = self
@@ -278,6 +299,23 @@ extension ExpoSwiftUI {
278
299
  }
279
300
  }
280
301
 
302
+ #if os(iOS) || os(tvOS)
303
+ // Records whether UIKit forwarded appearance, so `HostingView` can forward it when UIKit misses it.
304
+ private final class AppearanceTrackingHostingController: UIHostingController<AnyView> {
305
+ private(set) var isAppearing = false
306
+
307
+ override func viewWillAppear(_ animated: Bool) {
308
+ super.viewWillAppear(animated)
309
+ isAppearing = true
310
+ }
311
+
312
+ override func viewDidDisappear(_ animated: Bool) {
313
+ super.viewDidDisappear(animated)
314
+ isAppearing = false
315
+ }
316
+ }
317
+ #endif
318
+
281
319
  extension UIHostingController {
282
320
  /// Applies the `ignoreSafeArea` mode reactively, restoring the default safe area when `nil` so
283
321
  /// clearing the prop re-enables the safe area without an app reload.
@@ -8,6 +8,8 @@ extension ExpoSwiftUI {
8
8
  */
9
9
  struct UIViewHost: UIViewRepresentable, AnyChild {
10
10
  let view: UIView
11
+ // Fabric can mount a recycled view again; a new identity per mount gives it a new container.
12
+ private let mountToken = MountToken()
11
13
 
12
14
  // MARK: - UIViewRepresentable implementations
13
15
 
@@ -64,8 +66,14 @@ extension ExpoSwiftUI {
64
66
  var uiView: UIView? {
65
67
  view
66
68
  }
69
+
70
+ var childIdentity: ExpoSwiftUI.ChildIdentity {
71
+ .object(ObjectIdentifier(mountToken))
72
+ }
67
73
  }
68
74
 
75
+ private final class MountToken {}
76
+
69
77
  #if !os(macOS)
70
78
  /**
71
79
  Disposable UIView handed to SwiftUI in place of the React-managed view —
@@ -8,16 +8,28 @@ import Foundation
8
8
  @available(tvOS, deprecated: 18.0, message: "Use Mutex from the Synchronization framework")
9
9
  public final class Mutex<Value>: @unchecked Sendable {
10
10
  private var _value: Value
11
- private let _lock = NSLock()
11
+
12
+ // An `os_unfair_lock` must not move in memory, so it lives in its own allocation. Under contention it
13
+ // costs much less than `NSLock`, which waits in the kernel.
14
+ private let _lock: os_unfair_lock_t = {
15
+ let lock = os_unfair_lock_t.allocate(capacity: 1)
16
+ lock.initialize(to: os_unfair_lock())
17
+ return lock
18
+ }()
12
19
 
13
20
  public init(_ initialValue: Value) {
14
21
  _value = initialValue
15
22
  }
16
23
 
24
+ deinit {
25
+ _lock.deinitialize(count: 1)
26
+ _lock.deallocate()
27
+ }
28
+
17
29
  @discardableResult
18
30
  public func withLock<T>(_ body: (inout Value) throws -> T) rethrows -> T {
19
- _lock.lock()
20
- defer { _lock.unlock() }
31
+ os_unfair_lock_lock(_lock)
32
+ defer { os_unfair_lock_unlock(_lock) }
21
33
  return try body(&_value)
22
34
  }
23
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-modules-core",
3
- "version": "58.0.23",
3
+ "version": "58.0.26",
4
4
  "description": "The core of Expo Modules architecture",
5
5
  "keywords": [
6
6
  "expo",
@@ -66,12 +66,12 @@
66
66
  "./package.json": "./package.json"
67
67
  },
68
68
  "dependencies": {
69
- "expo-modules-jsi": "~58.0.16",
70
- "expo-modules-macros": "0.21.0",
69
+ "expo-modules-jsi": "~58.0.19",
70
+ "expo-modules-macros": "0.22.0",
71
71
  "invariant": "^2.2.4"
72
72
  },
73
73
  "devDependencies": {
74
- "@expo/internal-scripts": "58.0.3",
74
+ "@expo/internal-scripts": "58.0.4",
75
75
  "@testing-library/react-native": "^14.0.1",
76
76
  "@types/invariant": "^2.2.33",
77
77
  "@types/react": "~19.3.0",