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 16import type { SourceFile } from 'typescript'; 17import { SyntaxKind } from 'typescript'; 18import type { FunctionEntity } from '../declaration-node/functionDeclaration'; 19import { getCallbackStatement, getReturnStatement } from './generateCommonUtil'; 20 21/** 22 * generate function 23 * @param rootName 24 * @param functionArray 25 * @param sourceFile 26 * @param mockApi 27 * @returns 28 */ 29export function generateExportFunction(functionEntity: FunctionEntity, sourceFile: SourceFile, mockApi: string): string { 30 let functionBody = ''; 31 functionBody = `const ${functionEntity.functionName} = function (...args) {`; 32 if (mockApi.includes(functionBody)) { 33 return ''; 34 } 35 functionBody += `console.warn('The ${functionEntity.functionName} interface in the Previewer is a mocked implementation and may behave differently than on a real device.');\n`; 36 37 const args = functionEntity.args; 38 const len = args.length; 39 if (args.length > 0 && args[len - 1].paramName.toLowerCase().includes('callback')) { 40 functionBody += getCallbackStatement(mockApi); 41 } 42 if (functionEntity.returnType.returnKind !== SyntaxKind.VoidKeyword) { 43 functionBody += getReturnStatement(functionEntity.returnType, sourceFile); 44 } 45 functionBody += '}'; 46 functionBody += ` 47 if (!global.${functionEntity.functionName}) { 48 global.${functionEntity.functionName} = ${functionEntity.functionName} 49 } 50 `; 51 return functionBody; 52} 53 54