check.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import fs from "fs-extra";
  2. import zlib from "zlib";
  3. import tar from "tar";
  4. import path from "path";
  5. import AdmZip from "adm-zip";
  6. import fetch from "node-fetch";
  7. import proxyAgent from "https-proxy-agent";
  8. import { execSync } from "child_process";
  9. const cwd = process.cwd();
  10. const TEMP_DIR = path.join(cwd, "node_modules/.verge");
  11. const FORCE = process.argv.includes("--force");
  12. const PLATFORM_MAP = {
  13. "x86_64-pc-windows-msvc": "win32",
  14. "i686-pc-windows-msvc": "win32",
  15. "aarch64-pc-windows-msvc": "win32",
  16. "x86_64-apple-darwin": "darwin",
  17. "aarch64-apple-darwin": "darwin",
  18. "x86_64-unknown-linux-gnu": "linux",
  19. "i686-unknown-linux-gnu": "linux",
  20. "aarch64-unknown-linux-gnu": "linux",
  21. "armv7-unknown-linux-gnueabihf": "linux",
  22. };
  23. const ARCH_MAP = {
  24. "x86_64-pc-windows-msvc": "x64",
  25. "i686-pc-windows-msvc": "ia32",
  26. "aarch64-pc-windows-msvc": "arm64",
  27. "x86_64-apple-darwin": "x64",
  28. "aarch64-apple-darwin": "arm64",
  29. "x86_64-unknown-linux-gnu": "x64",
  30. "i686-unknown-linux-gnu": "ia32",
  31. "aarch64-unknown-linux-gnu": "arm64",
  32. "armv7-unknown-linux-gnueabihf": "arm",
  33. };
  34. const arg1 = process.argv.slice(2)[0];
  35. const arg2 = process.argv.slice(2)[1];
  36. const target = arg1 === "--force" ? arg2 : arg1;
  37. const { platform, arch } = target
  38. ? { platform: PLATFORM_MAP[target], arch: ARCH_MAP[target] }
  39. : process;
  40. const SIDECAR_HOST = target
  41. ? target
  42. : execSync("rustc -vV")
  43. .toString()
  44. .match(/(?<=host: ).+(?=\s*)/g)[0];
  45. /* ======= clash meta alpha======= */
  46. const META_ALPHA_VERSION_URL =
  47. "https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha/version.txt";
  48. const META_ALPHA_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha`;
  49. let META_ALPHA_VERSION;
  50. const META_ALPHA_MAP = {
  51. "win32-x64": "mihomo-windows-amd64-compatible",
  52. "win32-ia32": "mihomo-windows-386",
  53. "win32-arm64": "mihomo-windows-arm64",
  54. "darwin-x64": "mihomo-darwin-amd64-cgo",
  55. "darwin-arm64": "mihomo-darwin-arm64",
  56. "linux-x64": "mihomo-linux-amd64-compatible",
  57. "linux-ia32": "mihomo-linux-386",
  58. "linux-arm64": "mihomo-linux-arm64",
  59. "linux-arm": "mihomo-linux-armv7",
  60. };
  61. // Fetch the latest alpha release version from the version.txt file
  62. async function getLatestAlphaVersion() {
  63. const options = {};
  64. const httpProxy =
  65. process.env.HTTP_PROXY ||
  66. process.env.http_proxy ||
  67. process.env.HTTPS_PROXY ||
  68. process.env.https_proxy;
  69. if (httpProxy) {
  70. options.agent = proxyAgent(httpProxy);
  71. }
  72. try {
  73. const response = await fetch(META_ALPHA_VERSION_URL, {
  74. ...options,
  75. method: "GET",
  76. });
  77. let v = await response.text();
  78. META_ALPHA_VERSION = v.trim(); // Trim to remove extra whitespaces
  79. console.log(`Latest alpha version: ${META_ALPHA_VERSION}`);
  80. } catch (error) {
  81. console.error("Error fetching latest alpha version:", error.message);
  82. process.exit(1);
  83. }
  84. }
  85. /* ======= clash meta stable ======= */
  86. const META_VERSION_URL =
  87. "https://github.com/MetaCubeX/mihomo/releases/latest/download/version.txt";
  88. const META_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download`;
  89. let META_VERSION;
  90. const META_MAP = {
  91. "win32-x64": "mihomo-windows-amd64-compatible",
  92. "win32-ia32": "mihomo-windows-386",
  93. "win32-arm64": "mihomo-windows-arm64",
  94. "darwin-x64": "mihomo-darwin-amd64-cgo",
  95. "darwin-arm64": "mihomo-darwin-arm64",
  96. "linux-x64": "mihomo-linux-amd64-compatible",
  97. "linux-ia32": "mihomo-linux-386",
  98. "linux-arm64": "mihomo-linux-arm64",
  99. "linux-arm": "mihomo-linux-armv7",
  100. };
  101. // Fetch the latest release version from the version.txt file
  102. async function getLatestReleaseVersion() {
  103. const options = {};
  104. const httpProxy =
  105. process.env.HTTP_PROXY ||
  106. process.env.http_proxy ||
  107. process.env.HTTPS_PROXY ||
  108. process.env.https_proxy;
  109. if (httpProxy) {
  110. options.agent = proxyAgent(httpProxy);
  111. }
  112. try {
  113. const response = await fetch(META_VERSION_URL, {
  114. ...options,
  115. method: "GET",
  116. });
  117. let v = await response.text();
  118. META_VERSION = v.trim(); // Trim to remove extra whitespaces
  119. console.log(`Latest release version: ${META_VERSION}`);
  120. } catch (error) {
  121. console.error("Error fetching latest release version:", error.message);
  122. process.exit(1);
  123. }
  124. }
  125. /*
  126. * check available
  127. */
  128. if (!META_MAP[`${platform}-${arch}`]) {
  129. throw new Error(
  130. `clash meta alpha unsupported platform "${platform}-${arch}"`
  131. );
  132. }
  133. if (!META_ALPHA_MAP[`${platform}-${arch}`]) {
  134. throw new Error(
  135. `clash meta alpha unsupported platform "${platform}-${arch}"`
  136. );
  137. }
  138. /**
  139. * core info
  140. */
  141. function clashMetaAlpha() {
  142. const name = META_ALPHA_MAP[`${platform}-${arch}`];
  143. const isWin = platform === "win32";
  144. const urlExt = isWin ? "zip" : "gz";
  145. const downloadURL = `${META_ALPHA_URL_PREFIX}/${name}-${META_ALPHA_VERSION}.${urlExt}`;
  146. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  147. const zipFile = `${name}-${META_ALPHA_VERSION}.${urlExt}`;
  148. return {
  149. name: "clash-meta-alpha",
  150. targetFile: `clash-meta-alpha-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  151. exeFile,
  152. zipFile,
  153. downloadURL,
  154. };
  155. }
  156. function clashMeta() {
  157. const name = META_MAP[`${platform}-${arch}`];
  158. const isWin = platform === "win32";
  159. const urlExt = isWin ? "zip" : "gz";
  160. const downloadURL = `${META_URL_PREFIX}/${META_VERSION}/${name}-${META_VERSION}.${urlExt}`;
  161. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  162. const zipFile = `${name}-${META_VERSION}.${urlExt}`;
  163. return {
  164. name: "clash-meta",
  165. targetFile: `clash-meta-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  166. exeFile,
  167. zipFile,
  168. downloadURL,
  169. };
  170. }
  171. /**
  172. * download sidecar and rename
  173. */
  174. async function resolveSidecar(binInfo) {
  175. const { name, targetFile, zipFile, exeFile, downloadURL } = binInfo;
  176. const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
  177. const sidecarPath = path.join(sidecarDir, targetFile);
  178. await fs.mkdirp(sidecarDir);
  179. if (!FORCE && (await fs.pathExists(sidecarPath))) return;
  180. const tempDir = path.join(TEMP_DIR, name);
  181. const tempZip = path.join(tempDir, zipFile);
  182. const tempExe = path.join(tempDir, exeFile);
  183. await fs.mkdirp(tempDir);
  184. try {
  185. if (!(await fs.pathExists(tempZip))) {
  186. await downloadFile(downloadURL, tempZip);
  187. }
  188. if (zipFile.endsWith(".zip")) {
  189. const zip = new AdmZip(tempZip);
  190. zip.getEntries().forEach((entry) => {
  191. console.log(`[DEBUG]: "${name}" entry name`, entry.entryName);
  192. });
  193. zip.extractAllTo(tempDir, true);
  194. await fs.rename(tempExe, sidecarPath);
  195. console.log(`[INFO]: "${name}" unzip finished`);
  196. } else if (zipFile.endsWith(".tgz")) {
  197. // tgz
  198. await fs.mkdirp(tempDir);
  199. await tar.extract({
  200. cwd: tempDir,
  201. file: tempZip,
  202. //strip: 1, // 可能需要根据实际的 .tgz 文件结构调整
  203. });
  204. const files = await fs.readdir(tempDir);
  205. console.log(`[DEBUG]: "${name}" files in tempDir:`, files);
  206. const extractedFile = files.find((file) => file.startsWith("虚空终端-"));
  207. if (extractedFile) {
  208. const extractedFilePath = path.join(tempDir, extractedFile);
  209. await fs.rename(extractedFilePath, sidecarPath);
  210. console.log(`[INFO]: "${name}" file renamed to "${sidecarPath}"`);
  211. execSync(`chmod 755 ${sidecarPath}`);
  212. console.log(`[INFO]: "${name}" chmod binary finished`);
  213. } else {
  214. throw new Error(`Expected file not found in ${tempDir}`);
  215. }
  216. } else {
  217. // gz
  218. const readStream = fs.createReadStream(tempZip);
  219. const writeStream = fs.createWriteStream(sidecarPath);
  220. await new Promise((resolve, reject) => {
  221. const onError = (error) => {
  222. console.error(`[ERROR]: "${name}" gz failed:`, error.message);
  223. reject(error);
  224. };
  225. readStream
  226. .pipe(zlib.createGunzip().on("error", onError))
  227. .pipe(writeStream)
  228. .on("finish", () => {
  229. console.log(`[INFO]: "${name}" gunzip finished`);
  230. execSync(`chmod 755 ${sidecarPath}`);
  231. console.log(`[INFO]: "${name}" chmod binary finished`);
  232. resolve();
  233. })
  234. .on("error", onError);
  235. });
  236. }
  237. } catch (err) {
  238. // 需要删除文件
  239. await fs.remove(sidecarPath);
  240. throw err;
  241. } finally {
  242. // delete temp dir
  243. await fs.remove(tempDir);
  244. }
  245. }
  246. /**
  247. * download the file to the resources dir
  248. */
  249. async function resolveResource(binInfo) {
  250. const { file, downloadURL } = binInfo;
  251. const resDir = path.join(cwd, "src-tauri/resources");
  252. const targetPath = path.join(resDir, file);
  253. if (!FORCE && (await fs.pathExists(targetPath))) return;
  254. await fs.mkdirp(resDir);
  255. await downloadFile(downloadURL, targetPath);
  256. console.log(`[INFO]: ${file} finished`);
  257. }
  258. /**
  259. * download file and save to `path`
  260. */
  261. async function downloadFile(url, path) {
  262. const options = {};
  263. const httpProxy =
  264. process.env.HTTP_PROXY ||
  265. process.env.http_proxy ||
  266. process.env.HTTPS_PROXY ||
  267. process.env.https_proxy;
  268. if (httpProxy) {
  269. options.agent = proxyAgent(httpProxy);
  270. }
  271. const response = await fetch(url, {
  272. ...options,
  273. method: "GET",
  274. headers: { "Content-Type": "application/octet-stream" },
  275. });
  276. const buffer = await response.arrayBuffer();
  277. await fs.writeFile(path, new Uint8Array(buffer));
  278. console.log(`[INFO]: download finished "${url}"`);
  279. }
  280. /**
  281. * main
  282. */
  283. const SERVICE_URL = `https://github.com/clash-verge-rev/clash-verge-service/releases/download/${SIDECAR_HOST}`;
  284. const resolveService = () =>
  285. resolveResource({
  286. file: "clash-verge-service.exe",
  287. downloadURL: `${SERVICE_URL}/clash-verge-service.exe`,
  288. });
  289. const resolveInstall = () =>
  290. resolveResource({
  291. file: "install-service.exe",
  292. downloadURL: `${SERVICE_URL}/install-service.exe`,
  293. });
  294. const resolveUninstall = () =>
  295. resolveResource({
  296. file: "uninstall-service.exe",
  297. downloadURL: `${SERVICE_URL}/uninstall-service.exe`,
  298. });
  299. const resolveMmdb = () =>
  300. resolveResource({
  301. file: "Country.mmdb",
  302. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/country.mmdb`,
  303. });
  304. const resolveGeosite = () =>
  305. resolveResource({
  306. file: "geosite.dat",
  307. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat`,
  308. });
  309. const resolveGeoIP = () =>
  310. resolveResource({
  311. file: "geoip.dat",
  312. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat`,
  313. });
  314. const resolveEnableLoopback = () =>
  315. resolveResource({
  316. file: "enableLoopback.exe",
  317. downloadURL: `https://github.com/Kuingsmile/uwp-tool/releases/download/latest/enableLoopback.exe`,
  318. });
  319. const tasks = [
  320. // { name: "clash", func: resolveClash, retry: 5 },
  321. {
  322. name: "clash-meta-alpha",
  323. func: () =>
  324. getLatestAlphaVersion().then(() => resolveSidecar(clashMetaAlpha())),
  325. retry: 5,
  326. },
  327. {
  328. name: "clash-meta",
  329. func: () =>
  330. getLatestReleaseVersion().then(() => resolveSidecar(clashMeta())),
  331. retry: 5,
  332. },
  333. { name: "service", func: resolveService, retry: 5, winOnly: true },
  334. { name: "install", func: resolveInstall, retry: 5, winOnly: true },
  335. { name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true },
  336. { name: "mmdb", func: resolveMmdb, retry: 5 },
  337. { name: "geosite", func: resolveGeosite, retry: 5 },
  338. { name: "geoip", func: resolveGeoIP, retry: 5 },
  339. {
  340. name: "enableLoopback",
  341. func: resolveEnableLoopback,
  342. retry: 5,
  343. winOnly: true,
  344. },
  345. ];
  346. async function runTask() {
  347. const task = tasks.shift();
  348. if (!task) return;
  349. if (task.winOnly && process.platform !== "win32") return runTask();
  350. for (let i = 0; i < task.retry; i++) {
  351. try {
  352. await task.func();
  353. break;
  354. } catch (err) {
  355. console.error(`[ERROR]: task::${task.name} try ${i} ==`, err.message);
  356. if (i === task.retry - 1) throw err;
  357. }
  358. }
  359. return runTask();
  360. }
  361. runTask();
  362. runTask();