build-common.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // @ts-check
  2. import * as path from 'path';
  3. import { readFileByLine } from './lib/fetch-text-by-line';
  4. import { processLine } from './lib/process-line';
  5. import { createRuleset } from './lib/create-file';
  6. import { domainDeduper } from './lib/domain-deduper';
  7. import type { Span } from './trace';
  8. import { task } from './trace';
  9. import { SHARED_DESCRIPTION } from './lib/constants';
  10. import { fdir as Fdir } from 'fdir';
  11. import { appendArrayInPlace } from './lib/append-array-in-place';
  12. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  13. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  14. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  15. const sourceDir = path.resolve(__dirname, '../Source');
  16. const outputSurgeDir = path.resolve(__dirname, '../List');
  17. const outputClashDir = path.resolve(__dirname, '../Clash');
  18. const domainsetSrcFolder = 'domainset' + path.sep;
  19. export const buildCommon = task(typeof Bun !== 'undefined' ? Bun.main === __filename : require.main === module, __filename)(async (span) => {
  20. const promises: Array<Promise<unknown>> = [];
  21. const paths = await new Fdir()
  22. .withRelativePaths()
  23. // .exclude((dirName, dirPath) => {
  24. // if (dirName === 'domainset' || dirName === 'ip' || dirName === 'non_ip') {
  25. // return false;
  26. // }
  27. // console.error(picocolors.red(`[build-comman] Unknown dir: ${dirPath}`));
  28. // return true;
  29. // })
  30. .filter((filepath, isDirectory) => {
  31. if (isDirectory) return true;
  32. const extname = path.extname(filepath);
  33. if (extname === '.js' || extname === '.ts') {
  34. return false;
  35. }
  36. return true;
  37. })
  38. .crawl(sourceDir)
  39. .withPromise();
  40. for (let i = 0, len = paths.length; i < len; i++) {
  41. const relativePath = paths[i];
  42. const fullPath = sourceDir + path.sep + relativePath;
  43. if (relativePath.startsWith(domainsetSrcFolder)) {
  44. promises.push(transformDomainset(span, fullPath, relativePath));
  45. continue;
  46. }
  47. // if (
  48. // relativePath.startsWith('ip/')
  49. // || relativePath.startsWith('non_ip/')
  50. // ) {
  51. promises.push(transformRuleset(span, fullPath, relativePath));
  52. // continue;
  53. // }
  54. // console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  55. }
  56. return Promise.all(promises);
  57. });
  58. const processFile = (span: Span, sourcePath: string) => {
  59. // console.log('Processing', sourcePath);
  60. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  61. const lines: string[] = [];
  62. let title = '';
  63. const descriptions: string[] = [];
  64. try {
  65. for await (const line of readFileByLine(sourcePath)) {
  66. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  67. return null;
  68. }
  69. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  70. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  71. continue;
  72. }
  73. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  74. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  75. continue;
  76. }
  77. const l = processLine(line);
  78. if (l) {
  79. lines.push(l);
  80. }
  81. }
  82. } catch (e) {
  83. console.error('Error processing', sourcePath);
  84. console.trace(e);
  85. }
  86. return [title, descriptions, lines] as const;
  87. });
  88. };
  89. function transformDomainset(parentSpan: Span, sourcePath: string, relativePath: string) {
  90. return parentSpan
  91. .traceChildAsync(
  92. `transform domainset: ${path.basename(sourcePath, path.extname(sourcePath))}`,
  93. async (span) => {
  94. const res = await processFile(span, sourcePath);
  95. if (!res) return;
  96. const [title, descriptions, lines] = res;
  97. const deduped = domainDeduper(lines);
  98. let description: string[];
  99. if (descriptions.length) {
  100. description = SHARED_DESCRIPTION.slice();
  101. description.push('');
  102. appendArrayInPlace(description, descriptions);
  103. } else {
  104. description = SHARED_DESCRIPTION;
  105. }
  106. return createRuleset(
  107. span,
  108. title,
  109. description,
  110. new Date(),
  111. deduped,
  112. 'domainset',
  113. path.resolve(outputSurgeDir, relativePath),
  114. path.resolve(outputClashDir, `${relativePath.slice(0, -path.extname(relativePath).length)}.txt`)
  115. );
  116. }
  117. );
  118. }
  119. /**
  120. * Output Surge RULE-SET and Clash classical text format
  121. */
  122. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  123. return parentSpan
  124. .traceChild(`transform ruleset: ${path.basename(sourcePath, path.extname(sourcePath))}`)
  125. .traceAsyncFn(async (span) => {
  126. const res = await processFile(span, sourcePath);
  127. if (!res) return null;
  128. const [title, descriptions, lines] = res;
  129. let description: string[];
  130. if (descriptions.length) {
  131. description = SHARED_DESCRIPTION.slice();
  132. description.push('');
  133. appendArrayInPlace(description, descriptions);
  134. } else {
  135. description = SHARED_DESCRIPTION;
  136. }
  137. return createRuleset(
  138. span,
  139. title,
  140. description,
  141. new Date(),
  142. lines,
  143. 'ruleset',
  144. path.resolve(outputSurgeDir, relativePath),
  145. path.resolve(outputClashDir, `${relativePath.slice(0, -path.extname(relativePath).length)}.txt`)
  146. );
  147. });
  148. }