1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "console.h"
16 
17 #include <chrono>
18 #include <vector>
19 #include "log.h"
20 
21 namespace OHOS::JsSysModule {
22 using namespace Commonlibrary::Concurrent::Common;
23 
24 thread_local std::map<std::string, int64_t> Console::timerMap;
25 thread_local std::map<std::string, uint32_t> Console::counterMap;
26 thread_local std::string Console::groupIndent;
27 constexpr size_t GROUPINDETATIONWIDTH = 2; // 2 : indentation
28 constexpr uint32_t SECOND = 1000;
29 constexpr uint32_t MINUTE = 60 * SECOND;
30 constexpr uint32_t HOUR = 60 * MINUTE;
31 
32 std::map<std::string, std::string> tableChars = {
33     {"middleMiddle", "─"},
34     {"rowMiddle", "┼"},
35     {"topRight", "┐"},
36     {"topLeft", "┌"},
37     {"leftMiddle", "├"},
38     {"topMiddle", "┬"},
39     {"bottomRight", "┘"},
40     {"bottomLeft", "└"},
41     {"bottomMiddle", "┴"},
42     {"rightMiddle", "┤"},
43     {"left", "│ "},
44     {"right", " │"},
45     {"middle", " │ "},
46 };
47 
LogPrint(LogLevel level,const char * content)48 void Console::LogPrint(LogLevel level, const char* content)
49 {
50     switch (level) {
51         case LogLevel::DEBUG:
52             HILOG_DEBUG("%{public}s", content);
53             break;
54         case LogLevel::INFO:
55             HILOG_INFO("%{public}s", content);
56             break;
57         case LogLevel::WARN:
58             HILOG_WARN("%{public}s", content);
59             break;
60         case LogLevel::ERROR:
61             HILOG_ERROR("%{public}s", content);
62             break;
63         case LogLevel::FATAL:
64             HILOG_FATAL("%{public}s", content);
65             break;
66         default:
67             HILOG_FATAL("Console::LogPrint: this branch is unreachable");
68     }
69 }
70 
ParseLogContent(const std::vector<std::string> & params)71 std::string Console::ParseLogContent(const std::vector<std::string>& params)
72 {
73     std::string ret;
74     if (params.empty()) {
75         return ret;
76     }
77     std::string formatStr = params[0];
78     size_t size = params.size();
79     size_t len = formatStr.size();
80     size_t pos = 0;
81     size_t count = 1;
82     for (; pos < len; ++pos) {
83         if (count >= size) {
84             break;
85         }
86         if (formatStr[pos] == '%') {
87             if (pos + 1 >= len) {
88                 break;
89             }
90             switch (formatStr[pos + 1]) {
91                 case 's':
92                 case 'j':
93                 case 'd':
94                 case 'O':
95                 case 'o':
96                 case 'i':
97                 case 'f':
98                 case 'c':
99                     ret += params[count++];
100                     ++pos;
101                     break;
102                 case '%':
103                     ret += formatStr[pos];
104                     ++pos;
105                     break;
106                 default:
107                     ret += formatStr[pos];
108                     break;
109             }
110         } else {
111             ret += formatStr[pos];
112         }
113     }
114     if (pos < len) {
115         ret += formatStr.substr(pos, len - pos);
116     }
117     for (; count < size; ++count) {
118         ret += " ";
119         ret += params[count];
120     }
121     return ret;
122 }
123 
MakeLogContent(napi_env env,napi_callback_info info,size_t & argc,size_t startIdx,bool format)124 std::string Console::MakeLogContent(napi_env env, napi_callback_info info, size_t& argc, size_t startIdx, bool format)
125 {
126     std::vector<std::string> content;
127     content.reserve(argc);
128     // get argv
129     napi_value* argv = new napi_value[argc];
130     Helper::ObjectScope<napi_value> scope(argv, true);
131     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
132 
133     for (size_t i = startIdx; i < argc; i++) {
134         if (!Helper::NapiHelper::IsString(env, argv[i])) {
135             napi_value buffer;
136             napi_status status = napi_coerce_to_string(env, argv[i], &buffer);
137             if (status != napi_ok) {
138                 HILOG_ERROR("Console log failed to convert to string object");
139                 continue;
140             }
141             argv[i] = buffer;
142         }
143         std::string stringValue = Helper::NapiHelper::GetPrintString(env, argv[i]);
144         if (stringValue.empty()) {
145             continue;
146         }
147         content.emplace_back(stringValue);
148     }
149     if (format) {
150         return ParseLogContent(content);
151     } else {
152         std::string ret;
153         size_t size = content.size();
154         for (size_t i = 0; i < size; ++i) {
155             ret += " ";
156             ret += content[i];
157         }
158         return ret;
159     }
160 }
161 
StringRepeat(size_t number,const std::string & tableChars)162 std::string Console::StringRepeat(size_t number, const std::string& tableChars)
163 {
164     std::string divider;
165     size_t length = number;
166     for (size_t i = 0; i < length; i++) {
167         divider += tableChars;
168     }
169     return divider;
170 }
171 
172 
173 template<LogLevel LEVEL>
ConsoleLog(napi_env env,napi_callback_info info)174 napi_value Console::ConsoleLog(napi_env env, napi_callback_info info)
175 {
176     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
177     if (argc < 1) {
178         return Helper::NapiHelper::GetUndefinedValue(env);
179     }
180     std::string content;
181     content += groupIndent;
182     content += MakeLogContent(env, info, argc, 0); // startInx = 0
183     LogPrint(LEVEL, content.c_str());
184     return Helper::NapiHelper::GetUndefinedValue(env);
185 }
186 
GetTimerOrCounterName(napi_env env,napi_callback_info info,size_t argc)187 std::string Console::GetTimerOrCounterName(napi_env env, napi_callback_info info, size_t argc)
188 {
189     if (argc < 1) {
190         return "default";
191     }
192     napi_value* argv = new napi_value[argc];
193     Helper::ObjectScope<napi_value> scope(argv, true);
194     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
195     if (!Helper::NapiHelper::IsString(env, argv[0])) {
196         napi_value buffer = nullptr;
197         napi_status status = napi_coerce_to_string(env, argv[0], &buffer);
198         if (status != napi_ok) {
199             Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
200                 "the type of Timer or Counter name must be string.");
201             return "";
202         }
203         argv[0] = buffer;
204     }
205     std::string name = Helper::NapiHelper::GetPrintString(env, argv[0]);
206     if (name.empty()) {
207         Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
208                                         "Timer or Counter name must be not null.");
209         return "";
210     }
211     return name;
212 }
213 
Count(napi_env env,napi_callback_info info)214 napi_value Console::Count(napi_env env, napi_callback_info info)
215 {
216     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
217     std::string counterName = GetTimerOrCounterName(env, info, argc);
218     counterMap[counterName]++;
219     HILOG_INFO("%{public}s%{public}s: %{public}d",
220                groupIndent.c_str(), counterName.c_str(), counterMap[counterName]);
221     return Helper::NapiHelper::GetUndefinedValue(env);
222 }
223 
CountReset(napi_env env,napi_callback_info info)224 napi_value Console::CountReset(napi_env env, napi_callback_info info)
225 {
226     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
227     std::string counterName = GetTimerOrCounterName(env, info, argc);
228     if (counterMap.find(counterName) == counterMap.end()) {
229         HILOG_WARN("%{public}sCounter %{public}s doesn't exists, please check Counter Name.",
230                    groupIndent.c_str(), counterName.c_str());
231         return Helper::NapiHelper::GetUndefinedValue(env);
232     }
233     counterMap.erase(counterName);
234     return Helper::NapiHelper::GetUndefinedValue(env);
235 }
236 
Dir(napi_env env,napi_callback_info info)237 napi_value Console::Dir(napi_env env, napi_callback_info info)
238 {
239     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
240     if (argc < 1) {
241         HILOG_INFO("%{public}sundefined", groupIndent.c_str());
242         return Helper::NapiHelper::GetUndefinedValue(env);
243     }
244     napi_value* argv = new napi_value[argc];
245     Helper::ObjectScope<napi_value> scope(argv, true);
246     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
247     std::string ctorVal = Helper::NapiHelper::GetConstructorName(env, argv[0]);
248     // JSON.stringify()
249     napi_value globalValue = nullptr;
250     napi_get_global(env, &globalValue);
251     napi_value jsonValue;
252     napi_get_named_property(env, globalValue, "JSON", &jsonValue);
253     napi_value stringifyValue = nullptr;
254     napi_get_named_property(env, jsonValue, "stringify", &stringifyValue);
255     napi_value transValue = nullptr;
256     napi_call_function(env, jsonValue, stringifyValue, 1, &argv[0], &transValue);
257     if (transValue == nullptr) {
258         Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR, "Dir content must not be null.");
259         return Helper::NapiHelper::GetUndefinedValue(env);
260     }
261     std::string content = Helper::NapiHelper::GetPrintString(env, transValue);
262     bool functionFlag = Helper::NapiHelper::IsFunction(env, argv[0]);
263     if (!ctorVal.empty() && !functionFlag) {
264         HILOG_INFO("%{public}s%{public}s: %{public}s", groupIndent.c_str(), ctorVal.c_str(), content.c_str());
265     } else if (!ctorVal.empty() && functionFlag) {
266         HILOG_INFO("%{public}s[Function %{public}s]", groupIndent.c_str(), ctorVal.c_str());
267     } else {
268         HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), content.c_str());
269     }
270     return Helper::NapiHelper::GetUndefinedValue(env);
271 }
272 
Group(napi_env env,napi_callback_info info)273 napi_value Console::Group(napi_env env, napi_callback_info info)
274 {
275     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
276     if (argc > 0) {
277         ConsoleLog<LogLevel::INFO>(env, info);
278     }
279     groupIndent += StringRepeat(GROUPINDETATIONWIDTH, " ");
280     return Helper::NapiHelper::GetUndefinedValue(env);
281 }
282 
GroupEnd(napi_env env,napi_callback_info info)283 napi_value Console::GroupEnd(napi_env env, napi_callback_info info)
284 {
285     size_t length = groupIndent.size();
286     if (length > GROUPINDETATIONWIDTH) {
287         groupIndent = groupIndent.substr(0, length - GROUPINDETATIONWIDTH);
288     }
289     return Helper::NapiHelper::GetUndefinedValue(env);
290 }
291 
ArrayJoin(std::vector<std::string> rowDivider,const std::string & tableChars)292 std::string Console::ArrayJoin(std::vector<std::string> rowDivider, const std::string& tableChars)
293 {
294     size_t size = rowDivider.size();
295     if (size == 0) {
296         return "no rowDivider";
297     }
298     std::string result = rowDivider[0];
299     for (size_t i = 1; i < size; i++) {
300         result += tableChars;
301         result += rowDivider[i];
302     }
303     return result;
304 }
305 
RenderHead(napi_env env,napi_value head,std::vector<size_t> columnWidths)306 std::string Console::RenderHead(napi_env env, napi_value head, std::vector<size_t> columnWidths)
307 {
308     std::string result = tableChars["left"];
309     size_t length = columnWidths.size();
310     for (size_t i = 0; i < length; i++) {
311         napi_value element = nullptr;
312         napi_get_element(env, head, i, &element);
313         napi_value string = nullptr;
314         napi_status status = napi_coerce_to_string(env, element, &string);
315         if (status != napi_ok) {
316             Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
317                                             "Table elements can't convert to string.");
318             return "";
319         }
320         std::string elemStr = Helper::NapiHelper::GetPrintString(env, string);
321         size_t stringLen = elemStr.size();
322         size_t left = (columnWidths[i] - stringLen) / 2; // 2: half
323         size_t right = columnWidths[i] - stringLen - left;
324         result += StringRepeat(left, " ") + elemStr + StringRepeat(right, " ");
325         if (i != length - 1) {
326             result += tableChars["middle"];
327         }
328     }
329     result += tableChars["right"];
330     return result;
331 }
332 
GetStringAndStringWidth(napi_env env,napi_value element,size_t & stringLen)333 std::string Console::GetStringAndStringWidth(napi_env env, napi_value element, size_t& stringLen)
334 {
335     napi_value string = nullptr;
336     napi_status status = napi_coerce_to_string(env, element, &string);
337     if (status != napi_ok) {
338         Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
339                                         "GetStringAndStringWidth: can't convert to string.");
340         return "";
341     }
342     std::string result = Helper::NapiHelper::GetPrintString(env, string);
343     napi_valuetype valuetype;
344     napi_typeof(env, element, &valuetype);
345     if (valuetype != napi_undefined) {
346         stringLen = result.size();  // If element type is undefined, length is 0.
347     }
348     return result;
349 }
350 
PrintRows(napi_env env,napi_value Rows,std::vector<size_t> columnWidths,size_t indexNum)351 void Console::PrintRows(napi_env env, napi_value Rows, std::vector<size_t> columnWidths, size_t indexNum)
352 {
353     size_t length = columnWidths.size();
354     for (size_t i = 0; i < indexNum; i++) {
355         std::string result = tableChars["left"];
356         for (size_t j = 0; j < length; j++) {
357             napi_value element = nullptr;
358             napi_get_element(env, Rows, j * indexNum + i, &element);
359             size_t stringLen = 0;
360             std::string stringVal = GetStringAndStringWidth(env, element, stringLen);
361             if (stringLen > 0) {
362                 size_t left = (columnWidths[j] - stringLen) / 2; // 2: half
363                 size_t right = columnWidths[j] - stringLen - left;
364                 result += StringRepeat(left, " ") + stringVal + StringRepeat(right, " ");
365             } else {
366                 result += StringRepeat(columnWidths[j], " ");
367             }
368             if (j != length - 1) {
369                 result += tableChars["middle"];
370             }
371         }
372         result += tableChars["right"];
373         HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), result.c_str());
374     }
375 }
376 
GraphTable(napi_env env,napi_value head,napi_value columns,const size_t & length)377 void Console::GraphTable(napi_env env, napi_value head, napi_value columns, const size_t& length)
378 {
379     uint32_t columnLen = 0;
380     napi_get_array_length(env, head, &columnLen);
381     std::vector<size_t> columnWidths(columnLen);
382     std::vector<std::string> rowDivider(columnLen);
383     // get maxColumnWidths and get rowDivider(------)
384     // get key string length
385     for (size_t i = 0; i < columnLen; i++) {
386         napi_value element = nullptr;
387         napi_get_element(env, head, i, &element);
388         size_t stringLen = 0;
389         GetStringAndStringWidth(env, element, stringLen);
390         columnWidths[i] = stringLen;
391     }
392     // compare key/value string and get max length
393     for (size_t i = 0; i < columnLen; i++) {
394         for (size_t j = 0; j < length; j++) {
395             napi_value element = nullptr;
396             napi_get_element(env, columns, i * length + j, &element);
397             size_t stringLen = 0;
398             GetStringAndStringWidth(env, element, stringLen);
399             columnWidths[i] = columnWidths[i] > stringLen ? columnWidths[i] :  stringLen;
400         }
401         rowDivider[i] = StringRepeat(columnWidths[i] + 2, tableChars["middleMiddle"]); // 2: two space
402     }
403     // print head row
404     std::string indexRow1 = tableChars["topLeft"] +
405                             ArrayJoin(rowDivider, tableChars["topMiddle"]) +
406                             tableChars["topRight"];
407     std::string indexRow2 = RenderHead(env, head, columnWidths);
408     std::string indexRow3 = tableChars["leftMiddle"] +
409                             ArrayJoin(rowDivider, tableChars["rowMiddle"]) +
410                             tableChars["rightMiddle"];
411     HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), indexRow1.c_str());
412     HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), indexRow2.c_str());
413     HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), indexRow3.c_str());
414     // print value row
415     PrintRows(env, columns, columnWidths, length);
416     // print end row
417     std::string endRow = tableChars["bottomLeft"] +
418                          ArrayJoin(rowDivider, tableChars["bottomMiddle"]) +
419                          tableChars["bottomRight"];
420     HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), endRow.c_str());
421 }
422 
GetKeyArray(napi_env env,napi_value map)423 napi_value GetKeyArray(napi_env env, napi_value map)
424 {
425     napi_value mapKeys = nullptr;
426     napi_object_get_keys(env, map, &mapKeys);
427     uint32_t maplen = 0;
428     napi_get_array_length(env, mapKeys, &maplen);
429 
430     size_t keyLength = maplen + 1;
431     napi_value outputKeysArray = nullptr;
432     napi_create_array_with_length(env, keyLength, &outputKeysArray);
433     // set (index) to array
434     napi_value result = nullptr;
435     napi_create_string_utf8(env, "(index)", NAPI_AUTO_LENGTH, &result);
436     napi_set_element(env, outputKeysArray, 0, result);
437 
438     // set Keys to array
439     for (size_t j = 0; j < maplen ; ++j) {
440         napi_value keyNumber = nullptr;
441         napi_get_element(env, mapKeys, j, &keyNumber);
442         napi_set_element(env, outputKeysArray, j + 1, keyNumber); // startkeyIdx = 1
443     }
444     return outputKeysArray;
445 }
446 
GetValueArray(napi_env env,napi_value map,const size_t & length,napi_value keyArray)447 napi_value GetValueArray(napi_env env, napi_value map, const size_t& length, napi_value keyArray)
448 {
449     napi_value mapKeys = nullptr;
450     napi_object_get_keys(env, map, &mapKeys);
451     uint32_t maplen = 0;
452     napi_get_array_length(env, mapKeys, &maplen);
453     size_t keyLength = maplen + 1;
454 
455     size_t valueLength = keyLength * length;
456     napi_value outputValuesArray = nullptr;
457     napi_create_array_with_length(env, valueLength, &outputValuesArray);
458     // set indexKeyValue
459     size_t valueIdx = 0;
460     for (size_t j = 0; j < length ; ++j) {
461         napi_value keyNumber = nullptr;
462         napi_get_element(env, keyArray, j, &keyNumber);
463         napi_set_element(env, outputValuesArray, valueIdx++, keyNumber);
464     }
465     for (size_t i = 0; i < maplen ; ++i) {
466         napi_value keyNumber = nullptr;
467         napi_get_element(env, mapKeys, i, &keyNumber);
468         char* innerKey = Helper::NapiHelper::GetChars(env, keyNumber);
469         if (innerKey == nullptr) {
470             Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
471                                             "property key must not be null.");
472             return Helper::NapiHelper::GetUndefinedValue(env);
473         }
474         napi_value valueNumber = nullptr;
475         napi_get_named_property(env, map, innerKey, &valueNumber);
476         Helper::CloseHelp::DeletePointer(innerKey, true);
477         for (size_t j = 0; j < length ; ++j) {
478             napi_value value = nullptr;
479             napi_get_element(env, valueNumber, j, &value);
480             napi_set_element(env, outputValuesArray, valueIdx++, value);
481         }
482     }
483     return outputValuesArray;
484 }
485 
SetPrimitive(napi_env env,napi_value map,const size_t & length,napi_value valuesKeyArray,napi_value outputKeysArray,napi_value outputValuesArray)486 void SetPrimitive(napi_env env, napi_value map, const size_t& length, napi_value valuesKeyArray,
487                   napi_value outputKeysArray, napi_value outputValuesArray)
488 {
489     napi_value mapKeys = nullptr;
490     napi_object_get_keys(env, map, &mapKeys);
491     uint32_t maplen = 0;
492     napi_get_array_length(env, mapKeys, &maplen);
493     napi_value result = nullptr;
494     napi_create_string_utf8(env, "Values", NAPI_AUTO_LENGTH, &result);
495     napi_set_element(env, outputKeysArray, maplen + 1, result);
496     uint32_t valuesLen = 0;
497     napi_get_array_length(env, valuesKeyArray, &valuesLen);
498     size_t startVal = (maplen + 1) * length;
499     for (size_t j = 0; j < length ; ++j) {
500         napi_value value = nullptr;
501         napi_get_element(env, valuesKeyArray, j, &value);
502         napi_set_element(env, outputValuesArray, startVal + j, value);
503     }
504 }
505 
ProcessNestedObject(napi_env env,napi_value item,napi_value & map,std::map<std::string,bool> & initialMap,size_t index)506 void ProcessNestedObject(napi_env env, napi_value item, napi_value& map, std::map<std::string, bool>& initialMap,
507                          size_t index)
508 {
509     napi_value keys = nullptr;
510     napi_object_get_keys(env, item, &keys);
511     uint32_t innerLength = 0;
512     napi_get_array_length(env, keys, &innerLength);
513     for (size_t j = 0; j < innerLength; ++j) {
514         napi_value keyNumber = nullptr;
515         napi_get_element(env, keys, j, &keyNumber);
516         char* innerKey = Helper::NapiHelper::GetChars(env, keyNumber);
517         if (innerKey == nullptr) {
518             Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
519                                             "property key must not be null.");
520             return;
521         }
522         napi_value innerItem = nullptr;
523         napi_get_named_property(env, item, innerKey, &innerItem);
524         if (initialMap.find(std::string(innerKey)) == initialMap.end()) {
525             napi_value mapArray = nullptr;
526             napi_create_array_with_length(env, innerLength, &mapArray);
527             napi_set_element(env, mapArray, index, innerItem);
528             napi_set_named_property(env, map, innerKey, mapArray);
529             initialMap[innerKey] = true;
530         } else {
531             napi_value mapArray = nullptr;
532             napi_get_named_property(env, map, innerKey, &mapArray);
533             napi_set_element(env, mapArray, index, innerItem);
534             napi_set_named_property(env, map, innerKey, mapArray);
535         }
536         Helper::CloseHelp::DeletePointer(innerKey, true);
537     }
538 }
539 
InitializeValuesKeyArray(napi_env env,napi_value valuesKeyArray,uint32_t length)540 void InitializeValuesKeyArray(napi_env env, napi_value valuesKeyArray, uint32_t length)
541 {
542     for (size_t j = 0; j < length ; ++j) {
543         napi_value result = nullptr;
544         napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &result);
545         napi_set_element(env, valuesKeyArray, j, result);
546     }
547 }
548 
ProcessTabularData(napi_env env,napi_value tabularData)549 napi_value Console::ProcessTabularData(napi_env env, napi_value tabularData)
550 {
551     napi_value keyArray = nullptr;
552     napi_object_get_keys(env, tabularData, &keyArray);
553     uint32_t length = 0;
554     napi_get_array_length(env, keyArray, &length);
555     napi_value valuesKeyArray = nullptr;
556     napi_create_array_with_length(env, length, &valuesKeyArray);
557 
558     napi_value map = nullptr;
559     napi_create_object(env, &map);
560     bool hasPrimitive = false;
561     bool primitiveInit = false;
562     std::map<std::string, bool> initialMap;
563 
564     for (size_t i = 0; i < length; i++) {
565         napi_value keyItem = nullptr;
566         napi_get_element(env, keyArray, i, &keyItem);
567         char* key = Helper::NapiHelper::GetChars(env, keyItem);
568         if (key == nullptr) {
569             Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
570                                             "property key must not be null.");
571             return Helper::NapiHelper::GetUndefinedValue(env);
572         }
573         napi_value item = nullptr;
574         napi_get_named_property(env, tabularData, key, &item);
575         Helper::CloseHelp::DeletePointer(key, true);
576         bool isPrimitive = ((item == nullptr) ||
577                             (!Helper::NapiHelper::IsObject(env, item) && !Helper::NapiHelper::IsFunction(env, item)));
578         if (isPrimitive) {
579             if (!primitiveInit) {
580                 InitializeValuesKeyArray(env, valuesKeyArray, length);
581                 primitiveInit = true;
582             }
583             hasPrimitive = true;
584             napi_set_element(env, valuesKeyArray, i, item);
585         } else {
586             ProcessNestedObject(env, item, map, initialMap, i);
587         }
588     }
589     // set outputKeysArray
590     napi_value outputKeysArray = GetKeyArray(env, map);
591     // set outputValuesArray
592     napi_value outputValuesArray = GetValueArray(env, map, length, keyArray);
593     // if has Primitive, add new colomn Values
594     if (hasPrimitive) {
595         SetPrimitive(env, map, length, valuesKeyArray, outputKeysArray, outputValuesArray);
596     }
597     GraphTable(env, outputKeysArray, outputValuesArray, length);
598     return Helper::NapiHelper::GetUndefinedValue(env);
599 }
600 
Table(napi_env env,napi_callback_info info)601 napi_value Console::Table(napi_env env, napi_callback_info info)
602 {
603     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
604     if (argc < 1) {
605         return Helper::NapiHelper::GetUndefinedValue(env);
606     }
607     napi_value* argv = new napi_value[argc];
608     Helper::ObjectScope<napi_value> scope(argv, true);
609     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
610     if (!Helper::NapiHelper::IsObject(env, argv[0])) {
611         ConsoleLog<LogLevel::INFO>(env, info);
612     }
613     napi_value tabularData = argv[0];
614     return ProcessTabularData(env, tabularData);
615 }
616 
PrintTime(std::string timerName,double time,const std::string & log)617 void Console::PrintTime(std::string timerName, double time, const std::string& log)
618 {
619     uint32_t hours = 0;
620     uint32_t minutes = 0;
621     uint32_t seconds = 0;
622     uint32_t ms = time;
623     if (ms >= SECOND) {
624         if (ms >= MINUTE) {
625             if (ms >= HOUR) {
626                 hours = ms / HOUR;
627                 ms = ms - HOUR * hours;
628             }
629             minutes = ms / MINUTE;
630             ms = ms - MINUTE * minutes;
631         }
632         seconds = ms / SECOND;
633         ms = ms - SECOND * seconds;
634     }
635     if (hours != 0) {
636         HILOG_INFO("%{public}s%{public}s: %{public}d:%{public}.2d:%{public}.2d.%{public}.3d(h:m:s.mm) %{public}s",
637             groupIndent.c_str(), timerName.c_str(), hours, minutes, seconds, ms, log.c_str());
638         return;
639     }
640     if (minutes != 0) {
641         HILOG_INFO("%{public}s%{public}s: %{public}d:%{public}.2d.%{public}.3d(m:s.mm) %{public}s",
642             groupIndent.c_str(), timerName.c_str(), minutes, seconds, ms, log.c_str());
643         return;
644     }
645     if (seconds != 0) {
646         HILOG_INFO("%{public}s%{public}s: %{public}d.%{public}.3ds %{public}s",
647             groupIndent.c_str(), timerName.c_str(), seconds, ms, log.c_str());
648         return;
649     }
650     HILOG_INFO("%{public}s%{public}s: %{public}.3fms %{public}s",
651         groupIndent.c_str(), timerName.c_str(), time, log.c_str());
652 }
653 
Time(napi_env env,napi_callback_info info)654 napi_value Console::Time(napi_env env, napi_callback_info info)
655 {
656     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
657     std::string timerName = GetTimerOrCounterName(env, info, argc);
658     if (timerMap.find(timerName) == timerMap.end()) {
659         timerMap[timerName] = std::chrono::duration_cast<std::chrono::microseconds>
660                               (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
661     } else {
662         HILOG_WARN("Timer %{public}s already exists,  please check Timer Name", timerName.c_str());
663     }
664     return Helper::NapiHelper::GetUndefinedValue(env);
665 }
666 
TimeLog(napi_env env,napi_callback_info info)667 napi_value Console::TimeLog(napi_env env, napi_callback_info info)
668 {
669     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
670     std::string timerName = GetTimerOrCounterName(env, info, argc);
671     if (timerMap.find(timerName) != timerMap.end()) {
672         // get time in ms
673         int64_t endTime = std::chrono::duration_cast<std::chrono::microseconds>
674                           (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
675         double ms = static_cast<uint64_t>(endTime - timerMap[timerName]) / 1000.0;
676         std::string content = MakeLogContent(env, info, argc, 1, false); // startInx = 1, format = false;
677         PrintTime(timerName, ms, content);
678     } else {
679         HILOG_WARN("%{public}sTimer %{public}s doesn't exists, please check Timer Name.",
680                    groupIndent.c_str(), timerName.c_str());
681     }
682     return Helper::NapiHelper::GetUndefinedValue(env);
683 }
684 
TimeEnd(napi_env env,napi_callback_info info)685 napi_value Console::TimeEnd(napi_env env, napi_callback_info info)
686 {
687     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
688     std::string timerName = GetTimerOrCounterName(env, info, argc);
689     if (timerMap.find(timerName) != timerMap.end()) {
690         // get time in ms
691         int64_t endTime = std::chrono::duration_cast<std::chrono::microseconds>
692                           (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
693         double ms = static_cast<uint64_t>(endTime - timerMap[timerName]) / 1000.0;
694         PrintTime(timerName, ms, "");
695         timerMap.erase(timerName);
696     } else {
697         HILOG_WARN("%{public}sTimer %{public}s doesn't exists, please check Timer Name.",
698                    groupIndent.c_str(), timerName.c_str());
699     }
700     return Helper::NapiHelper::GetUndefinedValue(env);
701 }
702 
Trace(napi_env env,napi_callback_info info)703 napi_value Console::Trace(napi_env env, napi_callback_info info)
704 {
705     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
706     std::string content;
707     if (argc > 0) {
708         content = MakeLogContent(env, info, argc, 0); // startInx = 0
709     }
710     HILOG_INFO("%{public}sTrace: %{public}s", groupIndent.c_str(), content.c_str());
711     std::string stack;
712     napi_get_stack_trace(env, stack);
713     std::string tempStr = "";
714     for (size_t i = 0; i < stack.length(); i++) {
715         if (stack[i] == '\n') {
716             HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), tempStr.c_str());
717             tempStr = "";
718         } else {
719             tempStr += stack[i];
720         }
721     }
722     return Helper::NapiHelper::GetUndefinedValue(env);
723 }
724 
TraceHybridStack(napi_env env,napi_callback_info info)725 napi_value Console::TraceHybridStack(napi_env env, napi_callback_info info)
726 {
727     std::string stack;
728     napi_get_hybrid_stack_trace(env, stack);
729     HILOG_INFO("%{public}sTraceHybridStack: ", groupIndent.c_str());
730     std::string tempStr = "";
731     for (size_t i = 0; i < stack.length(); i++) {
732         if (stack[i] == '\n') {
733             HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), tempStr.c_str());
734             tempStr = "";
735         } else {
736             tempStr += stack[i];
737         }
738     }
739     return Helper::NapiHelper::GetUndefinedValue(env);
740 }
741 
Assert(napi_env env,napi_callback_info info)742 napi_value Console::Assert(napi_env env, napi_callback_info info)
743 {
744     // 1. check args
745     size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
746     if (argc < 1) {
747         HILOG_ERROR("%{public}sAssertion failed", groupIndent.c_str());
748         return Helper::NapiHelper::GetUndefinedValue(env);
749     }
750     napi_value* argv = new napi_value[argc];
751     Helper::ObjectScope<napi_value> scope(argv, true);
752     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
753 
754     if (Helper::NapiHelper::GetBooleanValue(env, argv[0])) {
755         return Helper::NapiHelper::GetUndefinedValue(env);
756     }
757     std::string content = "Assertion failed";
758     if (argc > 1) {
759         content += ":";
760         content += MakeLogContent(env, info, argc, 1); // startIndex = 1
761     }
762     HILOG_ERROR("%{public}s%{public}s", groupIndent.c_str(), content.c_str());
763     return Helper::NapiHelper::GetUndefinedValue(env);
764 }
765 
InitConsoleModule(napi_env env)766 void Console::InitConsoleModule(napi_env env)
767 {
768     napi_property_descriptor properties[] = {
769         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("log", ConsoleLog<LogLevel::INFO>),
770         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("debug", ConsoleLog<LogLevel::DEBUG>),
771         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("info", ConsoleLog<LogLevel::INFO>),
772         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("warn", ConsoleLog<LogLevel::WARN>),
773         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("error", ConsoleLog<LogLevel::ERROR>),
774         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("fatal", ConsoleLog<LogLevel::FATAL>),
775         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("group", Group),
776         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("groupCollapsed", Group),
777         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("groupEnd", GroupEnd),
778         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("table", Table),
779         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("time", Time),
780         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("timeLog", TimeLog),
781         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("timeEnd", TimeEnd),
782         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("trace", Trace),
783         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("traceHybridStack", TraceHybridStack),
784         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("assert", Assert),
785         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("count", Count),
786         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("countReset", CountReset),
787         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("dir", Dir),
788         DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("dirxml", ConsoleLog<LogLevel::INFO>)
789     };
790     napi_value globalObj = Helper::NapiHelper::GetGlobalObject(env);
791     napi_value console = nullptr;
792     napi_create_object(env, &console);
793     napi_define_properties(env, console, sizeof(properties) / sizeof(properties[0]), properties);
794     napi_set_named_property(env, globalObj, "console", console);
795 }
796 } // namespace Commonlibrary::JsSysModule