create-file-new.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 { 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. abstract class RuleOutput {
  13. protected domainTrie = createTrie<unknown>(null, true);
  14. protected domainKeywords = new Set<string>();
  15. protected domainWildcard = new Set<string>();
  16. protected ipcidr = new Set<string>();
  17. protected ipcidrNoResolve = new Set<string>();
  18. protected ipcidr6 = new Set<string>();
  19. protected ipcidr6NoResolve = new Set<string>();
  20. protected otherRules: Array<[raw: string, orderWeight: number]> = [];
  21. protected abstract type: 'domainset' | 'non_ip' | 'ip';
  22. protected pendingPromise = Promise.resolve();
  23. static jsonToLines(this: void, json: unknown): string[] {
  24. return stringify(json).split('\n');
  25. }
  26. constructor(
  27. protected readonly span: Span,
  28. protected readonly id: string
  29. ) {}
  30. protected title: string | null = null;
  31. withTitle(title: string) {
  32. this.title = title;
  33. return this;
  34. }
  35. protected description: string[] | readonly string[] | null = null;
  36. withDescription(description: string[] | readonly string[]) {
  37. this.description = description;
  38. return this;
  39. }
  40. protected date = new Date();
  41. withDate(date: Date) {
  42. this.date = date;
  43. return this;
  44. }
  45. protected apexDomainMap: Map<string, string> | null = null;
  46. protected subDomainMap: Map<string, string> | null = null;
  47. withDomainMap(apexDomainMap: Map<string, string>, subDomainMap: Map<string, string>) {
  48. this.apexDomainMap = apexDomainMap;
  49. this.subDomainMap = subDomainMap;
  50. return this;
  51. }
  52. addDomain(domain: string) {
  53. this.domainTrie.add(domain);
  54. return this;
  55. }
  56. addDomainSuffix(domain: string) {
  57. this.domainTrie.add(domain[0] === '.' ? domain : '.' + domain);
  58. return this;
  59. }
  60. bulkAddDomainSuffix(domains: string[]) {
  61. for (let i = 0, len = domains.length; i < len; i++) {
  62. this.addDomainSuffix(domains[i]);
  63. }
  64. return this;
  65. }
  66. addDomainKeyword(keyword: string) {
  67. this.domainKeywords.add(keyword);
  68. return this;
  69. }
  70. addDomainWildcard(wildcard: string) {
  71. this.domainWildcard.add(wildcard);
  72. return this;
  73. }
  74. private async addFromDomainsetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  75. for await (const line of source) {
  76. if (line[0] === '.') {
  77. this.addDomainSuffix(line);
  78. } else {
  79. this.addDomain(line);
  80. }
  81. }
  82. }
  83. addFromDomainset(source: AsyncIterable<string> | Iterable<string> | string[]) {
  84. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  85. return this;
  86. }
  87. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string>) {
  88. for await (const line of source) {
  89. const splitted = line.split(',');
  90. const type = splitted[0];
  91. const value = splitted[1];
  92. const arg = splitted[2];
  93. switch (type) {
  94. case 'DOMAIN':
  95. this.addDomain(value);
  96. break;
  97. case 'DOMAIN-SUFFIX':
  98. this.addDomainSuffix(value);
  99. break;
  100. case 'DOMAIN-KEYWORD':
  101. this.addDomainKeyword(value);
  102. break;
  103. case 'DOMAIN-WILDCARD':
  104. this.addDomainWildcard(value);
  105. break;
  106. case 'IP-CIDR':
  107. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  108. break;
  109. case 'IP-CIDR6':
  110. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  111. break;
  112. default:
  113. this.otherRules.push([line, type in sortTypeOrder ? sortTypeOrder[type] : sortTypeOrder[defaultSortTypeOrder]]);
  114. break;
  115. }
  116. }
  117. }
  118. addFromRuleset(source: AsyncIterable<string> | Iterable<string>) {
  119. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  120. return this;
  121. }
  122. bulkAddCIDR4(cidr: string[]) {
  123. for (let i = 0, len = cidr.length; i < len; i++) {
  124. this.ipcidr.add(cidr[i]);
  125. }
  126. return this;
  127. }
  128. bulkAddCIDR6(cidr: string[]) {
  129. for (let i = 0, len = cidr.length; i < len; i++) {
  130. this.ipcidr6.add(cidr[i]);
  131. }
  132. return this;
  133. }
  134. abstract write(): Promise<void>;
  135. }
  136. export class DomainsetOutput extends RuleOutput {
  137. protected type = 'domainset' as const;
  138. async write() {
  139. await this.pendingPromise;
  140. invariant(this.title, 'Missing title');
  141. invariant(this.description, 'Missing description');
  142. const sorted = sortDomains(this.domainTrie.dump(), this.apexDomainMap, this.subDomainMap);
  143. sorted.push('this_ruleset_is_made_by_sukkaw.ruleset.skk.moe');
  144. const surge = sorted;
  145. const clash = surgeDomainsetToClashDomainset(sorted);
  146. // TODO: Implement singbox directly using data
  147. const singbox = RuleOutput.jsonToLines(surgeDomainsetToSingbox(sorted));
  148. await Promise.all([
  149. compareAndWriteFile(
  150. this.span,
  151. withBannerArray(
  152. this.title,
  153. this.description,
  154. this.date,
  155. surge
  156. ),
  157. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  158. ),
  159. compareAndWriteFile(
  160. this.span,
  161. withBannerArray(
  162. this.title,
  163. this.description,
  164. this.date,
  165. clash
  166. ),
  167. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  168. ),
  169. compareAndWriteFile(
  170. this.span,
  171. singbox,
  172. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  173. )
  174. ]);
  175. }
  176. }
  177. export class IPListOutput extends RuleOutput {
  178. protected type = 'ip' as const;
  179. constructor(span: Span, id: string, private readonly clashUseRule = true) {
  180. super(span, id);
  181. }
  182. async write() {
  183. await this.pendingPromise;
  184. invariant(this.title, 'Missing title');
  185. invariant(this.description, 'Missing description');
  186. const sorted4 = Array.from(this.ipcidr);
  187. const sorted6 = Array.from(this.ipcidr6);
  188. const merged = appendArrayInPlace(appendArrayInPlace([], sorted4), sorted6);
  189. const surge = sorted4.map(i => `IP-CIDR,${i}`);
  190. appendArrayInPlace(surge, sorted6.map(i => `IP-CIDR6,${i}`));
  191. surge.push('DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe');
  192. const clash = this.clashUseRule ? surge : merged;
  193. // TODO: Implement singbox directly using data
  194. const singbox = RuleOutput.jsonToLines(ipCidrListToSingbox(merged));
  195. await Promise.all([
  196. compareAndWriteFile(
  197. this.span,
  198. withBannerArray(
  199. this.title,
  200. this.description,
  201. this.date,
  202. surge
  203. ),
  204. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  205. ),
  206. compareAndWriteFile(
  207. this.span,
  208. withBannerArray(
  209. this.title,
  210. this.description,
  211. this.date,
  212. clash
  213. ),
  214. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  215. ),
  216. compareAndWriteFile(
  217. this.span,
  218. singbox,
  219. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  220. )
  221. ]);
  222. }
  223. }
  224. export class RulesetOutput extends RuleOutput {
  225. constructor(span: Span, id: string, protected type: 'non_ip' | 'ip') {
  226. super(span, id);
  227. }
  228. async write() {
  229. await this.pendingPromise;
  230. invariant(this.title, 'Missing title');
  231. invariant(this.description, 'Missing description');
  232. const results: string[] = [
  233. 'DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'
  234. ];
  235. const sortedDomains = sortDomains(this.domainTrie.dump(), this.apexDomainMap, this.subDomainMap);
  236. for (let i = 0, len = sortedDomains.length; i < len; i++) {
  237. const domain = sortedDomains[i];
  238. if (domain[0] === '.') {
  239. results.push(`DOMAIN-SUFFIX,${domain.slice(1)}`);
  240. } else {
  241. results.push(`DOMAIN,${domain}`);
  242. }
  243. }
  244. for (const keyword of this.domainKeywords) {
  245. results.push(`DOMAIN-KEYWORD,${keyword}`);
  246. }
  247. for (const wildcard of this.domainWildcard) {
  248. results.push(`DOMAIN-WILDCARD,${wildcard}`);
  249. }
  250. const sortedRules = this.otherRules.sort((a, b) => a[1] - b[1]);
  251. for (let i = 0, len = sortedRules.length; i < len; i++) {
  252. results.push(sortedRules[i][0]);
  253. }
  254. this.ipcidr.forEach(cidr => results.push(`IP-CIDR,${cidr}`));
  255. this.ipcidrNoResolve.forEach(cidr => results.push(`IP-CIDR,${cidr},no-resolve`));
  256. this.ipcidr6.forEach(cidr => results.push(`IP-CIDR6,${cidr}`));
  257. this.ipcidr6NoResolve.forEach(cidr => results.push(`IP-CIDR6,${cidr},no-resolve`));
  258. const surge = results;
  259. const clash = surgeRulesetToClashClassicalTextRuleset(results);
  260. // TODO: Implement singbox directly using data
  261. const singbox = RuleOutput.jsonToLines(surgeRulesetToSingbox(results));
  262. await Promise.all([
  263. compareAndWriteFile(
  264. this.span,
  265. withBannerArray(
  266. this.title,
  267. this.description,
  268. this.date,
  269. surge
  270. ),
  271. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  272. ),
  273. compareAndWriteFile(
  274. this.span,
  275. withBannerArray(
  276. this.title,
  277. this.description,
  278. this.date,
  279. clash
  280. ),
  281. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  282. ),
  283. compareAndWriteFile(
  284. this.span,
  285. singbox,
  286. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  287. )
  288. ]);
  289. }
  290. }