import { spawn } from 'node:child_process' import { mkdtemp, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, dirname } from 'node:path' import { fileURLToPath } from 'node:url' const url = process.argv[2] const EDGE = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' const dir = dirname(fileURLToPath(import.meta.url)) const profile = await mkdtemp(join(tmpdir(), 'ss-sidebar-')) const sleep = ms => new Promise(r => setTimeout(r, ms)) let browser, ws const result = {} try { browser = spawn(EDGE, ['--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'], { stdio:['ignore','ignore','pipe'] }) const endpoint = await new Promise((res, rej) => { let log=''; const t=setTimeout(()=>rej(Error('timeout')),20000); browser.stderr.on('data', b=>{ log+=b; const m=log.match(/DevTools listening on (.+)/); if(m){clearTimeout(t);res(m[1].trim())} }); browser.on('error',rej) }) ws = new WebSocket(endpoint); await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j}) let n=0; const pend=new Map() ws.onmessage = e => { const m=JSON.parse(e.data); if(m.id){const p=pend.get(m.id);pend.delete(m.id);m.error?p.reject(Error(JSON.stringify(m.error))):p.resolve(m.result)} } const cdp=(method,params={},sid)=>new Promise((res,rej)=>{const id=++n;pend.set(id,{resolve:res,reject:rej});ws.send(JSON.stringify({id,method,params,...(sid?{sessionId:sid}:{})}))}) const { targetId } = await cdp('Target.createTarget',{url:'about:blank'}) const { sessionId } = await cdp('Target.attachToTarget',{targetId,flatten:true}) const call=(m,p={})=>cdp(m,p,sessionId) await call('Page.enable'); await call('Runtime.enable') const ev = async expr => { const r = await call('Runtime.evaluate',{expression:expr,returnByValue:true,awaitPromise:true}); if(r.exceptionDetails) throw Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text); return r.result.value } await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false}) await call('Page.navigate',{url}) for(let i=0;i<80;i++){ if(await ev("document.readyState==='complete'")) break; await sleep(200) } try { await ev("(() => { const b=[...document.querySelectorAll('button')].find(x=>(x.innerText||'').trim()==='继续'); if(b)b.click(); return !!b })()") } catch {} await sleep(500) try { await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27}); await call('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape',windowsVirtualKeyCode:27}) } catch {} await sleep(3000) result.dom = await ev(`(() => { const ses = [...document.querySelectorAll('[data-session-id]')] const bodyText = (document.body.innerText||'').replace(/\\s+/g,' ').trim() return { bodySnippet: bodyText.slice(0, 1100), sessionAttrCount: ses.length, sessionIds: ses.map(e => e.getAttribute('data-session-id')).slice(0, 20), hasNewSessionWord: (bodyText.match(/新会话/g)||[]).length, } })()`) const shot = await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}) await writeFile(join(dir,'live-08-sidebar.png'), Buffer.from(shot.data,'base64')) } catch (e) { result.fatal = String(e?.stack ?? e) } finally { try{ws?.close()}catch{}; try{browser?.kill()}catch{} } console.log(JSON.stringify(result, null, 2))