Files
pages/internal/server/testdata/feed-gecko-browser.mjs
T
Anya Tokugawa 5321d613b4
Build and publish container images / images (push) Successful in 11m45s
Release container images / release (push) Successful in 21s
feat(feeds): add opt-in Gecko relay and folder shortcuts
Document engine redistribution requirements; exclude upstream engine assets and keep the viewer disabled by default.
2026-11-08 16:14:34 +09:00

41 lines
4.9 KiB
JavaScript

import {spawn} from 'node:child_process';
import {writeFile} from 'node:fs/promises';
import {setTimeout as delay} from 'node:timers/promises';
const [url,profile,screenshot]=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<seconds*5;n++){if(await evaluate(expression))return;await delay(200);}if(screenshot){const {data}=await call('Page.captureScreenshot',{format:'png'});await writeFile(screenshot,Buffer.from(data,'base64'));}throw Error('Timeout: '+expression+'\n'+logs.slice(-30).join('\n'));};
await call('Runtime.enable');await call('Log.enable');await call('Page.enable');
// Only synthetic fixture diagnostics; production does not log article URLs.
await call('Page.addScriptToEvaluateOnNewDocument',{source:`if(location.pathname.endsWith('/browser/'))import('/_/api/v1/extension/organizer.feeds/browser/assets/v0.0.1/gecko.js').then(({Gecko})=>{const init=Gecko.prototype.init;Gecko.prototype.init=function(){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`);
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'));
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`);
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.querySelector('.feed-external button').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, 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);}