react-native-nitro-modules 0.0.8 → 0.1.4

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 (37) hide show
  1. package/NitroModules.podspec +3 -1
  2. package/android/src/main/cpp/platform/ThreadUtils.cpp +5 -0
  3. package/cpp/core/AnyMap.hpp +2 -1
  4. package/cpp/core/HybridObject.hpp +3 -4
  5. package/cpp/jsi/JSIConverter+AnyMap.hpp +64 -0
  6. package/cpp/jsi/JSIConverter+ArrayBuffer.hpp +41 -0
  7. package/cpp/jsi/JSIConverter+Function.hpp +124 -0
  8. package/cpp/jsi/JSIConverter+HybridObject.hpp +123 -0
  9. package/cpp/jsi/JSIConverter+Optional.hpp +41 -0
  10. package/cpp/jsi/JSIConverter+Promise.hpp +87 -0
  11. package/cpp/jsi/JSIConverter+Tuple.hpp +60 -0
  12. package/cpp/jsi/JSIConverter+UnorderedMap.hpp +50 -0
  13. package/cpp/jsi/JSIConverter+Variant.hpp +97 -0
  14. package/cpp/jsi/JSIConverter+Vector.hpp +48 -0
  15. package/cpp/jsi/JSIConverter.hpp +22 -498
  16. package/cpp/platform/ThreadUtils.hpp +6 -0
  17. package/cpp/threading/ThreadPool.cpp +84 -0
  18. package/cpp/threading/ThreadPool.hpp +53 -0
  19. package/ios/core/HybridContext.cpp +8 -0
  20. package/{cpp → ios}/core/HybridContext.hpp +6 -3
  21. package/ios/platform/ThreadUtils.cpp +4 -0
  22. package/lib/NativeNitroModules.d.ts +5 -0
  23. package/lib/NativeNitroModules.js +5 -0
  24. package/lib/NativeNitroModules.web.d.ts +4 -0
  25. package/lib/NativeNitroModules.web.js +3 -0
  26. package/lib/commonjs/NativeNitroModules.js +6 -0
  27. package/lib/commonjs/NativeNitroModules.js.map +1 -1
  28. package/lib/commonjs/NativeNitroModules.web.js +10 -0
  29. package/lib/commonjs/NativeNitroModules.web.js.map +1 -0
  30. package/lib/module/NativeNitroModules.js +5 -0
  31. package/lib/module/NativeNitroModules.js.map +1 -1
  32. package/lib/module/NativeNitroModules.web.js +4 -0
  33. package/lib/module/NativeNitroModules.web.js.map +1 -0
  34. package/lib/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +3 -6
  36. package/src/NativeNitroModules.ts +11 -0
  37. package/src/NativeNitroModules.web.ts +9 -0
