convert-clash-meta-mrs.ts 1.9 KB

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