check.mjs 10 KB

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