diff --git a/packages/react-native/ReactCxxPlatform/react/io/BlobModule.cpp b/packages/react-native/ReactCxxPlatform/react/io/BlobModule.cpp new file mode 100644 index 000000000000..4fdcad6dd1d0 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/BlobModule.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "BlobModule.h" + +#include +#include +#include + +namespace facebook::react { + +namespace { + +constexpr const char* kBlobCollectorProvider = "__blobCollectorProvider"; + +/// Lets JavaScript-held blobs free their bytes when garbage collected. +/// BlobManager.createFromOptions attaches a collector to each Blob. +class BlobCollector : public jsi::HostObject { + public: + BlobCollector(std::weak_ptr store, std::string blobId) + : store_(std::move(store)), blobId_(std::move(blobId)) {} + + BlobCollector(const BlobCollector&) = delete; + BlobCollector& operator=(const BlobCollector&) = delete; + BlobCollector(BlobCollector&&) = delete; + BlobCollector& operator=(BlobCollector&&) = delete; + + ~BlobCollector() override { + if (auto store = store_.lock()) { + store->remove(blobId_); + } + } + + private: + std::weak_ptr store_; + std::string blobId_; +}; + +/// Converts a JavaScript offset/size to an index, rejecting values that are not +/// non-negative integers representable as `std::size_t`. +std::optional toBlobIndex(const jsi::Value& value) { + if (!value.isNumber()) { + return std::nullopt; + } + const double number = value.getNumber(); + // `!(number >= 0)` also rejects NaN. The size_t maximum rounds up to a power + // of two as a double, so `<` keeps the cast in range. + if (!(number >= 0) || + number >= static_cast(std::numeric_limits::max()) || + std::trunc(number) != number) { + return std::nullopt; + } + return static_cast(number); +} + +} // namespace + +std::optional> resolveBlobData( + jsi::Runtime& rt, + const jsi::Object& blobData, + const BlobStore& store) { + auto blobId = blobData.getProperty(rt, "blobId"); + auto offset = toBlobIndex(blobData.getProperty(rt, "offset")); + auto size = toBlobIndex(blobData.getProperty(rt, "size")); + if (!blobId.isString() || !offset || !size) { + return std::nullopt; + } + return store.resolve(blobId.getString(rt).utf8(rt), *offset, *size); +} + +BlobModule::BlobModule( + std::shared_ptr jsInvoker, + std::shared_ptr store) + : NativeBlobModuleCxxSpec(std::move(jsInvoker)), store_(std::move(store)) {} + +jsi::Object BlobModule::getConstants(jsi::Runtime& rt) { + auto constants = jsi::Object(rt); + constants.setProperty( + rt, "BLOB_URI_SCHEME", jsi::String::createFromAscii(rt, "blob")); + constants.setProperty(rt, "BLOB_URI_HOST", jsi::Value::null()); + return constants; +} + +void BlobModule::addNetworkingHandler(jsi::Runtime& /*rt*/) {} + +void BlobModule::addWebSocketHandler(jsi::Runtime& rt, double /*id*/) { + throw jsi::JSError(rt, "BlobModule: WebSocket blobs are not supported"); +} + +void BlobModule::removeWebSocketHandler(jsi::Runtime& /*rt*/, double /*id*/) {} + +void BlobModule::sendOverSocket( + jsi::Runtime& rt, + jsi::Object /*blob*/, + double /*socketID*/) { + throw jsi::JSError(rt, "BlobModule: WebSocket blobs are not supported"); +} + +void BlobModule::createFromParts( + jsi::Runtime& rt, + jsi::Array parts, + const std::string& withId) { + std::vector bytes; + const auto count = parts.size(rt); + for (size_t i = 0; i < count; ++i) { + auto part = parts.getValueAtIndex(rt, i).asObject(rt); + auto type = part.getProperty(rt, "type").asString(rt).utf8(rt); + if (type == "string") { + auto text = part.getProperty(rt, "data").asString(rt).utf8(rt); + bytes.insert(bytes.end(), text.begin(), text.end()); + } else if (type == "blob") { + auto data = resolveBlobData( + rt, part.getProperty(rt, "data").asObject(rt), *store_); + if (!data) { + throw jsi::JSError( + rt, "BlobModule: createFromParts references an invalid blob"); + } + bytes.insert(bytes.end(), data->begin(), data->end()); + } else { + throw jsi::JSError(rt, "BlobModule: invalid type for blob: " + type); + } + } + store_->store(withId, std::move(bytes)); +} + +void BlobModule::release(jsi::Runtime& /*rt*/, const std::string& blobId) { + store_->remove(blobId); +} + +void BlobModule::installJSIBindingsWithRuntime(jsi::Runtime& rt) { + auto global = rt.global(); + if (global.hasProperty(rt, kBlobCollectorProvider)) { + return; + } + auto name = jsi::PropNameID::forAscii(rt, kBlobCollectorProvider); + global.setProperty( + rt, + name, + jsi::Function::createFromHostFunction( + rt, + name, + 1, + [store = std::weak_ptr(store_)]( + jsi::Runtime& rt, + const jsi::Value& /*thisVal*/, + const jsi::Value* args, + size_t count) -> jsi::Value { + if (count < 1 || !args->isString()) { + throw jsi::JSError( + rt, "__blobCollectorProvider expects a blob id"); + } + return jsi::Object::createFromHostObject( + rt, + std::make_shared( + store, args->getString(rt).utf8(rt))); + })); +} + +BlobNetworkingResponseHandler::BlobNetworkingResponseHandler( + std::shared_ptr store) + : store_(std::move(store)) {} + +bool BlobNetworkingResponseHandler::supports( + const std::string& responseType) const { + return responseType == "blob"; +} + +jsi::Value BlobNetworkingResponseHandler::toResponseData( + jsi::Runtime& rt, + std::vector body) { + const auto size = static_cast(body.size()); + auto blobId = store_->store(std::move(body)); + try { + auto blobData = jsi::Object(rt); + blobData.setProperty(rt, "blobId", jsi::String::createFromUtf8(rt, blobId)); + blobData.setProperty(rt, "offset", 0); + blobData.setProperty(rt, "size", size); + return blobData; + } catch (...) { + store_->remove(blobId); + throw; + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/BlobModule.h b/packages/react-native/ReactCxxPlatform/react/io/BlobModule.h new file mode 100644 index 000000000000..6bc6080942fb --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/BlobModule.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +/// Returns the bytes referenced by a JS `BlobData` object +/// (`{blobId, offset, size}`), or `std::nullopt` if they are not stored. +std::optional> +resolveBlobData(facebook::jsi::Runtime &rt, const facebook::jsi::Object &blobData, const BlobStore &store); + +/// C++ implementation of React Native's `BlobModule` TurboModule (see +/// `Libraries/Blob/NativeBlobModule.js`). WebSocket blobs are not supported. +class BlobModule : public NativeBlobModuleCxxSpec, public TurboModuleWithJSIBindings { + public: + BlobModule(std::shared_ptr jsInvoker, std::shared_ptr store); + + facebook::jsi::Object getConstants(facebook::jsi::Runtime &rt); + void addNetworkingHandler(facebook::jsi::Runtime &rt); + [[noreturn]] void addWebSocketHandler(facebook::jsi::Runtime &rt, double id); + void removeWebSocketHandler(facebook::jsi::Runtime &rt, double id); + [[noreturn]] void sendOverSocket(facebook::jsi::Runtime &rt, facebook::jsi::Object blob, double socketID); + void createFromParts(facebook::jsi::Runtime &rt, facebook::jsi::Array parts, const std::string &withId); + void release(facebook::jsi::Runtime &rt, const std::string &blobId); + + private: + void installJSIBindingsWithRuntime(jsi::Runtime &rt) override; + + std::shared_ptr store_; +}; + +/// Stores `Networking` response bodies requested with responseType "blob" and +/// delivers them to JS as `BlobData`, as Android's `BlobModule` does. +class BlobNetworkingResponseHandler : public INetworkingResponseHandler { + public: + explicit BlobNetworkingResponseHandler(std::shared_ptr store); + + [[nodiscard]] bool supports(const std::string &responseType) const override; + facebook::jsi::Value toResponseData(facebook::jsi::Runtime &rt, std::vector body) override; + + private: + std::shared_ptr store_; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/BlobStore.cpp b/packages/react-native/ReactCxxPlatform/react/io/BlobStore.cpp new file mode 100644 index 000000000000..523dee2dfcb5 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/BlobStore.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "BlobStore.h" + +#include + +namespace facebook::react { + +std::string BlobStore::store(std::vector bytes) { + std::lock_guard lock(mutex_); + // JavaScript blob identifiers are UUIDs; this generated prefix is distinct. + auto blobId = "native-blob-" + std::to_string(nextId_++); + blobs_.insert_or_assign(blobId, std::move(bytes)); + return blobId; +} + +void BlobStore::store(const std::string& blobId, std::vector bytes) { + std::lock_guard lock(mutex_); + blobs_.insert_or_assign(blobId, std::move(bytes)); +} + +std::optional> BlobStore::resolve( + const std::string& blobId, + std::size_t offset, + std::size_t size) const { + std::lock_guard lock(mutex_); + auto it = blobs_.find(blobId); + if (it == blobs_.end()) { + return std::nullopt; + } + const auto& bytes = it->second; + if (offset > bytes.size() || size > bytes.size() - offset) { + return std::nullopt; + } + auto first = bytes.begin() + + static_cast::difference_type>(offset); + return std::vector( + first, first + static_cast::difference_type>(size)); +} + +void BlobStore::remove(const std::string& blobId) { + std::lock_guard lock(mutex_); + blobs_.erase(blobId); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/BlobStore.h b/packages/react-native/ReactCxxPlatform/react/io/BlobStore.h new file mode 100644 index 000000000000..4832d282947c --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/BlobStore.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +/// Thread-safe byte storage shared by BlobModule, FileReaderModule and +/// blob-aware Networking. Contents are undecoded byte vectors. +class BlobStore { + public: + /// Stores `bytes` under a newly generated id and returns that id. + std::string store(std::vector bytes); + void store(const std::string &blobId, std::vector bytes); + + /// Returns `size` bytes starting at `offset`, or `std::nullopt` when the id + /// is unknown or the range is out of bounds. + std::optional> resolve(const std::string &blobId, std::size_t offset, std::size_t size) const; + + void remove(const std::string &blobId); + + private: + mutable std::mutex mutex_; + std::unordered_map> blobs_; + uint64_t nextId_{0}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/CMakeLists.txt b/packages/react-native/ReactCxxPlatform/react/io/CMakeLists.txt index 42c589f05ce9..78a2d178a5e6 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/CMakeLists.txt +++ b/packages/react-native/ReactCxxPlatform/react/io/CMakeLists.txt @@ -14,6 +14,7 @@ add_library(react_cxx_platform_react_io OBJECT ${react_cxx_platform_react_io_SRC target_include_directories(react_cxx_platform_react_io PUBLIC ${REACT_CXX_PLATFORM_DIR}) target_link_libraries(react_cxx_platform_react_io + folly_runtime glog jsi react_cxx_platform_react_nativemodule diff --git a/packages/react-native/ReactCxxPlatform/react/io/FileReaderModule.cpp b/packages/react-native/ReactCxxPlatform/react/io/FileReaderModule.cpp new file mode 100644 index 000000000000..36626610c696 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/FileReaderModule.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "FileReaderModule.h" + +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +constexpr std::string_view kUtf8Bom = "\xEF\xBB\xBF"; +constexpr const char* kInvalidBlob = "The specified blob is invalid"; + +std::string_view asStringView(const std::vector& bytes) { + if (bytes.empty()) { + return std::string_view{""}; + } + // Character views may alias byte storage; the caller keeps the vector alive. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return {reinterpret_cast(bytes.data()), bytes.size()}; +} + +} // namespace + +/* static */ +std::string FileReaderModule::decodeUtf8(std::string_view bytes) { + if (bytes.starts_with(kUtf8Bom)) { + bytes.remove_prefix(kUtf8Bom.size()); + } + + if (bytes.empty()) { + return {}; + } + + std::string out; + out.reserve(bytes.size()); + // Unsigned character views may alias the input bytes for Folly's decoder. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + auto cursor = reinterpret_cast(bytes.data()); + // The one-past-end pointer stays within the non-empty input range. + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + auto end = cursor + bytes.size(); + while (cursor < end) { + folly::appendCodePointToUtf8( + folly::utf8ToCodePoint(cursor, end, /*skipOnError=*/true), out); + } + return out; +} + +FileReaderModule::FileReaderModule( + std::shared_ptr jsInvoker, + std::shared_ptr store) + : NativeFileReaderModuleCxxSpec(std::move(jsInvoker)), + store_(std::move(store)) {} + +AsyncPromise FileReaderModule::readAsDataURL( + jsi::Runtime& rt, + jsi::Object blob) { + AsyncPromise promise(rt, jsInvoker_); + auto bytes = resolveBlobData(rt, blob, *store_); + if (!bytes) { + promise.reject(Error(kInvalidBlob)); + return promise; + } + auto type = blob.getProperty(rt, "type"); + std::string mimeType = "application/octet-stream"; + if (type.isString()) { + if (auto value = type.getString(rt).utf8(rt); !value.empty()) { + mimeType = std::move(value); + } + } + auto view = asStringView(*bytes); + promise.resolve("data:" + mimeType + ";base64," + base64Encode(view)); + return promise; +} + +AsyncPromise FileReaderModule::readAsText( + jsi::Runtime& rt, + jsi::Object blob, + const std::string& /*encoding*/) { + AsyncPromise promise(rt, jsInvoker_); + auto bytes = resolveBlobData(rt, blob, *store_); + if (!bytes) { + promise.reject(Error(kInvalidBlob)); + return promise; + } + auto view = asStringView(*bytes); + promise.resolve(decodeUtf8(view)); + return promise; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/FileReaderModule.h b/packages/react-native/ReactCxxPlatform/react/io/FileReaderModule.h new file mode 100644 index 000000000000..f65acf17c95c --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/FileReaderModule.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +/// C++ implementation of React Native's `FileReaderModule` TurboModule (see +/// `Libraries/Blob/NativeFileReaderModule.js`), reading from `BlobStore`. +class FileReaderModule : public NativeFileReaderModuleCxxSpec { + public: + FileReaderModule(std::shared_ptr jsInvoker, std::shared_ptr store); + + /// Decodes bytes as UTF-8 with Folly, dropping a leading byte-order mark. + /// Invalid sequences advance one byte at a time and emit U+FFFD. + static std::string decodeUtf8(std::string_view bytes); + + AsyncPromise readAsDataURL(facebook::jsi::Runtime &rt, facebook::jsi::Object blob); + + /// Only UTF-8 is implemented; other labels also decode as UTF-8, the File + /// API's fallback for encodings a reader does not support. + AsyncPromise + readAsText(facebook::jsi::Runtime &rt, facebook::jsi::Object blob, const std::string &encoding); + + private: + std::shared_ptr store_; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.cpp b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.cpp index 0722d58d537f..6798fb439c87 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.cpp +++ b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.cpp @@ -109,8 +109,10 @@ bool Requests::isStopped() { NetworkingModule::NetworkingModule( std::shared_ptr jsInvoker, - const HttpClientFactory& httpClientFactory) - : NativeNetworkingAndroidCxxSpec(jsInvoker) { + const HttpClientFactory& httpClientFactory, + std::shared_ptr responseHandler) + : NativeNetworkingAndroidCxxSpec(jsInvoker), + responseHandler_(std::move(responseHandler)) { httpClient_ = httpClientFactory(); } @@ -299,6 +301,23 @@ void NetworkingModule::didReceiveNetworkData( return; } + if (responseHandler_ != nullptr && responseHandler_->supports(responseType)) { + emitDeviceEvent( + "didReceiveNetworkData", + [requestId, + body = buf->to>(), + responseHandler = responseHandler_]( + jsi::Runtime& rt, std::vector& args) mutable { + args.emplace_back( + rt, + jsi::Array::createWithElements( + rt, + static_cast(requestId), + responseHandler->toResponseData(rt, std::move(body)))); + }); + return; + } + auto responseData = encodeResponseBody(responseType, buf->toString()); emitDeviceEvent( "didReceiveNetworkData", diff --git a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h index 0d67e3b302de..f7035d3be336 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h @@ -9,9 +9,11 @@ #include #include +#include #include #include #include +#include namespace facebook::react { @@ -64,11 +66,27 @@ class Requests { std::atomic stopped_{false}; }; +// Converts a response body into the value delivered to JS for a responseType +// that NetworkingModule does not encode itself, e.g. "blob". Mirrors +// NetworkingModule.ResponseHandler on Android. +class INetworkingResponseHandler { + public: + virtual ~INetworkingResponseHandler() = default; + + virtual bool supports(const std::string &responseType) const = 0; + + // Called on the JavaScript thread with owned, undecoded response bytes. + virtual jsi::Value toResponseData(jsi::Runtime &rt, std::vector body) = 0; +}; + // Implementation of "Networking" TurboModule class NetworkingModule : public NativeNetworkingAndroidCxxSpec, public std::enable_shared_from_this { public: - NetworkingModule(std::shared_ptr jsInvoker, const HttpClientFactory &httpClientFactory); + NetworkingModule( + std::shared_ptr jsInvoker, + const HttpClientFactory &httpClientFactory, + std::shared_ptr responseHandler = nullptr); ~NetworkingModule() override; @@ -114,6 +132,7 @@ class NetworkingModule : public NativeNetworkingAndroidCxxSpec void didCompleteNetworkResponse(uint32_t requestId, const std::string &error, bool timeoutError); std::unique_ptr httpClient_; + std::shared_ptr responseHandler_; Requests requests_; }; diff --git a/packages/react-native/ReactCxxPlatform/react/io/README.md b/packages/react-native/ReactCxxPlatform/react/io/README.md new file mode 100644 index 000000000000..174061adf682 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/README.md @@ -0,0 +1,59 @@ +# C++ blob I/O + +`BlobModule`, `FileReaderModule`, and `BlobNetworkingResponseHandler` provide +in-memory blob storage and response-body reading for C++ hosts. + +## Registration + +Create one `BlobStore` per JavaScript runtime, and share it between the modules: + +```cpp +auto store = std::make_shared(); +auto blobModule = std::make_shared(jsInvoker, store); +auto fileReaderModule = std::make_shared(jsInvoker, store); +auto networkingModule = std::make_shared( + jsInvoker, + httpClientFactory, + std::make_shared(store)); +``` + +Register them under their normal module names through `TurboModuleBinding`. +`BlobModule` implements `TurboModuleWithJSIBindings`, which installs the +`__blobCollectorProvider` used by JavaScript `BlobManager` when the module is +bound. Do not install that global separately or share a store between runtimes. + +`addNetworkingHandler()` is a compatibility no-op: the response handler must be +provided when constructing `NetworkingModule`, as shown above. Networking +without a response handler retains its existing response representation. + +## Supported behaviour + +- `createFromParts` combines strings and stored blob slices; `release` removes + stored blobs. Blob descriptors use `{blobId, offset, size}` with byte offsets. +- Networking responses requested as `blob` are stored without text decoding and + delivered as blob descriptors. +- `readAsText` uses Folly's UTF-8 decoding and drops a leading UTF-8 byte-order + mark. Malformed sequences advance one byte at a time, producing U+FFFD for + each rejected byte. This intentionally differs from WHATWG maximal-subpart + replacement for truncated sequences. +- `readAsDataURL` produces base64 data URLs. React Native's JavaScript + `FileReader.readAsArrayBuffer` also uses this method. +- Offsets and sizes must be finite non-negative whole numbers with valid ranges. + Missing, released, or out-of-range blobs reject through the normal module + error path. + +The store uses `std::vector` for binary bytes. Networking copies the +`IOBuf` chain directly into this vector, which the response handler moves into +storage without an intermediate string. Embedded null bytes and non-UTF-8 bytes +are preserved. Text and base64 readers use temporary string views over owned +byte slices; only text decoding interprets the bytes as UTF-8. + +## Limits + +- Text decoding currently uses UTF-8 for every encoding label. Other character + sets are not implemented; this is not full encoding parity with the Android + and Apple modules. +- WebSocket blob registration and sending throw as unsupported. Ordinary + non-blob WebSocket operations are unaffected by these modules. +- This response handler does not add blob request-body encoding or a resolver + for `blob:` URLs. diff --git a/packages/react-native/ReactCxxPlatform/react/io/tests/BlobModuleTests.cpp b/packages/react-native/ReactCxxPlatform/react/io/tests/BlobModuleTests.cpp new file mode 100644 index 000000000000..598edd8fc29e --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/tests/BlobModuleTests.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { +namespace { + +class ThrowOnBlobSizeRuntime + : public jsi::RuntimeDecorator { + public: + explicit ThrowOnBlobSizeRuntime(jsi::Runtime& runtime) + : RuntimeDecorator(runtime) {} + + void setPropertyValue( + const jsi::Object& object, + const jsi::String& name, + const jsi::Value& value) override { + if (name.utf8(*this) == "size") { + blobId = object.getProperty(*this, "blobId").asString(*this).utf8(*this); + throw std::runtime_error("injected blob descriptor failure"); + } + RuntimeDecorator::setPropertyValue(object, name, value); + } + + std::string blobId; +}; + +class BlobModuleTest : public ::testing::Test { + protected: + void SetUp() override { + runtime_ = facebook::hermes::makeHermesRuntime(); + invoker_ = std::make_shared(*runtime_); + store_ = std::make_shared(); + auto module = std::make_shared(invoker_, store_); + TurboModuleWithJSIBindings::installJSIBindings(module, *runtime_); + runtime_->global().setProperty( + *runtime_, + "BlobModule", + jsi::Object::createFromHostObject(*runtime_, module)); + } + + void TearDown() override { + invoker_->flushQueue(); + LongLivedObjectCollection::get(*runtime_).clear(*runtime_); + invoker_ = nullptr; + runtime_ = nullptr; + } + + jsi::Value eval(const std::string& source) { + return runtime_->evaluateJavaScript( + std::make_shared(source), "blob-module-test.js"); + } + + std::shared_ptr runtime_; + std::shared_ptr invoker_; + std::shared_ptr store_; +}; + +} // namespace + +TEST_F(BlobModuleTest, CollectorBindingIsInstalledBeforeBlobMethods) { + EXPECT_TRUE(eval("typeof __blobCollectorProvider === 'function'").getBool()); +} + +TEST_F(BlobModuleTest, GetConstantsReturnsBlobScheme) { + EXPECT_EQ( + eval("BlobModule.getConstants().BLOB_URI_SCHEME") + .asString(*runtime_) + .utf8(*runtime_), + "blob"); + EXPECT_TRUE( + eval("BlobModule.getConstants().BLOB_URI_HOST === null").getBool()); +} + +TEST_F(BlobModuleTest, CreateFromPartsPreservesStringBytesAndSlices) { + eval(R"( + BlobModule.createFromParts([{type: 'string', data: 'café 日本語 😺'}], 'a'); + BlobModule.createFromParts( + [{type: 'string', data: '<'}, {type: 'blob', data: {blobId: 'a', offset: 6, size: 9}}, + {type: 'string', data: '>'}], 'b'); + )"); + const std::string expected = "<日本語>"; + EXPECT_EQ( + store_->resolve("b", 0, expected.size()), + std::optional>( + std::vector(expected.begin(), expected.end()))); +} + +TEST_F(BlobModuleTest, InvalidPartsRejectBeforeIndexConversion) { + eval("BlobModule.createFromParts([{type: 'string', data: 'abcd'}], 'n');"); + for (const auto* part : + {"{blobId: 'n', offset: NaN, size: 1}", + "{blobId: 'n', offset: 0, size: Infinity}", + "{blobId: 'n', offset: 0.5, size: 1}", + "{blobId: 'n', offset: 1e30, size: 1}"}) { + EXPECT_THROW( + eval( + "BlobModule.createFromParts([{type: 'blob', data: " + + std::string(part) + "}], 'x');"), + jsi::JSError); + } +} + +TEST_F(BlobModuleTest, ReleaseAndOutOfRangeSlicesAreInvalid) { + eval("BlobModule.createFromParts([{type: 'string', data: 'abc'}], 'r');"); + EXPECT_FALSE(store_->resolve("r", 1, 3).has_value()); + EXPECT_TRUE(store_->resolve("r", 3, 0).has_value()); + eval("BlobModule.release('r');"); + EXPECT_FALSE(store_->resolve("r", 0, 3).has_value()); +} + +TEST_F(BlobModuleTest, CollectedBlobIsReleased) { + eval(R"( + BlobModule.createFromParts([{type: 'string', data: 'abc'}], 'gc'); + (function () { __blobCollectorProvider('gc'); })(); + )"); + runtime_->instrumentation().collectGarbage("BlobModuleTest"); + EXPECT_FALSE(store_->resolve("gc", 0, 3).has_value()); +} + +TEST_F(BlobModuleTest, ResponseDescriptorFailureReleasesStoredBytes) { + auto throwingRuntime = ThrowOnBlobSizeRuntime(*runtime_); + auto handler = BlobNetworkingResponseHandler(store_); + const std::vector body{0, 255, 128}; + EXPECT_THROW( + handler.toResponseData(throwingRuntime, body), std::runtime_error); + ASSERT_FALSE(throwingRuntime.blobId.empty()); + EXPECT_FALSE( + store_->resolve(throwingRuntime.blobId, 0, body.size()).has_value()); + + auto response = handler.toResponseData(*runtime_, body).asObject(*runtime_); + auto blobId = response.getProperty(*runtime_, "blobId") + .asString(*runtime_) + .utf8(*runtime_); + EXPECT_EQ( + store_->resolve(blobId, 0, body.size()), + std::optional>(body)); +} + +TEST_F(BlobModuleTest, WebSocketBlobsAreUnsupported) { + EXPECT_THROW(eval("BlobModule.addWebSocketHandler(1);"), jsi::JSError); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/tests/FileReaderModuleTests.cpp b/packages/react-native/ReactCxxPlatform/react/io/tests/FileReaderModuleTests.cpp new file mode 100644 index 000000000000..132bf6ca572d --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/io/tests/FileReaderModuleTests.cpp @@ -0,0 +1,350 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +// UTF-8 text containing non-ASCII punctuation and emoji. +constexpr std::string_view kCaptionUtf8 = + "He\xE2\x80\x99s my coworker now \xF0\x9F\x98\xBA #cat \xF0\x9F\x98\x8D\xF0\x9F\x98\x82"; +constexpr std::string_view kCaptionJsLiteral = + R"("He’s my coworker now 😺 #cat 😍😂")"; + +class FakeHttpClient : public IHttpClient { + public: + explicit FakeHttpClient(std::shared_ptr responseBody) + : responseBody_(std::move(responseBody)) {} + + std::unique_ptr sendRequest( + http::NetworkCallbacks&& callbacks, + const std::string& /*method*/, + const std::string& /*url*/, + const http::Headers& /*headers*/, + const http::Body& /*body*/, + uint32_t /*timeout*/, + std::optional /*loggingId*/) override { + callbacks.onResponse( + 200, {{"content-type", "application/json; charset=utf-8"}}); + callbacks.onBody(folly::IOBuf::copyBuffer(*responseBody_)); + callbacks.onResponseComplete("", false); + return nullptr; + } + + private: + std::shared_ptr responseBody_; +}; + +class FileReaderTest : public ::testing::Test { + protected: + void SetUp() override { + runtime_ = facebook::hermes::makeHermesRuntime(); + jsInvoker_ = std::make_shared(*runtime_); + responseBody_ = std::make_shared(); + // Hermes' Promise implementation schedules reactions with setImmediate. + auto setImmediateName = + jsi::PropNameID::forAscii(*runtime_, "setImmediate"); + runtime_->global().setProperty( + *runtime_, + setImmediateName, + jsi::Function::createFromHostFunction( + *runtime_, + setImmediateName, + 1, + [jsInvoker = jsInvoker_]( + jsi::Runtime& rt, + const jsi::Value& /*thisVal*/, + const jsi::Value* args, + size_t /*count*/) { + jsInvoker->invokeAsync([callback = std::make_shared( + rt, *args)](jsi::Runtime& rt) { + callback->asObject(rt).asFunction(rt).call(rt); + }); + return jsi::Value::undefined(); + })); + auto store = std::make_shared(); + registerModule( + "BlobModule", std::make_shared(jsInvoker_, store)); + registerModule( + "FileReaderModule", + std::make_shared(jsInvoker_, store)); + registerModule( + "Networking", + std::make_shared( + jsInvoker_, + [body = responseBody_]() { + return std::make_unique(body); + }, + std::make_shared(store))); + eval(R"( + var events = []; + globalThis.__rctDeviceEventEmitter = { + emit: function (name, payload) { events.push([name, payload]); }, + }; + function settle(promise) { + var state = {}; + promise.then( + function (value) { state.value = value; }, + function (error) { state.error = error.message; }); + return state; + } + )"); + } + + void TearDown() override { + jsInvoker_->flushQueue(); + LongLivedObjectCollection::get(*runtime_).clear(*runtime_); + jsInvoker_ = nullptr; + runtime_ = nullptr; + } + + jsi::Value eval(const std::string& js) { + auto result = runtime_->evaluateJavaScript( + std::make_shared(js), "FileReaderTest.js"); + jsInvoker_->flushQueue(); + return result; + } + + std::string evalString(const std::string& js) { + return eval(js).asString(*runtime_).utf8(*runtime_); + } + + bool evalBool(const std::string& js) { + return eval(js).getBool(); + } + + void registerModule(const char* name, std::shared_ptr module) { + TurboModuleWithJSIBindings::installJSIBindings(module, *runtime_); + runtime_->global().setProperty( + *runtime_, name, jsi::Object::createFromHostObject(*runtime_, module)); + } + + std::shared_ptr runtime_; + std::shared_ptr jsInvoker_; + std::shared_ptr responseBody_; +}; + +} // namespace + +TEST_F(FileReaderTest, StoresAreIndependent) { + eval( + "BlobModule.createFromParts([{type: 'string', data: 'abc'}], 'shared-id');"); + auto otherReader = std::make_shared( + jsInvoker_, std::make_shared()); + runtime_->global().setProperty( + *runtime_, + "otherReader", + jsi::Object::createFromHostObject(*runtime_, otherReader)); + eval(R"( + var descriptor = {blobId: 'shared-id', offset: 0, size: 3}; + var original = settle(FileReaderModule.readAsText(descriptor, 'utf-8')); + var other = settle(otherReader.readAsText(descriptor, 'utf-8')); + )"); + EXPECT_EQ(evalString("original.value"), "abc"); + EXPECT_EQ(evalString("other.error"), "The specified blob is invalid"); +} + +// The read path of `fetch(...).then(r => r.text())` once BlobModule exists: +// whatwg-fetch sets responseType 'blob', XMLHttpRequest wraps the native +// BlobData in a Blob, and `text()` calls FileReader.readAsText(blob, 'utf-8'). +TEST_F(FileReaderTest, BlobResponseReadAsTextDecodesUtf8) { + *responseBody_ = R"({"text":")" + std::string(kCaptionUtf8) + R"("})"; + eval(R"( + BlobModule.addNetworkingHandler(); + Networking.sendRequest( + 'POST', 'https://example.com/text', 1, + [['Content-Type', 'application/x-www-form-urlencoded']], + {string: 'message=hello'}, 'blob', false, 0, false); + )"); + eval(R"( + var data = events.filter(function (e) { return e[0] === 'didReceiveNetworkData'; })[0][1]; + var blob = data[1]; + var read = settle(FileReaderModule.readAsText(blob, 'utf-8')); + )"); + EXPECT_TRUE(evalBool("data[0] === 1 && typeof blob === 'object'")); + EXPECT_TRUE(evalBool( + "blob.offset === 0 && blob.size === " + + std::to_string(responseBody_->size()))); + EXPECT_TRUE(evalBool("read.error === undefined")); + EXPECT_TRUE(evalBool( + "JSON.parse(read.value).text === " + std::string(kCaptionJsLiteral))); + EXPECT_EQ(evalString("JSON.parse(read.value).text"), kCaptionUtf8); + EXPECT_TRUE(evalBool( + "events.some(function (e) { return e[0] === 'didCompleteNetworkResponse'; })")); +} + +TEST_F(FileReaderTest, BinaryResponsePreservesNullAndHighBytes) { + *responseBody_ = std::string("\0\xFF\x80\0", 4); + eval(R"( + Networking.sendRequest('GET', 'https://example.com/binary', 3, [], {}, 'blob', false, 0, false); + )"); + eval(R"( + var data = events.filter(function (e) { return e[0] === 'didReceiveNetworkData'; })[0][1][1]; + var whole = settle(FileReaderModule.readAsDataURL(data)); + BlobModule.createFromParts( + [{type: 'blob', data: {blobId: data.blobId, offset: 1, size: 2}}], 'binary-slice'); + var slice = settle(FileReaderModule.readAsDataURL( + {blobId: 'binary-slice', offset: 0, size: 2})); + )"); + EXPECT_EQ( + evalString("whole.value"), + "data:application/octet-stream;base64,AP+AAA=="); + EXPECT_EQ( + evalString("slice.value"), "data:application/octet-stream;base64,/4A="); + EXPECT_EQ(eval("data.size").getNumber(), 4); +} + +TEST_F(FileReaderTest, EmptyBlobReadsAsTextAndDataUrl) { + eval(R"( + BlobModule.createFromParts([], 'empty'); + var descriptor = {blobId: 'empty', offset: 0, size: 0}; + var text = settle(FileReaderModule.readAsText(descriptor, 'utf-8')); + var url = settle(FileReaderModule.readAsDataURL(descriptor)); + )"); + EXPECT_EQ(evalString("text.value"), ""); + EXPECT_EQ(evalString("url.value"), "data:application/octet-stream;base64,"); +} + +TEST_F(FileReaderTest, TextResponseTypeIsUnchanged) { + *responseBody_ = std::string(kCaptionUtf8); + eval(R"( + Networking.sendRequest('GET', 'https://example.com', 2, [], {}, 'text', false, 0, false); + )"); + eval(R"( + var text = events.filter(function (e) { return e[0] === 'didReceiveNetworkData'; })[0][1][1]; + )"); + EXPECT_TRUE(evalBool("typeof text === 'string'")); + EXPECT_EQ(evalString("text"), kCaptionUtf8); +} + +TEST_F(FileReaderTest, CreateFromPartsRoundTripsStringsAndBlobSlices) { + eval(R"( + BlobModule.createFromParts([{type: 'string', data: 'café 日本語 😺'}], 'a'); + // 'café ' is 6 bytes and '日本語' is 9: slice the CJK out of blob 'a'. + BlobModule.createFromParts( + [{type: 'string', data: '<'}, {type: 'blob', data: {blobId: 'a', offset: 6, size: 9}}, + {type: 'string', data: '>'}], + 'b'); + var whole = settle(FileReaderModule.readAsText({blobId: 'a', offset: 0, size: 20}, 'UTF-8')); + var slice = settle(FileReaderModule.readAsText({blobId: 'b', offset: 0, size: 11}, 'utf-8')); + )"); + EXPECT_TRUE(evalBool( + "whole.value === 'caf\\u00e9 \\u65e5\\u672c\\u8a9e \\ud83d\\ude3a'")); + EXPECT_TRUE(evalBool("slice.value === '<\\u65e5\\u672c\\u8a9e>'")); +} + +TEST_F(FileReaderTest, ReadAsDataUrlEncodesBase64WithType) { + eval(R"( + BlobModule.createFromParts([{type: 'string', data: '😺'}], 'cat'); + var typed = settle(FileReaderModule.readAsDataURL( + {blobId: 'cat', offset: 0, size: 4, type: 'text/plain'})); + var untyped = settle(FileReaderModule.readAsDataURL({blobId: 'cat', offset: 0, size: 4})); + )"); + EXPECT_EQ(evalString("typed.value"), "data:text/plain;base64,8J+Yug=="); + EXPECT_EQ( + evalString("untyped.value"), + "data:application/octet-stream;base64,8J+Yug=="); +} + +TEST_F(FileReaderTest, ReleasedAndOutOfRangeBlobsReject) { + eval(R"( + BlobModule.createFromParts([{type: 'string', data: 'abc'}], 'r'); + var outOfRange = settle(FileReaderModule.readAsText({blobId: 'r', offset: 1, size: 3}, 'utf-8')); + BlobModule.release('r'); + var released = settle(FileReaderModule.readAsText({blobId: 'r', offset: 0, size: 3}, 'utf-8')); + )"); + EXPECT_EQ(evalString("outOfRange.error"), "The specified blob is invalid"); + EXPECT_EQ(evalString("released.error"), "The specified blob is invalid"); +} + +TEST_F(FileReaderTest, NonIndexOffsetsAndSizesReject) { + eval(R"( + BlobModule.createFromParts([{type: 'string', data: 'abcd'}], 'n'); + function read(offset, size) { + return settle(FileReaderModule.readAsText({blobId: 'n', offset: offset, size: size}, 'utf-8')); + } + var bad = [ + [NaN, 1], [0, NaN], [Infinity, 1], [0, Infinity], [1.5, 1], [0, 1.5], + [-1, 1], [0, -1], [-0.5, 1], [1e30, 1], [0, 1e30], [5, 0], [0, 5], + [Math.pow(2, 64), 1], [0, Math.pow(2, 64)], + ].map(function (args) { return read(args[0], args[1]); }); + var valid = read(1, 2); + var empty = read(4, 0); + )"); + EXPECT_EQ(eval("bad.length").getNumber(), 15); + EXPECT_TRUE(evalBool( + "bad.every(function (r) { return r.error === 'The specified blob is invalid'; })")); + EXPECT_EQ(evalString("valid.value"), "bc"); + EXPECT_EQ(evalString("empty.value"), ""); + for (const auto* part : + {"{blobId: 'n', offset: NaN, size: 1}", + "{blobId: 'n', offset: 0, size: Infinity}", + "{blobId: 'n', offset: 0.5, size: 1}", + "{blobId: 'n', offset: 1e30, size: 1}"}) { + EXPECT_THROW( + eval( + "BlobModule.createFromParts([{type: 'blob', data: " + + std::string(part) + "}], 'x');"), + jsi::JSError) + << part; + } +} + +TEST(DecodeUtf8Test, KeepsValidUtf8) { + EXPECT_EQ(FileReaderModule::decodeUtf8(kCaptionUtf8), kCaptionUtf8); + EXPECT_EQ( + FileReaderModule::decodeUtf8( + "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E \xED\x95\x9C\xEA\xB8\x80"), + "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E \xED\x95\x9C\xEA\xB8\x80"); + EXPECT_EQ(FileReaderModule::decodeUtf8(std::string_view{}), ""); + EXPECT_EQ(FileReaderModule::decodeUtf8(""), ""); +} + +TEST(DecodeUtf8Test, StripsLeadingBom) { + EXPECT_EQ(FileReaderModule::decodeUtf8("\xEF\xBB\xBF"), ""); + EXPECT_EQ(FileReaderModule::decodeUtf8("\xEF\xBB\xBF{}"), "{}"); + EXPECT_EQ(FileReaderModule::decodeUtf8("a\xEF\xBB\xBF"), "a\xEF\xBB\xBF"); +} + +TEST(DecodeUtf8Test, ReplacesInvalidSequencesWithReplacementCharacter) { + constexpr std::string_view kFffd = "\xEF\xBF\xBD"; + const std::string fffd(kFffd); + // Lone continuation byte, and bytes that never appear in UTF-8. + EXPECT_EQ(FileReaderModule::decodeUtf8("a\x80z"), "a" + fffd + "z"); + EXPECT_EQ(FileReaderModule::decodeUtf8("\xFF\xFE"), fffd + fffd); + // A lead byte followed by ASCII: the ASCII byte is kept. + EXPECT_EQ(FileReaderModule::decodeUtf8("\xC3("), fffd + "("); + // Folly advances one byte on an error, including truncated sequences. + EXPECT_EQ(FileReaderModule::decodeUtf8("\xE2\x80"), fffd + fffd); + EXPECT_EQ( + FileReaderModule::decodeUtf8(std::string("\xF0\x9F\x98") + "A"), + fffd + fffd + fffd + "A"); + // Overlong encodings, UTF-16 surrogates and code points above U+10FFFF. + EXPECT_EQ(FileReaderModule::decodeUtf8("\xC0\xAF"), fffd + fffd); + EXPECT_EQ(FileReaderModule::decodeUtf8("\xE0\x80\xAF"), fffd + fffd + fffd); + EXPECT_EQ(FileReaderModule::decodeUtf8("\xED\xA0\x80"), fffd + fffd + fffd); + EXPECT_EQ( + FileReaderModule::decodeUtf8("\xF4\x90\x80\x80"), + fffd + fffd + fffd + fffd); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp b/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp index 640b0904aa84..1cecf18910f7 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp +++ b/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp @@ -21,6 +21,67 @@ namespace facebook::react { +namespace { + +class FakeHttpClient : public IHttpClient { + public: + explicit FakeHttpClient(std::string body = "body bytes") + : body_(std::move(body)) {} + + std::unique_ptr sendRequest( + http::NetworkCallbacks&& callbacks, + const std::string& /*method*/, + const std::string& /*url*/, + const http::Headers& /*headers*/, + const http::Body& /*body*/, + uint32_t /*timeout*/, + std::optional /*loggingId*/) override { + auto body = folly::IOBuf::copyBuffer(body_.substr(0, body_.size() / 2)); + body->appendToChain( + folly::IOBuf::copyBuffer(body_.substr(body_.size() / 2))); + callbacks.onBody(std::move(body)); + callbacks.onResponseComplete("", false); + return nullptr; + } + + private: + std::string body_; +}; + +class FakeResponseHandler : public INetworkingResponseHandler { + public: + bool supports(const std::string& responseType) const override { + return responseType == "blob"; + } + + jsi::Value toResponseData(jsi::Runtime& rt, std::vector body) + override { + auto data = jsi::Object(rt); + data.setProperty( + rt, + "handled", + jsi::String::createFromUtf8(rt, std::string(body.begin(), body.end()))); + return data; + } +}; + +class RecordingResponseHandler : public INetworkingResponseHandler { + public: + bool supports(const std::string& responseType) const override { + return responseType == "blob"; + } + + jsi::Value toResponseData(jsi::Runtime& /*rt*/, std::vector body) + override { + bytes = std::move(body); + return static_cast(bytes.size()); + } + + std::vector bytes; +}; + +} // namespace + class NetworkingModuleTests : public testing::Test { protected: void SetUp() override { @@ -90,6 +151,80 @@ TEST_F(NetworkingModuleTests, formDataTest) { "form-data; name=\"header2\""}); } +// A response handler replaces the body delivered for the response types it +// supports and leaves every other response type alone. +TEST_F(NetworkingModuleTests, responseHandlerTest) { + auto module = std::make_shared( + jsInvoker_, + []() { return std::make_unique(); }, + std::make_shared()); + rt_->evaluateJavaScript( + std::make_shared(R"( + var data = {}; + globalThis.__rctDeviceEventEmitter = { + emit: function (name, payload) { + if (name === 'didReceiveNetworkData') { data[payload[0]] = payload[1]; } + }, + }; + )"), + "responseHandlerTest.js"); + + module->sendRequest( + *rt_, "GET", "https://example.com", 1, {}, {}, "blob", false, 0, false); + module->sendRequest( + *rt_, "GET", "https://example.com", 2, {}, {}, "text", false, 0, false); + std::static_pointer_cast(jsInvoker_)->flushQueue(); + + auto data = rt_->global().getPropertyAsObject(*rt_, "data"); + auto blob = data.getProperty(*rt_, "1"); + ASSERT_TRUE(blob.isObject()); + EXPECT_EQ( + blob.asObject(*rt_) + .getProperty(*rt_, "handled") + .asString(*rt_) + .utf8(*rt_), + "body bytes"); + auto text = data.getProperty(*rt_, "2"); + ASSERT_TRUE(text.isString()); + EXPECT_EQ(text.asString(*rt_).utf8(*rt_), "body bytes"); +} + +TEST_F(NetworkingModuleTests, responseHandlerPreservesBinaryChainBytes) { + auto handler = std::make_shared(); + auto module = std::make_shared( + jsInvoker_, + []() { + return std::make_unique(std::string("\0\xFF\x80\0", 4)); + }, + handler); + rt_->evaluateJavaScript( + std::make_shared(R"( + var received; + globalThis.__rctDeviceEventEmitter = { + emit: function (name, payload) { + if (name === 'didReceiveNetworkData') { received = payload[1]; } + }, + }; + )"), + "binaryResponseHandlerTest.js"); + module->sendRequest( + *rt_, + "GET", + "https://example.com/binary", + 1, + {}, + {}, + "blob", + false, + 0, + false); + std::static_pointer_cast(jsInvoker_)->flushQueue(); + const std::vector expected{0, 255, 128, 0}; + EXPECT_EQ(handler->bytes, expected); + EXPECT_EQ( + rt_->global().getProperty(*rt_, "received").getNumber(), expected.size()); +} + // Test parsing a body with string data TEST_F(NetworkingModuleTests, stringDataTest) { auto dynamic = folly::parseJson(