misc.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import path, { dirname } from 'path';
  2. import fs from 'fs';
  3. import fsp from 'fs/promises';
  4. import { makeRe } from 'picomatch';
  5. export const isTruthy = <T>(i: T | 0 | '' | false | null | undefined): i is T => !!i;
  6. export const fastStringArrayJoin = (arr: string[], sep: string) => {
  7. let result = '';
  8. for (let i = 0, len = arr.length; i < len; i++) {
  9. if (i !== 0) {
  10. result += sep;
  11. }
  12. result += arr[i];
  13. }
  14. return result;
  15. };
  16. interface Write {
  17. (
  18. destination: string,
  19. input: NodeJS.TypedArray | string,
  20. ): Promise<unknown>
  21. }
  22. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)) => {
  23. if (!fs.existsSync(dir)) {
  24. await fsp.mkdir(dir, { recursive: true });
  25. }
  26. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  27. };
  28. export const domainWildCardToRegex = (domain: string) => {
  29. return makeRe(domain, { contains: false, strictSlashes: true }).source;
  30. };
  31. const OUTPUT_SURGE_DIR = path.resolve(__dirname, '../../List');
  32. const OUTPUT_CLASH_DIR = path.resolve(__dirname, '../../Clash');
  33. const OUTPUT_SINGBOX_DIR = path.resolve(__dirname, '../../sing-box');
  34. export const output = (id: string, type: 'non_ip' | 'ip' | 'domainset') => {
  35. return [
  36. path.join(OUTPUT_SURGE_DIR, type, id + '.conf'),
  37. path.join(OUTPUT_CLASH_DIR, type, id + '.txt'),
  38. path.join(OUTPUT_SINGBOX_DIR, type, id + '.json')
  39. ] as const;
  40. };