misc.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import path, { dirname } from 'path';
  2. import fs from 'fs';
  3. import fsp from 'fs/promises';
  4. export const isTruthy = <T>(i: T | 0 | '' | false | null | undefined): i is T => !!i;
  5. export const fastStringArrayJoin = (arr: string[], sep: string) => {
  6. let result = '';
  7. for (let i = 0, len = arr.length; i < len; i++) {
  8. if (i !== 0) {
  9. result += sep;
  10. }
  11. result += arr[i];
  12. }
  13. return result;
  14. };
  15. interface Write {
  16. (
  17. destination: string,
  18. input: NodeJS.TypedArray | string,
  19. ): Promise<unknown>
  20. }
  21. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)) => {
  22. if (!fs.existsSync(dir)) {
  23. await fsp.mkdir(dir, { recursive: true });
  24. }
  25. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  26. };
  27. export const domainWildCardToRegex = (domain: string) => {
  28. let result = '^';
  29. for (let i = 0, len = domain.length; i < len; i++) {
  30. switch (domain[i]) {
  31. case '.':
  32. result += String.raw`\.`;
  33. break;
  34. case '*':
  35. result += '[a-zA-Z0-9-_.]*?';
  36. break;
  37. case '?':
  38. result += '[a-zA-Z0-9-_.]';
  39. break;
  40. default:
  41. result += domain[i];
  42. }
  43. }
  44. result += '$';
  45. return result;
  46. };
  47. const OUTPUT_SURGE_DIR = path.resolve(__dirname, '../../List');
  48. const OUTPUT_CLASH_DIR = path.resolve(__dirname, '../../Clash');
  49. const OUTPUT_SINGBOX_DIR = path.resolve(__dirname, '../../sing-box');
  50. export const output = (id: string, type: 'non_ip' | 'ip' | 'domainset') => {
  51. return [
  52. path.join(OUTPUT_SURGE_DIR, type, id + '.conf'),
  53. path.join(OUTPUT_CLASH_DIR, type, id + '.txt'),
  54. path.join(OUTPUT_SINGBOX_DIR, type, id + '.json')
  55. ] as const;
  56. };