expo-modules-core 58.0.26 → 58.0.28

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 (31) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/ExpoModulesWorklets.podspec +5 -0
  3. package/android/build.gradle +3 -3
  4. package/android/prebuilt/metadata.json +3 -3
  5. package/android/prebuilt/native-libs.tar.xz +0 -0
  6. package/android/src/main/cpp/ArrayBuffer.cpp +7 -1
  7. package/android/src/main/cpp/ArrayBuffer.h +2 -0
  8. package/android/src/main/java/expo/modules/interfaces/taskManager/TaskServiceProviderHelper.kt +1 -1
  9. package/common/cpp/fabric/ExpoViewShadowNode.h +34 -5
  10. package/expo-module-gradle-plugin/build.gradle.kts +1 -1
  11. package/ios/Benchmarks/EventEmitterBenchmarks.swift +73 -0
  12. package/ios/Core/AppContext.swift +32 -5
  13. package/ios/Core/Coding/JavaScriptCodable+SharedObject.swift +9 -3
  14. package/ios/Core/Events/EventEmitter.swift +102 -25
  15. package/ios/Core/ExpoModulesMacros.swift +15 -15
  16. package/ios/Core/ModuleHolder.swift +7 -9
  17. package/ios/Core/Modules/ModuleDefinition.swift +2 -3
  18. package/ios/Core/Protocols/AnyModule.swift +12 -4
  19. package/ios/Core/SharedObjects/SharedObject.swift +24 -1
  20. package/ios/Core/SharedObjects/SharedObjectNativeState.swift +1 -1
  21. package/ios/Core/SharedObjects/SharedObjectRegistry.swift +2 -11
  22. package/ios/DevTools/CdpNetworkTypes.swift +16 -0
  23. package/ios/DevTools/ExpoRequestCdpInterceptor.swift +5 -0
  24. package/ios/DevTools/ExpoRequestInterceptorProtocol.swift +22 -19
  25. package/ios/JS/JavaScriptBindings.swift +53 -0
  26. package/package.json +4 -4
  27. package/prebuilds/output/debug/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  28. package/prebuilds/output/debug/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  29. package/prebuilds/output/headers/xcframeworks/ExpoModulesCoreHeaders.tar.gz +0 -0
  30. package/prebuilds/output/release/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  31. package/prebuilds/output/release/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 58.0.28
