// Where does a resolve's wall time actually go? Splits the one-shot resolver
// into its phases so "keep the browser warm" can be checked against numbers
// rather than assumed. Run from the repo root (needs its node_modules).
import { chromium } from 'patchright';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const T0 = Date.now();
const ms = () => Date.now() - T0;
const mark = (label) => console.log(`${String(ms()).padStart(6)}ms ${label}`);
const [, , TYPE = 'series', TMDB = '138502', S = '2', E = '7'] = process.argv;
const WATCH = TYPE === 'series'
? `https://vidcore.net/tv/${TMDB}/${S}/${E}?autoPlay=true&nextButton=false`
: `https://vidcore.net/movie/${TMDB}?autoPlay=true&nextButton=false`;
const PROFILE = fs.mkdtempSync(path.join(os.tmpdir(), 'vc_probe_'));
process.on('exit', () => { try { fs.rmSync(PROFILE, { recursive: true, force: true }); } catch {} });
mark('start');
const ctx = await chromium.launchPersistentContext(PROFILE, {
headless: false, args: ['--no-sandbox'], viewport: { width: 1280, height: 720 }, locale: 'en-US',
});
const tLaunch = ms();
mark('browser launched');
const media = new Map();
const MEDIA = /\.m3u8(\?|$)|\/playlist|\/master/i;
const NOISE = /youtube|googlevideo|ytimg|chaturbate|mmcdn|canAutoplay/i;
ctx.on('request', r => { const u = r.url(); if (MEDIA.test(u) && !NOISE.test(u)) media.set(u, 1); });
ctx.on('page', p => setTimeout(() => { if (!p.isClosed() && !/vidcore/.test(p.url())) p.close().catch(() => {}); }, 500));
const page = ctx.pages()[0] || await ctx.newPage();
await page.setExtraHTTPHeaders({ Referer: 'https://flixlab.org/' });
const tPre = ms();
await page.goto(WATCH, { waitUntil: 'domcontentloaded', timeout: 60000 }).catch(e => mark('goto warn ' + e.message));
const tGoto = ms();
mark(`goto done (+${tGoto - tPre}ms)`);
let tMedia = null;
for (let i = 0; i < 12 && !media.size; i++) {
await page.waitForTimeout(1000);
const v = await page.$('video').catch(() => null);
if (v) await v.click({ timeout: 1200, force: true }).catch(() => {});
}
if (media.size) { tMedia = ms(); mark(`m3u8 seen (+${tMedia - tGoto}ms after goto)`); }
else mark('no m3u8 in 12s');
await ctx.close();
mark('closed');
console.log(JSON.stringify({
launch_ms: tLaunch,
goto_ms: tGoto - tPre,
poll_ms: tMedia === null ? null : tMedia - tGoto,
total_to_m3u8_ms: tMedia,
found: media.size > 0,
}));