1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8 #include "ABI48_0_0RAMBundleRegistry.h"
9
10 #include <folly/String.h>
11
12 #include <memory>
13
14 namespace ABI48_0_0facebook {
15 namespace ABI48_0_0React {
16
17 constexpr uint32_t RAMBundleRegistry::MAIN_BUNDLE_ID;
18
singleBundleRegistry(std::unique_ptr<JSModulesUnbundle> mainBundle)19 std::unique_ptr<RAMBundleRegistry> RAMBundleRegistry::singleBundleRegistry(
20 std::unique_ptr<JSModulesUnbundle> mainBundle) {
21 return std::make_unique<RAMBundleRegistry>(std::move(mainBundle));
22 }
23
multipleBundlesRegistry(std::unique_ptr<JSModulesUnbundle> mainBundle,std::function<std::unique_ptr<JSModulesUnbundle> (std::string)> factory)24 std::unique_ptr<RAMBundleRegistry> RAMBundleRegistry::multipleBundlesRegistry(
25 std::unique_ptr<JSModulesUnbundle> mainBundle,
26 std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> factory) {
27 return std::make_unique<RAMBundleRegistry>(
28 std::move(mainBundle), std::move(factory));
29 }
30
RAMBundleRegistry(std::unique_ptr<JSModulesUnbundle> mainBundle,std::function<std::unique_ptr<JSModulesUnbundle> (std::string)> factory)31 RAMBundleRegistry::RAMBundleRegistry(
32 std::unique_ptr<JSModulesUnbundle> mainBundle,
33 std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> factory)
34 : m_factory(std::move(factory)) {
35 m_bundles.emplace(MAIN_BUNDLE_ID, std::move(mainBundle));
36 }
37
registerBundle(uint32_t bundleId,std::string bundlePath)38 void RAMBundleRegistry::registerBundle(
39 uint32_t bundleId,
40 std::string bundlePath) {
41 m_bundlePaths.emplace(bundleId, std::move(bundlePath));
42 }
43
getModule(uint32_t bundleId,uint32_t moduleId)44 JSModulesUnbundle::Module RAMBundleRegistry::getModule(
45 uint32_t bundleId,
46 uint32_t moduleId) {
47 if (m_bundles.find(bundleId) == m_bundles.end()) {
48 if (!m_factory) {
49 throw std::runtime_error(
50 "You need to register factory function in order to "
51 "support multiple RAM bundles.");
52 }
53
54 auto bundlePath = m_bundlePaths.find(bundleId);
55 if (bundlePath == m_bundlePaths.end()) {
56 throw std::runtime_error(
57 "In order to fetch RAM bundle from the registry, its file "
58 "path needs to be registered first.");
59 }
60 m_bundles.emplace(bundleId, m_factory(bundlePath->second));
61 }
62
63 auto module = getBundle(bundleId)->getModule(moduleId);
64 if (bundleId == MAIN_BUNDLE_ID) {
65 return module;
66 }
67 return {
68 folly::to<std::string>("seg-", bundleId, '_', std::move(module.name)),
69 std::move(module.code),
70 };
71 }
72
getBundle(uint32_t bundleId) const73 JSModulesUnbundle *RAMBundleRegistry::getBundle(uint32_t bundleId) const {
74 return m_bundles.at(bundleId).get();
75 }
76
77 } // namespace ABI48_0_0React
78 } // namespace ABI48_0_0facebook
79