import chalk from 'chalk'; import fs from 'fs'; import path from 'path'; import LocalFunctionServer from '../service/cloud_function/localFunctionServer'; import logger from '../utils/logger'; import invokeLocalFunction from '../service/cloud_function/invokeLocalFunction'; import postLog from '../service/post.log'; import debugProcess from './util/debug.process'; import commander from 'commander'; async function createServerAction(options) { const appId = options.appId; const action = 'CLOUD_FUNCTION_DEV'; postLog({ action, }); const privateKeyPath = options.privateKeyPath; let privateKey: string | null = null; if (privateKeyPath) { privateKey = fs.readFileSync(privateKeyPath, { encoding: 'utf-8', }); } const project = path.resolve(options.project); const server = new LocalFunctionServer({ appId, project, port: options.port, privateKey, }); try { await server.createServer(); const address = chalk.green(`http://localhost:${server.options.port}`); const tips = [ `本地云函数运行服务已启动, 代理地址: ${address}`, `修改小程序代码中new MPServerless的endpoint: ${address}`, ]; if (options.inspect) { const devtoolsUrl = await debugProcess(project, server.options.port); tips.push('在chrome浏览器打开以下调试地址:'); tips.push(devtoolsUrl); tips.push('如果chrome打开调试地址无响应,打开 chrome://inspect/ , 点击Node开发工具即可'); } logger.orderListLog(tips); } catch (e) { logger.error(e, { action, }); } } async function invokeLocalFunctionAction(options) { const action = 'CLOUD_FUNCTION_LOCAL'; postLog({ action, }); try { const input = options.input; const project = path.resolve(options.project); let functionArgs = {}; if (input) { functionArgs = JSON.parse(input); } const result = await invokeLocalFunction({ project, name: options.name, functionArgs, appId: options.appId, spaceId: options.spaceId, }); logger.log(`本地函数 ${options.name} 运行结果: `); logger.log(result); } catch (e) { logger.error(e, { action, }); } } /** * 注册云函数本地运行命令 */ export default function registerFunctionRunCommand(program: commander.Command): void { program .command('dev') .requiredOption('-i, --app-id ', '小程序appId') .requiredOption('-p --project ', '云函数本地目录') .option('--port [port]', '服务启动端口') .option('--inspect [inspect]', '启动chrome调试器') // 阿里云空间服务端私钥路径,内部小程序参数 .option('-k, --private-key-path [privateKeyPath]', '') .description('启动本地云函数运行环境') .action(createServerAction); program .command('local') .storeOptionsAsProperties(false) .requiredOption('-i, --app-id ', '小程序appId') .requiredOption('-s, --space-id ', '云开发服务空间ID') .requiredOption('-p --project ', '云函数本地目录') .requiredOption('-n, --name ', '云函数名') .option('--input ', '云函数参数,JSON字符串') .description('调用本地云函数') .action(invokeLocalFunctionAction); }