download-mock-assets.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { task } from './trace';
  2. import path from 'node:path';
  3. import fs from 'node:fs';
  4. import { pipeline } from 'node:stream/promises';
  5. import { OUTPUT_MOCK_DIR } from './constants/dir';
  6. import { mkdirp } from './lib/misc';
  7. import { $fetch } from './lib/make-fetch-happen';
  8. const ASSETS_LIST = {
  9. 'www-google-analytics-com_ga.js': 'https://unpkg.com/@adguard/scriptlets@latest/dist/redirect-files/google-analytics-ga.js',
  10. 'www-googletagservices-com_gpt.js': 'https://unpkg.com/@adguard/scriptlets@latest/dist/redirect-files/googletagservices-gpt.js',
  11. 'www-google-analytics-com_analytics.js': 'https://unpkg.com/@adguard/scriptlets@latest/dist/redirect-files/google-analytics.js',
  12. 'www-googlesyndication-com_adsbygoogle.js': 'https://unpkg.com/@adguard/scriptlets@latest/dist/redirect-files/googlesyndication-adsbygoogle.js',
  13. 'amazon-adsystem-com_amazon-apstag.js': 'https://unpkg.com/@adguard/scriptlets@latest/dist/redirect-files/amazon-apstag.js'
  14. } as const;
  15. export const downloadMockAssets = task(require.main === module, __filename)(async (span) => {
  16. const p = mkdirp(OUTPUT_MOCK_DIR);
  17. if (p) {
  18. await p;
  19. }
  20. return Promise.all(Object.entries(ASSETS_LIST).map(
  21. ([filename, url]) => span
  22. .traceChildAsync(url, async () => {
  23. const res = await $fetch(url);
  24. if (!res.ok) {
  25. console.error(`Failed to download ${url}`);
  26. // we can safely skip this since we can always use previous version
  27. return;
  28. }
  29. if (!res.body) {
  30. console.error(`Empty body from ${url}`);
  31. // we can safely skip this since we can always use previous version
  32. return;
  33. }
  34. const src = path.join(OUTPUT_MOCK_DIR, filename);
  35. return pipeline(
  36. res.body,
  37. fs.createWriteStream(src, 'utf-8')
  38. );
  39. })
  40. ));
  41. });