dsh-sansheng-liubu/preview/check-v012.mjs

73 lines
5.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// v0.1.2 验收:左侧导航位置 + 点击进入右侧工作台(隔离测试 DSH)。
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]
if (!url) { console.error('usage: check-v012.mjs <url>'); process.exit(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-v012-'))
const errors = []
const result = { url, nav: null, workbench: null, consoleErrors: errors }
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('browser 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((res, rej) => { ws.onopen = res; ws.onerror = rej })
let n = 0; const pending = new Map()
ws.onmessage = e => { const m = JSON.parse(e.data); if (m.id) { const p = pending.get(m.id); pending.delete(m.id); m.error ? p.reject(Error(JSON.stringify(m.error))) : p.resolve(m.result) } else if (m.method === 'Runtime.exceptionThrown') errors.push('exception: ' + (m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text)) }
const cdp = (method, params = {}, sid) => new Promise((res, rej) => { const id = ++n; pending.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 }
const waitFor = async (expr, timeout = 45000) => { const end = Date.now() + timeout; while (Date.now() < end) { try { if (await ev(expr)) return true } catch {} await sleep(250) } return false }
const shot = async name => { const r = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); await writeFile(join(dir, name), Buffer.from(r.data, 'base64')) }
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 {}
await sleep(600)
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 {}
const found = await waitFor("!!document.querySelector('.ssw-nav-hit')", 60000)
result.nav = await ev(`(() => {
const hit = document.querySelector('.ssw-nav-hit')
const rowText = hit ? (hit.closest('button, [role=button], a, li')?.innerText || hit.parentElement?.innerText || '').replace(/\\s+/g, ' ').trim() : null
const labels = [...document.querySelectorAll('button, a, [role=button], li')]
.map(el => (el.innerText || '').replace(/\\s+/g, ' ').trim())
.filter(t => t && t.length <= 12)
const uniq = [...new Set(labels)]
const idx = name => uniq.indexOf(name)
return { found: !!hit, rowText, navLabels: uniq, sanshengIndex: idx('三省六部'), memoryIndex: idx('记忆系统'), moreIndex: idx('更多'), newSessionCount: (document.body.innerText.match(/新会话/g) || []).length }
})()`)
await shot('v012-entry.png')
if (found) {
await ev("document.querySelector('.ssw-nav-hit').click(); true")
const rootFound = await waitFor("!!document.querySelector('.ssw-root')", 20000)
await sleep(3500)
result.workbench = await ev(`(() => {
const root = document.querySelector('.ssw-root')
const main = document.querySelector('main')
return {
found: !!root,
rootClass: root ? root.className : null,
seatCount: document.querySelectorAll('.ssw-seat').length,
seatNames: [...document.querySelectorAll('.ssw-seat .ssw-role-name')].map(e => e.innerText.trim()),
countLabel: document.querySelector('.ssw-count')?.innerText?.trim() ?? null,
floating: !!document.querySelector('.ssw-float'),
empty: document.querySelector('.ssw-empty')?.innerText?.replace(/\\s+/g, ' ').trim() ?? null,
error: document.querySelector('.ssw-error')?.innerText?.trim() ?? null,
mainText: (main?.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 180),
}
})()`)
await shot('v012-workbench.png')
}
} catch (e) { result.fatal = String(e?.stack ?? e) } finally { try { ws?.close() } catch {} ; try { browser?.kill() } catch {} }
console.log(JSON.stringify(result, null, 2))