@@ -0,0 +1,97 @@
1
+ //
2
+ // Created by Marc Rousavy on 21.02.24.
3
+ //
4
+
5
+ #pragma once
6
+
7
+ // Forward declare a few of the common types that might have cyclic includes.
8
+ namespace margelo::nitro {
9
+ struct AnyValue;
10
+ class AnyMap;
11
+
12
+ template <typename T, typename Enable>
13
+ struct JSIConverter;
14
+ } // namespace margelo::nitro
15
+
16
+ #include "JSIConverter.hpp"
17
+ #include "JSIConverter+Vector.hpp"
18
+ #include "JSIConverter+UnorderedMap.hpp"
19
+
20
+ #include "AnyMap.hpp"
21
+ #include "IsInPack.hpp"
22
+ #include "TypeInfo.hpp"
23
+ #include <jsi/jsi.h>
24
+ #include <memory>
25
+ #include <variant>
26
+
27
+ namespace margelo::nitro {
28
+
29
+ using namespace facebook;
30
+
31
+ // std::variant<A, B, C> <> A | B | C
32
+ template <typename... Types>
33
+ struct JSIConverter<std::variant<Types...>> {
34
+ static inline std::variant<Types...> fromJSI(jsi::Runtime& runtime, const jsi::Value& value) {
35
+ if (value.isNull()) {
36
+ if constexpr (is_in_pack_v<std::monostate, Types...>) {
37
+ return std::monostate();
38
+ } else {
39
+ throw typeNotSupportedError("null");
40
+ }
41
+ } else if (value.isBool()) {
42
+ if constexpr (is_in_pack_v<bool, Types...>) {
43
+ return JSIConverter<bool>::fromJSI(runtime, value);
44
+ } else {
45
+ throw typeNotSupportedError("boolean");
46
+ }
47
+ } else if (value.isNumber()) {
48
+ if constexpr (is_in_pack_v<double, Types...>) {
49
+ return JSIConverter<double>::fromJSI(runtime, value);
50
+ } else {
51
+ throw typeNotSupportedError("number");
52
+ }
53
+ } else if (value.isString()) {
54
+ if constexpr (is_in_pack_v<std::string, Types...>) {
55
+ return JSIConverter<std::string>::fromJSI(runtime, value);
56
+ } else {
57
+ throw typeNotSupportedError("string");
58
+ }
59
+ } else if (value.isBigInt()) {
60
+ if constexpr (is_in_pack_v<int64_t, Types...>) {
61
+ return JSIConverter<int64_t>::fromJSI(runtime, value);
62
+ } else {
63
+ throw typeNotSupportedError("bigint");
64
+ }
65
+ } else if (value.isObject()) {
66
+ jsi::Object valueObj = value.getObject(runtime);
67
+ if (valueObj.isArray(runtime)) {
68
+ if constexpr (is_in_pack_v<std::vector<AnyValue>, Types...>) {
69
+ return JSIConverter<std::vector<AnyValue>>::fromJSI(runtime, value);
70
+ } else {
71
+ throw typeNotSupportedError("array[]");
72
+ }
73
+ } else {
74
+ if constexpr (is_in_pack_v<std::unordered_map<std::string, AnyValue>, Types...>) {
75
+ return JSIConverter<std::unordered_map<std::string, AnyValue>>::fromJSI(runtime, value);
76
+ } else {
77
+ throw typeNotSupportedError("object{}");
78
+ }
79
+ }
80
+ } else {
81
+ std::string stringRepresentation = value.toString(runtime).utf8(runtime);
82
+ throw std::runtime_error("Cannot convert \"" + stringRepresentation + "\" to std::variant<...>!");
83
+ }
84
+ }
85
+
86
+ static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::variant<Types...>& variant) {
87
+ return std::visit([&runtime](const auto& val) { return JSIConverter<std::decay_t<decltype(val)>>::toJSI(runtime, val); }, variant);
88
+ }
89
+
90
+ private:
91
+ static inline std::runtime_error typeNotSupportedError(const std::string& type) {
92
+ std::string types = TypeInfo::getFriendlyTypenames<Types...>();
93
+ return std::runtime_error(type + " is not supported in variant<" + types + ">!");
94
+ }
95
+ };
96
+
97
+ } // namespace margelo::nitro
@@ -0,0 +1,48 @@
1
+ //
2
+ // Created by Marc Rousavy on 21.02.24.
3
+ //
4
+
5
+ #pragma once
6
+
7
+ // Forward declare a few of the common types that might have cyclic includes.
8
+ namespace margelo::nitro {
9
+ template <typename T, typename Enable>
10
+ struct JSIConverter;
11
+ } // namespace margelo::nitro
12
+
13
+ #include "JSIConverter.hpp"
14
+
15
+ #include "AnyMap.hpp"
16
+ #include <jsi/jsi.h>
17
+ #include <vector>
18
+
19
+ namespace margelo::nitro {
20
+
21
+ using namespace facebook;
22
+
23
+ // std::vector<T> <> T[]
24
+ template <typename ElementType>
25
+ struct JSIConverter<std::vector<ElementType>> {
26
+ static inline std::vector<ElementType> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
27
+ jsi::Array array = arg.asObject(runtime).asArray(runtime);
28
+ size_t length = array.size(runtime);
29
+
30
+ std::vector<ElementType> vector;
31
+ vector.reserve(length);
32
+ for (size_t i = 0; i < length; ++i) {
33
+ jsi::Value elementValue = array.getValueAtIndex(runtime, i);
34
+ vector.emplace_back(JSIConverter<ElementType>::fromJSI(runtime, elementValue));
35
+ }
36
+ return vector;
37
+ }
38
+ static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::vector<ElementType>& vector) {
39
+ jsi::Array array(runtime, vector.size());
40
+ for (size_t i = 0; i < vector.size(); i++) {
41
+ jsi::Value value = JSIConverter<ElementType>::toJSI(runtime, vector[i]);
42
+ array.setValueAtIndex(runtime, i, std::move(value));
43
+ }
44
+ return array;
45
+ }
46
+ };
47
+
48
+ } // namespace margelo::nitro
@@ -4,46 +4,27 @@
4
4
 
5
5
  #pragma once
6
6
 
