expo-modules-jsi 58.0.7 → 58.0.8
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.
- package/CHANGELOG.md +12 -0
- package/apple/Benchmarks/RuntimeCacheBenchmarks.swift +71 -0
- package/apple/Benchmarks/UnownedDecodeBenchmarks.swift +121 -0
- package/apple/Sources/ExpoModulesJSI/Coding/JavaScriptCodable+Containers.swift +52 -10
- package/apple/Sources/ExpoModulesJSI/Coding/JavaScriptCodable+Data.swift +5 -0
- package/apple/Sources/ExpoModulesJSI/Coding/JavaScriptCodable+Date.swift +27 -5
- package/apple/Sources/ExpoModulesJSI/Coding/JavaScriptCodable+Primitives.swift +75 -0
- package/apple/Sources/ExpoModulesJSI/Coding/JavaScriptDecodable.swift +34 -5
- package/apple/Sources/ExpoModulesJSI/Coding/JavaScriptValueKinds.swift +73 -0
- package/apple/Sources/ExpoModulesJSI/Protocols/JSIRepresentable.swift +4 -2
- package/apple/Sources/ExpoModulesJSI/Runtime/JavaScriptRuntime.swift +18 -13
- package/apple/Sources/ExpoModulesJSI/Runtime/JavaScriptRuntimeCache.swift +74 -0
- package/apple/Sources/ExpoModulesJSI/Runtime/Values/JavaScriptArray.swift +26 -0
- package/apple/Sources/ExpoModulesJSI/Runtime/Values/JavaScriptObject.swift +22 -0
- package/apple/Sources/ExpoModulesJSI/Runtime/Values/JavaScriptPromise.swift +14 -14
- package/apple/Sources/ExpoModulesJSI/Runtime/Values/JavaScriptUnownedValue.swift +17 -0
- package/apple/Sources/ExpoModulesJSI/Runtime/Values/JavaScriptValue.swift +54 -1
- package/apple/Sources/ExpoModulesJSI/Utilities/String+JSI.swift +4 -3
- package/apple/Sources/ExpoModulesJSI-Cxx/include/JSIUtils.h +27 -0
- package/apple/Tests/JavaScriptDecodableKindsTests.swift +132 -0
- package/apple/Tests/JavaScriptRuntimeCacheTests.swift +117 -0
- package/apple/Tests/JavaScriptRuntimeTests.swift +59 -0
- package/apple/Tests/JavaScriptUnownedDecodeTests.swift +99 -0
- package/apple/Tests/JavaScriptUnownedElementsTests.swift +76 -0
- package/apple/scripts/build-xcframework.sh +15 -0
- package/package.json +1 -1
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Copyright 2026-present 650 Industries. All rights reserved.
|
|
2
|
+
|
|
3
|
+
internal import jsi
|
|
4
|
+
|
|
5
|
+
/// A set of JavaScript value kinds, as told apart by the value's type tag alone.
|
|
6
|
+
///
|
|
7
|
+
/// Unlike `JavaScriptValue.Kind`, a function is an `object` here: telling it apart needs a call into
|
|
8
|
+
/// the runtime, while every kind in this set is read from the tag without one. Used by
|
|
9
|
+
/// `JavaScriptDecodable.decodableKinds` to describe the kinds a type can decode from. Frozen, so a check
|
|
10
|
+
/// against it compiles to a mask test in the client.
|
|
11
|
+
@frozen
|
|
12
|
+
public struct JavaScriptValueKinds: OptionSet, Sendable {
|
|
13
|
+
public let rawValue: UInt16
|
|
14
|
+
|
|
15
|
+
// `UInt16` leaves room for more kinds without changing the frozen layout.
|
|
16
|
+
//
|
|
17
|
+
// The kinds are computed and inlinable rather than stored `static let`s, which a client would reach
|
|
18
|
+
// through a lazily initialized global, so a mask built from them folds to a constant.
|
|
19
|
+
|
|
20
|
+
@inlinable
|
|
21
|
+
public init(rawValue: UInt16) {
|
|
22
|
+
self.rawValue = rawValue
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@inlinable public static var undefined: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 0) }
|
|
26
|
+
@inlinable public static var null: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 1) }
|
|
27
|
+
@inlinable public static var bool: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 2) }
|
|
28
|
+
@inlinable public static var number: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 3) }
|
|
29
|
+
@inlinable public static var bigint: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 4) }
|
|
30
|
+
@inlinable public static var string: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 5) }
|
|
31
|
+
@inlinable public static var symbol: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 6) }
|
|
32
|
+
/// Any object, including arrays, typed arrays and functions.
|
|
33
|
+
@inlinable public static var object: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: 1 << 7) }
|
|
34
|
+
|
|
35
|
+
/// Every kind, including any added later: the bits above the current kinds are set too, so a type that
|
|
36
|
+
/// accepts every kind keeps doing so.
|
|
37
|
+
@inlinable public static var all: JavaScriptValueKinds { JavaScriptValueKinds(rawValue: .max) }
|
|
38
|
+
|
|
39
|
+
/// The kind of `value`.
|
|
40
|
+
///
|
|
41
|
+
/// Not inlinable on purpose: the type checks read the `jsi::Value`, which clients can't see, so an
|
|
42
|
+
/// inlined initializer would make one call into this module per check. Here it is a single call.
|
|
43
|
+
public init(of value: borrowing JavaScriptValue) {
|
|
44
|
+
self.init(of: value.pointee)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// The kind of the borrowed `value`, read the same way as from an owning value.
|
|
48
|
+
public init(of value: borrowing JavaScriptUnownedValue) {
|
|
49
|
+
self.init(of: value.pointer.pointee)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/// Reads the kind from the `jsi::Value` both public initializers wrap. The checks go from the most to
|
|
53
|
+
/// the least common kind of an argument.
|
|
54
|
+
private init(of value: borrowing facebook.jsi.Value) {
|
|
55
|
+
if value.isNumber() {
|
|
56
|
+
self = .number
|
|
57
|
+
} else if value.isString() {
|
|
58
|
+
self = .string
|
|
59
|
+
} else if value.isObject() {
|
|
60
|
+
self = .object
|
|
61
|
+
} else if value.isBool() {
|
|
62
|
+
self = .bool
|
|
63
|
+
} else if value.isNull() {
|
|
64
|
+
self = .null
|
|
65
|
+
} else if value.isUndefined() {
|
|
66
|
+
self = .undefined
|
|
67
|
+
} else if value.isBigInt() {
|
|
68
|
+
self = .bigint
|
|
69
|
+
} else {
|
|
70
|
+
self = .symbol
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -93,14 +93,16 @@ extension String: JSIRepresentable {
|
|
|
93
93
|
// allocation, copy and free per string. `withUTF8` is mutating (it makes a bridged string
|
|
94
94
|
// contiguous first), hence the local copy; native strings are already contiguous and pay nothing.
|
|
95
95
|
// The value is moved out through a local because `withUTF8` needs a `Copyable` closure result.
|
|
96
|
+
// The C++ helper moves the engine's `jsi::String` into the value, so this costs one engine handle;
|
|
97
|
+
// `jsi::Value(runtime, string)` would clone it and then release the original.
|
|
96
98
|
var string = self
|
|
97
99
|
var value = facebook.jsi.Value.undefined()
|
|
98
100
|
string.withUTF8 { utf8 in
|
|
99
101
|
guard let base = utf8.baseAddress else {
|
|
100
|
-
value =
|
|
102
|
+
value = expo.createStringValueFromAscii(runtime, "", 0)
|
|
101
103
|
return
|
|
102
104
|
}
|
|
103
|
-
value =
|
|
105
|
+
value = expo.createStringValueFromUtf8(runtime, base, utf8.count)
|
|
104
106
|
}
|
|
105
107
|
return value
|
|
106
108
|
}
|
|
@@ -146,7 +146,7 @@ open class JavaScriptRuntime: Equatable, Identifiable, @unchecked Sendable {
|
|
|
146
146
|
// when the last reference is gone. `deinit` is `nonisolated`, so it can touch the actor-isolated
|
|
147
147
|
// registry directly given that exclusive access.
|
|
148
148
|
propNameIdsRegistry.removeAll()
|
|
149
|
-
|
|
149
|
+
cache.clear()
|
|
150
150
|
expo.destroyRuntime(runtimePointee)
|
|
151
151
|
}
|
|
152
152
|
|
|
@@ -203,7 +203,8 @@ open class JavaScriptRuntime: Equatable, Identifiable, @unchecked Sendable {
|
|
|
203
203
|
let propertyName = String(jsiPropNameID: propertyName.pointee, in: runtime.pointee)
|
|
204
204
|
return JavaScriptActor.assumeIsolated {
|
|
205
205
|
return forwardingSwiftErrorsToJS(runtime: runtime) {
|
|
206
|
-
try context.get(propertyName)
|
|
206
|
+
var result = try context.get(propertyName)
|
|
207
|
+
JavaScriptValue.write(&result, to: resultPtr)
|
|
207
208
|
}
|
|
208
209
|
}
|
|
209
210
|
}
|
|
@@ -789,12 +790,14 @@ open class JavaScriptRuntime: Equatable, Identifiable, @unchecked Sendable {
|
|
|
789
790
|
@JavaScriptActor
|
|
790
791
|
internal var propNameIdsRegistry: [String: JavaScriptPropNameID] = [:]
|
|
791
792
|
|
|
792
|
-
// MARK: -
|
|
793
|
+
// MARK: - Cache
|
|
793
794
|
|
|
794
|
-
///
|
|
795
|
-
///
|
|
795
|
+
/// Values cached with ``cached(_:_:)``. Unchecked exclusivity skips the dynamic access checks on
|
|
796
|
+
/// every lookup: the cache is only used on the JavaScript thread, and `cached(_:_:)` never keeps an
|
|
797
|
+
/// access open while it calls out, so accesses can't overlap.
|
|
796
798
|
@JavaScriptActor
|
|
797
|
-
|
|
799
|
+
@exclusivity(unchecked)
|
|
800
|
+
internal var cache = Cache()
|
|
798
801
|
|
|
799
802
|
// MARK: - Long-lived objects
|
|
800
803
|
|
|
@@ -826,12 +829,12 @@ open class JavaScriptRuntime: Equatable, Identifiable, @unchecked Sendable {
|
|
|
826
829
|
// hop back to the JavaScript thread first.
|
|
827
830
|
JavaScriptActor.assumeIsolated {
|
|
828
831
|
longLivedObjects.clear()
|
|
829
|
-
// Also flush the cached `jsi::PropNameID`s and the
|
|
830
|
-
//
|
|
831
|
-
//
|
|
832
|
-
//
|
|
832
|
+
// Also flush the cached `jsi::PropNameID`s and the cache: a non-owning wrapper can outlive its
|
|
833
|
+
// runtime (e.g. captured by a task abandoned on reload) and would otherwise destroy them against
|
|
834
|
+
// the freed runtime when it deallocates. `self` is weak so the teardown object doesn't retain the
|
|
835
|
+
// wrapper; the owning wrapper clears both in `deinit`.
|
|
833
836
|
self?.propNameIdsRegistry.removeAll()
|
|
834
|
-
self?.
|
|
837
|
+
self?.cache.clear()
|
|
835
838
|
}
|
|
836
839
|
}
|
|
837
840
|
let object = createObject()
|
|
@@ -883,7 +886,8 @@ private func createFunctionClosure(
|
|
|
883
886
|
let this = UnsafeMutablePointer(mutating: thisPtr).move()
|
|
884
887
|
let arguments = JavaScriptValuesBuffer(runtime, start: argumentsPtr, count: argumentsCount)
|
|
885
888
|
let thisValue = JavaScriptValue(runtime, this)
|
|
886
|
-
try context.call(thisValue, consume arguments)
|
|
889
|
+
var result = try context.call(thisValue, consume arguments)
|
|
890
|
+
JavaScriptValue.write(&result, to: resultPtr)
|
|
887
891
|
}
|
|
888
892
|
}
|
|
889
893
|
}
|
|
@@ -926,7 +930,8 @@ private func createFunctionClosure(
|
|
|
926
930
|
return forwardingSwiftErrorsToJS(runtime: runtime) {
|
|
927
931
|
let arguments = JavaScriptValuesBuffer(runtime, start: argumentsPtr, count: argumentsCount)
|
|
928
932
|
let thisValue = JavaScriptUnownedValue(runtime.pointee, thisPtr)
|
|
929
|
-
try context.call(thisValue, consume arguments)
|
|
933
|
+
var result = try context.call(thisValue, consume arguments)
|
|
934
|
+
JavaScriptValue.write(&result, to: resultPtr)
|
|
930
935
|
}
|
|
931
936
|
}
|
|
932
937
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Copyright 2026-present 650 Industries. All rights reserved.
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
extension JavaScriptRuntime {
|
|
6
|
+
/// Values cached by a runtime, stored by their keys' indices. Isolated to the JavaScript thread
|
|
7
|
+
/// together with the runtime that owns it. Values are read and created through
|
|
8
|
+
/// ``JavaScriptRuntime/cached(_:_:)``.
|
|
9
|
+
public struct Cache: ~Copyable {
|
|
10
|
+
/// A key for a value that a runtime creates once and then reuses, such as a JavaScript constructor
|
|
11
|
+
/// or a property name. Declare keys as `static let`s and pass them to ``JavaScriptRuntime/cached(_:_:)``.
|
|
12
|
+
///
|
|
13
|
+
/// Each key gets a fixed index from a process-wide counter when it is created, so a lookup reads one
|
|
14
|
+
/// array slot instead of hashing a string. Every runtime keeps its own values for the same keys.
|
|
15
|
+
public struct Key<Value: AnyObject>: Sendable {
|
|
16
|
+
internal let index: Int
|
|
17
|
+
|
|
18
|
+
public init() {
|
|
19
|
+
self.index = nextCacheKeyIndex.withLock { index in
|
|
20
|
+
defer { index += 1 }
|
|
21
|
+
return index
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// A slot per key index, up to the highest index used so far in this runtime. Slots of keys that
|
|
27
|
+
// haven't been used here yet are `nil`. `ContiguousArray` stores the references directly, without
|
|
28
|
+
// the bridging checks that `Array` can do for class elements on Apple platforms.
|
|
29
|
+
private var storage = ContiguousArray<AnyObject?>()
|
|
30
|
+
|
|
31
|
+
internal func value<Value>(for key: Key<Value>) -> Value? {
|
|
32
|
+
guard key.index < storage.count, let value = storage[key.index] else {
|
|
33
|
+
return nil
|
|
34
|
+
}
|
|
35
|
+
// The key's type guarantees the type of the value stored under it.
|
|
36
|
+
return unsafeDowncast(value, to: Value.self)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
internal mutating func store<Value>(_ value: Value, for key: Key<Value>) {
|
|
40
|
+
if key.index >= storage.count {
|
|
41
|
+
storage.append(contentsOf: repeatElement(nil, count: key.index - storage.count + 1))
|
|
42
|
+
}
|
|
43
|
+
storage[key.index] = value
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/// Releases all cached values. They often hold JSI objects, which must be destroyed before the
|
|
47
|
+
/// runtime they belong to.
|
|
48
|
+
internal mutating func clear() {
|
|
49
|
+
storage.removeAll()
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Returns the value cached under `key`, creating it with `make` the first time the key is used in
|
|
54
|
+
/// this runtime. If `make` throws, nothing is cached and the next call tries again.
|
|
55
|
+
///
|
|
56
|
+
/// `make` may look up other cached values, for example to build a prototype from a cached
|
|
57
|
+
/// constructor.
|
|
58
|
+
@JavaScriptActor
|
|
59
|
+
public func cached<Value>(_ key: Cache.Key<Value>, _ make: () throws -> Value) rethrows -> Value {
|
|
60
|
+
if let value = cache.value(for: key) {
|
|
61
|
+
return value
|
|
62
|
+
}
|
|
63
|
+
// Call `make` without accessing the cache, so that the lookups it does itself don't overlap with
|
|
64
|
+
// an access in progress here.
|
|
65
|
+
let value = try make()
|
|
66
|
+
cache.store(value, for: key)
|
|
67
|
+
return value
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// The index for the next created ``JavaScriptRuntime/Cache/Key``. Keys can be created on any thread,
|
|
72
|
+
/// for example by initializing a `static let`, so the counter is behind a lock. That costs nothing on
|
|
73
|
+
/// the lookup path, since each key takes an index only once.
|
|
74
|
+
private let nextCacheKeyIndex = OSAllocatedUnfairLock(initialState: 0)
|
|
@@ -460,6 +460,32 @@ public struct JavaScriptArray: JavaScriptType, ~Copyable {
|
|
|
460
460
|
return result
|
|
461
461
|
}
|
|
462
462
|
|
|
463
|
+
/// Transforms each element like `map(_:)`, but lends each element to `transform` as a
|
|
464
|
+
/// `JavaScriptUnownedValue` instead of wrapping it in a new `JavaScriptValue`. An element is valid only
|
|
465
|
+
/// for the duration of its `transform` call and must not be stored or escaped.
|
|
466
|
+
public func mapUnowned<T>(_ transform: (borrowing JavaScriptUnownedValue) throws -> T) rethrows -> [T] {
|
|
467
|
+
guard let jsiRuntime else {
|
|
468
|
+
FatalError.runtimeLost()
|
|
469
|
+
}
|
|
470
|
+
let count = self.length
|
|
471
|
+
var result: [T] = []
|
|
472
|
+
result.reserveCapacity(count)
|
|
473
|
+
for index in 0..<count {
|
|
474
|
+
let element = pointee.getValueAtIndex(jsiRuntime, index)
|
|
475
|
+
// `withUnsafeBytes(of:)` rather than `withUnsafePointer(to:)`; see `JavaScriptValue.withUnsafePointee(_:)`.
|
|
476
|
+
try withUnsafeBytes(of: element) { bytes in
|
|
477
|
+
guard let baseAddress = bytes.baseAddress else {
|
|
478
|
+
preconditionFailure(
|
|
479
|
+
"withUnsafeBytes(of:) gave an empty buffer for a jsi::Value, which can't happen for a non-zero-sized type"
|
|
480
|
+
)
|
|
481
|
+
}
|
|
482
|
+
let pointer = baseAddress.assumingMemoryBound(to: facebook.jsi.Value.self)
|
|
483
|
+
result.append(try transform(JavaScriptUnownedValue(jsiRuntime, pointer)))
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return result
|
|
487
|
+
}
|
|
488
|
+
|
|
463
489
|
/// Converts the JavaScript array to a `JavaScriptValue`.
|
|
464
490
|
///
|
|
465
491
|
/// - Returns: A `JavaScriptValue` representing this array
|
|
@@ -146,6 +146,28 @@ public struct JavaScriptObject: JavaScriptType, Sendable, ~Copyable {
|
|
|
146
146
|
return JavaScriptValue(runtimeHandle, pointee.getProperty(jsiRuntime, name.toJSIPropNameID(in: jsiRuntime)))
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
+
/// Calls `body` with the property of the object with the given name, or `undefined` if there is no
|
|
150
|
+
/// such property, lent as a `JavaScriptUnownedValue` instead of wrapped in a new `JavaScriptValue`.
|
|
151
|
+
/// The value is valid only for the duration of the closure and must not be stored or escaped.
|
|
152
|
+
public func withUnownedProperty<R>(_ name: String, _ body: (borrowing JavaScriptUnownedValue) throws -> R) rethrows
|
|
153
|
+
-> R
|
|
154
|
+
{
|
|
155
|
+
guard let jsiRuntime else {
|
|
156
|
+
FatalError.runtimeLost()
|
|
157
|
+
}
|
|
158
|
+
let property = pointee.getProperty(jsiRuntime, name.toJSIPropNameID(in: jsiRuntime))
|
|
159
|
+
// `withUnsafeBytes(of:)` rather than `withUnsafePointer(to:)`; see `JavaScriptValue.withUnsafePointee(_:)`.
|
|
160
|
+
return try withUnsafeBytes(of: property) { bytes in
|
|
161
|
+
guard let baseAddress = bytes.baseAddress else {
|
|
162
|
+
preconditionFailure(
|
|
163
|
+
"withUnsafeBytes(of:) gave an empty buffer for a jsi::Value, which can't happen for a non-zero-sized type"
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
let pointer = baseAddress.assumingMemoryBound(to: facebook.jsi.Value.self)
|
|
167
|
+
return try body(JavaScriptUnownedValue(jsiRuntime, pointer))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
149
171
|
/// Returns the property of the object with the given prop name id,
|
|
150
172
|
/// or `undefined` value if the name is not a property of the object.
|
|
151
173
|
public func getProperty(_ propName: JavaScriptPropNameID) -> JavaScriptValue {
|
|
@@ -284,20 +284,20 @@ extension JavaScriptRuntime {
|
|
|
284
284
|
/// optimize like any other closure.
|
|
285
285
|
@JavaScriptActor
|
|
286
286
|
fileprivate func deferredPromiseFactory() throws -> JavaScriptValue {
|
|
287
|
-
|
|
288
|
-
return
|
|
287
|
+
return try cached(deferredPromiseFactoryKey) {
|
|
288
|
+
return try eval(
|
|
289
|
+
label: "expo-modules-jsi/deferred-promise.js",
|
|
290
|
+
"""
|
|
291
|
+
(function () {
|
|
292
|
+
let resolve, reject;
|
|
293
|
+
const promise = new Promise(function (a, b) { resolve = a; reject = b; });
|
|
294
|
+
return [promise, resolve, reject];
|
|
295
|
+
})
|
|
296
|
+
"""
|
|
297
|
+
)
|
|
289
298
|
}
|
|
290
|
-
let factory = try eval(
|
|
291
|
-
label: "expo-modules-jsi/deferred-promise.js",
|
|
292
|
-
"""
|
|
293
|
-
(function () {
|
|
294
|
-
let resolve, reject;
|
|
295
|
-
const promise = new Promise(function (a, b) { resolve = a; reject = b; });
|
|
296
|
-
return [promise, resolve, reject];
|
|
297
|
-
})
|
|
298
|
-
"""
|
|
299
|
-
)
|
|
300
|
-
cachedDeferredPromiseFactory = factory
|
|
301
|
-
return factory
|
|
302
299
|
}
|
|
303
300
|
}
|
|
301
|
+
|
|
302
|
+
/// Key of the deferred promise factory in each runtime's cache.
|
|
303
|
+
private let deferredPromiseFactoryKey = JavaScriptRuntime.Cache.Key<JavaScriptValue>()
|
|
@@ -130,6 +130,23 @@ public struct JavaScriptUnownedValue: ~Copyable {
|
|
|
130
130
|
return JavaScriptObject(runtime, pointer.pointee.getObject(self.runtime))
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
+
/// Whether the value is an array. The zero-copy counterpart of ``JavaScriptValue/isArray()``.
|
|
134
|
+
public func isArray() -> Bool {
|
|
135
|
+
return pointer.pointee.isObject() && pointer.pointee.getObject(runtime).isArray(runtime)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// Returns the value as a ``JavaScriptArray``, or asserts if it is not an array. The zero-copy
|
|
139
|
+
/// counterpart of ``JavaScriptValue/getArray()``, with the same runtime contract as
|
|
140
|
+
/// ``getObject(in:)``.
|
|
141
|
+
public func getArray(in runtime: JavaScriptRuntime) -> JavaScriptArray {
|
|
142
|
+
assert(isArray(), "Value is not an array")
|
|
143
|
+
assert(
|
|
144
|
+
Unmanaged.passUnretained(runtime.pointee).toOpaque() == Unmanaged.passUnretained(self.runtime).toOpaque(),
|
|
145
|
+
"`getArray(in:)` must be passed the runtime that owns the borrowed value"
|
|
146
|
+
)
|
|
147
|
+
return JavaScriptArray(runtime, pointer.pointee.getObject(self.runtime).getArray(self.runtime))
|
|
148
|
+
}
|
|
149
|
+
|
|
133
150
|
// MARK: - Throwing conversions ("as functions")
|
|
134
151
|
|
|
135
152
|
/// Returns the value as a boolean, or throws `TypeError` if it is not a boolean.
|
|
@@ -10,7 +10,10 @@ public final class JavaScriptValue: JavaScriptType, Equatable, Escapable {
|
|
|
10
10
|
/// Handle to the runtime the value belongs to. `nil` only for runtime-free values (undefined, null,
|
|
11
11
|
/// booleans and numbers).
|
|
12
12
|
internal let runtimeHandle: JavaScriptRuntimeHandle?
|
|
13
|
-
|
|
13
|
+
/// Mutable only so that ``write(_:to:)`` can move the engine value out of a uniquely referenced
|
|
14
|
+
/// instance on the JS thread, right before it is deallocated. Unchecked exclusivity keeps reads of
|
|
15
|
+
/// a mutable class property free of the dynamic exclusivity check.
|
|
16
|
+
@exclusivity(unchecked) nonisolated(unsafe) internal var pointee: facebook.jsi.Value
|
|
14
17
|
|
|
15
18
|
/// The runtime the value belongs to, or `nil` if it has been deallocated or the value is runtime-free.
|
|
16
19
|
/// Prefer ``jsiRuntime`` on hot paths: it costs no reference counting.
|
|
@@ -119,6 +122,45 @@ public final class JavaScriptValue: JavaScriptType, Equatable, Escapable {
|
|
|
119
122
|
}
|
|
120
123
|
}
|
|
121
124
|
|
|
125
|
+
/// Calls `body` with a `JavaScriptUnownedValue` that borrows this value's `jsi::Value`, without
|
|
126
|
+
/// copying it. The unowned value is valid only for the duration of the closure and must not be
|
|
127
|
+
/// stored or escaped.
|
|
128
|
+
///
|
|
129
|
+
/// `runtime` must be the runtime the value belongs to. It is passed in because a runtime-free value
|
|
130
|
+
/// (undefined, null, a boolean or a number) doesn't hold one.
|
|
131
|
+
///
|
|
132
|
+
/// Inlinable, so the closure and `R` specialize in the caller; only `borrowUnownedValue(in:)` is a
|
|
133
|
+
/// call into this module.
|
|
134
|
+
@inlinable
|
|
135
|
+
public func withUnownedValue<R>(
|
|
136
|
+
in runtime: borrowing JavaScriptRuntime,
|
|
137
|
+
_ body: (borrowing JavaScriptUnownedValue) throws -> R
|
|
138
|
+
) rethrows -> R {
|
|
139
|
+
let unownedValue = borrowUnownedValue(in: runtime)
|
|
140
|
+
// The unowned value points into `self`, so `self` must outlive `body`.
|
|
141
|
+
defer { withExtendedLifetime(self) {} }
|
|
142
|
+
return try body(unownedValue)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// A `JavaScriptUnownedValue` pointing at the stored `jsi::Value`. It stays valid while `self` is
|
|
146
|
+
/// alive: the value is a stored property of this instance, so its address doesn't change, and
|
|
147
|
+
/// `withUnsafeBytes(of:)` yields that address because a `jsi::Value` can't be copied. Not inlinable,
|
|
148
|
+
/// since it touches the JSI types; `withUnownedValue(in:_:)` is the only caller.
|
|
149
|
+
@usableFromInline
|
|
150
|
+
internal func borrowUnownedValue(in runtime: borrowing JavaScriptRuntime) -> JavaScriptUnownedValue {
|
|
151
|
+
let pointer = withUnsafeBytes(of: pointee) { bytes in
|
|
152
|
+
// `withUnsafeBytes(of:)` rather than `withUnsafePointer(to:)`, for the same SIL optimizer crash
|
|
153
|
+
// `withUnsafePointee(_:)` avoids.
|
|
154
|
+
guard let baseAddress = bytes.baseAddress else {
|
|
155
|
+
preconditionFailure(
|
|
156
|
+
"withUnsafeBytes(of:) gave an empty buffer for a jsi::Value, which can't happen for a non-zero-sized type"
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
return baseAddress.assumingMemoryBound(to: facebook.jsi.Value.self)
|
|
160
|
+
}
|
|
161
|
+
return JavaScriptUnownedValue(runtime.pointee, pointer)
|
|
162
|
+
}
|
|
163
|
+
|
|
122
164
|
// MARK: - Type checks
|
|
123
165
|
|
|
124
166
|
public func isUndefined() -> Bool {
|
|
@@ -534,6 +576,17 @@ public final class JavaScriptValue: JavaScriptType, Equatable, Escapable {
|
|
|
534
576
|
return copy()
|
|
535
577
|
}
|
|
536
578
|
|
|
579
|
+
/// Writes `value` into a host callback's result slot. A uniquely referenced instance, the normal
|
|
580
|
+
/// case for a value the callback just created, has its engine value moved out instead of cloned,
|
|
581
|
+
/// since the instance is deallocated right after. Shared instances go through ``writeJSIValue(to:)``.
|
|
582
|
+
internal static func write(_ value: inout JavaScriptValue, to slot: UnsafeMutablePointer<facebook.jsi.Value>) {
|
|
583
|
+
if value.runtimeHandle != nil, isKnownUniquelyReferenced(&value) {
|
|
584
|
+
expo.emplaceMovedValue(slot, &value.pointee)
|
|
585
|
+
} else {
|
|
586
|
+
value.writeJSIValue(to: slot)
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
537
590
|
/// Writes this value into a host callback's result slot. Undefined, null, booleans and numbers are
|
|
538
591
|
/// emplaced with the engine's inline constructors, so the common results skip the out-of-line
|
|
539
592
|
/// `jsi::Value` move and destroy that assigning to the slot would cost; everything else is copied
|
|
@@ -69,9 +69,10 @@ private func appendEngineStringChunk(ctx: UnsafeMutableRawPointer?, ascii: Bool,
|
|
|
69
69
|
let chunk: String
|
|
70
70
|
if ascii {
|
|
71
71
|
let bytes = UnsafeBufferPointer(start: data.assumingMemoryBound(to: UInt8.self), count: count)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
// `String(decoding:as:)` re-validates bytes the engine already guarantees to be ASCII, but it
|
|
73
|
+
// builds short strings inline. `String(unsafeUninitializedCapacity:)` always allocates heap
|
|
74
|
+
// storage first, which measured 5 to 10 ns slower for 6 and 22 byte strings.
|
|
75
|
+
chunk = String(decoding: bytes, as: UTF8.self)
|
|
75
76
|
} else {
|
|
76
77
|
let units = UnsafeBufferPointer(start: data.assumingMemoryBound(to: UInt16.self), count: count)
|
|
77
78
|
if count < 512 {
|
|
@@ -165,6 +165,8 @@ inline void collectGarbage(jsi::IRuntime &runtime, const std::string &cause) {
|
|
|
165
165
|
// owns nothing; an object or string there would leak its engine handle. Both callers,
|
|
166
166
|
// `createHostFunction` and `HostObject::get`, pass a default-constructed slot. The Swift side picks
|
|
167
167
|
// the helper by kind in `JavaScriptValue.writeJSIValue(to:)` and moves everything else.
|
|
168
|
+
// `JavaScriptValue.write(_:to:)` moves a uniquely referenced value's handle into the slot the same
|
|
169
|
+
// way, through `emplaceMovedValue`.
|
|
168
170
|
inline void emplaceUndefined(jsi::Value *_Nonnull slot) noexcept {
|
|
169
171
|
::new (slot) jsi::Value();
|
|
170
172
|
}
|
|
@@ -181,6 +183,31 @@ inline void emplaceNumber(jsi::Value *_Nonnull slot, double value) noexcept {
|
|
|
181
183
|
::new (slot) jsi::Value(value);
|
|
182
184
|
}
|
|
183
185
|
|
|
186
|
+
/**
|
|
187
|
+
Moves the value at `source` into the engine's result slot. Placement new, like the `emplace*`
|
|
188
|
+
helpers above: the slot must hold a value that owns nothing. `source` is left holding a null
|
|
189
|
+
pointer, so destroying it afterwards releases nothing.
|
|
190
|
+
*/
|
|
191
|
+
inline void emplaceMovedValue(jsi::Value *_Nonnull slot, jsi::Value *_Nonnull source) noexcept {
|
|
192
|
+
::new (slot) jsi::Value(std::move(*source));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
Creates a string value straight from UTF-8 bytes. The `jsi::String` returned by `createFromUtf8`
|
|
197
|
+
is moved into the value, so the engine allocates one handle. Going through `jsi::Value(runtime,
|
|
198
|
+
const jsi::String &)` from Swift instead clones the handle and then releases the original.
|
|
199
|
+
*/
|
|
200
|
+
inline jsi::Value createStringValueFromUtf8(jsi::IRuntime &runtime, const uint8_t *_Nonnull utf8, size_t length) {
|
|
201
|
+
return jsi::Value(jsi::String::createFromUtf8(runtime, utf8, length));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
Same as `createStringValueFromUtf8`, for bytes the caller knows to be ASCII.
|
|
206
|
+
*/
|
|
207
|
+
inline jsi::Value createStringValueFromAscii(jsi::IRuntime &runtime, const char *_Nonnull ascii, size_t length) {
|
|
208
|
+
return jsi::Value(jsi::String::createFromAscii(runtime, ascii, length));
|
|
209
|
+
}
|
|
210
|
+
|
|
184
211
|
inline jsi::Value callFunction(jsi::IRuntime &runtime, const jsi::Function &function, const jsi::Value *_Nullable args, size_t count) {
|
|
185
212
|
return expo::CppError::tryCatch(runtime, [&] {
|
|
186
213
|
return function.call(runtime, args, count);
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Copyright 2026-present 650 Industries. All rights reserved.
|
|
2
|
+
|
|
3
|
+
import ExpoModulesJSI
|
|
4
|
+
import Foundation
|
|
5
|
+
import Testing
|
|
6
|
+
|
|
7
|
+
@Suite("JavaScriptDecodable.decodableKinds")
|
|
8
|
+
@JavaScriptActor
|
|
9
|
+
struct JavaScriptDecodableKindsTests {
|
|
10
|
+
let runtime = JavaScriptRuntime()
|
|
11
|
+
|
|
12
|
+
/// One sample value of each JS type, keyed by the source that evaluates to it.
|
|
13
|
+
static let samples = [
|
|
14
|
+
"42", "1.5", "'text'", "true", "null", "undefined", "10n", "Symbol()", "({})", "[1]", "new Uint8Array(1)",
|
|
15
|
+
"(function () {})",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
// MARK: - JavaScriptValueKinds(of:)
|
|
19
|
+
|
|
20
|
+
@Test
|
|
21
|
+
func `reads the kind of every JS type from owning and unowned values`() throws {
|
|
22
|
+
let expected: [String: JavaScriptValueKinds] = [
|
|
23
|
+
"42": .number, "1.5": .number, "'text'": .string, "true": .bool, "null": .null,
|
|
24
|
+
"undefined": .undefined, "10n": .bigint, "Symbol()": .symbol, "({})": .object, "[1]": .object,
|
|
25
|
+
"new Uint8Array(1)": .object, "(function () {})": .object,
|
|
26
|
+
]
|
|
27
|
+
for source in Self.samples {
|
|
28
|
+
let value = try runtime.eval(source)
|
|
29
|
+
#expect(JavaScriptValueKinds(of: value) == expected[source], "owning \(source)")
|
|
30
|
+
|
|
31
|
+
let buffer = JavaScriptValuesBuffer.allocate(in: runtime, with: value)
|
|
32
|
+
let unownedKind = JavaScriptValueKinds(of: buffer.unownedValue(at: 0))
|
|
33
|
+
#expect(unownedKind == expected[source], "unowned \(source)")
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// MARK: - decodableKinds
|
|
38
|
+
|
|
39
|
+
/// Checks that `decodableKinds` contains the kind of exactly the `accepted` samples, and that `decode`
|
|
40
|
+
/// throws for every rejected one. A rejection must be definitive, because a union skips the case
|
|
41
|
+
/// without trying to decode it.
|
|
42
|
+
private func expectDecodableKinds<T: JavaScriptDecodable>(
|
|
43
|
+
_ type: T.Type,
|
|
44
|
+
accept accepted: Set<String>,
|
|
45
|
+
sourceLocation: SourceLocation = #_sourceLocation
|
|
46
|
+
) throws {
|
|
47
|
+
for source in Self.samples {
|
|
48
|
+
let value = try runtime.eval(source)
|
|
49
|
+
let expected = accepted.contains(source)
|
|
50
|
+
#expect(
|
|
51
|
+
T.decodableKinds.contains(JavaScriptValueKinds(of: value)) == expected,
|
|
52
|
+
"\(source)",
|
|
53
|
+
sourceLocation: sourceLocation
|
|
54
|
+
)
|
|
55
|
+
if !expected {
|
|
56
|
+
#expect(throws: (any Error).self, "decode \(source)", sourceLocation: sourceLocation) {
|
|
57
|
+
_ = try T.decode(value, in: runtime)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
static let numbers: Set<String> = ["42", "1.5"]
|
|
64
|
+
static let objects: Set<String> = ["({})", "[1]", "new Uint8Array(1)", "(function () {})"]
|
|
65
|
+
|
|
66
|
+
@Test
|
|
67
|
+
func `Bool accepts only booleans`() throws {
|
|
68
|
+
try expectDecodableKinds(Bool.self, accept: ["true"])
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@Test
|
|
72
|
+
func `String accepts only strings`() throws {
|
|
73
|
+
try expectDecodableKinds(String.self, accept: ["'text'"])
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
@Test
|
|
77
|
+
func `floating-point types accept only numbers`() throws {
|
|
78
|
+
try expectDecodableKinds(Double.self, accept: Self.numbers)
|
|
79
|
+
try expectDecodableKinds(Float.self, accept: Self.numbers)
|
|
80
|
+
try expectDecodableKinds(CGFloat.self, accept: Self.numbers)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
@Test
|
|
84
|
+
func `narrow integer types accept only numbers`() throws {
|
|
85
|
+
try expectDecodableKinds(Int8.self, accept: Self.numbers)
|
|
86
|
+
try expectDecodableKinds(Int16.self, accept: Self.numbers)
|
|
87
|
+
try expectDecodableKinds(Int32.self, accept: Self.numbers)
|
|
88
|
+
try expectDecodableKinds(UInt8.self, accept: Self.numbers)
|
|
89
|
+
try expectDecodableKinds(UInt16.self, accept: Self.numbers)
|
|
90
|
+
try expectDecodableKinds(UInt32.self, accept: Self.numbers)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
@Test
|
|
94
|
+
func `64-bit integer types accept numbers and bigints`() throws {
|
|
95
|
+
let accepted = Self.numbers.union(["10n"])
|
|
96
|
+
try expectDecodableKinds(Int.self, accept: accepted)
|
|
97
|
+
try expectDecodableKinds(Int64.self, accept: accepted)
|
|
98
|
+
try expectDecodableKinds(UInt.self, accept: accepted)
|
|
99
|
+
try expectDecodableKinds(UInt64.self, accept: accepted)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
@Test
|
|
103
|
+
func `Optional accepts null, undefined and what the wrapped type accepts`() throws {
|
|
104
|
+
try expectDecodableKinds(String?.self, accept: ["'text'", "null", "undefined"])
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
@Test
|
|
108
|
+
func `Array accepts objects and what the element type accepts`() throws {
|
|
109
|
+
// A non-array value is decoded as a single-element array.
|
|
110
|
+
try expectDecodableKinds([String].self, accept: Self.objects.union(["'text'"]))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
@Test
|
|
114
|
+
func `Dictionary accepts only objects`() throws {
|
|
115
|
+
try expectDecodableKinds([String: Int].self, accept: Self.objects)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
@Test
|
|
119
|
+
func `Data accepts only objects`() throws {
|
|
120
|
+
try expectDecodableKinds(Data.self, accept: Self.objects)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
@Test
|
|
124
|
+
func `Date accepts numbers, strings and objects`() throws {
|
|
125
|
+
try expectDecodableKinds(Date.self, accept: Self.numbers.union(["'text'"]).union(Self.objects))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@Test
|
|
129
|
+
func `JavaScriptValue accepts every value`() throws {
|
|
130
|
+
try expectDecodableKinds(JavaScriptValue.self, accept: Set(Self.samples))
|
|
131
|
+
}
|
|
132
|
+
}
|