convert-clash-meta-mrs.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import path from 'node:path';
  2. import fs from 'node:fs';
  3. import fsp from 'node:fs/promises';
  4. import { pipeline } from 'node:stream/promises';
  5. import zlib from 'node:zlib';
  6. import process from 'node:process';
  7. import { async as ezspawn } from '@jsdevtools/ez-spawn';
  8. import { mkdirp } from './misc';
  9. import { $fetch } from './make-fetch-happen';
  10. const mihomoBinaryDir = path.join(__dirname, '../../node_modules/.cache/mihomo');
  11. const mihomoBinaryPath = path.join(mihomoBinaryDir, 'mihomo');
  12. const mihomoBinaryUrl: Partial<Record<NodeJS.Platform, Partial<Record<NodeJS.Architecture, string>>>> = {
  13. linux: {
  14. x64: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.18.7/mihomo-linux-amd64-compatible-v1.18.7.gz'
  15. },
  16. darwin: {
  17. x64: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.18.7/mihomo-darwin-amd64-v1.18.7.gz',
  18. arm64: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.18.7/mihomo-darwin-arm64-v1.18.7.gz'
  19. }
  20. };
  21. async function ensureMihomoBinary() {
  22. await mkdirp(mihomoBinaryDir);
  23. if (!fs.existsSync(mihomoBinaryPath)) {
  24. const writeStream = fs.createWriteStream(mihomoBinaryPath);
  25. const downloadUrl = mihomoBinaryUrl[process.platform]?.[process.arch];
  26. if (!downloadUrl) {
  27. throw new Error(`Unsupported platform: ${process.platform} ${process.arch}`);
  28. }
  29. const res = await $fetch(downloadUrl);
  30. if (!res.ok || !res.body) {
  31. throw new Error(`Failed to download mihomo binary: ${res.statusText}`);
  32. }
  33. const gunzip = zlib.createGunzip();
  34. await pipeline(
  35. res.body,
  36. gunzip,
  37. writeStream
  38. );
  39. }
  40. await fsp.chmod(mihomoBinaryPath, 0o755);
  41. }
  42. export async function convertClashMetaMrs(type: 'domain', format: 'text', input: string, output: string) {
  43. await ensureMihomoBinary();
  44. const { stderr } = await ezspawn(mihomoBinaryPath, ['convert-ruleset', type, format, input, output]);
  45. if (stderr) {
  46. throw new Error(stderr);
  47. }
  48. }