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_0MethodCall.h"
9 
10 #include <folly/json.h>
11 #include <stdexcept>
12 
13 namespace ABI48_0_0facebook {
14 namespace ABI48_0_0React {
15 
16 #define REQUEST_MODULE_IDS 0
17 #define REQUEST_METHOD_IDS 1
18 #define REQUEST_PARAMSS 2
19 #define REQUEST_CALLID 3
20 
21 static const char *errorPrefix = "Malformed calls from JS: ";
22 
parseMethodCalls(folly::dynamic && jsonData)23 std::vector<MethodCall> parseMethodCalls(folly::dynamic &&jsonData) {
24   if (jsonData.isNull()) {
25     return {};
26   }
27 
28   if (!jsonData.isArray()) {
29     throw std::invalid_argument(folly::to<std::string>(
30         errorPrefix, "input isn't array but ", jsonData.typeName()));
31   }
32 
33   if (jsonData.size() < REQUEST_PARAMSS + 1) {
34     throw std::invalid_argument(
35         folly::to<std::string>(errorPrefix, "size == ", jsonData.size()));
36   }
37 
38   auto &moduleIds = jsonData[REQUEST_MODULE_IDS];
39   auto &methodIds = jsonData[REQUEST_METHOD_IDS];
40   auto &params = jsonData[REQUEST_PARAMSS];
41   int callId = -1;
42 
43   if (!moduleIds.isArray() || !methodIds.isArray() || !params.isArray()) {
44     throw std::invalid_argument(folly::to<std::string>(
45         errorPrefix,
46         "not all fields are arrays.\n\n",
47         folly::toJson(jsonData)));
48   }
49 
50   if (moduleIds.size() != methodIds.size() ||
51       moduleIds.size() != params.size()) {
52     throw std::invalid_argument(folly::to<std::string>(
53         errorPrefix,
54         "field sizes are different.\n\n",
55         folly::toJson(jsonData)));
56   }
57 
58   if (jsonData.size() > REQUEST_CALLID) {
59     if (!jsonData[REQUEST_CALLID].isNumber()) {
60       throw std::invalid_argument(folly::to<std::string>(
61           errorPrefix, "invalid callId", jsonData[REQUEST_CALLID].typeName()));
62     }
63     callId = (int)jsonData[REQUEST_CALLID].asInt();
64   }
65 
66   std::vector<MethodCall> methodCalls;
67   for (size_t i = 0; i < moduleIds.size(); i++) {
68     if (!params[i].isArray()) {
69       throw std::invalid_argument(folly::to<std::string>(
70           errorPrefix,
71           "method arguments isn't array but ",
72           params[i].typeName()));
73     }
74 
75     methodCalls.emplace_back(
76         static_cast<int>(moduleIds[i].asInt()),
77         static_cast<int>(methodIds[i].asInt()),
78         std::move(params[i]),
79         callId);
80 
81     // only increment callid if contains valid callid as callid is optional
82     callId += (callId != -1) ? 1 : 0;
83   }
84 
85   return methodCalls;
86 }
87 
88 } // namespace ABI48_0_0React
89 } // namespace ABI48_0_0facebook
90