misc.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import path, { dirname } from 'node:path';
  2. import fs from 'node:fs';
  3. import fsp from 'node:fs/promises';
  4. import { OUTPUT_CLASH_DIR, OUTPUT_SINGBOX_DIR, OUTPUT_SURGE_DIR } from '../constants/dir';
  5. import type { HeadersInit } from 'undici';
  6. export const isTruthy = <T>(i: T | 0 | '' | false | null | undefined): i is T => !!i;
  7. export function fastStringArrayJoin(arr: string[], sep: string) {
  8. const len = arr.length;
  9. if (len === 0) {
  10. return '';
  11. }
  12. let result = arr[0];
  13. for (let i = 1; i < len; i++) {
  14. result += sep;
  15. result += arr[i];
  16. }
  17. return result;
  18. }
  19. export function fastStringCompare(a: string, b: string) {
  20. const lenA = a.length;
  21. const lenB = b.length;
  22. const minLen = lenA < lenB ? lenA : lenB;
  23. for (let i = 0; i < minLen; ++i) {
  24. const ca = a.charCodeAt(i);
  25. const cb = b.charCodeAt(i);
  26. if (ca > cb) return 1;
  27. if (ca < cb) return -1;
  28. }
  29. if (lenA === lenB) {
  30. return 0;
  31. }
  32. return lenA > lenB ? 1 : -1;
  33. };
  34. interface Write {
  35. (
  36. destination: string,
  37. input: NodeJS.TypedArray | string,
  38. ): Promise<unknown>
  39. }
  40. export function mkdirp(dir: string) {
  41. if (fs.existsSync(dir)) {
  42. return;
  43. }
  44. return fsp.mkdir(dir, { recursive: true });
  45. }
  46. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)) => {
  47. const p = mkdirp(dir);
  48. if (p) {
  49. await p;
  50. }
  51. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  52. };
  53. export const removeFiles = async (files: string[]) => Promise.all(files.map((file) => fsp.rm(file, { force: true })));
  54. export function domainWildCardToRegex(domain: string) {
  55. let result = '^';
  56. for (let i = 0, len = domain.length; i < len; i++) {
  57. switch (domain[i]) {
  58. case '.':
  59. result += String.raw`\.`;
  60. break;
  61. case '*':
  62. result += '[a-zA-Z0-9-_.]*?';
  63. break;
  64. case '?':
  65. result += '[a-zA-Z0-9-_.]';
  66. break;
  67. default:
  68. result += domain[i];
  69. }
  70. }
  71. result += '$';
  72. return result;
  73. }
  74. export const identity = <T, R = T>(x: T): R => x as any;
  75. export function appendArrayFromSet<T>(dest: T[], source: Set<T> | Array<Set<T>>, transformer: (item: T) => T = identity) {
  76. const casted = Array.isArray(source) ? source : [source];
  77. for (let i = 0, len = casted.length; i < len; i++) {
  78. const iterator = casted[i].values();
  79. let step: IteratorResult<T, undefined>;
  80. while ((step = iterator.next(), !step.done)) {
  81. dest.push(transformer(step.value));
  82. }
  83. }
  84. return dest;
  85. }
  86. export function output(id: string, type: 'non_ip' | 'ip' | 'domainset') {
  87. return [
  88. path.join(OUTPUT_SURGE_DIR, type, id + '.conf'),
  89. path.join(OUTPUT_CLASH_DIR, type, id + '.txt'),
  90. path.join(OUTPUT_SINGBOX_DIR, type, id + '.json')
  91. ] as const;
  92. }
  93. export function withBannerArray(title: string, description: string[] | readonly string[], date: Date, content: string[]) {
  94. return [
  95. '#########################################',
  96. `# ${title}`,
  97. `# Last Updated: ${date.toISOString()}`,
  98. `# Size: ${content.length}`,
  99. ...description.map(line => (line ? `# ${line}` : '#')),
  100. '#########################################',
  101. ...content,
  102. '################## EOF ##################'
  103. ];
  104. };
  105. export function mergeHeaders<T extends RequestInit['headers'] | HeadersInit>(headersA: T | undefined, headersB: T | undefined): T {
  106. if (headersA == null) {
  107. return headersB!;
  108. }
  109. if (Array.isArray(headersB)) {
  110. throw new TypeError('Array headers is not supported');
  111. }
  112. const result = new Headers(headersA as any);
  113. if (headersB instanceof Headers) {
  114. headersB.forEach((value, key) => {
  115. result.set(key, value);
  116. });
  117. return result as T;
  118. }
  119. for (const key in headersB) {
  120. if (Object.hasOwn(headersB, key)) {
  121. result.set(key, (headersB as Record<string, any>)[key]);
  122. }
  123. }
  124. return result as T;
  125. }