build-common.ts 4.2 KB

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