const Service=require("../service"),path=require("path"),fs=require("fs"),{ErrorWithCode:ErrorWithCode,getRealWorkspace:getRealWorkspace}=require("../../utils/index");function checkEncrypt(e,r,s=!1){if(r.includes(e))return;if(r.push(e),fs.existsSync(path.resolve(e,"encrypt")))throw new ErrorWithCode({code:s?"FUNCTION_ENCRYPTED":"MODULE_ENCRYPTED",message:s?"云函数已加密不支持本地运行":"云函数依赖加密公共模块不可本地调试"});let c;try{c=require(path.resolve(e,"package.json"))}catch(e){}if(!c)return;const t=c.dependencies;if(!t)return;const o=Object.keys(t);for(let s=0;s<o.length;s++){const c=t[o[s]];c.indexOf("file:")>-1&&checkEncrypt(path.resolve(e,c.slice(5)),r)}}class CheckFunctionService extends Service{async exec(){const{name:e,platform:r,provider:s,spaceId:c}=this.ctx.data,{hxConfig:t,logger:o}=this.ctx;if(!e)return o.error("云函数/云对象名称不可为空"),{code:"INVALID_PARAM",message:"function/object name is required"};const a=getRealWorkspace({provider:s});if(!a)return{code:"SWITCH_TO_CLOUD",message:"此服务空间不在本项目下，需要切换为已部署的云函数"};let n,i;if(t){let e;switch(n=t.provider,r){case"app":case"app-plus":e=t.app||t["app-plus"];break;case"web":case"h5":e=t.web||t.h5;break;default:e=t[r]}const s=t.default;i=Object.assign({},s,e).launchtype}let u=[];try{u=JSON.parse(process.env.UNICLOUD_SPACE_LIST)}catch(e){return o.error("项目关联的uniCloud服务空间信息不正确"),{code:"INTERNAL_ERROR",message:"项目关联的uniCloud服务空间信息不正确"}}if(u.every((e=>e.spaceId!==c)))return{code:"SWITCH_TO_CLOUD",message:"此服务空间不在本项目下，需要切换为已部署的云函数"};if(n&&!n.split(",").includes(s))return{code:"SWITCH_TO_CLOUD",message:"当前provider需使用云端云函数"};if(!n)switch(u.length){case 0:return{code:"INTERNAL_ERROR",message:"项目未关联uniCloud服务空间"};case 1:break;case 2:return{code:"INTERNAL_ERROR",message:"项目关联了多个服务空间（一个阿里云一个腾讯云），需要指定调试服务使用的服务空间"};default:return{code:"INTERNAL_ERROR",message:"未知错误"}}if("local"!==i)return{code:"SWITCH_TO_CLOUD",message:"切换至云端"};const d=path.resolve(a,`uniCloud-${process.env.UNICLOUD_SPACE_PROVIDER}`),p=path.resolve(d,"cloudfunctions",e);try{checkEncrypt(p,[],!0)}catch(e){return{code:e.code,message:e.message}}return{code:0,message:"使用本地云函数"}}}module.exports=CheckFunctionService;