get-gorhill-publicsuffix.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const { toASCII } = require('punycode/');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { traceAsync } = require('./trace-runner');
  5. const publicSuffixPath = path.resolve(__dirname, '../../node_modules/.cache/public_suffix_list_dat.txt');
  6. const getGorhillPublicSuffix = () => traceAsync('create gorhill public suffix instance', async () => {
  7. const customFetch = async (url) => {
  8. const buf = await fs.promises.readFile(url);
  9. return {
  10. arrayBuffer() { return Promise.resolve(buf.buffer); }
  11. };
  12. };
  13. const [publicSuffixListDat, { default: gorhill }] = await Promise.all([
  14. fs.existsSync(publicSuffixPath)
  15. ? fs.promises.readFile(publicSuffixPath, 'utf-8')
  16. : fetch('https://publicsuffix.org/list/public_suffix_list.dat').then(r => {
  17. console.log('public_suffix_list.dat not found, fetch directly from remote.');
  18. return r.text();
  19. }),
  20. import('gorhill-publicsuffixlist')
  21. ]);
  22. gorhill.parse(publicSuffixListDat, toASCII);
  23. await gorhill.enableWASM({ customFetch });
  24. return gorhill;
  25. });
  26. /** @type {Promise<import('gorhill-publicsuffixlist').default> | null} */
  27. let gorhillPublicSuffixPromise = null;
  28. module.exports.getGorhillPublicSuffixPromise = () => {
  29. gorhillPublicSuffixPromise ||= getGorhillPublicSuffix();
  30. return gorhillPublicSuffixPromise;
  31. };