build-common.ts 4.6 KB

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