build-common.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 'foxts/append-array-in-place';
  10. import { SOURCE_DIR } from './constants/dir';
  11. import { DomainsetOutput } from './lib/rules/domainset';
  12. import { RulesetOutput } from './lib/rules/ruleset';
  13. const MAGIC_COMMAND_SKIP = '# $ custom_build_script';
  14. const MAGIC_COMMAND_TITLE = '# $ meta_title ';
  15. const MAGIC_COMMAND_DESCRIPTION = '# $ meta_description ';
  16. const MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES = '# $ sgmodule_mitm_hostnames ';
  17. const clawSourceDirPromise = new Fdir()
  18. .withRelativePaths()
  19. .filter((filepath, isDirectory) => {
  20. if (isDirectory) return true;
  21. const extname = path.extname(filepath);
  22. return extname !== '.js' && extname !== '.ts';
  23. })
  24. .crawl(SOURCE_DIR)
  25. .withPromise();
  26. export const buildCommon = task(require.main === module, __filename)(async (span) => {
  27. const promises: Array<Promise<unknown>> = [];
  28. const paths = await clawSourceDirPromise;
  29. for (let i = 0, len = paths.length; i < len; i++) {
  30. const relativePath = paths[i];
  31. const fullPath = SOURCE_DIR + path.sep + relativePath;
  32. // if (
  33. // relativePath.startsWith('ip/')
  34. // || relativePath.startsWith('non_ip/')
  35. // ) {
  36. promises.push(transform(span, fullPath, relativePath));
  37. // continue;
  38. // }
  39. // console.error(picocolors.red(`[build-comman] Unknown file: ${relativePath}`));
  40. }
  41. return Promise.all(promises);
  42. });
  43. const $skip = Symbol('skip');
  44. function processFile(span: Span, sourcePath: string) {
  45. return span.traceChildAsync(`process file: ${sourcePath}`, async () => {
  46. const lines: string[] = [];
  47. let title = '';
  48. const descriptions: string[] = [];
  49. let sgmodulePathname: string | null = null;
  50. try {
  51. let l: string | null = '';
  52. for await (const line of readFileByLine(sourcePath)) {
  53. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  54. return $skip;
  55. }
  56. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  57. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  58. continue;
  59. }
  60. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  61. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  62. continue;
  63. }
  64. if (line.startsWith(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES)) {
  65. sgmodulePathname = line.slice(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES.length).trim();
  66. continue;
  67. }
  68. 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, sgmodulePathname] as const;
  78. });
  79. }
  80. async function transform(parentSpan: Span, sourcePath: string, relativePath: string) {
  81. const extname = path.extname(sourcePath);
  82. const id = path.basename(sourcePath, extname);
  83. return parentSpan
  84. .traceChild(`transform ruleset: ${id}`)
  85. .traceAsyncFn(async (span) => {
  86. const type = relativePath.slice(0, relativePath.indexOf(path.sep));
  87. if (type !== 'ip' && type !== 'non_ip' && type !== 'domainset') {
  88. throw new TypeError(`Invalid type: ${type}`);
  89. }
  90. const res = await processFile(span, sourcePath);
  91. if (res === $skip) return;
  92. const [title, descriptions, lines, sgmoduleName] = res;
  93. let finalDescriptions: string[];
  94. if (descriptions.length) {
  95. finalDescriptions = SHARED_DESCRIPTION.slice();
  96. finalDescriptions.push('');
  97. appendArrayInPlace(finalDescriptions, descriptions);
  98. } else {
  99. finalDescriptions = SHARED_DESCRIPTION;
  100. }
  101. if (type === 'domainset') {
  102. return new DomainsetOutput(span, id)
  103. .withTitle(title)
  104. .withDescription(finalDescriptions)
  105. .addFromDomainset(lines)
  106. .write();
  107. }
  108. return new RulesetOutput(span, id, type)
  109. .withTitle(title)
  110. .withDescription(finalDescriptions)
  111. .withMitmSgmodulePath(sgmoduleName)
  112. .addFromRuleset(lines)
  113. .write();
  114. });
  115. }