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-v020-')) const out = { consoleErrors: [] } const sleep = ms => new Promise(r => setTimeout(r, ms)) let browser, ws 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((resolve, reject) => { let log=''; const t=setTimeout(()=>reject(Error('timeout')),20000); browser.stderr.on('data', b=>{ log+=b; const m=log.match(/DevTools listening on (.+)/); if(m){clearTimeout(t);resolve(m[1].trim())} }); browser.on('error',reject) }) 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)} else if(m.method==='Runtime.exceptionThrown'){ out.consoleErrors.push((m.params.exceptionDetails.exception?.description||m.params.exceptionDetails.text||'').slice(0,160)) } } 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 x => { const r=await call('Runtime.evaluate',{expression:x,returnByValue:true,awaitPromise:true}); if(r.exceptionDetails) throw Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text); return r.result.value } const waitFor = async (x,t=45000)=>{ const end=Date.now()+t; while(Date.now() { const r=await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}); await writeFile(join(dir,name),Buffer.from(r.data,'base64')) } const openWorkbench = async () => { await waitFor("!!document.querySelector('.ssw-nav-hit')",60000) await ev("document.querySelector('.ssw-nav-hit').click(); true") return await waitFor("!!document.querySelector('.ssw-root')",20000) } await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false}) await call('Page.navigate',{url}) await waitFor("document.readyState === 'complete'",30000) try { await ev("(() => { const b=[...document.querySelectorAll('button')].find(x=>(x.innerText||'').trim()==='继续'); if(b)b.click(); return !!b })()") } catch {} out.opened = await openWorkbench() await sleep(2500) out.tabs = await ev("(() => [...document.querySelectorAll('.ssw-tab')].map(b=>({ text:(b.innerText||'').replace(/\\s+/g,' ').trim(), active:b.getAttribute('aria-selected') })))()") // 通过同源 API 造一条任务和一条成果(选十席都绑定的项目) out.seeded = await ev("(async () => { const call=async(endpoint,payload)=>{const r=await fetch('api/sansheng',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({endpoint,payload})}); return (await r.json())}; const list=await call('list',null); let best=null; for(const p of (list.value?.projects||[])){ const view=await call('project',{projectId:p.id}); if(view.ok && view.value.project.seats.filter(s=>s.status==='bound').length===10){ best={id:p.id,name:p.name}; break } } if(!best) best=(list.value?.projects||[])[0]; if(!best) return {error:'no project'}; const t=await call('taskCreate',{projectId:best.id,title:'整理需求',goal:'写清楚验收标准',ownerSeatId:'zhongshu'}); const a=await call('artifactAdd',{projectId:best.id,title:'需求说明.pdf',path:'D:/out/需求说明.pdf',summary:'首版交付'}); return { project:best, task:t.ok, artifact:a.ok } })()") await call('Page.reload',{}) await waitFor("document.readyState === 'complete'",30000) await sleep(1200) try { await ev("(() => { const b=[...document.querySelectorAll('button')].find(x=>(x.innerText||'').trim()==='继续'); if(b)b.click(); return !!b })()") } catch {} await openWorkbench() await sleep(2500) out.tabsAfter = await ev("(() => [...document.querySelectorAll('.ssw-tab')].map(b=>(b.innerText||'').replace(/\\s+/g,' ').trim()))()") await ev("(() => { const b=[...document.querySelectorAll('.ssw-tab')].find(x=>(x.innerText||'').includes('任务')); if(b) b.click(); return !!b })()") await sleep(800) out.taskRows = await ev("(() => [...document.querySelectorAll('[data-task]')].map(el=>(el.innerText||'').replace(/\\s+/g,' ').trim().slice(0,80)))()") await shot('v020-tasks.png') await ev("(() => { const b=[...document.querySelectorAll('.ssw-tab')].find(x=>(x.innerText||'').includes('成果')); if(b) b.click(); return !!b })()") await sleep(800) out.artifactRows = await ev("(() => [...document.querySelectorAll('[data-artifact]')].map(el=>(el.innerText||'').replace(/\\s+/g,' ').trim().slice(0,80)))()") await shot('v020-artifacts.png') } catch(e) { out.fatal = String(e?.stack ?? e) } finally { try{ws?.close()}catch{}; try{browser?.kill()}catch{} } console.log(JSON.stringify(out, null, 2))