build-common.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 } 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. for await (const line of readFileByLine(sourcePath)) {
  52. if (line.startsWith(MAGIC_COMMAND_SKIP)) {
  53. return $skip;
  54. }
  55. if (line.startsWith(MAGIC_COMMAND_TITLE)) {
  56. title = line.slice(MAGIC_COMMAND_TITLE.length).trim();
  57. continue;
  58. }
  59. if (line.startsWith(MAGIC_COMMAND_DESCRIPTION)) {
  60. descriptions.push(line.slice(MAGIC_COMMAND_DESCRIPTION.length).trim());
  61. continue;
  62. }
  63. if (line.startsWith(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES)) {
  64. sgmodulePathname = line.slice(MAGIC_COMMAND_SGMODULE_MITM_HOSTNAMES.length).trim();
  65. continue;
  66. }
  67. const l = processLine(line);
  68. if (l) {
  69. lines.push(l);
  70. }
  71. }
  72. } catch (e) {
  73. console.error('Error processing', sourcePath);
  74. console.trace(e);
  75. }
  76. return [title, descriptions, lines, sgmodulePathname] as const;
  77. });
  78. }
  79. async function transform(parentSpan: Span, sourcePath: string, relativePath: string) {
  80. const extname = path.extname(sourcePath);
  81. const id = path.basename(sourcePath, extname);
  82. return parentSpan
  83. .traceChild(`transform ruleset: ${id}`)
  84. .traceAsyncFn(async (span) => {
  85. const type = relativePath.slice(0, relativePath.indexOf(path.sep));
  86. if (type !== 'ip' && type !== 'non_ip' && type !== 'domainset') {
  87. throw new TypeError(`Invalid type: ${type}`);
  88. }
  89. const res = await processFile(span, sourcePath);
  90. if (res === $skip) return;
  91. const [title, descriptions, lines, sgmoduleName] = res;
  92. let finalDescriptions: string[];
  93. if (descriptions.length) {
  94. finalDescriptions = SHARED_DESCRIPTION.slice();
  95. finalDescriptions.push('');
  96. appendArrayInPlace(finalDescriptions, descriptions);
  97. } else {
  98. finalDescriptions = SHARED_DESCRIPTION;
  99. }
  100. if (type === 'domainset') {
  101. return new DomainsetOutput(span, id)
  102. .withTitle(title)
  103. .withDescription(finalDescriptions)
  104. .addFromDomainset(lines)
  105. .write();
  106. }
  107. return new RulesetOutput(span, id, type)
  108. .withTitle(title)
  109. .withDescription(finalDescriptions)
  110. .withMitmSgmodulePath(sgmoduleName)
  111. .addFromRuleset(lines)
  112. .write();
  113. });
  114. }