import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { createServer } from 'node:http'; import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, extname, join, resolve } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const site = process.env.TURKOS_VISUAL_SITE_DIR ? resolve(process.env.TURKOS_VISUAL_SITE_DIR) : join(root, 'site'); const development = JSON.parse(readFileSync(join(site, 'K601-K2500-development.json'))); const chrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; const profile = mkdtempSync(join(tmpdir(), 'turkos-chrome-')); const output = process.env.TURKOS_VISUAL_REPORT_DIR; if (output) mkdirSync(output, { recursive: true }); const routes = readdirSync(site).filter((name) => name.endsWith('.html')).map((name) => name === 'index.html' ? '/' : `/${name.slice(0, -5)}`); const server = createServer((request, response) => { const path = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); const name = path === '/' ? 'index.html' : extname(path) ? path.slice(1) : `${path.slice(1)}.html`; if (!/^[a-z0-9-]+\.(html|css|js|svg|ico)$/.test(name)) { response.writeHead(404).end(); return; } try { const type = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' }[extname(name)]; response.writeHead(200, { 'content-type': `${type}; charset=utf-8` }).end(readFileSync(join(site, name))); } catch { response.writeHead(404).end(); } }); class Cdp { constructor(url) { this.socket = new WebSocket(url); this.pending = new Map(); this.nextId = 1; this.socket.addEventListener('message', (event) => { const message = JSON.parse(event.data); if (!message.id) return; const promise = this.pending.get(message.id); if (!promise) return; this.pending.delete(message.id); if (message.error) promise.reject(new Error(message.error.message)); else promise.resolve(message.result); }); } async ready() { if (this.socket.readyState === WebSocket.OPEN) return; await new Promise((resolveOpen, reject) => { this.socket.addEventListener('open', resolveOpen, { once: true }); this.socket.addEventListener('error', reject, { once: true }); }); } send(method, params = {}) { return new Promise((resolveResult, reject) => { const id = this.nextId++; this.pending.set(id, { resolve: resolveResult, reject }); this.socket.send(JSON.stringify({ id, method, params })); }); } async eval(expression) { const result = await this.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); if (result.exceptionDetails) throw new Error(result.exceptionDetails.text); return result.result.value; } close() { this.socket.close(); } } let browser; let cdp; try { await new Promise((resolveListen) => server.listen(0, '127.0.0.1', resolveListen)); const startupErrors = []; browser = spawn(chrome, ['--headless=new', '--disable-gpu', '--disable-extensions', '--disable-background-networking', '--no-first-run', '--no-default-browser-check', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] }); browser.stderr.on('data', (chunk) => { if (startupErrors.join('').length < 8192) startupErrors.push(chunk.toString('utf8')); }); browser.on('error', (error) => startupErrors.push(error.message)); let port; for (let i = 0; i < 300; i++) { try { const candidate = Number(readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0]); if (Number.isInteger(candidate) && candidate > 0) { port = candidate; break; } } catch { /* Chrome writes DevToolsActivePort after its profile initializes. */ } if (browser.exitCode !== null || browser.signalCode !== null) break; await delay(100); } assert.ok(port, `Chrome DevTools did not start (exit=${browser.exitCode}, signal=${browser.signalCode}): ${startupErrors.join('').slice(-4000)}`); const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); cdp = new Cdp(targets.find((target) => target.type === 'page').webSocketDebuggerUrl); await cdp.ready(); await cdp.send('Page.enable'); await cdp.send('Runtime.enable'); async function navigate(route) { const target = new URL(route, 'http://localhost'); await cdp.send('Page.navigate', { url: `http://127.0.0.1:${server.address().port}${route}` }); for (let i = 0; i < 100; i++) { if (await cdp.eval(`location.pathname === ${JSON.stringify(target.pathname)} && location.hash === ${JSON.stringify(target.hash)} && document.readyState === "complete"`)) return; await delay(50); } throw new Error(`${route}: page did not load`); } const failures = []; for (const width of [390, 768, 1440]) { await cdp.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false }); for (const route of routes) { await navigate(route); const state = await cdp.eval(`(() => { const main = document.querySelector('main'); const nav = document.querySelector('.site-nav'); const active = nav.querySelectorAll('[aria-current="page"]'); const journalHero = document.querySelector('.journal-hero'); const journalIntro = journalHero?.querySelector('p'); return { width: innerWidth, scroll: document.documentElement.scrollWidth, main: !!main, active: active.length, journalIntroClipped: !!journalIntro && journalIntro.getBoundingClientRect().right > journalHero.getBoundingClientRect().right - 12, clippedText: [...document.querySelectorAll('main h1,main h2,main h3,main p,main a,main code')] .filter(el => { const r=el.getBoundingClientRect(); const style=getComputedStyle(el); return r.width > 0 && r.left > innerWidth + 2 && style.position !== 'absolute'; }) .slice(0, 3).map(el => ({ text: el.textContent.trim().slice(0, 50), left: el.getBoundingClientRect().left, width: el.getBoundingClientRect().width, parent: el.parentElement?.getBoundingClientRect().left, parentWidth: el.parentElement?.getBoundingClientRect().width, parentText: el.parentElement?.textContent.slice(0, 170), className: el.parentElement?.className })) }; })()`); if (state.width !== width || state.scroll > width + 2 || !state.main || state.active !== 1 || state.journalIntroClipped || state.clippedText.length) { failures.push({ route, ...state }); } if (output && ['/', '/cekirdek', '/gelistirme-gunlugu', '/testler'].includes(route)) { const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(output, `${route.slice(1) || 'index'}-${width}.png`), Buffer.from(screenshot.data, 'base64')); } } await navigate('/gelistirme-gunlugu'); await cdp.eval(`document.querySelector('#deney-p02 summary').focus()`); await cdp.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); await cdp.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); const planState = await cdp.eval(`(() => { const card = document.querySelector('#deney-p02'); const program = document.querySelector('#deney-programi'); document.documentElement.style.scrollBehavior = 'auto'; card.scrollIntoView({ block: 'start', behavior: 'instant' }); return { count: program.querySelectorAll('.experiment-card').length, waves: program.querySelectorAll('.experiment-wave').length, open: card.open, fields: card.querySelectorAll('.experiment-fields > div').length, width: document.documentElement.scrollWidth, cardWidth: card.getBoundingClientRect().width }; })()`); assert.equal(planState.count, 15, 'journal experiment card count'); assert.equal(planState.waves, 4, 'journal experiment wave count'); assert.equal(planState.open, true, 'Enter must expand planned experiment'); assert.equal(planState.fields, 6, 'planned experiment protocol fields'); assert.ok(planState.width <= width + 2 && planState.cardWidth <= width, `journal experiment overflow at ${width}px: ${JSON.stringify(planState)}`); await delay(100); if (output) { const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(output, `gelistirme-gunlugu-plan-${width}.png`), Buffer.from(screenshot.data, 'base64')); } await navigate('/cekirdek'); const kernelGuideState = await cdp.eval(`(() => { const section = document.querySelector('#rehber-sanal-bellek'); document.documentElement.style.scrollBehavior = 'auto'; section.scrollIntoView({ block: 'start', behavior: 'instant' }); return { records: document.querySelectorAll('.kernel-guide-record').length, terms: document.querySelectorAll('.kernel-glossary dt').length, source: !!section.querySelector('.kernel-guide-source pre'), width: document.documentElement.scrollWidth, sectionWidth: section.getBoundingClientRect().width }; })()`); assert.equal(kernelGuideState.records, 11, 'kernel technical guide records'); assert.equal(kernelGuideState.terms, 12, 'kernel concept definitions'); assert.ok(kernelGuideState.source, 'MMU section must show real source'); assert.ok(kernelGuideState.width <= width + 2 && kernelGuideState.sectionWidth <= width, `kernel guide overflow at ${width}px: ${JSON.stringify(kernelGuideState)}`); const baselineState = await cdp.eval(`(() => { const phase = document.querySelector('#cekirdek-faz-01'); const first = phase.querySelector('#cekirdek-hamle-k001'); document.documentElement.style.scrollBehavior = 'auto'; first.scrollIntoView({ block: 'start', behavior: 'instant' }); return { moves: phase.querySelectorAll('.kernel-roadmap-moves li').length, fields: first.querySelectorAll('.kernel-move-detail > div').length, protocol: first.querySelector('.kernel-move-detail').textContent.includes('sh scripts/verify.sh'), width: document.documentElement.scrollWidth, cardWidth: first.getBoundingClientRect().width }; })()`); assert.equal(baselineState.moves, 20, 'baseline phase must contain 20 moves'); assert.equal(baselineState.fields, 5, 'each move needs reason, procedure, verification, failure and artifact'); assert.equal(baselineState.protocol, true, 'K001 needs a reproducible command'); assert.ok(baselineState.width <= width + 2 && baselineState.cardWidth <= width, `baseline move overflow at ${width}px: ${JSON.stringify(baselineState)}`); if (output) { const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(output, `cekirdek-faz-01-${width}.png`), Buffer.from(screenshot.data, 'base64')); } const roadmapState = await cdp.eval(`(() => { const search = document.querySelector('#kernel-roadmap-search'); const phases = document.querySelectorAll('.kernel-roadmap-phase'); const moves = document.querySelectorAll('.kernel-roadmap-moves li'); search.value = '0x40201000 uzak sayfayı işaretle'; search.dispatchEvent(new Event('input', { bubbles: true })); const filtered = [...moves].filter(move => !move.hidden).length; const visiblePhases = [...phases].filter(phase => !phase.hidden).length; const open = [...phases].filter(phase => !phase.hidden).every(phase => phase.open); search.value = ''; search.dispatchEvent(new Event('input', { bubbles: true })); location.hash = '#cekirdek-hamle-k500'; return { phases: phases.length, moves: moves.length, filtered, visiblePhases, open, restored: [...moves].filter(move => !move.hidden).length, lastOpen: document.querySelector('#cekirdek-hamle-k500').closest('details').open, width: document.documentElement.scrollWidth }; })()`); assert.equal(roadmapState.phases, 25, 'kernel roadmap phase count'); assert.equal(roadmapState.moves, 500, 'kernel roadmap needs 500 actual moves'); assert.equal(roadmapState.filtered, 1, 'kernel roadmap search must find the remote no-map move'); assert.equal(roadmapState.visiblePhases, 1, 'search must hide unrelated phases'); assert.equal(roadmapState.open, true, 'matching phase must open'); assert.equal(roadmapState.restored, 500, 'clearing search must restore all moves'); assert.ok(roadmapState.width <= width + 2, `kernel roadmap overflow at ${width}px: ${JSON.stringify(roadmapState)}`); await delay(50); assert.equal(await cdp.eval('document.querySelector("#cekirdek-hamle-k500").closest("details").open'), true, 'deep link must expand the target phase'); if (output) { await cdp.eval(`(() => { document.documentElement.style.scrollBehavior = 'auto'; document.querySelector('#cekirdek-500').scrollIntoView({ block: 'start', behavior: 'instant' }); })()`); await delay(100); const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(output, `cekirdek-500-${width}.png`), Buffer.from(screenshot.data, 'base64')); } await delay(100); if (output) { const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(output, `cekirdek-rehber-${width}.png`), Buffer.from(screenshot.data, 'base64')); } await navigate('/cekirdek-testleri'); await cdp.eval("location.hash = '#test-k500'"); await delay(50); const moveTestState = await cdp.eval(`(() => { const target = document.querySelector('#test-k500'); document.documentElement.style.scrollBehavior = 'auto'; target.scrollIntoView({ block: 'start', behavior: 'instant' }); return { phases: document.querySelectorAll('.kernel-move-test-phase').length, moves: document.querySelectorAll('.kernel-move-test').length, fields: document.querySelector('#test-k001').querySelectorAll('.kernel-move-test-fields > div').length, open: target.closest('details').open, width: document.documentElement.scrollWidth, cardWidth: target.getBoundingClientRect().width }; })()`); assert.equal(moveTestState.phases, 25, 'test ledger phase count'); assert.equal(moveTestState.moves, 500, 'one test contract per kernel move'); assert.equal(moveTestState.fields, 4, 'each test contract needs setup, positive, negative and command'); assert.equal(moveTestState.open, true, 'deep link must open the relevant test phase'); assert.ok(moveTestState.width <= width + 2 && moveTestState.cardWidth <= width, `test ledger overflow at ${width}px: ${JSON.stringify(moveTestState)}`); if (output) { await cdp.eval(`(() => { document.querySelector('#test-k001').scrollIntoView({ block: 'start', behavior: 'instant' }); })()`); const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(output, `cekirdek-testleri-k001-${width}.png`), Buffer.from(screenshot.data, 'base64')); } // These check plan navigation/UI only, never claim a future OS test ran. await navigate('/isletim-sistemi-faz-01#k601'); await delay(100); const osInitial = await cdp.eval(`({count:document.querySelectorAll('[data-os-move]').length, open:document.querySelector('#k601').open, focused:document.activeElement===document.querySelector('#k601 summary'), active:document.activeElement.outerHTML.slice(0,160), top:document.querySelector('#k601 summary').getBoundingClientRect().top, states:[...document.querySelectorAll('[data-os-move]')].map(c=>c.dataset.osStatus), width:document.documentElement.scrollWidth})`); assert.deepEqual({count:osInitial.count, open:osInitial.open, focused:osInitial.focused, states:osInitial.states}, {count:100, open:true, focused:true, states:development.moves.slice(0,100).map(m=>m.status)}, `OS phase deep link and recorded state; active=${osInitial.active}`); assert.ok(osInitial.width <= width + 2, `expanded OS contract overflow at ${width}px`); assert.ok(osInitial.top >= 0 && osInitial.top < 120, `deep link must put the OS summary in view, not just open it: top=${osInitial.top}`); await cdp.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); await cdp.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); assert.equal(await cdp.eval('document.querySelector("#k601").open'), false, 'Enter must close OS action summary'); const osFilter = await cdp.eval(`(() => { const input=document.querySelector('#os-filter-input'); input.value='no-match-fixture-zzxy'; input.dispatchEvent(new Event('input')); const none=[...document.querySelectorAll('[data-os-move]')].filter(c=>!c.hidden).length; input.value='Doğrudan ve UEFI kaynak türü'; input.dispatchEvent(new Event('input')); const visible=[...document.querySelectorAll('[data-os-move]')].filter(c=>!c.hidden); document.querySelector('#os-expand').click(); const expanded=visible.every(c=>c.open); const overflow=document.documentElement.scrollWidth; document.querySelector('#os-collapse').click(); const collapsed=visible.every(c=>!c.open); return {none, count:visible.length, expanded, collapsed, overflow}; })()`); assert.deepEqual({none:osFilter.none,count:osFilter.count,expanded:osFilter.expanded,collapsed:osFilter.collapsed}, {none:0,count:5,expanded:true,collapsed:true}, 'OS feature search and expand/collapse'); assert.ok(osFilter.overflow <= width + 2, `OS expanded five-stage feature overflow at ${width}px`); await cdp.eval(`location.hash='#k700'`); await delay(120); assert.equal(await cdp.eval(`document.querySelector('#k700').open && !document.querySelector('#k700').hidden && document.querySelector('#os-filter-input').value === ''`), true, 'OS hash must clear a stale filter'); await navigate('/isletim-sistemi'); const osOverview = await cdp.eval(`(() => { const form=document.querySelector('#os-jump'); document.querySelector('#os-jump-number').value='K2501'; form.dispatchEvent(new Event('submit',{cancelable:true})); return {cards:document.querySelectorAll('.os-phase-card').length,path:location.pathname,message:document.querySelector('#os-jump-result').textContent}; })()`); assert.equal(osOverview.cards, 19); assert.equal(osOverview.path, '/isletim-sistemi'); assert.match(osOverview.message, /Geçerli aralık/); await cdp.eval(`document.querySelector('#os-jump-number').value='K2500'; document.querySelector('#os-jump').dispatchEvent(new Event('submit',{cancelable:true}))`); await delay(200); const osLast = await cdp.eval(`({path:location.pathname,hash:location.hash,open:document.querySelector('#k2500')?.open,width:document.documentElement.scrollWidth})`); assert.deepEqual({path:osLast.path,hash:osLast.hash,open:osLast.open}, {path:'/isletim-sistemi-faz-19',hash:'#k2500',open:true}, 'K2500 must open on its separate phase page'); assert.ok(osLast.width <= width + 2, `last OS action overflow at ${width}px`); if (output) { await navigate('/isletim-sistemi'); const overviewShot = await cdp.send('Page.captureScreenshot', { format:'png', captureBeyondViewport:false }); writeFileSync(join(output, `isletim-sistemi-${width}.png`), Buffer.from(overviewShot.data,'base64')); await navigate('/isletim-sistemi-faz-01#k601'); const phaseShot = await cdp.send('Page.captureScreenshot', { format:'png', captureBeyondViewport:false }); writeFileSync(join(output, `isletim-sistemi-k601-${width}.png`), Buffer.from(phaseShot.data,'base64')); } const recordId=development.moves.find(m=>m.id===development.lastAcceptedGuest).evidence.recordId; await navigate('/os-gelistirme#kanit-'+recordId); await delay(150); const developmentView=await cdp.eval(`(() => { const record=document.getElementById('kanit-${recordId}'); const deep={open:record.open,focused:document.activeElement===record.querySelector('summary'),top:record.getBoundingClientRect().top,width:document.documentElement.scrollWidth}; const input=document.querySelector('#development-search'),select=document.querySelector('#development-kind'); const visible=()=>[...document.querySelectorAll('[data-development-record]')].filter(r=>!r.hidden); input.value='no-match-fixture-zzxy';input.dispatchEvent(new Event('input'));const none=visible().length; input.value='${development.lastAcceptedGuest}';input.dispatchEvent(new Event('input'));const found=visible().some(r=>r.id==='kanit-${recordId}'); input.value='';select.value='failure';select.dispatchEvent(new Event('change'));const failed=visible().map(r=>r.dataset.kind); return {deep,none,found,failed}; })()`); assert.equal(developmentView.deep.open,true);assert.equal(developmentView.deep.focused,true); assert.ok(developmentView.deep.top>=0&&developmentView.deep.top<120,JSON.stringify(developmentView.deep)); assert.ok(developmentView.deep.width<=width+2,'expanded development record overflow'); assert.equal(developmentView.none,0);assert.equal(developmentView.found,true); assert.deepEqual(developmentView.failed,development.failures.map(()=> 'failure')); if(output) { await navigate('/os-gelistirme'); const shot=await cdp.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}); writeFileSync(join(output,`os-gelistirme-${width}.png`),Buffer.from(shot.data,'base64')); } if (width === 390) { await navigate('/gelistirme-gunlugu'); await cdp.eval('document.querySelector(".menu-toggle").focus()'); await cdp.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); await cdp.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 36 }); const opened = await cdp.eval('({expanded:document.querySelector(".menu-toggle").getAttribute("aria-expanded"), focused:document.activeElement === document.querySelector(".menu-toggle"), display:getComputedStyle(document.querySelector(".menu-toggle")).display, year:document.querySelector("#year").textContent})'); assert.equal(opened.expanded, 'true', `Enter must open mobile navigation: ${JSON.stringify(opened)}`); await cdp.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9, nativeVirtualKeyCode: 48 }); await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9, nativeVirtualKeyCode: 48 }); assert.equal(await cdp.eval('document.activeElement.closest("#site-nav") !== null'), true, 'Tab must enter open navigation'); await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }); await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }); assert.equal(await cdp.eval('document.querySelector(".menu-toggle").getAttribute("aria-expanded")'), 'false', 'Escape must close mobile navigation'); assert.equal(await cdp.eval('document.activeElement === document.querySelector(".menu-toggle")'), true, 'Escape must restore menu focus'); assert.notEqual(await cdp.eval('getComputedStyle(document.querySelector(".menu-toggle")).outlineStyle'), 'none', 'keyboard focus must be visible'); } } assert.deepEqual(failures, [], `Visual layout failures: ${JSON.stringify(failures)}`); console.log(`PASS: ${routes.length} pages × 390/768/1440 px, keyboard menu open/close/focus`); } finally { cdp?.close(); if (browser && browser.exitCode === null) { browser.kill(); await Promise.race([new Promise((resolveExit) => browser.once('exit', resolveExit)), delay(2000)]); } await new Promise((resolveClose) => server.close(resolveClose)); rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }