1/* 2 * Copyright (c) 2022 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 16import { firstCharacterToUppercase } from "../common/commonUtils"; 17 18/** 19 * save all mock function 20 */ 21const indexArray: Array<IndexEntity> = []; 22 23export function addToIndexArray(indexEntity: IndexEntity) { 24 indexArray.push(indexEntity); 25} 26 27export function getIndexArray(): Array<IndexEntity> { 28 return indexArray; 29} 30 31/** 32 * generate index 33 * @returns 34 */ 35export function generateIndex(): string { 36 let indexBody = ''; 37 let caseBody = ''; 38 const filterSet: Set<string> = new Set<string>(); 39 40 indexArray.forEach(value => { 41 let functionName = value.mockFunctionName; 42 let isHasSameValue = false; 43 if (filterSet.has(value.mockFunctionName)) { 44 isHasSameValue = true; 45 const tmpArr = value.fileName.split('_'); 46 let tmpName = tmpArr[0]; 47 for (let i = 1; i < tmpArr.length; i++) { 48 tmpName += firstCharacterToUppercase(tmpArr[i]); 49 } 50 functionName = `${tmpName}`; 51 } 52 filterSet.add(functionName); 53 if (isHasSameValue) { 54 indexBody += `import { ${value.mockFunctionName} as ${functionName} } from './${value.fileName}';\n`; 55 } else { 56 indexBody += `import { ${functionName} } from './${value.fileName}';\n`; 57 } 58 59 if (value.fileName.startsWith('ohos_')) { 60 caseBody += `case '${value.fileName.split('ohos_')[1].replace(/_/g, '.')}':\n\treturn ${functionName}();\n`; 61 } else { 62 caseBody += `case '${value.fileName}':\n\treturn ${functionName}();\n`; 63 } 64 }); 65 66 indexBody += `export function mockRequireNapiFun() { 67 global.requireNapi = function (...args) { 68 const globalNapi = global.requireNapiPreview(...args); 69 if (globalNapi !== undefined) { 70 return globalNapi; 71 } 72 switch (args[0]) {`; 73 indexBody += caseBody; 74 const endBody = `} 75 } 76 }`; 77 indexBody += endBody; 78 return indexBody; 79} 80 81interface IndexEntity { 82 fileName: string, 83 mockFunctionName: string 84} 85