"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.generateMiniappIOSResources=void 0;const tslib_1=require("tslib"),zip_1=require("../../utils/zip"),request_1=require("../../utils/request"),tools_1=require("../../utils/tools"),log=tslib_1.__importStar(require("../../utils/log")),tools_2=require("../utils/tools"),fse=require("fs-extra"),path=require("path"),CDN_PREFIX="https://dldir1.qq.com/WechatWebDev/";class SDKVersionManager{constructor(e){this.project=e,this.iosBaseDir=(0,tools_2.getMiniappIOSCacheDir)(),this.downloadBigFile=async(e,s)=>{const i=fse.createWriteStream(s,{mode:511});return new Promise((s,o)=>{(0,request_1.simpleRequest)({url:""+e,method:"get"},e=>{e&&o(e)}).pipe(i),i.on("error",e=>{o(e)}),i.on("close",()=>{s({})})})},this.downloadMiniappIOSResources=async(e,s=!1)=>{log.info("Download ios resources...");const i=path.join(this.iosBaseDir,"v2-ipa",e);fse.existsSync(i)||(fse.emptyDirSync(path.dirname(i)),fse.ensureDirSync(i));const o=["x86.zip","arm64.zip",`WeAppSDK-${e}.zip`];s&&(o.push("x86_ipad.zip"),o.push("arm64_ipad.zip"));try{const s=[];o.forEach(o=>{const r=`${CDN_PREFIX}donut/ios/${e}/${o}`,t=path.join(i,o);fse.existsSync(t)||s.push(this.downloadBigFile(r,t))}),await Promise.all(s),log.info("Download ios resources successfully")}catch(e){throw fse.removeSync(i),new Error(`download ios resources resources failed: ${e.message}. Network issue or SDK Version may not suitable for IPad beta`)}return i},this.generateMiniappIOSResources=async(e,s,i=!1,o=!1)=>{try{log.info((i?"is":"not")+" using iPad Beta");const o=await this.downloadMiniappIOSResources(e,i);log.info("Archive ios resources...");let r="";r=i?path.join(o,"arm64"===s?"arm64_ipad.zip":"x86_ipad.zip"):path.join(o,"arm64"===s?"arm64.zip":"x86.zip");const t=path.join(o,`WeAppSDK-${e}.zip`),a=path.join(this.iosBaseDir,"v2-ipa",e,`ipa-${s}${i?"-iPad":""}-${(0,tools_1.generateMD5)(this.project.projectPath)}/Payload`);fse.existsSync(a)||await(0,zip_1.unzip)(r,a);const n=path.join(this.iosBaseDir,"v2-ipa",e,"sdk-"+(0,tools_1.generateMD5)(this.project.projectPath));return fse.existsSync(n)||await(0,zip_1.unzip)(t,n),log.info("Archive ios resources successfully"),{demoIpaPath:path.join(a,"demo.app"),sdkPath:n}}catch(r){const t=path.join(this.iosBaseDir,"v2-ipa",e);if(fse.existsSync(t)&&fse.removeSync(t),o){log.info(`Start retry, Process resources failed: ${r.message}.`);return await this.generateMiniappIOSResources(e,s,i,!1)}throw log.error("Archive ios resources failed, please retry and check whether your network is running smoothly..."),new Error("Download and unzip the ios resources failed: "+r.message)}},this.project=e}}async function generateMiniappIOSResources(e,s,i,o=!1){return await new SDKVersionManager(e).generateMiniappIOSResources(s,i,o,!0)}exports.generateMiniappIOSResources=generateMiniappIOSResources;