// Optional browser regression test; see README for setup. Uses an isolated app copy. import { chromium } from './artifacts/node_modules/playwright/index.mjs'; import { mkdtemp, cp, mkdir, rm } from 'node:fs/promises'; import { spawn, execFileSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; import assert from 'node:assert/strict'; const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); const root=await mkdtemp(path.join(web,'tests/artifacts/browser-')); for(const f of ['api.php','index.php','auth.php','callback.php','router.php','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true}); await mkdir(path.join(root,'data')); const port=18081; const server=spawn('php',['-S',`127.0.0.1:${port}`,'-t',root,path.join(root,'router.php')],{stdio:'ignore'}); const base=`http://127.0.0.1:${port}`; let browser; try{ for(let i=0;i<100;i++){try{await fetch(base);break;}catch{await new Promise(r=>setTimeout(r,50));}} browser=await chromium.launch({headless:true,args:['--no-sandbox']}); const ca=await browser.newContext({viewport:{width:1440,height:1080}}),cb=await browser.newContext({viewport:{width:1440,height:1080}}); const a=await ca.newPage(),b=await cb.newPage(),errors=[]; for(const p of[a,b]){p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.type()==='error')errors.push(m.text());});} await a.goto(base);await b.goto(base); await a.locator('#avatar-button').click(); await a.locator('[data-avatar-choice="blue-knight"]').waitFor(); await a.locator('[data-avatar-group="standard"]').click(); await a.locator('#avatar-color').selectOption('Blue'); assert.equal(await a.locator('.avatar-choice').count(),6,'Six blue standard chess pieces'); await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-desktop.png')}); await a.locator('[data-avatar-choice="blue-knight"]').click(); await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor(); await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor(); await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click(); await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor(); await a.locator('#friend-link').click();await a.locator('#share-url').waitFor(); const friendLink=await a.locator('#share-url').inputValue(); await a.locator('#modal-close').click(); await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click(); await a.locator('[data-friend="local:test_user_2"]').waitFor(); await b.locator('[data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor(); await a.locator('[data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click(); await b.getByRole('button',{name:'Accept',exact:true}).click(); await a.locator('.board').waitFor();await b.locator('.board').waitFor(); await b.locator('.card-header img[src$="blue-knight.png"]').waitFor(); async function state(p){return p.evaluate(async()=>{const r=await fetch('api.php');return r.json();});} async function post(p,action,fields={}){return p.evaluate(async({action,fields})=>{const s=await(await fetch('api.php')).json();const r=await fetch('api.php',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':s.csrf},body:JSON.stringify({action,...fields})});const out=await r.json();if(!r.ok)throw Error(out.error);return out;},{action,fields});} const initial=await state(a),id=initial.games[0].id; const white=initial.games[0].color==='w'?a:b,black=white===a?b:a; await white.locator(`[data-game="${id}"] [data-square="15"]`).click(); assert.equal(await white.locator(`[data-game="${id}"] .legal`).count(),1,'Pawn legal dot'); await white.locator(`[data-game="${id}"] [data-square="11"]`).click(); const held=white.locator(`#your-games [data-game="${id}"]`); await held.locator('[data-square="11"]:disabled').waitFor(); const heldAt=Date.now(),heldRect=await held.boundingBox(); assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board'); await white.waitForTimeout(2200); assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause'); assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position'); const relocated=white.locator(`#waiting-games [data-game="${id}"]`); await relocated.waitFor({state:'attached'}); assert(Date.now()-heldAt>=2800,'Tile waits approximately three seconds before relocating'); assert(await relocated.evaluate(el=>el.getAnimations().length>0),'Tile animates to the waiting grid'); await relocated.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished))); await black.locator(`[data-game="${id}"] [data-square="4"]:not([disabled])`).waitFor(); assert.equal(await white.locator('#waiting-games .square:not([disabled])').count(),0,'Waiting board inert'); // Actual pointer drag. const from=await black.locator(`[data-game="${id}"] [data-square="4"]`).boundingBox(); const to=await black.locator(`[data-game="${id}"] [data-square="8"]`).boundingBox(); await black.mouse.move(from.x+from.width/2,from.y+from.height/2);await black.mouse.down();await black.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:8});await black.mouse.up(); await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor(); assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved'); // Fixture a legal promotion position in the isolated database. const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null}; fixture.history=[fixture.board.join('')+'w']; execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(fixture),String(id)]); await white.waitForTimeout(3000); await white.locator(`[data-game="${id}"] [data-square="5"]`).click();await white.locator(`[data-game="${id}"] [data-square="1"]`).click(); assert.equal(await white.locator('[data-promotion]').count(),4,'Four promotion options'); await white.locator('[data-promotion="n"]').click(); await white.getByRole('heading',{name:'A game well matched.'}).waitFor(); assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved'); await white.getByRole('button',{name:'Rematch',exact:true}).click(); await black.getByText(/wants a rematch/).waitFor(); await black.getByRole('button',{name:'Rematch',exact:true}).click(); await white.locator('.board').waitFor(); assert.equal((await state(white)).games[0].color,'b','Rematch flips colors'); // Three real game links for desktop layout coverage. for(let i=0;i<3;i++){const link=await post(a,'create_link',{kind:'match'});await post(b,'accept_link',{token:new URL(link.url).searchParams.get('invite')});} await a.reload();await a.locator('.game-card').nth(3).waitFor(); await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true}); assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load'); await a.setViewportSize({width:390,height:844}); assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow'); assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column'); await a.locator('#friends-toggle').click();await a.locator('#sidebar.open').waitFor();await a.waitForTimeout(250); await a.locator('#avatar-button').click(); await a.locator('[data-avatar-group="fairy"]').click(); await a.locator('#avatar-color').selectOption('Purple'); await a.locator('[data-avatar-choice="purple-elephant"]').waitFor(); assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load'); await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')}); await a.locator('[data-avatar-choice="purple-elephant"]').click(); await a.locator('#avatar-button img[src$="purple-elephant.png"]').waitFor(); await a.screenshot({path:path.join(web,'tests/artifacts/mobile-friends.png'),fullPage:false}); await a.locator('#friends-close').click();await a.waitForTimeout(250);await a.screenshot({path:path.join(web,'tests/artifacts/mobile.png'),fullPage:true}); // Touch events exercise the mobile pointer path, not mouse emulation. const sa=await state(a),sb=await state(b); const owner=sa.games.some(g=>g.yourTurn)?a:b; const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()}); const touch=await mobileContext.newPage();await touch.goto(base); const tg=(await state(touch)).games.find(g=>g.yourTurn),tm=tg.legal[0]; const fs=touch.locator(`[data-game="${tg.id}"] [data-square="${tm.from}"]`); await fs.scrollIntoViewIfNeeded();const fb=await fs.boundingBox(); const tb=await touch.locator(`[data-game="${tg.id}"] [data-square="${tm.to}"]`).boundingBox(); const cdp=await mobileContext.newCDPSession(touch); await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:fb.x+fb.width/2,y:fb.y+fb.height/2}]}); for(let i=1;i<=8;i++)await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:fb.x+fb.width/2+(tb.x-fb.x)*i/8,y:fb.y+fb.height/2+(tb.y-fb.y)*i/8}]}); await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]}); await touch.waitForTimeout(500); assert.equal((await state(touch)).games.find(g=>g.id===tg.id).state.ply,tg.state.ply+1,'Mobile touch drag saved'); assert.equal(await touch.locator(`#your-games [data-game="${tg.id}"]`).count(),1,'Mobile move also stays in place'); const mobileWaiting=touch.locator(`#waiting-games [data-game="${tg.id}"]`); await mobileWaiting.waitFor({state:'attached'}); assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid'); await mobileContext.close(); assert.deepEqual(errors,[],'No browser errors'); console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.'); }finally{ await browser?.close();server.kill();await new Promise(r=>server.once('exit',r));await rm(root,{recursive:true,force:true}); }