create-file.ts 7.9 KB

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