7
+ // Forward declare a few of the common types that might have cyclic includes.
7
8
  namespace margelo::nitro {
8
- class HybridObject;
9
- }
9
+ template <typename T, typename Enable>
10
+ struct JSIConverter;
11
+ } // namespace margelo::nitro
10
12
 
11
- #include "AnyMap.hpp"
12
- #include "ArrayBuffer.hpp"
13
- #include "Dispatcher.hpp"
14
- #include "FutureType.hpp"
15
- #include "HybridObject.hpp"
16
- #include "IsHostObject.hpp"
17
- #include "IsInPack.hpp"
18
- #include "IsNativeState.hpp"
19
- #include "JSICache.hpp"
20
- #include "NitroHash.hpp"
21
- #include "Promise.hpp"
22
- #include "TypeInfo.hpp"
23
- #include <array>
24
- #include <future>
25
13
  #include <jsi/jsi.h>
26
- #include <memory>
27
- #include <tuple>
28
14
  #include <type_traits>
29
- #include <unordered_map>
30
15
  #include <variant>
31
16
 
32
- #define DO_NULL_CHECKS true
33
-
34
17
  namespace margelo::nitro {
35
18
 
36
- /**
37
- The JSIConverter<T> class can convert any type from and to a jsi::Value.
38
- It uses templates to statically create fromJSI/toJSI methods, and will throw compile-time errors
39
- if a given type is not convertable.
40
- Value types, custom types (HostObjects), and even functions with any number of arguments/types are supported.
41
- This type can be extended by just creating a new template for JSIConverter in a header.
42
- */
43
-
44
19
  using namespace facebook;
45
20
 
46
- // Unknown type (error)
21
+ /**
22
+ * The JSIConverter<T> class can convert any type from and to a jsi::Value.
23
+ * It uses templates to statically create fromJSI/toJSI methods, and will throw compile-time errors
24
+ * if a given type is not convertable.
25
+ * Value types, custom types (HostObjects), and even functions with any number of arguments/types are supported.
26
+ * This type can be extended by just creating a new template for JSIConverter in a header.
27
+ */
47
28
  template <typename ArgType, typename Enable = void>
48
29
  struct JSIConverter final {
49
30
  JSIConverter() = delete;
@@ -150,472 +131,15 @@ struct JSIConverter<std::string> {
150
131
  }
151
132
  };
152
133
 
153
- // std::optional<T> <> T | undefined
154
- template <typename TInner>
155
- struct JSIConverter<std::optional<TInner>> {
156
- static inline std::optional<TInner> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
157
- if (arg.isUndefined() || arg.isNull()) {
158
- return std::nullopt;
159
- } else {
160
- return JSIConverter<TInner>::fromJSI(runtime, arg);
161
- }
162
- }
163
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::optional<TInner>& arg) {
164
- if (arg == std::nullopt) {
165
- return jsi::Value::undefined();
166
- } else {
167
- return JSIConverter<TInner>::toJSI(runtime, arg.value());
168
- }
169
- }
170
- };
171
-
172
- // std::future<T> <> Promise<T>
173
- template <typename TResult>
174
- struct JSIConverter<std::future<TResult>> {
175
- static inline std::future<TResult> fromJSI(jsi::Runtime&, const jsi::Value&) {
176
- throw std::runtime_error("Promise cannot be converted to a native type - it needs to be awaited first!");
177
- }
178
- static inline jsi::Value toJSI(jsi::Runtime& runtime, std::future<TResult>&& arg) {
179
- auto sharedFuture = std::make_shared<std::future<TResult>>(std::move(arg));
180
- std::shared_ptr<Dispatcher> strongDispatcher = Dispatcher::getRuntimeGlobalDispatcher(runtime);
181
- std::weak_ptr<Dispatcher> weakDispatcher = strongDispatcher;
182
-
183
- return Promise::createPromise(runtime, [sharedFuture, weakDispatcher](jsi::Runtime& runtime, std::shared_ptr<Promise> promise) {
184
- // Spawn new async thread to synchronously wait for the `future<T>` to complete
185
- std::thread waiterThread([promise, &runtime, weakDispatcher, sharedFuture]() {
186
- // synchronously wait until the `future<T>` completes. we are running on a background task here.
187
- sharedFuture->wait();
188
-
189
- // the async function completed successfully, get a JS Dispatcher so we can resolve on JS Thread
190
- std::shared_ptr<Dispatcher> dispatcher = weakDispatcher.lock();
191
- if (!dispatcher) {
192
- Logger::log("JSIConverter", "Tried resolving Promise on JS Thread, but the `Dispatcher` has already been destroyed.");
193
- return;
194
- }
195
-
196
- dispatcher->runAsync([&runtime, promise, sharedFuture]() mutable {
197
- try {
198
- if constexpr (std::is_void_v<TResult>) {
199
- // it's returning void, just return undefined to JS
200
- sharedFuture->get();
201
- promise->resolve(runtime, jsi::Value::undefined());
202
- } else {
203
- // it's returning a custom type, convert it to a jsi::Value
204
- TResult result = sharedFuture->get();
205
- jsi::Value jsResult = JSIConverter<TResult>::toJSI(runtime, result);
206
- promise->resolve(runtime, std::move(jsResult));
207
- }
208
- } catch (const std::exception& exception) {
209
- // the async function threw an error, reject the promise on JS Thread
210
- std::string what = exception.what();
211
- promise->reject(runtime, what);
212
- } catch (...) {
213
- // the async function threw a non-std error, try getting it
214
- std::string name = TypeInfo::getCurrentExceptionName();
215
- promise->reject(runtime, "Unknown non-std exception: " + name);
216
- }
217
-
218
- // This lambda owns the promise shared pointer, and we need to call its
219
- // destructor on the correct thread here - otherwise it might be called
220
- // from the waiterThread.
221
- promise = nullptr;
222
- });
223
- });
224
- waiterThread.detach();
225
- });
226
- }
227
- };
228
-
229
- // [](Args...) -> T {} <> (Args...) => T
230
- template <typename ReturnType, typename... Args>
231
- struct JSIConverter<std::function<ReturnType(Args...)>> {
232
- // std::future<T> -> T
233
- using ResultingType = future_type_v<ReturnType>;
234
-
235
- static inline ResultingType callJSFunction(jsi::Runtime& runtime, const OwningReference<jsi::Function>& function, const Args&... args) {
236
- // Throw a lock on the OwningReference<T> so we can guarantee safe access (Hermes GC cannot delete it while `lock` is alive)
237
- OwningLock<jsi::Function> lock = function.lock();
238
-
239
- if (!function) {
240
- if constexpr (std::is_void_v<ResultingType>) {
241
- // runtime has already been deleted. since this returns void, we can just ignore it being deleted.
242
- Logger::log("JSIConverter", "Tried calling void(..) function, but it has already been deleted by JS!");
243
- return;
244
- } else {
245
- // runtime has already been deleted, but we are expecting a return value - throw an error in this case.
246
- throw std::runtime_error("Cannot call the given Function - the JS Dispatcher has already been destroyed by the JS Runtime!");
247
- }
248
- }
249
-
250
- if constexpr (std::is_void_v<ResultingType>) {
251
- // It returns void. Just call the function
252
- function->call(runtime, JSIConverter<std::decay_t<Args>>::toJSI(runtime, args)...);
253
- } else {
254
- // It returns some kind of value - call the function, and convert the return value.
255
- jsi::Value result = function->call(runtime, JSIConverter<std::decay_t<Args>>::toJSI(runtime, args)...);
256
- return JSIConverter<ResultingType>::fromJSI(runtime, std::move(result));
257
- }
258
- }
259
-
260
- static inline std::function<ReturnType(Args...)> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
261
- // Make function global - it'll be managed by the Runtime's memory, and we only have a weak_ref to it.
262
- auto cache = JSICache<jsi::Function>::getOrCreateCache(runtime);
263
- jsi::Function function = arg.asObject(runtime).asFunction(runtime);
264
- OwningReference<jsi::Function> sharedFunction = cache.makeGlobal(std::move(function));
265
-
266
- std::shared_ptr<Dispatcher> strongDispatcher = Dispatcher::getRuntimeGlobalDispatcher(runtime);
267
- std::weak_ptr<Dispatcher> weakDispatcher = strongDispatcher;
268
-
269
- // Create a C++ function that can be called by the consumer.
270
- // This will call the jsi::Function if it is still alive.
271
- return [&runtime, weakDispatcher, sharedFunction = std::move(sharedFunction)](Args... args) -> ReturnType {
272
- // Try to get the JS Dispatcher if the Runtime is still alive
273
- std::shared_ptr<Dispatcher> dispatcher = weakDispatcher.lock();
274
- if (!dispatcher) {
275
- if constexpr (std::is_void_v<ResultingType>) {
276
- Logger::log("JSIConverter", "Tried calling void(..) function, but the JS Dispatcher has already been deleted by JS!");
277
- return;
278
- } else {
279
- throw std::runtime_error("Cannot call the given Function - the JS Dispatcher has already been destroyed by the JS Runtime!");
280
- }
281
- }
282
-
283
- if constexpr (std::is_void_v<ResultingType>) {
284
- dispatcher->runAsync([&runtime, sharedFunction = std::move(sharedFunction), ... args = std::move(args)]() {
285
- callJSFunction(runtime, sharedFunction, args...);
286
- });
287
- } else {
288
- return dispatcher->runAsyncAwaitable<ResultingType>(
289
- [&runtime, sharedFunction = std::move(sharedFunction), ... args = std::move(args)]() -> ResultingType {
290
- return callJSFunction(runtime, sharedFunction, args...);
291
- });
292
- }
293
- };
294
- }
295
-
296
- template <size_t... Is>
297
- static inline jsi::Value callHybridFunction(const std::function<ReturnType(Args...)>& function, jsi::Runtime& runtime,
298
- const jsi::Value* args, std::index_sequence<Is...>) {
299
- if constexpr (std::is_void_v<ReturnType>) {
300
- // it is a void function (will return undefined in JS)
301
- function(JSIConverter<std::decay_t<Args>>::fromJSI(runtime, args[Is])...);
302
- return jsi::Value::undefined();
303
- } else {
304
- // it is a custom type, parse it to a JS value
305
- ReturnType result = function(JSIConverter<std::decay_t<Args>>::fromJSI(runtime, args[Is])...);
306
- return JSIConverter<ReturnType>::toJSI(runtime, result);
307
- }
308
- }
309
- static inline jsi::Value toJSI(jsi::Runtime& runtime, std::function<ReturnType(Args...)>&& function) {
310
- jsi::HostFunctionType jsFunction = [function = std::move(function)](jsi::Runtime& runtime, const jsi::Value& thisValue,
311
- const jsi::Value* args, size_t count) -> jsi::Value {
312
- if (count != sizeof...(Args)) [[unlikely]] {
313
- throw jsi::JSError(runtime, "Function expected " + std::to_string(sizeof...(Args)) + " arguments, but received " +
314
- std::to_string(count) + "!");
315
- }
316
- return callHybridFunction(function, runtime, args, std::index_sequence_for<Args...>{});
317
- };
318
- return jsi::Function::createFromHostFunction(runtime, jsi::PropNameID::forUtf8(runtime, "hostFunction"), sizeof...(Args), jsFunction);
319
- }
320
- };
321
-
322
- // std::vector<T> <> T[]
323
- template <typename ElementType>
324
- struct JSIConverter<std::vector<ElementType>> {
325
- static inline std::vector<ElementType> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
326
- jsi::Array array = arg.asObject(runtime).asArray(runtime);
327
- size_t length = array.size(runtime);
328
-
329
- std::vector<ElementType> vector;
330
- vector.reserve(length);
331
- for (size_t i = 0; i < length; ++i) {
332
- jsi::Value elementValue = array.getValueAtIndex(runtime, i);
333
- vector.emplace_back(JSIConverter<ElementType>::fromJSI(runtime, elementValue));
334
- }
335
- return vector;
336
- }
337
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::vector<ElementType>& vector) {
338
- jsi::Array array(runtime, vector.size());
339
- for (size_t i = 0; i < vector.size(); i++) {
340
- jsi::Value value = JSIConverter<ElementType>::toJSI(runtime, vector[i]);
341
- array.setValueAtIndex(runtime, i, std::move(value));
342
- }
343
- return array;
344
- }
345
- };
346
-
347
- // std::unordered_map<std::string, T> <> Record<string, T>
348
- template <typename ValueType>
349
- struct JSIConverter<std::unordered_map<std::string, ValueType>> {
350
- static inline std::unordered_map<std::string, ValueType> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
351
- jsi::Object object = arg.asObject(runtime);
352
- jsi::Array propertyNames = object.getPropertyNames(runtime);
353
- size_t length = propertyNames.size(runtime);
354
-
355
- std::unordered_map<std::string, ValueType> map;
356
- map.reserve(length);
357
- for (size_t i = 0; i < length; ++i) {
358
- std::string key = propertyNames.getValueAtIndex(runtime, i).asString(runtime).utf8(runtime);
359
- jsi::Value value = object.getProperty(runtime, key.c_str());
360
- map.emplace(key, JSIConverter<ValueType>::fromJSI(runtime, value));
361
- }
362
- return map;
363
- }
364
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::unordered_map<std::string, ValueType>& map) {
365
- jsi::Object object(runtime);
366
- for (const auto& pair : map) {
367
- jsi::Value value = JSIConverter<ValueType>::toJSI(runtime, pair.second);
368
- object.setProperty(runtime, pair.first.c_str(), std::move(value));
369
- }
370
- return object;
371
- }
372
- };
373
-
374
- // std::tuple<A, B, C> <> [A, B, C]
375
- template <typename... Types>
376
- struct JSIConverter<std::tuple<Types...>> {
377
- static inline std::tuple<Types...> fromJSI(jsi::Runtime& runtime, const jsi::Value& value) {
378
- jsi::Object object = value.asObject(runtime);
379
- jsi::Array array = object.asArray(runtime);
380
- if (array.size(runtime) != sizeof...(Types)) [[unlikely]] {
381
- std::string types = TypeInfo::getFriendlyTypenames<Types...>();
382
- throw std::runtime_error("The given JS Array has " + std::to_string(array.size(runtime)) + " items, but std::tuple<" + types +
383
- "> expects " + std::to_string(sizeof...(Types)) + " items.");
384
- }
385
-
386
- return copyArrayItemsToTuple(runtime, array, std::index_sequence_for<Types...>{});
387
- }
388
-
389
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::tuple<Types...>& tuple) {
390
- jsi::Array array(runtime, sizeof...(Types));
391
- copyTupleItemsToArray(runtime, array, tuple, std::index_sequence_for<Types...>{});
392
- return array;
393
- }
394
-
395
- private:
396
- template <std::size_t... Is>
397
- static inline std::tuple<Types...> copyArrayItemsToTuple(jsi::Runtime& runtime, const jsi::Array& array, std::index_sequence<Is...>) {
398
- return std::make_tuple(JSIConverter<Types>::fromJSI(runtime, array.getValueAtIndex(runtime, Is))...);
399
- }
400
-
401
- template <std::size_t... Is>
402
- static inline void copyTupleItemsToArray(jsi::Runtime& runtime, jsi::Array& array, const std::tuple<Types...>& tuple,
403
- std::index_sequence<Is...>) {
404
- ((array.setValueAtIndex(runtime, Is,
405
- JSIConverter<std::tuple_element_t<Is, std::tuple<Types...>>>::toJSI(runtime, std::get<Is>(tuple)))),
406
- ...);
407
- }
408
- };
409
-
410
- // std::variant<A, B, C> <> A | B | C
411
- template <typename... Types>
412
- struct JSIConverter<std::variant<Types...>> {
413
- static inline std::variant<Types...> fromJSI(jsi::Runtime& runtime, const jsi::Value& value) {
414
- if (value.isNull()) {
415
- if constexpr (is_in_pack_v<std::monostate, Types...>) {
416
- return std::monostate();
417
- } else {
418
- throw typeNotSupportedError("null");
419
- }
420
- } else if (value.isBool()) {
421
- if constexpr (is_in_pack_v<bool, Types...>) {
422
- return JSIConverter<bool>::fromJSI(runtime, value);
423
- } else {
424
- throw typeNotSupportedError("boolean");
425
- }
426
- } else if (value.isNumber()) {
427
- if constexpr (is_in_pack_v<double, Types...>) {
428
- return JSIConverter<double>::fromJSI(runtime, value);
429
- } else {
430
- throw typeNotSupportedError("number");
431
- }
432
- } else if (value.isString()) {
433
- if constexpr (is_in_pack_v<std::string, Types...>) {
434
- return JSIConverter<std::string>::fromJSI(runtime, value);
435
- } else {
436
- throw typeNotSupportedError("string");
437
- }
438
- } else if (value.isBigInt()) {
439
- if constexpr (is_in_pack_v<int64_t, Types...>) {
440
- return JSIConverter<int64_t>::fromJSI(runtime, value);
441
- } else {
442
- throw typeNotSupportedError("bigint");
443
- }
444
- } else if (value.isObject()) {
445
- jsi::Object valueObj = value.getObject(runtime);
446
- if (valueObj.isArray(runtime)) {
447
- if constexpr (is_in_pack_v<std::vector<AnyValue>, Types...>) {
448
- return JSIConverter<std::vector<AnyValue>>::fromJSI(runtime, value);
449
- } else {
450
- throw typeNotSupportedError("array[]");
451
- }
452
- } else {
453
- if constexpr (is_in_pack_v<std::unordered_map<std::string, AnyValue>, Types...>) {
454
- return JSIConverter<std::unordered_map<std::string, AnyValue>>::fromJSI(runtime, value);
455
- } else {
456
- throw typeNotSupportedError("object{}");
457
- }
458
- }
459
- } else {
460
- std::string stringRepresentation = value.toString(runtime).utf8(runtime);
461
- throw std::runtime_error("Cannot convert \"" + stringRepresentation + "\" to std::variant<...>!");
462
- }
463
- }
464
-
465
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const std::variant<Types...>& variant) {
466
- return std::visit([&runtime](const auto& val) { return JSIConverter<std::decay_t<decltype(val)>>::toJSI(runtime, val); }, variant);
467
- }
468
-
469
- private:
470
- static inline std::runtime_error typeNotSupportedError(const std::string& type) {
471
- std::string types = TypeInfo::getFriendlyTypenames<Types...>();
472
- return std::runtime_error(type + " is not supported in variant<" + types + ">!");
473
- }
474
- };
475
-
476
- // AnyValue <> Record<K, V>
477
- template <>
478
- struct JSIConverter<AnyValue> {
479
- static inline AnyValue fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
480
- return JSIConverter<AnyValue::variant>::fromJSI(runtime, arg);
481
- }
482
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const AnyValue& value) {
483
- return JSIConverter<std::variant<AnyValue::variant>>::toJSI(runtime, value);
484
- }
485
- };
486
-
487
- // AnyMap <> Record<K, V>
488
- template <>
489
- struct JSIConverter<std::shared_ptr<AnyMap>> {
490
- static inline std::shared_ptr<AnyMap> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
491
- jsi::Object object = arg.asObject(runtime);
492
- jsi::Array propNames = object.getPropertyNames(runtime);
493
- size_t size = propNames.size(runtime);
494
- std::shared_ptr<AnyMap> map = AnyMap::make();
495
- for (size_t i = 0; i < size; i++) {
496
- jsi::String jsKey = propNames.getValueAtIndex(runtime, i).getString(runtime);
497
- jsi::Value jsValue = object.getProperty(runtime, jsKey);
498
- map->setAny(jsKey.utf8(runtime), JSIConverter<AnyValue>::fromJSI(runtime, jsValue));
499
- }
500
- return map;
501
- }
502
- static inline jsi::Value toJSI(jsi::Runtime& runtime, std::shared_ptr<AnyMap> map) {
503
- jsi::Object object(runtime);
504
- for (const auto& item : map->getMap()) {
505
- jsi::String key = jsi::String::createFromUtf8(runtime, item.first);
506
- jsi::Value value = JSIConverter<AnyValue>::toJSI(runtime, item.second);
507
- object.setProperty(runtime, std::move(key), std::move(value));
508
- }
509
- return object;
510
- }
511
- };
512
-
513
- // MutableBuffer <> ArrayBuffer
514
- template <>
515
- struct JSIConverter<std::shared_ptr<jsi::MutableBuffer>> {
516
- static inline std::shared_ptr<ArrayBuffer> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
517
- jsi::Object object = arg.asObject(runtime);
518
- if (!object.isArrayBuffer(runtime)) [[unlikely]] {
519
- throw std::runtime_error("Object \"" + arg.toString(runtime).utf8(runtime) + "\" is not an ArrayBuffer!");
520
- }
521
- jsi::ArrayBuffer arrayBuffer = object.getArrayBuffer(runtime);
522
- return std::make_shared<ArrayBuffer>(arrayBuffer.data(runtime), arrayBuffer.size(runtime), false);
523
- }
524
- static inline jsi::Value toJSI(jsi::Runtime& runtime, std::shared_ptr<jsi::MutableBuffer> buffer) {
525
- return jsi::ArrayBuffer(runtime, buffer);
526
- }
527
- };
528
-
529
- // HybridObject <> {}
530
- template <typename T>
531
- struct JSIConverter<T, std::enable_if_t<is_shared_ptr_to_host_object_v<T>>> {
532
- using TPointee = typename T::element_type;
533
-
534
- static inline T fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
535
- #if DO_NULL_CHECKS
536
- if (arg.isUndefined()) [[unlikely]] {
537
- throw jsi::JSError(runtime, invalidTypeErrorMessage("undefined", "It is undefined!"));
538
- }
539
- if (!arg.isObject()) [[unlikely]] {
540
- std::string stringRepresentation = arg.toString(runtime).utf8(runtime);
541
- throw jsi::JSError(runtime, invalidTypeErrorMessage(stringRepresentation, "It is not an object!"));
542
- }
543
- #endif
544
- jsi::Object object = arg.asObject(runtime);
545
- #if DO_NULL_CHECKS
546
- if (!object.isHostObject<TPointee>(runtime)) [[unlikely]] {
547
- std::string stringRepresentation = arg.toString(runtime).utf8(runtime);
548
- throw jsi::JSError(runtime, invalidTypeErrorMessage(stringRepresentation, "It is a different HostObject<T>!"));
549
- }
550
- #endif
551
- return object.asHostObject<TPointee>(runtime);
552
- }
553
-
554
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const T& arg) {
555
- #if DO_NULL_CHECKS
556
- if (arg == nullptr) [[unlikely]] {
557
- std::string typeName = TypeInfo::getFriendlyTypename<TPointee>();
558
- throw jsi::JSError(runtime, "Cannot convert nullptr to HostObject<" + typeName + ">!");
559
- }
560
- #endif
561
- if constexpr (std::is_base_of_v<HybridObject, TPointee>) {
562
- // It's a HybridObject - use it's internal constructor which caches jsi::Objects for proper memory management!
563
- return arg->toObject(runtime);
564
- } else {
565
- // It's any other kind of jsi::HostObject - just create it as normal.
566
- return jsi::Object::createFromHostObject(runtime, arg);
567
- }
568
- }
569
-
570
- private:
571
- static inline std::string invalidTypeErrorMessage(const std::string& typeDescription, const std::string& reason) {
572
- std::string typeName = TypeInfo::getFriendlyTypename<TPointee>();
573
- return "Cannot convert \"" + typeDescription + "\" to HostObject<" + typeName + ">! " + reason;
574
- }
575
- };
576
-
577
- // NativeState <> {}
578
- template <typename T>
579
- struct JSIConverter<T, std::enable_if_t<is_shared_ptr_to_native_state_v<T>>> {
580
- using TPointee = typename T::element_type;
581
-
582
- static inline T fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
583
- #if DO_NULL_CHECKS
584
- if (arg.isUndefined()) [[unlikely]] {
585
- throw jsi::JSError(runtime, invalidTypeErrorMessage("undefined", "It is undefined!"));
586
- }
587
- if (!arg.isObject()) [[unlikely]] {
588
- std::string stringRepresentation = arg.toString(runtime).utf8(runtime);
589
- throw jsi::JSError(runtime, invalidTypeErrorMessage(stringRepresentation, "It is not an object!"));
590
- }
591
- #endif
592
- jsi::Object object = arg.asObject(runtime);
593
- #if DO_NULL_CHECKS
594
- if (!object.hasNativeState<TPointee>(runtime)) [[unlikely]] {
595
- std::string stringRepresentation = arg.toString(runtime).utf8(runtime);
596
- throw jsi::JSError(runtime, invalidTypeErrorMessage(stringRepresentation, "It is a different NativeState<T>!"));
597
- }
598
- #endif
599
- return object.getNativeState<TPointee>(runtime);
600
- }
601
-
602
- static inline jsi::Value toJSI(jsi::Runtime& runtime, const T& arg) {
603
- #if DO_NULL_CHECKS
604
- if (arg == nullptr) [[unlikely]] {
605
- std::string typeName = TypeInfo::getFriendlyTypename<TPointee>();
606
- throw jsi::JSError(runtime, "Cannot convert nullptr to NativeState<" + typeName + ">!");
607
- }
608
- #endif
609
- jsi::Object object(runtime);
610
- object.setNativeState(runtime, arg);
611
- return object;
612
- }
613
-
614
- private:
615
- static inline std::string invalidTypeErrorMessage(const std::string& typeDescription, const std::string& reason) {
616
- std::string typeName = TypeInfo::getFriendlyTypename<TPointee>();
617
- return "Cannot convert \"" + typeDescription + "\" to NativeState<" + typeName + ">! " + reason;
618
- }
619
- };
620
-
621
134
  } // namespace margelo::nitro
135
+
136
+ #include "JSIConverter+AnyMap.hpp"
137
+ #include "JSIConverter+ArrayBuffer.hpp"
138
+ #include "JSIConverter+Function.hpp"
139
+ #include "JSIConverter+HybridObject.hpp"
140
+ #include "JSIConverter+Optional.hpp"
141
+ #include "JSIConverter+Promise.hpp"
142
+ #include "JSIConverter+Tuple.hpp"
143
+ #include "JSIConverter+UnorderedMap.hpp"
144
+ #include "JSIConverter+Variant.hpp"
145
+ #include "JSIConverter+Vector.hpp"