create-file-new.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import path from 'node:path';
  2. import type { Span } from '../trace';
  3. import { surgeDomainsetToClashDomainset, surgeRulesetToClashClassicalTextRuleset } from './clash';
  4. import { compareAndWriteFile, defaultSortTypeOrder, sortTypeOrder, withBannerArray } from './create-file';
  5. import { ipCidrListToSingbox, surgeDomainsetToSingbox, surgeRulesetToSingbox } from './singbox';
  6. import { buildParseDomainMap, sortDomains } from './stable-sort-domain';
  7. import { createTrie } from './trie';
  8. import { invariant } from 'foxact/invariant';
  9. import { OUTPUT_CLASH_DIR, OUTPUT_SINGBOX_DIR, OUTPUT_SURGE_DIR } from '../constants/dir';
  10. import stringify from 'json-stringify-pretty-compact';
  11. import { appendArrayInPlace } from './append-array-in-place';
  12. import { nullthrow } from 'foxact/nullthrow';
  13. import createKeywordFilter from './aho-corasick';
  14. abstract class RuleOutput {
  15. protected domainTrie = createTrie<unknown>(null, true);
  16. protected domainKeywords = new Set<string>();
  17. protected domainWildcard = new Set<string>();
  18. protected ipcidr = new Set<string>();
  19. protected ipcidrNoResolve = new Set<string>();
  20. protected ipcidr6 = new Set<string>();
  21. protected ipcidr6NoResolve = new Set<string>();
  22. protected otherRules: Array<[raw: string, orderWeight: number]> = [];
  23. protected abstract type: 'domainset' | 'non_ip' | 'ip';
  24. protected pendingPromise = Promise.resolve();
  25. static jsonToLines(this: void, json: unknown): string[] {
  26. return stringify(json).split('\n');
  27. }
  28. constructor(
  29. protected readonly span: Span,
  30. protected readonly id: string
  31. ) {}
  32. protected title: string | null = null;
  33. withTitle(title: string) {
  34. this.title = title;
  35. return this;
  36. }
  37. protected description: string[] | readonly string[] | null = null;
  38. withDescription(description: string[] | readonly string[]) {
  39. this.description = description;
  40. return this;
  41. }
  42. protected date = new Date();
  43. withDate(date: Date) {
  44. this.date = date;
  45. return this;
  46. }
  47. protected apexDomainMap: Map<string, string> | null = null;
  48. protected subDomainMap: Map<string, string> | null = null;
  49. withDomainMap(apexDomainMap: Map<string, string>, subDomainMap: Map<string, string>) {
  50. this.apexDomainMap = apexDomainMap;
  51. this.subDomainMap = subDomainMap;
  52. return this;
  53. }
  54. addDomain(domain: string) {
  55. this.domainTrie.add(domain);
  56. return this;
  57. }
  58. addDomainSuffix(domain: string) {
  59. this.domainTrie.add(domain[0] === '.' ? domain : '.' + domain);
  60. return this;
  61. }
  62. bulkAddDomainSuffix(domains: string[]) {
  63. for (let i = 0, len = domains.length; i < len; i++) {
  64. this.addDomainSuffix(domains[i]);
  65. }
  66. return this;
  67. }
  68. addDomainKeyword(keyword: string) {
  69. this.domainKeywords.add(keyword);
  70. return this;
  71. }
  72. addDomainWildcard(wildcard: string) {
  73. this.domainWildcard.add(wildcard);
  74. return this;
  75. }
  76. private async addFromDomainsetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  77. for await (const line of source) {
  78. if (line[0] === '.') {
  79. this.addDomainSuffix(line);
  80. } else {
  81. this.addDomain(line);
  82. }
  83. }
  84. }
  85. addFromDomainset(source: AsyncIterable<string> | Iterable<string> | string[]) {
  86. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  87. return this;
  88. }
  89. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string>) {
  90. for await (const line of source) {
  91. const splitted = line.split(',');
  92. const type = splitted[0];
  93. const value = splitted[1];
  94. const arg = splitted[2];
  95. switch (type) {
  96. case 'DOMAIN':
  97. this.addDomain(value);
  98. break;
  99. case 'DOMAIN-SUFFIX':
  100. this.addDomainSuffix(value);
  101. break;
  102. case 'DOMAIN-KEYWORD':
  103. this.addDomainKeyword(value);
  104. break;
  105. case 'DOMAIN-WILDCARD':
  106. this.addDomainWildcard(value);
  107. break;
  108. case 'IP-CIDR':
  109. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  110. break;
  111. case 'IP-CIDR6':
  112. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  113. break;
  114. default:
  115. this.otherRules.push([line, type in sortTypeOrder ? sortTypeOrder[type] : sortTypeOrder[defaultSortTypeOrder]]);
  116. break;
  117. }
  118. }
  119. }
  120. addFromRuleset(source: AsyncIterable<string> | Iterable<string>) {
  121. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  122. return this;
  123. }
  124. bulkAddCIDR4(cidr: string[]) {
  125. for (let i = 0, len = cidr.length; i < len; i++) {
  126. this.ipcidr.add(cidr[i]);
  127. }
  128. return this;
  129. }
  130. bulkAddCIDR4NoResolve(cidr: string[]) {
  131. for (let i = 0, len = cidr.length; i < len; i++) {
  132. this.ipcidrNoResolve.add(cidr[i]);
  133. }
  134. return this;
  135. }
  136. bulkAddCIDR6(cidr: string[]) {
  137. for (let i = 0, len = cidr.length; i < len; i++) {
  138. this.ipcidr6.add(cidr[i]);
  139. }
  140. return this;
  141. }
  142. bulkAddCIDR6NoResolve(cidr: string[]) {
  143. for (let i = 0, len = cidr.length; i < len; i++) {
  144. this.ipcidr6NoResolve.add(cidr[i]);
  145. }
  146. return this;
  147. }
  148. abstract write(): Promise<void>;
  149. }
  150. export class DomainsetOutput extends RuleOutput {
  151. protected type = 'domainset' as const;
  152. private $dumped: string[] | null = null;
  153. get dumped() {
  154. if (!this.$dumped) {
  155. const kwfilter = createKeywordFilter(this.domainKeywords);
  156. const results: string[] = [];
  157. const dumped = this.domainTrie.dump();
  158. for (let i = 0, len = dumped.length; i < len; i++) {
  159. const domain = dumped[i];
  160. if (!kwfilter(domain)) {
  161. results.push(domain);
  162. }
  163. }
  164. this.$dumped = results;
  165. }
  166. return this.$dumped;
  167. }
  168. calcDomainMap() {
  169. if (!this.apexDomainMap || !this.subDomainMap) {
  170. const { domainMap, subdomainMap } = buildParseDomainMap(this.dumped);
  171. this.apexDomainMap = domainMap;
  172. this.subDomainMap = subdomainMap;
  173. }
  174. }
  175. async write() {
  176. await this.pendingPromise;
  177. invariant(this.title, 'Missing title');
  178. invariant(this.description, 'Missing description');
  179. const sorted = sortDomains(this.dumped, this.apexDomainMap, this.subDomainMap);
  180. sorted.push('this_ruleset_is_made_by_sukkaw.ruleset.skk.moe');
  181. const surge = sorted;
  182. const clash = surgeDomainsetToClashDomainset(sorted);
  183. // TODO: Implement singbox directly using data
  184. const singbox = RuleOutput.jsonToLines(surgeDomainsetToSingbox(sorted));
  185. await Promise.all([
  186. compareAndWriteFile(
  187. this.span,
  188. withBannerArray(
  189. this.title,
  190. this.description,
  191. this.date,
  192. surge
  193. ),
  194. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  195. ),
  196. compareAndWriteFile(
  197. this.span,
  198. withBannerArray(
  199. this.title,
  200. this.description,
  201. this.date,
  202. clash
  203. ),
  204. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  205. ),
  206. compareAndWriteFile(
  207. this.span,
  208. singbox,
  209. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  210. )
  211. ]);
  212. }
  213. getStatMap() {
  214. invariant(this.dumped, 'Non dumped yet');
  215. invariant(this.apexDomainMap, 'Missing apex domain map');
  216. return Array.from(
  217. (
  218. nullthrow(this.dumped, 'Non dumped yet').reduce<Map<string, number>>((acc, cur) => {
  219. const suffix = this.apexDomainMap!.get(cur);
  220. if (suffix) {
  221. acc.set(suffix, (acc.get(suffix) ?? 0) + 1);
  222. }
  223. return acc;
  224. }, new Map())
  225. ).entries()
  226. )
  227. .filter(a => a[1] > 9)
  228. .sort(
  229. (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0])
  230. )
  231. .map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`);
  232. }
  233. }
  234. export class IPListOutput extends RuleOutput {
  235. protected type = 'ip' as const;
  236. constructor(span: Span, id: string, private readonly clashUseRule = true) {
  237. super(span, id);
  238. }
  239. async write() {
  240. await this.pendingPromise;
  241. invariant(this.title, 'Missing title');
  242. invariant(this.description, 'Missing description');
  243. const sorted4 = Array.from(this.ipcidr);
  244. const sorted6 = Array.from(this.ipcidr6);
  245. const merged = appendArrayInPlace(appendArrayInPlace([], sorted4), sorted6);
  246. const surge = sorted4.map(i => `IP-CIDR,${i}`);
  247. appendArrayInPlace(surge, sorted6.map(i => `IP-CIDR6,${i}`));
  248. surge.push('DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe');
  249. const clash = this.clashUseRule ? surge : merged;
  250. // TODO: Implement singbox directly using data
  251. const singbox = RuleOutput.jsonToLines(ipCidrListToSingbox(merged));
  252. await Promise.all([
  253. compareAndWriteFile(
  254. this.span,
  255. withBannerArray(
  256. this.title,
  257. this.description,
  258. this.date,
  259. surge
  260. ),
  261. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  262. ),
  263. compareAndWriteFile(
  264. this.span,
  265. withBannerArray(
  266. this.title,
  267. this.description,
  268. this.date,
  269. clash
  270. ),
  271. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  272. ),
  273. compareAndWriteFile(
  274. this.span,
  275. singbox,
  276. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  277. )
  278. ]);
  279. }
  280. }
  281. export class RulesetOutput extends RuleOutput {
  282. constructor(span: Span, id: string, protected type: 'non_ip' | 'ip') {
  283. super(span, id);
  284. }
  285. async write() {
  286. await this.pendingPromise;
  287. invariant(this.title, 'Missing title');
  288. invariant(this.description, 'Missing description');
  289. const results: string[] = [
  290. 'DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'
  291. ];
  292. const kwfilter = createKeywordFilter(this.domainKeywords);
  293. const sortedDomains = sortDomains(this.domainTrie.dump(), this.apexDomainMap, this.subDomainMap);
  294. for (let i = 0, len = sortedDomains.length; i < len; i++) {
  295. const domain = sortedDomains[i];
  296. if (kwfilter(domain)) {
  297. continue;
  298. }
  299. if (domain[0] === '.') {
  300. results.push(`DOMAIN-SUFFIX,${domain.slice(1)}`);
  301. } else {
  302. results.push(`DOMAIN,${domain}`);
  303. }
  304. }
  305. for (const keyword of this.domainKeywords) {
  306. results.push(`DOMAIN-KEYWORD,${keyword}`);
  307. }
  308. for (const wildcard of this.domainWildcard) {
  309. results.push(`DOMAIN-WILDCARD,${wildcard}`);
  310. }
  311. const sortedRules = this.otherRules.sort((a, b) => a[1] - b[1]);
  312. for (let i = 0, len = sortedRules.length; i < len; i++) {
  313. results.push(sortedRules[i][0]);
  314. }
  315. this.ipcidr.forEach(cidr => results.push(`IP-CIDR,${cidr}`));
  316. this.ipcidrNoResolve.forEach(cidr => results.push(`IP-CIDR,${cidr},no-resolve`));
  317. this.ipcidr6.forEach(cidr => results.push(`IP-CIDR6,${cidr}`));
  318. this.ipcidr6NoResolve.forEach(cidr => results.push(`IP-CIDR6,${cidr},no-resolve`));
  319. const surge = results;
  320. const clash = surgeRulesetToClashClassicalTextRuleset(results);
  321. // TODO: Implement singbox directly using data
  322. const singbox = RuleOutput.jsonToLines(surgeRulesetToSingbox(results));
  323. await Promise.all([
  324. compareAndWriteFile(
  325. this.span,
  326. withBannerArray(
  327. this.title,
  328. this.description,
  329. this.date,
  330. surge
  331. ),
  332. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  333. ),
  334. compareAndWriteFile(
  335. this.span,
  336. withBannerArray(
  337. this.title,
  338. this.description,
  339. this.date,
  340. clash
  341. ),
  342. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  343. ),
  344. compareAndWriteFile(
  345. this.span,
  346. singbox,
  347. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  348. )
  349. ]);
  350. }
  351. }