4
+
5
+ ### Patch Changes
6
+
7
+ - [iOS] Add `EventEmitter.emit(event:payload:encode:)`, which emits a payload that a closure encodes into a slot. `expo-modules-macros` uses it for an `@Event` whose payload holds a tuple, which can't conform to `JavaScriptEncodable`. ([#52392](https://github.com/expo/expo/pull/52392) by [@tsapeta](https://github.com/tsapeta))
8
+ - [iOS] Send `Network.loadingFailed` to the network inspector when a request fails, so failed requests no longer show as pending. ([#52431](https://github.com/expo/expo/pull/52431) by [@alanjhughes](https://github.com/alanjhughes))
9
+ - [iOS] Fix missing upload progress for `URLSession` requests, such as `XMLHttpRequest` and foreground `File.upload`, when the network inspector is enabled. ([#52428](https://github.com/expo/expo/pull/52428) by [@alanjhughes](https://github.com/alanjhughes))
10
+ - [iOS] Update `expo-modules-macros` to 0.27.0, which converts Swift tuples in `@JS` members, `@Record` properties, `@Union` payloads, `@Event` payloads and closure arguments, and resolves the tuple type aliases declared in `@ExpoModule` and `@SharedObject` classes. ([#52390](https://github.com/expo/expo/pull/52390) by [@tsapeta](https://github.com/tsapeta))
11
+ - [iOS] Update `expo-modules-macros` to 0.27.1, which binds sync `@JS` functions that return nothing through the `Void` host function overload. This reduces the overhead of calling them. ([#52435](https://github.com/expo/expo/pull/52435) by [@tsapeta](https://github.com/tsapeta))
12
+ - [iOS] Reduce the overhead of passing an existing shared object to JavaScript, as a function result or an event payload, and of emitting events from shared objects. ([#52180](https://github.com/expo/expo/pull/52180) by [@tsapeta](https://github.com/tsapeta))
13
+ - Rebuild precompiled iOS binaries against React Native 0.88.1. ([#52404](https://github.com/expo/expo/pull/52404) by [@intergalacticspacehighway](https://github.com/intergalacticspacehighway))
14
+ - Updated dependencies. ([#52210](https://github.com/expo/expo/pull/52210), [#52208](https://github.com/expo/expo/pull/52208), [#52293](https://github.com/expo/expo/pull/52293), [#52350](https://github.com/expo/expo/pull/52350), [#52286](https://github.com/expo/expo/pull/52286), [#52328](https://github.com/expo/expo/pull/52328), [#51880](https://github.com/expo/expo/pull/51880), [#52346](https://github.com/expo/expo/pull/52346), [#52254](https://github.com/expo/expo/pull/52254), [#52392](https://github.com/expo/expo/pull/52392), [#52404](https://github.com/expo/expo/pull/52404))
15
+ - expo-modules-jsi@58.0.21
16
+
17
+ ## 58.0.27
18
+
19
+ ### Patch Changes
20
+
21
+ - [Android] Fix a crash when a function returns the same `ArrayBuffer` to JavaScript many times. Each return held a new JNI global reference until garbage collection, which overflowed the global reference table. ([#52278](https://github.com/expo/expo/pull/52278) by [@github-actions](https://github.com/apps/github-actions))
22
+ - [Android] Avoid Kotlin reflection when sorting task service providers. ([`571588f`](https://github.com/expo/expo/commit/571588f363d0598e9196bb9560635bc1cf8fe817) by [@matthew-gizmo](https://github.com/matthew-gizmo))
23
+ - [iOS] Reduce the overhead of emitting events by reaching the JSI runtime, the emitter object and the payload in one call. ([#52178](https://github.com/expo/expo/pull/52178) by [@tsapeta](https://github.com/tsapeta))
24
+ - [iOS] Reduce the overhead of emitting events with a `JavaScriptEncodable` payload, including from `@Event` properties, by specializing `emit(event:payload:)` for the payload type in the caller's module. ([#52179](https://github.com/expo/expo/pull/52179) by [@tsapeta](https://github.com/tsapeta))
25
+ - [iOS] Build the JavaScript classes of `@SharedObject` classes registered with `@ExpoModule(classes:)` from their type, without a `ClassDefinition`. ([#52137](https://github.com/expo/expo/pull/52137) by [@tsapeta](https://github.com/tsapeta))
26
+ - [iOS] Update `expo-modules-macros` to 0.24.0. A sync closure argument of a `@JS` function now encodes its arguments with code specialized for their types. ([#52232](https://github.com/expo/expo/pull/52232) by [@tsapeta](https://github.com/tsapeta))
27
+ - [iOS] Update `expo-modules-macros` to 0.23.1. `@JS` now supports a `lazy var`, which is read-only from JavaScript and stores its value on the JavaScript object at the first read. `@SharedObject` now supports subclasses of `SharedRef<T>`. Macros in a generic type no longer fail to build when a generic parameter of the type has the same name as one in the generated code. ([#52200](https://github.com/expo/expo/pull/52200) by [@tsapeta](https://github.com/tsapeta))
28
+ - [iOS] Fix `MenuView` triggers that fill their parent, so text in them wraps and they resize on rotation. ([#52278](https://github.com/expo/expo/pull/52278) by [@github-actions](https://github.com/apps/github-actions))
29
+ - Updated dependencies. ([#52232](https://github.com/expo/expo/pull/52232), [#52164](https://github.com/expo/expo/pull/52164), [#52178](https://github.com/expo/expo/pull/52178))
30
+ - expo-modules-jsi@58.0.20
31
+
3
32
  ## 58.0.26
4
33
 
5
34
  ### Patch Changes
@@ -37,5 +37,10 @@ Pod::Spec.new do |s|
37
37
  test_spec.dependency 'ExpoModulesTestCore'
38
38
 
39
39
  test_spec.source_files = 'ios/WorkletsTests/**/*.{m,swift}'
40
+ # The test bundle links libExpoModulesCore.a (C++). ExpoModulesCore adds -lc++ in its
41
+ # `user_target_xcconfig`, which a test_spec target doesn't inherit, so link libc++ explicitly.
42
+ test_spec.pod_target_xcconfig = {
43
+ 'OTHER_LDFLAGS' => '$(inherited) -lc++'
44
+ }
40
45
  end
41
46
  end
@@ -46,7 +46,7 @@ if (shouldIncludeCompose) {
46
46
  }
47
47
 
48
48
  group = 'host.exp.exponent'
49
- version = '58.0.26'
49
+ version = '58.0.28'
50
50
 
51
51
  def isExpoModulesCoreTests = {
52
52
  Gradle gradle = getGradle()
@@ -97,7 +97,7 @@ if (workletsProject != null) {
97
97
 
98
98
  def reactNativeWorkletsRootDir = workletsProject?.projectDir?.parentFile
99
99
 
100
- def expoModulesV2Version = "0.2.5"
100
+ def expoModulesV2Version = "0.2.6"
101
101
 
102
102
  configurations {
103
103
  // Artifact-only: the C++ sources, not something to put on any classpath.
@@ -175,7 +175,7 @@ android {
175
175
  defaultConfig {
176
176
  consumerProguardFiles 'proguard-rules.pro'
177
177
  versionCode 1
178
- versionName "58.0.26"
178
+ versionName "58.0.28"
179
179
  buildConfigField "String", "EXPO_MODULES_CORE_VERSION", "\"${versionName}\""
180
180
  buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", "true"
181
181
 
@@ -1,6 +1,6 @@
1
1
  {
2
- "reactNativeVersion": "0.88.0",
3
- "sourceHash": "d5785b6fa4de4ea64f18bdac451d0308",
2
+ "reactNativeVersion": "0.88.1",
3
+ "sourceHash": "e93890c6e60394cdef56149d38614433",
4
4
  "variants": [
5
5
  "debug",
6
6
  "release"
@@ -16,5 +16,5 @@
16
16
  "libexpo-modules-jsi.so"
17
17
  ],
18
18
  "stripped": true,
19
- "createdAt": "2026-10-23T23:08:09.663847375Z"
19
+ "createdAt": "2026-10-28T14:36:11.677615Z"
20
20
  }
Binary file
@@ -282,7 +282,13 @@ jni::local_ref<jni::JByteBuffer> ByteBufferArrayBufferStorage::toDirectBuffer()
282
282
  }
283
283
 
284
284
  std::shared_ptr<jsi::MutableBuffer> ByteBufferArrayBufferStorage::jsiMutableBuffer() {
285
- return std::make_shared<ByteBufferJSIMutableBuffer>(jni::make_local(_byteBuffer));
285
+ // All JS array buffers of this storage share one mutable buffer. Each mutable buffer holds a
286
+ // JNI global reference, and Android aborts the app when the global reference table overflows.
287
+ std::lock_guard<std::mutex> lock(_jsiMutableBufferMutex);
288
+ if (_jsiMutableBuffer == nullptr) {
289
+ _jsiMutableBuffer = std::make_shared<ByteBufferJSIMutableBuffer>(jni::make_local(_byteBuffer));
290
+ }
291
+ return _jsiMutableBuffer;
286
292
  }
287
293
 
288
294
  jsi::Value ByteBufferArrayBufferStorage::toJSIValue(jsi::Runtime &runtime) {
@@ -87,6 +87,8 @@ public:
87
87
 
88
88
  private:
89
89
  jni::global_ref<jni::JByteBuffer> _byteBuffer;
90
+ std::mutex _jsiMutableBufferMutex;
91
+ std::shared_ptr<jsi::MutableBuffer> _jsiMutableBuffer;
90
92
  };
91
93
 
92
94
  class MutableBufferViewArrayBufferStorage : public ArrayBufferStorage {
@@ -30,7 +30,7 @@ object TaskServiceProviderHelper {
30
30
  // Invoke and get the list of packages
31
31
  val result = getPackageList.invoke(null) as? List<*> ?: return null
32
32
  val packages = result.filterIsInstance<Package>()
33
- .sortedByDescending { ModulePriorities.get(it::class.qualifiedName) }
33
+ .sortedByDescending { ModulePriorities.get(it.javaClass.canonicalName) }
34
34
 
35
35
  // Check if any of the packages are providing a task manager implementation
36
36
  return packages
@@ -95,6 +95,18 @@ public:
95
95
  return it != viewProps->propsMap.end() && it->second.isBool() && it->second.getBool();
96
96
  }
97
97
 
98
+ // Set by `MenuView`'s `RNHostView`, whose `Host` is sized by Yoga instead of its content.
99
+ static bool boundedByHost(const react::Props::Shared &props) {
100
+ auto const *viewProps = dynamic_cast<const ExpoViewProps *>(props.get());
101
+
102
+ if (viewProps == nullptr) {
103
+ return false;
104
+ }
105
+
106
+ auto const it = viewProps->propsMap.find("expoInternalBoundedByHost");
107
+ return it != viewProps->propsMap.end() && it->second.isBool() && it->second.getBool();
108
+ }
109
+
98
110
  // Yoga calls this method for RNHostView when it has matchContents set
99
111
  react::Size measureContent(
100
112
  const react::LayoutContext &layoutContext,
@@ -111,7 +123,14 @@ public:
111
123
  return {};
112
124
  }
113
125
 
114
- return content->measure(layoutContext, hostedContentConstraints(*content));
126
+ auto constraints = hostedContentConstraints(*content);
127
+
128
+ if (boundedByHost(this->getProps())) {
129
+ // Like any Yoga child, the content can't be bigger than the space the `Host` offers.
130
+ constrainToMaximumSize(constraints, layoutConstraints.maximumSize);
131
+ }
132
+
133
+ return content->measure(layoutContext, constraints);
115
134
  }
116
135
 
117
136
  // We override this so RNHostView can lay out it's children
@@ -130,11 +149,14 @@ public:
130
149
  }
131
150
 
132
151
  // Use the same constraint that was used to measure the content, so that the layout is consistent with the measurement
152
+ auto constraints = hostedContentConstraints(*content);
153
+
154
+ if (boundedByHost(this->getProps())) {
155
+ constrainToMaximumSize(constraints, this->getLayoutMetrics().frame.size);
156
+ }
157
+
133
158
  auto const clonedContent = content->clone({});
134
- static_cast<react::LayoutableShadowNode &>(*clonedContent).layoutTree(
135
- layoutContext,
136
- hostedContentConstraints(*content)
137
- );
159
+ static_cast<react::LayoutableShadowNode &>(*clonedContent).layoutTree(layoutContext, constraints);
138
160
 
139
161
  this->replaceChild(*content, clonedContent, 0);
140
162
 
@@ -145,6 +167,13 @@ public:
145
167
  }
146
168
 
147
169
  private:
170
+ static void constrainToMaximumSize(react::LayoutConstraints &constraints, react::Size maximumSize) {
171
+ constraints.maximumSize.width = std::min(constraints.maximumSize.width, maximumSize.width);
172
+ constraints.maximumSize.height = std::min(constraints.maximumSize.height, maximumSize.height);
173
+ constraints.minimumSize.width = std::min(constraints.minimumSize.width, constraints.maximumSize.width);
174
+ constraints.minimumSize.height = std::min(constraints.minimumSize.height, constraints.maximumSize.height);
175
+ }
176
+
148
177
  // Owning on purpose: `layout()` calls `replaceChild()`, which overwrites this node's only strong
149
178
  // reference to the content — `RNHostView` is a leaf Yoga node, so Yoga keeps no second one, and
150
179
  // `YogaLayoutableShadowNode::replaceChild()` reads `oldChild` right after.
@@ -33,7 +33,7 @@ dependencies {
33
33
  implementation("com.facebook.react:react-native-gradle-plugin")
34
34
  implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
35
35
  implementation("io.github.expo.pika:pika-gradle:1.1.0")
36
- implementation("io.github.expo:expo-modules-v2-gradle-plugin:0.2.5")
36
+ implementation("io.github.expo:expo-modules-v2-gradle-plugin:0.2.6")
37
37
 
38
38
  if (isExpoAutolinkingSettingsPluginAvailable) {
39
39
  implementation("expo.modules:expo-autolinking-plugin-shared")
@@ -21,6 +21,17 @@ extension Benchmarks {
21
21
  }
22
22
  }
23
23
 
24
+ @Test
25
+ func `emit: no payload through @Event`() async throws {
26
+ try await eventBenchmarkCase { module, runtime in
27
+ try benchmark("emit: no payload through @Event", runtime: runtime) { iterations in
28
+ for _ in 0..<iterations {
29
+ module.onPing()
30
+ }
31
+ }
32
+ }
33
+ }
34
+
24
35
  @Test
25
36
  func `emit: no payload, 100 other modules registered`() async throws {
26
37
  try await eventBenchmarkCase(otherModuleCount: 100) { module, runtime in
@@ -76,6 +87,17 @@ extension Benchmarks {
76
87
  }
77
88
  }
78
89
 
90
+ @Test
91
+ func `emit: record payload through @Event`() async throws {
92
+ try await eventBenchmarkCase { module, runtime in
93
+ try benchmark("emit: record payload through @Event", runtime: runtime) { iterations in
94
+ for index in 0..<iterations {
95
+ module.onProgress(ProgressPayload(percent: index, label: "loading"))
96
+ }
97
+ }
98
+ }
99
+ }
100
+
79
101
  @Test
80
102
  func `emit: record payload as AnyArgument`() async throws {
81
103
  try await eventBenchmarkCase { module, runtime in
@@ -86,6 +108,49 @@ extension Benchmarks {
86
108
  }
87
109
  }
88
110
  }
111
+
112
+ @Test
113
+ func `emit: shared object payload`() async throws {
114
+ try await eventBenchmarkCase { module, runtime in
115
+ // Encoding the object once pairs it with a JavaScript object, as an object already used from
116
+ // JavaScript would be. Holding that object keeps the pair alive across garbage collections.
117
+ // A shared object isn't `Sendable`, so it can't be sent to `emit` more than once without
118
+ // opting out of the check, and an `@Event` with this payload type doesn't compile.
119
+ nonisolated(unsafe) let payload = EventPayloadObject()
120
+ let payloadObject = try EventPayloadObject.encode(payload, in: runtime)
121
+
122
+ try withExtendedLifetime(payloadObject) {
123
+ try benchmark("emit: shared object payload", runtime: runtime) { iterations in
124
+ for _ in 0..<iterations {
125
+ module.emit(event: "object", payload: payload)
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ @Test
133
+ func `emit: [String: Any] payload`() async throws {
134
+ try await eventBenchmarkCase { module, runtime in
135
+ // `[String: Any]` isn't `Sendable`, so an `@Event` with this payload type doesn't compile.
136
+ try benchmark("emit: [String: Any] payload", runtime: runtime) { iterations in
137
+ for index in 0..<iterations {
138
+ module.emit(event: "dictionary", payload: ["percent": index, "label": "loading"] as [String: Any])
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ @Test
145
+ func `emit: [String: String] payload through @Event`() async throws {
146
+ try await eventBenchmarkCase { module, runtime in
147
+ try benchmark("emit: [String: String] payload through @Event", runtime: runtime) { iterations in
148
+ for _ in 0..<iterations {
149
+ module.onStrings(["state": "loading", "label": "file"])
150
+ }
151
+ }
152
+ }
153
+ }
89
154
  }
90
155
 
91
156
  @Record
@@ -94,6 +159,8 @@ private struct ProgressPayload {
94
159
  var label: String = ""
95
160
  }
96
161
 
162
+ private final class EventPayloadObject: SharedObject {}
163
+
97
164
  @ExpoModule
98
165
  private final class EventBenchmarkModule: Module {
99
166
  @Event
@@ -104,6 +171,9 @@ private final class EventBenchmarkModule: Module {
104
171
 
105
172
  @Event
106
173
  var onProgress: (ProgressPayload) -> Void
174
+
175
+ @Event
176
+ var onStrings: ([String: String]) -> Void
107
177
  }
108
178
 
109
179
  @ExpoModule
@@ -127,6 +197,9 @@ private func eventBenchmarkCase(
127
197
  expo.modules.EventBenchmarkModule.addListener('ping', listener);
128
198
  expo.modules.EventBenchmarkModule.addListener('count', listener);
129
199
  expo.modules.EventBenchmarkModule.addListener('progress', listener);
200
+ expo.modules.EventBenchmarkModule.addListener('object', listener);
201
+ expo.modules.EventBenchmarkModule.addListener('dictionary', listener);
202
+ expo.modules.EventBenchmarkModule.addListener('strings', listener);
130
203
  """
131
204
  )
132
205
  try body(module, runtime)
@@ -582,12 +582,9 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
582
582
  }) {
583
583
  instance = cachedInstance
584
584
  } else {
585
- guard let classDefinition = self.findClassDefinition(for: typeId) else {
586
- throw SharedObjectClassNotRegisteredException(String(describing: type(of: nativeObject)))
587
- }
588
- let built = try classDefinition.buildPrototype(
585
+ let built = try self.buildWorkletPrototype(
586
+ for: type(of: nativeObject),
589
587
  in: runtime,
590
- appContext: self,
591
588
  basePrototype: sharedObjectBaseProto.getObject()
592
589
  )
593
590
  instance = runtime.createObject(prototype: built)
@@ -601,6 +598,25 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
601
598
  sharedObjectClass.setProperty("__resolveInWorklet", value: resolveInWorklet.asObject())
602
599
  }
603
600
 
601
+ /// Builds the worklet prototype for a native shared object class, from the `ClassDefinition` of a module
602
+ /// that defines it or from a module that registers it in `_classTypes`.
603
+ @JavaScriptActor
604
+ private func buildWorkletPrototype(
605
+ for nativeType: SharedObject.Type,
606
+ in runtime: JavaScriptRuntime,
607
+ basePrototype: consuming JavaScriptObject
608
+ ) throws -> JavaScriptObject {
609
+ let typeId = ObjectIdentifier(nativeType)
610
+
611
+ if let classDefinition = findClassDefinition(for: typeId) {
612
+ return try classDefinition.buildPrototype(in: runtime, appContext: self, basePrototype: basePrototype)
613
+ }
614
+ if let classType = findClassType(for: typeId) {
615
+ return try JavaScriptBindings.buildSharedObjectPrototype(classType, in: runtime, basePrototype: basePrototype)
616
+ }
617
+ throw SharedObjectClassNotRegisteredException(String(describing: nativeType))
618
+ }
619
+
604
620
  /**
605
621
  Finds the ClassDefinition for a given native type identifier by searching all modules.
606
622
  */
@@ -616,6 +632,17 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
616
632
  return nil
617
633
  }
618
634
 
635
+ /// Finds the `@SharedObject` class for a given native type identifier among the classes that modules
636
+ /// register in `_classTypes`.
637
+ private func findClassType(for typeId: ObjectIdentifier) -> SharedObject.Type? {
638
+ for module in moduleRegistry {
639
+ if let classType = type(of: module.module)._classTypes.first(where: { ObjectIdentifier($0) == typeId }) {
640
+ return classType
641
+ }
642
+ }
643
+ return nil
644
+ }
645
+
619
646
  /**
620
647
  Unsets runtime objects that we hold for each module.
621
648
  */
@@ -35,9 +35,15 @@ extension SharedObject: JavaScriptDecodable, JavaScriptEncodable {
35
35
 
36
36
  @JavaScriptActor
37
37
  public static func encode(_ value: SharedObject, in runtime: borrowing JavaScriptRuntime) throws -> JavaScriptValue {
38
- // Delegates to `DynamicSharedObjectType.castToJS`, which returns the already-paired JS object or
39
- // creates and registers a new one. That needs the registry on the app context, recovered from the
40
- // runtime; an unprepared runtime throws `Exceptions.AppContextNotFound`.
38
+ // An object already paired in this runtime is read off its native state, which is how most objects
39
+ // are encoded (for example, when a module returns or emits an object it got from JavaScript).
40
+ if let jsObject = value.object(in: runtime) {
41
+ return jsObject.takeValue()
42
+ }
43
+ // Otherwise, delegates to `DynamicSharedObjectType.castToJS`, which mostly creates and registers a
44
+ // new JS object. It returns an already-paired one only when the object is paired in its app
45
+ // context's runtime and that isn't `runtime`. That needs the registry on the app context, recovered
46
+ // from the runtime; an unprepared runtime throws `Exceptions.AppContextNotFound`.
41
47
  //
42
48
  // TODO: creating the object isn't `encode`'s job. Once creation/pairing moves elsewhere, `encode`
43
49
  // would only read the native state, dropping the app-context lookup and becoming `@inlinable` too.
@@ -1,6 +1,6 @@
1
1
  // Copyright 2024-present 650 Industries. All rights reserved.
2
2
 
3
- import ExpoModulesJSI
3
+ @_spi(Internal) import ExpoModulesJSI
4
4
 
5
5
  /**
6
6
  A protocol for native objects that have an associated JavaScript object capable of receiving events.
@@ -27,6 +27,7 @@ public extension EventEmitter {
27
27
  /**
28
28
  Schedules an event with the given name to be emitted to the associated JavaScript object.
29
29
  */
30
+ @inlinable
30
31
  func emit(event: String) {
31
32
  emit(event: event, payload: JavaScriptUndefined())
32
33
  }
@@ -71,9 +72,12 @@ public extension EventEmitter {
71
72
  /**
72
73
  Schedules an event with the given name and payload to be emitted to the associated JavaScript object.
73
74
  */
75
+ @inlinable
74
76
  func emit<P: JavaScriptEncodable>(event: String, payload: sending P) {
75
- guard let appContext, let runtime = try? appContext.runtime else {
76
- log.warn("Trying to send event '\(event)' to \(type(of: self)), but the JS runtime has been lost")
77
+ // Inlinable, so `P` and the scheduled closure specialize in the caller's module. Unspecialized, the
78
+ // payload is boxed and `P.encode` goes through the witness table on every event. The non-generic
79
+ // parts are calls into this module.
80
+ guard let runtime = eventRuntime(forEvent: event) else {
77
81
  return
78
82
  }
79
83
  // See the note in `emit(event:payload:)` above - the emitter is captured in a weak, `@unchecked
@@ -89,22 +93,51 @@ public extension EventEmitter {
89
93
  do {
90
94
  jsPayload = try P.encode(payload, in: runtime)
91
95
  } catch {
92
- log.warn("Failed to convert payload for event '\(event)' on \(P.self); the event will not be emitted: \(error)")
96
+ warnPayloadNotEncoded(event: event, payloadType: P.self, error: error)
93
97
  return
94
98
  }
95
- let dispatched = emitter.withEventTarget { target in
96
- dispatchEvent(event: event, payload: jsPayload, to: target, in: runtime)
97
- return true
99
+ dispatchEvent(event: event, payload: jsPayload, from: emitter, in: runtime)
100
+ }
101
+ }
102
+
103
+ /// Schedules an event with the given name and payload to be emitted to the associated JavaScript object,
104
+ /// converting the payload with `encode`, which writes it into a slot like
105
+ /// `JavaScriptEncodable.encode(_:into:in:)`. The `@Event` macro uses it for payload types that can't
106
+ /// conform to `JavaScriptEncodable`, such as tuples.
107
+ @inlinable
108
+ func emit<P>(
109
+ event: String,
110
+ payload: sending P,
111
+ encode: @escaping @JavaScriptActor @Sendable (P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime) throws
112
+ -> Void
113
+ ) {
114
+ guard let runtime = eventRuntime(forEvent: event) else {
115
+ return
116
+ }
117
+ // See the note in `emit(event:payload:)` above.
118
+ let emitter = WeakEventEmitterReference(value: self)
119
+
120
+ runtime.schedule {
121
+ guard let emitter = emitter.value else {
122
+ return
98
123
  }
99
- if dispatched == nil {
100
- log.warn("Trying to send event '\(event)' to JS, but the JS object is no longer associated with the native instance")
124
+ let jsPayload: JavaScriptValue
125
+ do {
126
+ jsPayload = try JavaScriptValue.encoding(in: runtime) { slot in
127
+ try encode(payload, slot, runtime)
128
+ }
129
+ } catch {
130
+ warnPayloadNotEncoded(event: event, payloadType: P.self, error: error)
131
+ return
101
132
  }
133
+ dispatchEvent(event: event, payload: jsPayload, from: emitter, in: runtime)
102
134
  }
103
135
  }
104
136
 
105
137
  /**
106
138
  Schedules an event with the given name and payload to be emitted to the associated JavaScript object.
107
- Payloads that are `JavaScriptEncodable` use the overload above, which converts them statically.
139
+ Payloads that are `JavaScriptEncodable` use the `emit(event:payload:)` overload for them, which converts
140
+ them statically.
108
141
  */
109
142
  @_disfavoredOverload
110
143
  func emit<P: AnyArgument>(event: String, payload: sending P) {
@@ -140,9 +173,57 @@ public extension EventEmitter {
140
173
  }
141
174
 
142
175
  /// A weak reference to an event emitter that the scheduled `emit` closures capture by value, so it is stored
143
- /// in the closure context without an allocation of its own.
144
- private struct WeakEventEmitterReference: @unchecked Sendable {
176
+ /// in the closure context without an allocation of its own. Frozen, because with library evolution the
177
+ /// inlinable initializer can't assign the stored property of a struct whose layout isn't fixed.
178
+ @frozen
179
+ @usableFromInline
180
+ internal struct WeakEventEmitterReference: @unchecked Sendable {
181
+ @usableFromInline
145
182
  weak var value: (any EventEmitter)?
183
+
184
+ @inlinable
185
+ init(value: any EventEmitter) {
186
+ self.value = value
187
+ }
188
+ }
189
+
190
+ extension EventEmitter {
191
+ /// The runtime to schedule an event on, or `nil` after logging a warning when it has been lost.
192
+ @usableFromInline
193
+ internal func eventRuntime(forEvent event: String) -> JavaScriptRuntime? {
194
+ guard let appContext, let runtime = try? appContext.runtime else {
195
+ log.warn("Trying to send event '\(event)' to \(type(of: self)), but the JS runtime has been lost")
196
+ return nil
197
+ }
198
+ return runtime
199
+ }
200
+ }
201
+
202
+ /// Logs that the payload of an event couldn't be converted, so the event is not emitted.
203
+ @usableFromInline
204
+ internal func warnPayloadNotEncoded(event: String, payloadType: Any.Type, error: any Error) {
205
+ log.warn(
206
+ "Failed to convert payload for event '\(event)' on \(payloadType); the event will not be emitted: \(error)"
207
+ )
208
+ }
209
+
210
+ /// Sends a pre-converted event payload to the JavaScript object of the given emitter. Logs a warning
211
+ /// when the emitter is no longer associated with a JavaScript object.
212
+ @JavaScriptActor
213
+ @usableFromInline
214
+ internal func dispatchEvent(
215
+ event: String,
216
+ payload: borrowing JavaScriptValue,
217
+ from emitter: any EventEmitter,
218
+ in runtime: JavaScriptRuntime
219
+ ) {
220
+ let dispatched = emitter.withEventTarget { target in
221
+ dispatchEvent(event: event, payload: payload, to: target, in: runtime)
222
+ return true
223
+ }
224
+ if dispatched == nil {
225
+ log.warn("Trying to send event '\(event)' to JS, but the JS object is no longer associated with the native instance")
226
+ }
146
227
  }
147
228
 
148
229
  /**
@@ -151,19 +232,15 @@ private struct WeakEventEmitterReference: @unchecked Sendable {
151
232
  */
152
233
  @JavaScriptActor
153
234
  internal func dispatchEvent(event: String, payload: borrowing JavaScriptValue, to target: borrowing JavaScriptObject, in runtime: JavaScriptRuntime) {
154
- runtime.withUnsafePointee { runtimePtr in
155
- target.withUnsafePointee { objectPtr in
156
- payload.withUnsafePointee { payloadPtr in
157
- event.withCString { eventName in
158
- emitJSEvent(
159
- utf8Name: eventName,
160
- runtimePointer: runtimePtr,
161
- objectPointer: objectPtr,
162
- argumentsPointer: payloadPtr,
163
- argumentCount: 1
164
- )
165
- }
166
- }
235
+ runtime.withUnsafePointees(object: target, value: payload) { runtimePtr, objectPtr, payloadPtr in
236
+ event.withCString { eventName in
237
+ emitJSEvent(
238
+ utf8Name: eventName,
239
+ runtimePointer: runtimePtr,
240
+ objectPointer: objectPtr,
241
+ argumentsPointer: payloadPtr,
242
+ argumentCount: 1
243
+ )
167
244
  }
168
245
  }
169
246
  }
@@ -107,11 +107,9 @@ public macro Event(_ name: String? = nil, sync: Bool = false) =
107
107
  #externalMacro(module: "ExpoModulesMacros", type: "EventMacro")
108
108
 
109
109
  /// Member macro applied to a `Module` subclass. Scans the class body for declarations
110
- /// marked with `@JS` and synthesizes a framework-internal `_synthesizedDefinition()` method.
111
- /// `expo-modules-core` calls it automatically and merges the result into the module's
112
- /// definition, so the user doesn't have to reference it from `definition()`. `@JS` functions are
113
- /// additionally bound directly into the module's JS object by a synthesized
114
- /// `_decorateModule(object:in:)`.
110
+ /// marked with `@JS` and binds them directly into the module's JS object by a synthesized
111
+ /// `_decorateModule(object:in:)`. The `@SharedObject` classes in the `classes:` argument are
112
+ /// emitted as a `_classTypes` static, and core adds their JavaScript classes to the module's JS object.
115
113
  ///
116
114
  /// The module's JavaScript name is synthesized into a `_jsName` static and read by core, so there
117
115
  /// is no `Name(…)` DSL entry. It defaults to the class name; pass `@ExpoModule("CustomName")` to
@@ -127,8 +125,8 @@ public macro Event(_ name: String? = nil, sync: Bool = false) =
127
125
  @attached(
128
126
  member,
129
127
  names:
130
- named(_jsName), named(_synthesizedDefinition), named(appContext), named(init),
131
- named(_decorateModule))
128
+ named(_jsName), named(_classTypes), named(appContext), named(init),
129
+ named(_decorateModule), named(_assertTypesConformance))
132
130
  @attached(memberAttribute)
133
131
  @attached(extension, conformances: AnyModule)
134
132
  public macro ExpoModule(_ name: String? = nil, classes: [Any.Type] = []) =
@@ -136,15 +134,16 @@ public macro ExpoModule(_ name: String? = nil, classes: [Any.Type] = []) =
136
134
 
137
135
  /// Member macro applied to a `SharedObject` subclass. Scans the class body for declarations
138
136
  /// marked with `@JS` (including a single `@JS init(...)` for the JS constructor) and
139
- /// synthesizes a `_synthesizedClassDefinition()` static method returning a `ClassDefinition`.
140
- /// The companion `@ExpoModule(classes: [Foo.self])` wires the class into the module's
141
- /// exposed surface.
137
+ /// binds them through overrides of the `SharedObject` hooks below. The class's JavaScript name
138
+ /// is emitted as a `_jsName` override. The companion `@ExpoModule(classes: [Foo.self])` wires the
139
+ /// class into the module's exposed surface.
142
140
  ///
143
141
  /// `@JS` methods and properties are bound directly onto the class prototype by an override of
144
- /// `_decorateSharedObject(prototype:in:)`, and a single `@JS init(...)` becomes an override
145
- /// of `_constructSharedObject(this:arguments:in:)` that builds the native instance from the
146
- /// JS arguments. Core calls both when building the class, so the synthesized `Class(…)` block carries
147
- /// no DSL entries for the `@JS` members.
142
+ /// `_decorateSharedObject(prototype:in:)`, `static` and `class` ones onto the class itself by an
143
+ /// override of `_decorateSharedObject(constructor:in:)`, and a single `@JS init(...)` becomes an
144
+ /// override of `_constructSharedObject(this:arguments:in:)` that builds the native instance from the
145
+ /// JS arguments. Core calls them when building the class. The class must be a `SharedObject`
146
+ /// subclass, direct or not, or the `_jsName` override doesn't compile.
148
147
  ///
149
148
  /// Usage:
150
149
  ///
@@ -162,7 +161,8 @@ public macro ExpoModule(_ name: String? = nil, classes: [Any.Type] = []) =
162
161
  @attached(
163
162
  member,
164
163
  names:
165
- named(_synthesizedClassDefinition), named(_decorateSharedObject), named(_constructSharedObject))
164
+ named(_jsName), named(_decorateSharedObject), named(_constructSharedObject),
165
+ named(_assertTypesConformance))
166
166
  @attached(memberAttribute)
167
167
  public macro SharedObject(_ name: String? = nil) =
168
168
  #externalMacro(module: "ExpoModulesMacros", type: "SharedObjectMacro")
@@ -57,15 +57,8 @@ public final class ModuleHolder {
57
57
  post(event: .moduleCreate)
58
58
  }
59
59
 
60
- /// Combines the user-authored definition with the entries synthesized by the
61
- /// `@ExpoModule` macro on this module's class (if any). The macro emits a
62
- /// `_synthesizedDefinition()` method returning an `[AnyDefinition]` array of the
63
- /// `Function` / `Property` / `Constructor` entries it generated from `@JS`
64
- /// members. Those entries are prepended to the user's definitions and the
65
- /// whole list is fed back through `ModuleDefinition.init` so the merged
66
- /// result is rebucketed (into `functions`, `properties`, etc.) just like a
67
- /// hand-written definition. Modules that don't use the macro fall through
68
- /// the empty-synthesized fast path and return the user's definition unchanged.
60
+ /// Merges the entries from `_synthesizedDefinition()` into the user-authored definition. Only module
61
+ /// binaries built with earlier `@ExpoModule` macros return any, so other modules take the fast path.
69
62
  private static func buildDefinition(for module: AnyModule) -> ModuleDefinition {
70
63
  let userDefinition = module.definition()
71
64
  let synthesized = module._synthesizedDefinition()
@@ -137,6 +130,11 @@ public final class ModuleHolder {
137
130
  log.info("Creating JS object for module '\(name)'")
138
131
  let object = try definition.build(appContext: appContext)
139
132
 
133
+ // Install the `@SharedObject` classes the `@ExpoModule` macro registers by type.
134
+ for classType in type(of: module)._classTypes {
135
+ object.setProperty(classType._jsName, value: try JavaScriptBindings.buildSharedObjectClass(classType, appContext: appContext))
136
+ }
137
+
140
138
  // Install the `@JS` members the `@ExpoModule` macro binds directly into the JS object
141
139
  // (the direct-JSI path). A no-op for modules that don't use the macro.
142
140
  try module._decorateModule(object: object, in: appContext.runtime)
@@ -29,9 +29,8 @@ public final class ModuleDefinition: ObjectDefinition {
29
29
 
30
30
  let eventObservers: [AnyEventObservingDefinition]
31
31
 
32
- /// The raw list of definitions used to construct this module. Retained so
33
- /// that `ModuleHolder` can merge in the entries synthesized by the
34
- /// `@ExpoModule` macro without losing the user-authored ones.
32
+ /// The raw list of definitions used to construct this module. Retained so that `ModuleHolder` can
33
+ /// merge in the entries from `_synthesizedDefinition()` without losing the user-authored ones.
35
34
  let rawDefinitions: [AnyDefinition]
36
35
 
37
36
  /**
@@ -21,10 +21,14 @@ public protocol AnyModule: AnyObject, AnyArgument {
21
21
  /// Modules that don't use the macro fall back to the default, which is the class name.
22
22
  static var _jsName: String { get }
23
23
 
24
- /// Returns definitions synthesized from `@JS`-annotated members by the `@ExpoModule` macro.
25
- /// Framework-internal: the leading underscore signals this is not part of the public API and
26
- /// should only be called by `expo-modules-core` itself. Modules that don't use the macro fall
27
- /// back to the default empty implementation.
24
+ /// The `@SharedObject` classes the module exposes in its JavaScript object, emitted as a static
25
+ /// constant by the `@ExpoModule` macro from its `classes:` argument. Framework-internal (leading
26
+ /// underscore). Modules that don't use the macro fall back to the default empty list.
27
+ static var _classTypes: [SharedObject.Type] { get }
28
+
29
+ /// Returns definitions that core merges into the module's definition. The `@ExpoModule` macro no
30
+ /// longer emits it. It stays so that module binaries built with earlier macros keep loading and
31
+ /// keep their classes. Framework-internal (leading underscore).
28
32
  func _synthesizedDefinition() -> [AnyDefinition]
29
33
 
30
34
  /// Binds the module's `@JS` members directly into its JavaScript object, generated by the
@@ -62,6 +66,10 @@ extension AnyModule {
62
66
  @ModuleDefinitionBuilder
63
67
  public func definition() -> ModuleDefinition {}
64
68
 
69
+ public static var _classTypes: [SharedObject.Type] {
70
+ return []
71
+ }
72
+
65
73
  public func _synthesizedDefinition() -> [AnyDefinition] {
66
74
  return []
67
75
  }
@@ -99,6 +99,21 @@ open class SharedObject: AnySharedObject {
99
99
  return appContext?.sharedObjectRegistry.toJavaScriptObject(self)
100
100
  }
101
101
 
102
+ /// The native state, or `nil` if the object was released. A released native state can outlive the
103
+ /// release on a JS object that couldn't drop it (for example a frozen one).
104
+ internal var unreleasedNativeState: SharedObjectNativeState? {
105
+ guard let nativeState, !nativeState.isReleased else {
106
+ return nil
107
+ }
108
+ return nativeState
109
+ }
110
+
111
+ /// The JS object paired with this object in the given runtime, read off its native state. Returns
112
+ /// `nil` when the object isn't paired in that runtime or was released.
113
+ internal func object(in runtime: borrowing JavaScriptRuntime) -> JavaScriptObject? {
114
+ return unreleasedNativeState?.javaScriptObject(in: runtime)
115
+ }
116
+
102
117
  /**
103
118
  Backwards-compatible overload that forwards to `emit(event:payload:)`. Existing single-argument
104
119
  call sites keep working unchanged; the parameter has been renamed to `payload` to make the
@@ -111,6 +126,12 @@ open class SharedObject: AnySharedObject {
111
126
 
112
127
  // MARK: - Macro-synthesized JSI hooks
113
128
 
129
+ /// The name of the class in JavaScript. Overridden by the `@SharedObject` macro with the class name
130
+ /// or the `@SharedObject("CustomName")` argument. A module registers the class through `_classTypes`.
131
+ open class var _jsName: String {
132
+ return unqualifiedTypeName(self)
133
+ }
134
+
114
135
  /// Binds the class's `@JS` members onto its JavaScript prototype. Overridden by the `@SharedObject`
115
136
  /// macro; a `class func` (not a protocol requirement) so dispatch resolves per subclass.
116
137
  @JavaScriptActor
@@ -132,7 +153,9 @@ open class SharedObject: AnySharedObject {
132
153
  extension SharedObject: EventEmitter {
133
154
  @JavaScriptActor
134
155
  public func withEventTarget<R>(_ body: (borrowing JavaScriptObject) throws -> R) rethrows -> R? {
135
- guard let target = getJavaScriptObject() else {
156
+ // The same lookup as `getJavaScriptObject()`, without going through the registry, since it runs
157
+ // for every emitted event.
158
+ guard let runtime = try? appContext?.runtime, let target = object(in: runtime) else {
136
159
  return nil
137
160
  }
138
161
  return try body(target)
@@ -59,7 +59,7 @@ internal final class SharedObjectNativeState: JavaScriptNativeState {
59
59
 
60
60
  /// Returns the JS object paired with the native object in `runtime`, or `nil` if there is no live
61
61
  /// pairing there (none was created, or the JS object has been garbage-collected).
62
- internal func javaScriptObject(in runtime: JavaScriptRuntime) -> JavaScriptObject? {
62
+ internal func javaScriptObject(in runtime: borrowing JavaScriptRuntime) -> JavaScriptObject? {
63
63
  let runtimeId = runtime.id
64
64
 
65
65
  // Unwrap the ref first so the optional doesn't nest with `withValue`'s, which would form a
@@ -248,23 +248,14 @@ public final class SharedObjectRegistry: Sendable {
248
248
  guard let runtime = try? appContext?.runtime else {
249
249
  return nil
250
250
  }
251
- return unreleasedNativeState(of: nativeObject)?.javaScriptObject(in: runtime)
252
- }
253
-
254
- /// Returns the native object's native state, or `nil` if it was released. A released native state can
255
- /// outlive the release on a JS object that couldn't drop it (for example a frozen one).
256
- private func unreleasedNativeState(of nativeObject: SharedObject) -> SharedObjectNativeState? {
257
- guard let nativeState = nativeObject.nativeState, !nativeState.isReleased else {
258
- return nil
259
- }
260
- return nativeState
251
+ return nativeObject.object(in: runtime)
261
252
  }
262
253
 
263
254
  /// Returns the JS object paired with the native object in this registry's runtime, if it is alive and
264
255
  /// still holds the native object's native state.
265
256
  private func pairedObjectHoldingNativeState(of nativeObject: SharedObject, in runtime: JavaScriptRuntime?) -> JavaScriptObject? {
266
257
  guard let runtime,
267
- let nativeState = unreleasedNativeState(of: nativeObject),
258
+ let nativeState = nativeObject.unreleasedNativeState,
268
259
  let pairedObject = nativeState.javaScriptObject(in: runtime),
269
260
  pairedObject.getNativeState(as: SharedObjectNativeState.self) === nativeState
270
261
  else {
@@ -163,6 +163,22 @@ struct CdpNetwork {
163
163
  }
164
164
  }
165
165
 
166
+ struct LoadingFailedParams: EventParams {
167
+ let requestId: RequestId
168
+ let timestamp: MonotonicTime
169
+ let type: ResourceType
170
+ let errorText: String
171
+ let canceled: Bool
172
+
173
+ init(now: TimeInterval, requestId: RequestId, error: Error) {
174
+ self.requestId = requestId
175
+ self.timestamp = now
176
+ self.type = ResourceType.other
177
+ self.errorText = error.localizedDescription
178
+ self.canceled = (error as? URLError)?.code == .cancelled
179
+ }
180
+ }
181
+
166
182
  struct ExpoReceivedResponseBodyParams: EventParams {
167
183
  let requestId: RequestId
168
184
  let body: String
@@ -71,6 +71,11 @@ public final class ExpoRequestCdpInterceptor: NSObject, ExpoRequestInterceptorPr
71
71
  let params3 = CdpNetwork.LoadingFinishedParams(now: now, requestId: requestId, encodedDataLength: task.countOfBytesReceived)
72
72
  dispatchEvent(CdpNetwork.Event(method: "Network.loadingFinished", params: params3))
73
73
  }
74
+
75
+ func didFailLoading(requestId: String, task: URLSessionTask, error: Error) {
76
+ let params = CdpNetwork.LoadingFailedParams(now: Date().timeIntervalSince1970, requestId: requestId, error: error)
77
+ dispatchEvent(CdpNetwork.Event(method: "Network.loadingFailed", params: params))
78
+ }
74
79
  }
75
80
 
76
81
  /**
@@ -17,6 +17,7 @@ public final class ExpoRequestInterceptorProtocol: URLProtocol, URLSessionDataDe
17
17
  )
18
18
  private var requestId: String?
19
19
  private var dataTask_: URLSessionDataTask?
20
+ private weak var originalTask: URLSessionTask?
20
21
  private let responseBody = NSMutableData()
21
22
  private var responseBodyExceedsLimit = false
22
23
 
@@ -69,6 +70,17 @@ public final class ExpoRequestInterceptorProtocol: URLProtocol, URLSessionDataDe
69
70
  dataTask_ = dataTask
70
71
  }
71
72
 
73
+ @objc
74
+ public convenience init(
75
+ task: URLSessionTask,
76
+ cachedResponse: CachedURLResponse?,
77
+ client: URLProtocolClient?
78
+ ) {
79
+ // swiftlint:disable:next force_unwrapping
80
+ self.init(request: task.currentRequest!, cachedResponse: cachedResponse, client: client)
81
+ originalTask = task
82
+ }
83
+
72
84
  public override class func canonicalRequest(for request: URLRequest) -> URLRequest {
73
85
  request
74
86
  }
@@ -97,6 +109,9 @@ public final class ExpoRequestInterceptorProtocol: URLProtocol, URLSessionDataDe
97
109
 
98
110
  public func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
99
111
  if let error = error {
112
+ if let requestId {
113
+ Self.delegate.didFailLoading(requestId: requestId, task: task, error: error)
114
+ }
100
115
  client?.urlProtocol(self, didFailWithError: error)
101
116
  } else {
102
117
  if let response = task.response as? HTTPURLResponse,
@@ -179,28 +194,13 @@ public final class ExpoRequestInterceptorProtocol: URLProtocol, URLSessionDataDe
179
194
  // Workaround to get the original task's URLSessionDelegate through the internal property and send upload process
180
195
  // Fixes https://github.com/expo/expo/issues/28269
181
196
  // swiftlint:enable line_length
182
- guard let dataTask = dataTask_ else {
183
- return
184
- }
185
-
186
- // Prevent recursive delegate calls
187
- if task === dataTask {
188
- return
189
- }
190
-
191
- if #available(iOS 15.0, tvOS 15.0, macOS 12.0, *), let delegate = dataTask.delegate {
192
- // For the case if the task has a dedicated delegate than the default delegate from its URLSession
193
- delegate.urlSession?(
194
- session, task: dataTask, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend
195
- )
196
- return
197
- }
198
- guard let session = task.value(forKey: "session") as? URLSession,
199
- let delegate = session.delegate as? URLSessionTaskDelegate else {
197
+ guard let originalTask,
198
+ let originalSession = originalTask.value(forKey: "session") as? URLSession,
199
+ let delegate = originalTask.delegate ?? originalSession.delegate as? URLSessionTaskDelegate else {
200
200
  return
201
201
  }
202
202
  delegate.urlSession?(
203
- session, task: dataTask, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend
203
+ originalSession, task: originalTask, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend
204
204
  )
205
205
  }
206
206
 
@@ -223,6 +223,9 @@ protocol ExpoRequestInterceptorProtocolDelegate: Sendable {
223
223
 
224
224
  @objc
225
225
  func didReceiveResponse(requestId: String, task: URLSessionTask, responseBody: Data, isText: Bool, responseBodyExceedsLimit: Bool)
226
+
227
+ @objc
228
+ func didFailLoading(requestId: String, task: URLSessionTask, error: Error)
226
229
  }
227
230
 
228
231
  /**
@@ -0,0 +1,53 @@
1
+ // Copyright 2026-present 650 Industries. All rights reserved.
2
+
3
+ import ExpoModulesJSI
4
+
5
+ /// Binds native types into the JavaScript runtime: creates their JavaScript classes and objects,
6
+ /// installs them and registers them in the app context.
7
+ internal enum JavaScriptBindings {
8
+ // MARK: - Shared objects
9
+
10
+ /// Builds the JavaScript class of a `@SharedObject` class that a module registers in `_classTypes`,
11
+ /// and registers its prototype for the class in `ClassRegistry`. All members come from the macro
12
+ /// hooks, so no `ClassDefinition` is needed.
13
+ @JavaScriptActor
14
+ static func buildSharedObjectClass(_ type: SharedObject.Type, appContext: AppContext) throws -> JavaScriptObject {
15
+ let name = type._jsName
16
+ let constructor: JavaScriptRuntime.SyncFunctionClosure = { [weak appContext] this, arguments in
17
+ guard let appContext else {
18
+ throw Exceptions.AppContextLost()
19
+ }
20
+ // Pair the native instance with `this` (returning a different object would drop the prototype
21
+ // chain `new` set up). Without a `@JS init`, only the native side can create an instance.
22
+ guard let sharedObject = try type._constructSharedObject(this: this, arguments: arguments, in: appContext.runtime) else {
23
+ throw Exceptions.ConstructorUnavailable(name)
24
+ }
25
+ appContext.sharedObjectRegistry.add(native: sharedObject, javaScript: this.getObject(), inheritsBaseClass: true)
26
+ return this
27
+ }
28
+ let runtime = try appContext.runtime
29
+ let createClass = type is AnySharedRef.Type ? runtime.createSharedRefClass : runtime.createSharedObjectClass
30
+ let klass = try createClass(name, constructor).asObject()
31
+ let prototype = klass.getProperty("prototype").getObject()
32
+
33
+ try type._decorateSharedObject(prototype: prototype, in: runtime)
34
+ try type._decorateSharedObject(constructor: klass, in: runtime)
35
+
36
+ appContext.classRegistry.register(nativeClassId: ObjectIdentifier(type), prototype: prototype)
37
+ return klass
38
+ }
39
+
40
+ /// Builds a prototype for a `@SharedObject` class in an alternate runtime (e.g. the worklet runtime),
41
+ /// inheriting from the given base prototype. The counterpart of `ClassDefinition.buildPrototype` for
42
+ /// the classes that a module registers in `_classTypes`.
43
+ @JavaScriptActor
44
+ static func buildSharedObjectPrototype(
45
+ _ type: SharedObject.Type,
46
+ in runtime: JavaScriptRuntime,
47
+ basePrototype: consuming JavaScriptObject
48
+ ) throws -> JavaScriptObject {
49
+ let prototype = runtime.createObject(prototype: basePrototype)
50
+ try type._decorateSharedObject(prototype: prototype, in: runtime)
51
+ return prototype
52
+ }
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-modules-core",
3
- "version": "58.0.26",
3
+ "version": "58.0.28",
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.19",
70
- "expo-modules-macros": "0.22.0",
69
+ "expo-modules-jsi": "~58.0.21",
70
+ "expo-modules-macros": "0.27.1",
71
71
  "invariant": "^2.2.4"
72
72
  },
73
73
  "devDependencies": {
74
- "@expo/internal-scripts": "58.0.4",
74
+ "@expo/internal-scripts": "58.0.5",
75
75
  "@testing-library/react-native": "^14.0.1",
76
76
  "@types/invariant": "^2.2.33",
77
77
  "@types/react": "~19.3.0",