import {spawn} from 'node:child_process'; import {writeFile} from 'node:fs/promises'; import {setTimeout as delay} from 'node:timers/promises'; const [url,profile,screenshot,mode]=process.argv.slice(2); const browser=spawn('chromium',['--headless','--no-sandbox','--disable-gpu','--disable-background-networking','--no-proxy-server','--remote-debugging-port=0',`--user-data-dir=${profile}`,'about:blank']); process.on('SIGTERM',()=>{browser.kill();process.exit(1);}); let socket,logs=[]; try { const endpoint=await new Promise((resolve,reject)=>{let text='';browser.stderr.on('data',c=>{text+=c;const match=text.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(match)resolve(match[1]);});browser.on('error',reject);browser.on('exit',code=>reject(Error('Browser exited '+code)));}); socket=new WebSocket(endpoint);await new Promise((resolve,reject)=>{socket.onopen=resolve;socket.onerror=reject;}); let id=0;const pending=new Map(); socket.onmessage=e=>{const m=JSON.parse(e.data),p=pending.get(m.id);if(p){pending.delete(m.id);m.error?p.reject(Error(JSON.stringify(m.error))):p.resolve(m.result);}else if(['Runtime.exceptionThrown','Log.entryAdded','Runtime.consoleAPICalled'].includes(m.method))logs.push(JSON.stringify(m.params));}; const send=(method,params={},sessionId)=>new Promise((resolve,reject)=>{pending.set(++id,{resolve,reject});socket.send(JSON.stringify({id,method,params,sessionId}));}); const {targetId}=await send('Target.createTarget',{url:'about:blank'}),{sessionId}=await send('Target.attachToTarget',{targetId,flatten:true}); const call=(method,params)=>send(method,params,sessionId); const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;}; const wait=async(expression,seconds=15)=>{for(let n=0;n{const init=Gecko.prototype.init;Gecko.prototype.init=function(){window.fixtureEngine=this;this.opts.printErr=console.warn;this.opts.print=console.log;return init.call(this);};});`}); await call('Emulation.setDeviceMetricsOverride',{width:1280,height:850,deviceScaleFactor:1,mobile:false});await call('Page.navigate',{url}); await wait(`document.querySelector('.feed-row')`); if(!await evaluate('crossOriginIsolated'))throw Error('Parent not isolated'); await evaluate(`window.geckoReady=false;addEventListener('message',e=>{if(e.data?.type==='pageswiki-gecko'&&e.data.ready)geckoReady=true;});document.querySelector('.feed-row').click()`); await wait(`document.querySelector('.feed-original')`);await evaluate(`document.querySelector('.feed-original').click()`); await wait(`document.querySelector('.feed-external iframe')?.contentWindow.crossOriginIsolated`); if(mode==='startup-failure'){ await wait(`document.querySelector('.feed-external [role=alert]')&&!document.querySelector('.feed-external iframe')`); if(!await evaluate(`document.querySelector('.feed-external a[target=_blank]').href==='http://fixture.invalid/first'`))throw Error('Failure lost original fallback'); await evaluate(`document.querySelector('.feed-external').close()`); console.log('Gecko startup failure discarded iframe and retained original fallback'); }else{ await wait(`geckoReady || document.querySelector('.feed-external iframe')?.contentDocument?.querySelector('#status')?.textContent.includes('Viewer failed')`,100); if(!await evaluate('geckoReady'))throw Error('Gecko startup failed\n'+logs.slice(-8).join('\n')); if(mode==='public-https'){ const engine=`document.querySelector('.feed-external iframe').contentWindow.fixtureEngine`; await wait(`(async()=>/documentation examples/i.test(String(await ${engine}.evalChrome('document.body.textContent'))))()`,30); await evaluate(`${engine}.load('https://expired.badssl.com/')`); await wait(`(async()=>/^about:(neterror|certerror)/.test(String(await ${engine}.evalChrome('String(document.documentURI)'))))()`,30); const location=await evaluate(`${engine}.evalChrome('String(document.documentURI)')`); if(!String(location).startsWith('about:neterror')&&!String(location).startsWith('about:certerror'))throw Error('Expired certificate was not rejected: '+location); await wait(`document.querySelector('.feed-external iframe').contentDocument.querySelector('canvas').hidden && document.querySelector('.feed-external iframe').contentDocument.querySelector('#status').textContent.length>20`); await evaluate(`document.querySelector('.feed-external').close()`); console.log('Public HTTPS example.com rendered; expired.badssl.com certificate rejected; closed'); }else{ const pixel=`(()=>{const c=document.querySelector('.feed-external iframe').contentDocument.querySelector('canvas');return Array.from(c.getContext('2d').getImageData(400,200,1,1).data)})()`; await wait(`${pixel}[0]===255 && ${pixel}[1]===0`); await evaluate(`document.querySelector('.feed-external button[title*="Ctrl+F"]').click();document.querySelector('.feed-gecko-find input').value='学舎の園';document.querySelector('.feed-gecko-find').requestSubmit()`); await wait(`(async()=>String(await document.querySelector('.feed-external iframe').contentWindow.fixtureEngine.evalChrome('String(window.getSelection())'))==='学舎の園')()`); await wait(`getComputedStyle(document.querySelector('.feed-gecko-find')).display==='flex'`); await evaluate(`document.querySelector('.feed-gecko-find input').value='missing-synthetic-word';document.querySelector('.feed-gecko-find').requestSubmit()`); await wait(`document.querySelector('.feed-gecko-find output').textContent.length>0`); await evaluate(`document.querySelector('.feed-gecko-find button:last-child').click()`); await wait(`getComputedStyle(document.querySelector('.feed-gecko-find')).display==='none'`); const rect=await evaluate(`(()=>{const r=document.querySelector('.feed-external iframe').getBoundingClientRect();return {x:r.x+100,y:r.y+50}})()`); await call('Input.dispatchMouseEvent',{type:'mousePressed',...rect,button:'left',buttons:1,clickCount:1});await call('Input.dispatchMouseEvent',{type:'mouseReleased',...rect,button:'left',buttons:0,clickCount:1}); await wait(`${pixel}[0]===0 && ${pixel}[1]===255`); await wait(`document.querySelector('.feed-external a').href==='http://fixture.invalid/next'`); await evaluate(`[...document.querySelectorAll('.feed-external-bar button')].find(b=>b.textContent==='←').click()`); await wait(`${pixel}[0]===255 && ${pixel}[1]===0`); if(screenshot){const {data}=await call('Page.captureScreenshot',{format:'png'});await writeFile(screenshot,Buffer.from(data,'base64'));} await evaluate(`document.querySelector('.feed-external').close()`);await wait(`!document.querySelector('.feed-external')`); console.log('Real Gecko: isolation, Japanese find/missing match, Wisp article render, click navigation, viewer-local back and teardown passed'); } } }finally{socket?.close();browser.kill();await new Promise(resolve=>browser.once('exit',resolve));await delay(300);}