build-common.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // @ts-check
  2. import * as path from 'node:path';
  3. import { readFileByLine } from './lib/fetch-text-by-line';
  4. import { processLine } from './lib/process-line';
  5. import type { Span } from './trace';
  6. import { task } from './trace';
  7. import { SHARED_DESCRIPTION } from './constants/description';
  8. import { fdir as Fdir } from 'fdir';
  9. import { appendArrayInPlace } from './lib/append-array-in-place';
  10. import { SOURCE_DIR } from './constants/dir';
  11. import { DomainsetOutput, RulesetOutput } from './lib/create-file';
  12. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  13. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  14. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  15. const MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES = '# $ sgmodule_mitm_hostnames ';
  16. const domainsetSrcFolder = 'domainset' + path.sep;
  17. export const buildCommon = task(require.main === module, __filename)(async (span) => {
  18. const promises: Array<Promise<unknown>> = [];
  19. const paths = await new Fdir()
  20. .withRelativePaths()
  21. .filter((filepath, isDirectory) => {
  22. if (isDirectory) return true;
  23. const extname = path.extname(filepath);
  24. return !(extname === '.js' || extname === '.ts');
  25. })
  26. .crawl(SOURCE_DIR)
  27. .withPromise();
  28. for (let i = 0, len = paths.length; i < len; i++) {
  29. const relativePath = paths[i];
  30. const fullPath = SOURCE_DIR + path.sep + relativePath;
  31. if (relativePath.startsWith(domainsetSrcFolder)) {
  32. promises.push(transformDomainset(span, fullPath));
  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. const $skip = Symbol('skip');
  47. function processFile(span: Span, sourcePath: string) {
  48. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  49. const lines: string[] = [];
  50. let title = '';
  51. const descriptions: string[] = [];
  52. let sgmodulePathname: string | null = null;
  53. try {
  54. for await (const line of readFileByLine(sourcePath)) {
  55. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  56. return $skip;
  57. }
  58. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  59. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  60. continue;
  61. }
  62. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  63. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  64. continue;
  65. }
  66. if (line.startsWith(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES)) {
  67. sgmodulePathname = line.slice(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES.length).trim();
  68. continue;
  69. }
  70. const l = processLine(line);
  71. if (l) {
  72. lines.push(l);
  73. }
  74. }
  75. } catch (e) {
  76. console.error('Error processing', sourcePath);
  77. console.trace(e);
  78. }
  79. return [title, descriptions, lines, sgmodulePathname] as const;
  80. });
  81. }
  82. function transformDomainset(parentSpan: Span, sourcePath: string) {
  83. const extname = path.extname(sourcePath);
  84. const basename = path.basename(sourcePath, extname);
  85. return parentSpan
  86. .traceChildAsync(
  87. `transform domainset: ${basename}`,
  88. async (span) => {
  89. const res = await processFile(span, sourcePath);
  90. if (res === $skip) return;
  91. const id = basename;
  92. const [title, descriptions, lines] = res;
  93. let description: string[];
  94. if (descriptions.length) {
  95. description = SHARED_DESCRIPTION.slice();
  96. description.push('');
  97. appendArrayInPlace(description, descriptions);
  98. } else {
  99. description = SHARED_DESCRIPTION;
  100. }
  101. return new DomainsetOutput(span, id)
  102. .withTitle(title)
  103. .withDescription(description)
  104. .addFromDomainset(lines)
  105. .write();
  106. }
  107. );
  108. }
  109. /**
  110. * Output Surge RULE-SET and Clash classical text format
  111. */
  112. async function transformRuleset(parentSpan: Span, sourcePath: string, relativePath: string) {
  113. const extname = path.extname(sourcePath);
  114. const basename = path.basename(sourcePath, extname);
  115. return parentSpan
  116. .traceChild(`transform ruleset: ${basename}`)
  117. .traceAsyncFn(async (span) => {
  118. const res = await processFile(span, sourcePath);
  119. if (res === $skip) return;
  120. const id = basename;
  121. const type = relativePath.slice(0, -extname.length).split(path.sep)[0];
  122. if (type !== 'ip' && type !== 'non_ip') {
  123. throw new TypeError(`Invalid type: ${type}`);
  124. }
  125. const [title, descriptions, lines, sgmodulePathname] = res;
  126. let description: string[];
  127. if (descriptions.length) {
  128. description = SHARED_DESCRIPTION.slice();
  129. description.push('');
  130. appendArrayInPlace(description, descriptions);
  131. } else {
  132. description = SHARED_DESCRIPTION;
  133. }
  134. return new RulesetOutput(span, id, type)
  135. .withTitle(title)
  136. .withDescription(description)
  137. .withMitmSgmodulePath(sgmodulePathname)
  138. .addFromRuleset(lines)
  139. .write();
  140. });
  141. }