File size: 3,338 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const { pathToFileURL } = require('url');

function chromiumBinary() {
  const candidates = [process.env.CHROMIUM_BIN, '/snap/bin/chromium', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome'];
  const found = candidates.find(candidate => candidate && fs.existsSync(candidate));
  if (!found) throw new Error('offline Chromium binary is unavailable');
  return found;
}

function runBrowserCase(entryPath, caseFunction, input = null) {
  const snapShared = path.join(os.homedir(), 'snap', 'chromium', 'common');
  const stagingRoot = fs.existsSync(snapShared) ? snapShared : os.tmpdir();
  const tempDir = fs.mkdtempSync(path.join(stagingRoot, 'harbor-offline-browser-'));
  const wrapperPath = path.join(tempDir, 'runner.html');
  const candidateDir = path.join(tempDir, 'candidate');
  const resolvedEntry = path.resolve(entryPath);
  fs.cpSync(path.dirname(resolvedEntry), candidateDir, {
    recursive: true,
    filter: source => !['tests', 'logs', 'node_modules'].includes(path.basename(source)),
  });
  const entryUrl = pathToFileURL(path.join(candidateDir, path.basename(resolvedEntry))).href;
  const payload = JSON.stringify(input).replace(/</g, '\\u003c');
  const source = caseFunction.toString().replace(/<\/script/gi, '<\\/script');
  const html = `<!doctype html><meta charset="utf-8"><title>WAITING</title>
<iframe id="candidate" src="${entryUrl}"></iframe>
<script>
const finish = value => {
  const json = JSON.stringify(value);
  document.title = 'HARBOR_RESULT_' + btoa(unescape(encodeURIComponent(json)));
};
const frame = document.getElementById('candidate');
const timer = setTimeout(() => finish({ok:false,error:'candidate iframe timed out'}), 5000);
frame.addEventListener('load', async () => {
  clearTimeout(timer);
  try {
    const value = await (${source})(frame.contentDocument, frame.contentWindow, ${payload});
    finish({ok:true,value});
  } catch (error) {
    finish({ok:false,error:error && (error.stack || error.message) || String(error)});
  }
});
<\/script>`;
  fs.writeFileSync(wrapperPath, html, 'utf8');
  const result = spawnSync(chromiumBinary(), [
    '--headless=new', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage',
    '--disable-web-security', '--allow-file-access-from-files', '--disable-background-networking',
    '--disable-component-update', '--disable-default-apps', '--disable-sync',
    '--metrics-recording-only', '--no-first-run', '--host-resolver-rules=MAP * 0.0.0.0',
    `--user-data-dir=${path.join(tempDir, 'profile')}`,
    '--virtual-time-budget=6500', '--dump-dom', pathToFileURL(wrapperPath).href,
  ], { encoding: 'utf8', timeout: 15000, env: process.env });
  fs.rmSync(tempDir, { recursive: true, force: true });
  if (result.error) throw result.error;
  const match = result.stdout.match(/<title>HARBOR_RESULT_([^<]+)<\/title>/i);
  if (!match) throw new Error(`offline Chromium produced no result (exit ${result.status}); stdout=${result.stdout.slice(-1600)}; stderr=${result.stderr.slice(-1200)}`);
  const decoded = JSON.parse(Buffer.from(match[1], 'base64').toString('utf8'));
  if (!decoded.ok) throw new Error(decoded.error);
  return decoded.value;
}

module.exports = { runBrowserCase };