create-file.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // @ts-check
  2. import { surgeDomainsetToClashDomainset, surgeRulesetToClashClassicalTextRuleset } from './clash';
  3. import picocolors from 'picocolors';
  4. import type { Span } from '../trace';
  5. import path from 'node:path';
  6. import fs from 'node:fs';
  7. import { fastStringArrayJoin, writeFile } from './misc';
  8. import { readFileByLine } from './fetch-text-by-line';
  9. import stringify from 'json-stringify-pretty-compact';
  10. import { ipCidrListToSingbox, surgeDomainsetToSingbox, surgeRulesetToSingbox } from './singbox';
  11. import { createTrie } from './trie';
  12. import { pack, unpackFirst, unpackSecond } from './bitwise';
  13. import { asyncWriteToStream } from './async-write-to-stream';
  14. export const fileEqual = async (linesA: string[], source: AsyncIterable<string>): Promise<boolean> => {
  15. if (linesA.length === 0) {
  16. return false;
  17. }
  18. let index = -1;
  19. for await (const lineB of source) {
  20. index++;
  21. if (index > linesA.length - 1) {
  22. if (index === linesA.length && lineB === '') {
  23. index--;
  24. continue;
  25. }
  26. // The file becomes smaller
  27. return false;
  28. }
  29. const lineA = linesA[index];
  30. if (lineA[0] === '#' && lineB[0] === '#') {
  31. continue;
  32. }
  33. if (
  34. lineA[0] === '/'
  35. && lineA[1] === '/'
  36. && lineB[0] === '/'
  37. && lineB[1] === '/'
  38. && lineA[3] === '#'
  39. && lineB[3] === '#'
  40. ) {
  41. continue;
  42. }
  43. if (lineA !== lineB) {
  44. return false;
  45. }
  46. }
  47. if (index !== linesA.length - 1) {
  48. // The file becomes larger
  49. return false;
  50. }
  51. return true;
  52. };
  53. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  54. let isEqual = true;
  55. const linesALen = linesA.length;
  56. if (fs.existsSync(filePath)) {
  57. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  58. } else {
  59. console.log(`${filePath} does not exists, writing...`);
  60. isEqual = false;
  61. }
  62. if (isEqual) {
  63. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  64. return;
  65. }
  66. await span.traceChildAsync(`writing ${filePath}`, async () => {
  67. // The default highwater mark is normally 16384,
  68. // So we make sure direct write to file if the content is
  69. // most likely less than 500 lines
  70. if (linesALen < 500) {
  71. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  72. }
  73. const writeStream = fs.createWriteStream(filePath);
  74. for (let i = 0; i < linesALen; i++) {
  75. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  76. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  77. if (p) await p;
  78. }
  79. await asyncWriteToStream(writeStream, '\n');
  80. writeStream.end();
  81. });
  82. }
  83. const withBannerArray = (title: string, description: string[] | readonly string[], date: Date, content: string[]) => {
  84. return [
  85. '#########################################',
  86. `# ${title}`,
  87. `# Last Updated: ${date.toISOString()}`,
  88. `# Size: ${content.length}`,
  89. ...description.map(line => (line ? `# ${line}` : '#')),
  90. '#########################################',
  91. ...content,
  92. '################## EOF ##################'
  93. ];
  94. };
  95. const defaultSortTypeOrder = Symbol('defaultSortTypeOrder');
  96. const sortTypeOrder: Record<string | typeof defaultSortTypeOrder, number> = {
  97. DOMAIN: 1,
  98. 'DOMAIN-SUFFIX': 2,
  99. 'DOMAIN-KEYWORD': 10,
  100. // experimental domain wildcard support
  101. 'DOMAIN-WILDCARD': 20,
  102. 'DOMAIN-REGEX': 21,
  103. 'USER-AGENT': 30,
  104. 'PROCESS-NAME': 40,
  105. [defaultSortTypeOrder]: 50, // default sort order for unknown type
  106. 'URL-REGEX': 100,
  107. AND: 300,
  108. OR: 300,
  109. 'IP-CIDR': 400,
  110. 'IP-CIDR6': 400
  111. };
  112. const flagDomain = 1 << 2;
  113. const flagDomainSuffix = 1 << 3;
  114. // dedupe and sort based on rule type
  115. const processRuleSet = (ruleSet: string[]) => {
  116. const trie = createTrie<number>(null, true);
  117. /** Packed Array<[valueIndex: number, weight: number]> */
  118. const sortMap: number[] = [];
  119. for (let i = 0, len = ruleSet.length; i < len; i++) {
  120. const line = ruleSet[i];
  121. const [type, value] = line.split(',');
  122. let extraWeight = 0;
  123. switch (type) {
  124. case 'DOMAIN':
  125. trie.add(value, pack(i, flagDomain));
  126. break;
  127. case 'DOMAIN-SUFFIX':
  128. trie.add('.' + value, pack(i, flagDomainSuffix));
  129. break;
  130. case 'URL-REGEX':
  131. if (value.includes('.+') || value.includes('.*')) {
  132. extraWeight += 10;
  133. }
  134. if (value.includes('|')) {
  135. extraWeight += 1;
  136. }
  137. sortMap.push(pack(i, sortTypeOrder[type] + extraWeight));
  138. break;
  139. case null:
  140. sortMap.push(pack(i, 10));
  141. break;
  142. default:
  143. if (type in sortTypeOrder) {
  144. sortMap.push(pack(i, sortTypeOrder[type]));
  145. } else {
  146. sortMap.push(pack(i, sortTypeOrder[defaultSortTypeOrder]));
  147. }
  148. }
  149. }
  150. const dumped = trie.dumpMeta();
  151. for (let i = 0, len = dumped.length; i < len; i++) {
  152. const originalIndex = unpackFirst(dumped[i]);
  153. const flag = unpackSecond(dumped[i]);
  154. const type = flag === flagDomain ? 'DOMAIN' : 'DOMAIN-SUFFIX';
  155. sortMap.push(pack(originalIndex, sortTypeOrder[type]));
  156. }
  157. return sortMap
  158. .sort((a, b) => unpackSecond(a) - unpackSecond(b))
  159. .map(c => ruleSet[unpackFirst(c)]);
  160. };
  161. const MARK = 'this_ruleset_is_made_by_sukkaw.ruleset.skk.moe';
  162. export const createRuleset = (
  163. parentSpan: Span,
  164. title: string, description: string[] | readonly string[], date: Date, content: string[],
  165. type: 'ruleset' | 'domainset' | 'ipcidr' | 'ipcidr6',
  166. [surgePath, clashPath, singBoxPath, _clashMrsPath]: readonly [
  167. surgePath: string,
  168. clashPath: string,
  169. singBoxPath: string,
  170. _clashMrsPath?: string
  171. ]
  172. ) => parentSpan.traceChildAsync(
  173. `create ruleset: ${path.basename(surgePath, path.extname(surgePath))}`,
  174. async (childSpan) => {
  175. const surgeContent = childSpan.traceChildSync('process surge ruleset', () => {
  176. let _surgeContent;
  177. switch (type) {
  178. case 'domainset':
  179. _surgeContent = [MARK, ...content];
  180. break;
  181. case 'ruleset':
  182. _surgeContent = [`DOMAIN,${MARK}`, ...processRuleSet(content)];
  183. break;
  184. case 'ipcidr':
  185. _surgeContent = [`DOMAIN,${MARK}`, ...processRuleSet(content.map(i => `IP-CIDR,${i}`))];
  186. break;
  187. case 'ipcidr6':
  188. _surgeContent = [`DOMAIN,${MARK}`, ...processRuleSet(content.map(i => `IP-CIDR6,${i}`))];
  189. break;
  190. default:
  191. throw new TypeError(`Unknown type: ${type}`);
  192. }
  193. return withBannerArray(title, description, date, _surgeContent);
  194. });
  195. const clashContent = childSpan.traceChildSync('convert incoming ruleset to clash', () => {
  196. let _clashContent;
  197. switch (type) {
  198. case 'domainset':
  199. _clashContent = [MARK, ...surgeDomainsetToClashDomainset(content)];
  200. break;
  201. case 'ruleset':
  202. _clashContent = [`DOMAIN,${MARK}`, ...surgeRulesetToClashClassicalTextRuleset(processRuleSet(content))];
  203. break;
  204. case 'ipcidr':
  205. case 'ipcidr6':
  206. _clashContent = content;
  207. break;
  208. default:
  209. throw new TypeError(`Unknown type: ${type}`);
  210. }
  211. return withBannerArray(title, description, date, _clashContent);
  212. });
  213. const singboxContent = childSpan.traceChildSync('convert incoming ruleset to singbox', () => {
  214. let _singBoxContent;
  215. switch (type) {
  216. case 'domainset':
  217. _singBoxContent = surgeDomainsetToSingbox([MARK, ...processRuleSet(content)]);
  218. break;
  219. case 'ruleset':
  220. _singBoxContent = surgeRulesetToSingbox([`DOMAIN,${MARK}`, ...processRuleSet(content)]);
  221. break;
  222. case 'ipcidr':
  223. case 'ipcidr6':
  224. _singBoxContent = ipCidrListToSingbox(content);
  225. break;
  226. default:
  227. throw new TypeError(`Unknown type: ${type}`);
  228. }
  229. return stringify(_singBoxContent).split('\n');
  230. });
  231. await Promise.all([
  232. compareAndWriteFile(childSpan, surgeContent, surgePath),
  233. compareAndWriteFile(childSpan, clashContent, clashPath),
  234. compareAndWriteFile(childSpan, singboxContent, singBoxPath)
  235. ]);
  236. // if (clashMrsPath) {
  237. // if (type === 'domainset') {
  238. // await childSpan.traceChildAsync('clash meta mrs domain ' + clashMrsPath, async () => {
  239. // await fs.promises.mkdir(path.dirname(clashMrsPath), { recursive: true });
  240. // await convertClashMetaMrs(
  241. // 'domain', 'text', clashPath, clashMrsPath
  242. // );
  243. // });
  244. // }
  245. // }
  246. }
  247. );