download-mock-assets.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233
  1. import { task } from './trace';
  2. import path from 'path';
  3. import fs from 'fs';
  4. import { Readable } from 'stream';
  5. import { pipeline } from 'stream/promises';
  6. import { fetchWithRetry } from './lib/fetch-retry';
  7. const ASSETS_LIST = {
  8. 'www-google-analytics-com_ga.js': 'https://raw.githubusercontent.com/AdguardTeam/Scriptlets/master/dist/redirect-files/google-analytics-ga.js',
  9. 'www-googletagservices-com_gpt.js': 'https://raw.githubusercontent.com/AdguardTeam/Scriptlets/master/dist/redirect-files/googletagservices-gpt.js',
  10. 'www-google-analytics-com_analytics.js': 'https://raw.githubusercontent.com/AdguardTeam/Scriptlets/master/dist/redirect-files/google-analytics.js',
  11. 'www-googlesyndication-com_adsbygoogle.js': 'https://raw.githubusercontent.com/AdguardTeam/Scriptlets/master/dist/redirect-files/googlesyndication-adsbygoogle.js',
  12. 'amazon-adsystem-com_amazon-apstag.js': 'https://raw.githubusercontent.com/AdguardTeam/Scriptlets/master/dist/redirect-files/amazon-apstag.js'
  13. } as const;
  14. const mockDir = path.resolve(__dirname, '../Mock');
  15. export const downloadMockAssets = task(require.main === module, __filename)((span) => Promise.all(Object.entries(ASSETS_LIST).map(
  16. ([filename, url]) => span
  17. .traceChild(url)
  18. .traceAsyncFn(() => fetchWithRetry(url).then(res => {
  19. const src = path.join(mockDir, filename);
  20. if (!res.body) {
  21. throw new Error(`Empty body from ${url}`);
  22. }
  23. const writeStream = fs.createWriteStream(src, { encoding: 'utf-8' });
  24. return pipeline(
  25. Readable.fromWeb(res.body),
  26. writeStream
  27. );
  28. }))
  29. )));