import { createServer } from 'node:http'
import { existsSync } from 'node:fs'
import { readFile, writeFile } from 'node:fs/promises'
import { basename, resolve } from 'node:path'
import { spawn } from 'node:child_process'
import createOcctHistory from '../native/occt-history/dist/bitbybit-occt-history.js'
import { createChromeProfile, removeChromeProfile } from './chrome-profile.mjs'
const root = resolve(new URL('..', import.meta.url).pathname)
const reportPath = resolve(root, 'config/chrome-native-pipe-history-verification.json')
const occt = await createOcctHistory()
const profileStep = occt.shapeToStep(occt.makeRectangleFace(2, 2))
const spineStep = occt.shapeToStep(occt.makeLineWire(0, 0, 0, 0, 0, 5))
const waitForPort = (child) => new Promise((resolvePort, reject) => { let output = ''; const timer = setTimeout(() => reject(new Error(output)), 30_000); const onData = (chunk) => { output += String(chunk); const match = output.match(/http:\/\/127\.0\.0\.1:(\d+)/); if (match) { clearTimeout(timer); resolvePort(Number(match[1])) } }; child.stdout.on('data', onData); child.stderr.on('data', onData) })
const vite = spawn('./nodew', ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }); const vitePort = await waitForPort(vite)
let resolveReport; const reportPromise = new Promise((resolveValue) => { resolveReport = resolveValue })
const server = createServer(async (request, response) => {
  response.setHeader('Cross-Origin-Opener-Policy', 'same-origin'); response.setHeader('Cross-Origin-Embedder-Policy', 'require-corp'); response.setHeader('Cross-Origin-Resource-Policy', 'same-origin')
  if (request.method === 'POST' && request.url === '/__native-pipe-history-report') { let body = ''; request.on('data', (chunk) => { body += String(chunk) }); request.on('end', async () => { const report = JSON.parse(body); await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`); resolveReport(report); response.writeHead(204); response.end() }); return }
  if (request.url === '/chrome-native-pipe-history-harness.html') { response.end(await readFile(resolve(root, 'public/chrome-native-pipe-history-harness.html'))); return }
  if (request.url === '/native-pipe-profile.step') { response.setHeader('content-type', 'application/step'); response.end(profileStep); return }
  if (request.url === '/native-pipe-spine.step') { response.setHeader('content-type', 'application/step'); response.end(spineStep); return }
  if (request.url?.startsWith('/native/occt-history/')) { const name = basename(new URL(request.url, 'http://x').pathname); const file = resolve(root, 'native/occt-history/dist', name); if (!['bitbybit-occt-history.js', 'bitbybit-occt-history.wasm'].includes(name) || !existsSync(file)) { response.writeHead(404); response.end(); return }; response.setHeader('content-type', name.endsWith('.wasm') ? 'application/wasm' : 'text/javascript'); response.end(await readFile(file)); return }
  const upstream = await fetch(`http://127.0.0.1:${vitePort}${request.url}`); response.writeHead(upstream.status, Object.fromEntries(upstream.headers.entries())); response.end(Buffer.from(await upstream.arrayBuffer()))
})
await new Promise((resolveServer) => server.listen(0, '127.0.0.1', resolveServer))
const executable = process.env.CHROME_BIN || '/home/mes123456/.local/bin/google-chrome'; const profile = await createChromeProfile('native-pipe-history'); const chrome = spawn(executable, ['--headless=new', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage', `--user-data-dir=${profile}`, `http://127.0.0.1:${server.address().port}/chrome-native-pipe-history-harness.html`], { stdio: 'ignore' })
const report = await Promise.race([reportPromise, new Promise((resolveTimeout) => setTimeout(() => resolveTimeout({ status: 'timeout' }), 180_000))]); chrome.kill('SIGTERM'); vite.kill('SIGTERM'); server.closeAllConnections?.(); server.close(); await removeChromeProfile(profile); console.log(JSON.stringify(report, null, 2)); process.exit(report.status === 'pass' ? 0 : 1)
