ident
All repositories: gitoria
12.8 KB
// tests/e2e-usedin.mjs (ident#26, derived from e2e-theme.mjs): the theme move in a REAL browser (lisbeth's test Chrome over CDP, ONE existing tab reused,// never a new one), real mouse clicks and key events. Not a gate: prints numbers, writes screenshots.// node tests/e2e-theme.mjs <old|new> <port> <sink> <shotDir> <targetId> [cdpPort=8756]// ident runs on loreana on a COPY of the newest backup with a mail SINK file (never real mail), reached from lisbeth's Chrome through// `ssh -R <port>:127.0.0.1:<port>`. Per width (390, 1280): the signed-out pages, a real sign-in with the code read from the sink, the// 390 audit (tests/mobile-measure.js) of every page, then the walk: menus, sign out, register an app, an invite link, sign out everywhere.import { writeFileSync, readFileSync, existsSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const [mode, port, sink, shotDir, tidArg, cdpPort = '8756'] = process.argv.slice(2); // tidArg: 'auto' = the first existing page tab, picked fresh from /json (never /json/new): an about:blank page, else a page of some worker's local test app (never a HyperConductor page)const BASE = `http://${process.env.E2E_HOST || '127.0.0.1'}:${port}`, sleep = ms => new Promise(r => setTimeout(r, ms)), J = JSON.stringify;const MEASURE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'mobile-measure.js'), 'utf8');const EMAIL = '[email protected]'; // an account of the COPY (real data: apps, connections, notifications); the code goes to the sink fileconst list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();const tgt = tidArg && tidArg !== 'auto' ? list.find(t => t.id === tidArg) : (list.find(t => t.type === 'page' && t.url === 'about:blank') || list.find(t => t.type === 'page' && /^http:\/\/(127\.0\.0\.1|[a-z.]*localhost)[:\/]/.test(t.url)));const tid = tgt.id;const ws = new WebSocket(tgt.webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${cdpPort}`)); await new Promise(r => ws.onopen = r);let id = 0; const pend = new Map(), consoleErrors = [], dialogTexts = [];ws.onmessage = m => { const d = JSON.parse(m.data);if (d.id && pend.has(d.id)) { const [ok, bad] = pend.get(d.id); pend.delete(d.id); d.error ? bad(new Error(J(d.error))) : ok(d.result); }else if (d.method === 'Page.javascriptDialogOpening') { dialogTexts.push(d.params.message); send('Page.handleJavaScriptDialog', { accept: true }).catch(() => {}); } // the person presses OKelse if (d.method === 'Runtime.exceptionThrown') consoleErrors.push(J(d.params.exceptionDetails).slice(0, 200));else if (d.method === 'Runtime.consoleAPICalled' && d.params.type === 'error') consoleErrors.push(d.params.args.map(a => a.value || a.description).join(' ').slice(0, 200)); };const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(J({ id: i, method, params })); });const ev = async x => { const r = await send('Runtime.evaluate', { expression: x, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(J(r.exceptionDetails).slice(0, 300)); return r.result.value; };const waitFor = async (x, label, t = 25000) => { for (const end = Date.now() + t; Date.now() < end;) { if (await ev(x).catch(() => false)) return true; await sleep(150); } console.log(' TIMEOUT', label); return false; };const rect = async sel => ev(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width, h: r.height }; })()`);const click = async sel => { let r = await rect(sel); if (!r) throw new Error('no ' + sel); await sleep(120); r = await rect(sel); { const hit = await ev(`(() => { const t = document.querySelector(${J(sel)}); const h = document.elementFromPoint(${r.x}, ${r.y}); return t && h && (t === h || t.contains(h) || h.contains(t)) ? null : (h ? h.outerHTML.slice(0, 120) : 'nothing') + ' | vw=' + innerWidth + ' scrollY=' + scrollY; })()`).catch(() => null); if (hit) console.log(' CLICK COVERED', sel, hit); } for (const [type, extra] of [['mouseMoved', {}], ['mousePressed', { button: 'left', clickCount: 1 }], ['mouseReleased', { button: 'left', clickCount: 1 }]]) await send('Input.dispatchMouseEvent', { type, x: r.x, y: r.y, ...extra }); await sleep(150); const got = await ev('JSON.stringify(window.__got || [])').catch(() => '?'); if (got === '[]' || got === '?') console.log(' NO MOUSEDOWN reached the page after click on', sel, 'at', Math.round(r.x), Math.round(r.y), 'viewport', await ev('innerWidth + "x" + innerHeight + " dpr " + devicePixelRatio').catch(() => '?')); await ev('window.__got = []').catch(() => {}); };const key = async (k, code, vk) => { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: k, code, windowsVirtualKeyCode: vk }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk }); };const typeInto = async (sel, text, clear = false) => { await click(sel); if (clear) { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 }); await key('Backspace', 'Backspace', 8); } for (const ch of text) { await send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); } };const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${mode}-${name}.png`, Buffer.from(r.data, 'base64')); };const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };const hydrated = () => waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated');const go = async (path, ready) => { await send('Page.navigate', { url: BASE + path }); await waitFor(`!!document.querySelector(${J(ready)})`, 'ready ' + ready + ' on ' + path); await hydrated(); await sleep(700); };const shows = sel => ev(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);const txt = sel => ev(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);const lastCode = (EM = EMAIL) => { const ls = existsSync(sink) ? readFileSync(sink, 'utf8').split('\n').filter(l => l.startsWith(EM + ' ')) : []; return ls.length ? ls.at(-1).split(' ')[1] : null; };const audits = [];async function audit(name, W) {const m = await ev(`window.__W = ${W};` + MEASURE);const r = { name, W, scrollWidth: m.docScrollWidth, taps: m.taps, tapsSmall: m.tapsSmall, small: m.tapsSmallList.slice(0, 6), inputsSmall: m.inputsSmall, inputsSmallList: m.inputsSmallList.slice(0, 4), textSmall: m.textSmall, textSmallList: m.textSmallList.slice(0, 4), wide: m.wide, wideList: m.wideList.slice(0, 3), header: m.headerH };audits.push(r); console.log('AUDIT', J(r)); await shot(`${W}-${name.replace(/[^a-z0-9]+/gi, '-')}`);}// THE SIGN-IN: email typed, "Send me a code" clicked, the code read from the sink like a person reads mail, typed, "Sign in" clickedasync function signIn(W, EM = EMAIL) {await go('/', '#emailform');await typeInto('#email', EM); const before = lastCode(EM);await click('#sendcode'); await waitFor(`location.pathname === '/code' && !!document.querySelector('#code')`, 'code page'); await hydrated();for (let i = 0; i < 160 && lastCode(EM) === before; i++) await sleep(250);const c = lastCode(EM); check(`${W}: the sink got a 6-digit code`, /^\d{6}$/.test(c || ''), String(c));if (W) await audit('code-page', W);await typeInto('#code', c); await ev('window.__m = 1'); await click('#verify'); // __m survives only WITHOUT a reload (mission 013)const ok = await waitFor(`!!document.querySelector('#whoami')`, 'signed in');await hydrated(); return ok;}await send('Page.enable'); await send('Runtime.enable'); await send('DOM.enable'); await send('Network.enable');await send('Target.activateTarget', { targetId: tid }).catch(() => {});await send('Page.bringToFront');await send('Page.addScriptToEvaluateOnNewDocument', { source: "window.__got = []; addEventListener('mousedown', e => window.__got.push((e.target.tagName || '') + '#' + (e.target.id || '') + '@' + Math.round(e.clientX) + ',' + Math.round(e.clientY)), true);" });await send('Storage.clearDataForOrigin', { origin: BASE, storageTypes: 'service_workers,cache_storage,local_storage' }).catch(() => {});await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});const view = async W => { if (W === 390) { await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }); await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }); } else { await send('Emulation.setTouchEmulationEnabled', { enabled: false }); await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); } await sleep(300); };const menuOpen = async (btn, pop) => { await click(btn); await waitFor(`document.querySelector(${J(pop)}).matches(':popover-open')`, pop + ' open'); await sleep(300); };const esc = async () => { await key('Escape', 'Escape', 27); await sleep(300); };try {for (const W of [390, 1280]) {await view(W); const T = `${W}-`; await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});const ok = await signIn(0); check(`${T}${mode}: sign-in with a code from the sink`, ok && (await txt('#whoami')) === EMAIL, await txt('#whoami'));await go('/', '#identities'); await sleep(500);await shot(`identities-${W}`);const ids = await ev(`[...document.querySelectorAll('#identities li')].map(li => li.querySelector('identity-label').textContent).join(',')`);console.log(' identities:', ids);if (mode === 'new') {check(`${T}every identity has a "Used in…" link of at least 44 px`, await ev(`[...document.querySelectorAll('#identities li identity-actions a')].length === 3 && [...document.querySelectorAll('#identities li identity-actions a')].every(a => { const r = a.getBoundingClientRect(); return r.width >= 44 && r.height >= 44; })`));await click('#identities li:nth-child(1) identity-actions a');await waitFor(`location.pathname.startsWith('/identity/') && !!document.querySelector('#usedin')`, 'identity page'); await hydrated(); await sleep(500);const rows = await ev(`[...document.querySelectorAll('#usedin li')].map(li => li.querySelector('used-app').textContent + ' | ' + li.querySelector('used-line').textContent).join(' ## ')`);console.log(' rows:', rows);check(`${T}Default: at least one app, each with since + last use`, rows !== '' && rows.split(' ## ').every(r => / \| since [A-Z][a-z]{2} \d+ · last use (just now|\d+ (min|h|d) ago)$/.test(r)), rows);const firstApp = await txt('#usedin li:nth-child(1) used-app');check(`${T}no horizontal overflow`, await ev('document.documentElement.scrollWidth <= innerWidth'));check(`${T}every tap target on the page is >= 44 px`, await ev(`[...document.querySelectorAll('main a, main button')].every(e => { const r = e.getBoundingClientRect(); return r.width === 0 || (r.width >= 43.5 && r.height >= 43.5); })`));await shot(`used-in-${W}`);await click('#usedin li:nth-child(1) a');await waitFor(`location.pathname.startsWith('/inbox/') && !!document.querySelector('#connapp')`, 'per-app page'); await hydrated(); await sleep(400);check(`${T}"Notif." opens the per-app page (first row's app / Default)`, (await txt('#connapp')) === firstApp && (await txt('#connidentity')) === 'Default');await shot(`perapp-${W}`);await go('/', '#identities'); await click('#identities li:nth-child(3) identity-actions a');await waitFor(`!!document.querySelector('#usedinnone')`, 'empty state'); await sleep(400);check(`${T}Idle (never used): the empty-state text`, /Not used in any app yet/.test(await txt('#usedinnone')), await txt('ident-card'));await shot(`used-in-empty-${W}`);} else {// OLD: nothing to tap; the same URL does not existconst href = await ev(`document.querySelector('#identities li') ? 'present' : 'none'`);await go('/inbox', '#connsection'); await shot(`inbox-${W}`);}}} finally {console.log(`${mode}: ${results.filter(r => r[1]).length} passed, ${results.filter(r => !r[1]).length} failed; console errors: ${consoleErrors.length}`);for (const e of consoleErrors.slice(0, 5)) console.log(' console:', e);await send('Emulation.clearDeviceMetricsOverride').catch(() => {});await send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {});ws.close();process.exit(results.some(r => !r[1]) ? 1 : 0);}
Branches
Latest commits
- 0f6d1592Merge branch 'f18b-shell-session' into mainIdent
- 19868218|||PR ident#39 shell reads its session member instead of a cross-file emitmre
- 5d1b3fedMerge branch 'v61-day61' into mainIdent
- 83faeb15|||PR ident: vendor Hybriel day61mre
- b2572b34Merge branch 'v59-day59' into mainIdent
- 67cf016d|||PR ident: vendor Hybriel day59mre
- 600c043dMerge branch 'v58-day58' into mainIdent
- 365f8c80|||PR ident: vendor Hybriel day58mre
- 585126e5Merge branch 'f16-setf' into mainIdent
- 953bf03a|||PR ident setF mirror dropped (hybriel#370)mre
- a1419d9cMerge branch 'f15-navigate' into mainIdent
- 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
- e36f4516Merge branch 'f14-online' into mainIdent
- 2c5eac91|||PR ident#38 online state without probe timermre
- bf1980f2Merge branch 'v56-day56' into mainIdent
- 62ae0adf|||PR ident: vendor Hybriel day56mre
- 0d18abc4Merge branch 'f13-avatar' into mainIdent
- 2a99730a|||PR ident#37 avatar in hlmre
- fa4ed25bMerge branch 'f11-upsert' into mainIdent
- 8f3d9bc9|||PR ident#42 keyed upsert and removemre