notes
All repositories: gitoria
12.4 KB
// tests/realdata-offline.mjs (notes#4, mission 007): the offline notes on a COPY of real data, in real Chrome.// node tests/realdata-offline.mjs <backup.tgz> <port> <chrome-from>-<chrome-to>// Unpacks storage/mpackdb of the backup into .scratch/realdata-offline (a fresh copy, deleted at the end), signs in as the// creator (identity az5b2 → users @id 0muh6o5a3kkd) through a session file written before the start, then: every live// note is listed; screenshots 390 / 1280; Chrome offline (CDP, page + worker), reload offline, edit a note with real keys;// back online → the server has the edit (in that note, no copy). Kills only what it started.import { spawn, execFileSync } from 'node:child_process';import { writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs';import { createHash, randomBytes } from 'node:crypto';import { join, resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser } from './cdp.mjs';const [tgz, portArg, chromeArg] = process.argv.slice(2);const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const PORT = Number(portArg);const [CH_FROM, CH_TO] = (chromeArg || '8735-8739').split('-').map(Number);const BASE = `http://notes.test:${PORT}`, API = `http://127.0.0.1:${PORT}`;const W = join(APP, '.scratch/realdata-offline');const USER = '0muh6o5a3kkd';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';process.env.HL_CHROME_ARGS = `--host-resolver-rules=MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=${BASE}`;rmSync(W, { recursive: true, force: true });mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true });execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);const sid = randomBytes(16).toString('hex');const now = Date.now();writeFileSync(join(W, 'sessions', createHash('sha256').update(sid).digest('hex')),JSON.stringify({ created: now, data: { tag: 'rd-offline' }, handled: [], id: sid, seen: now, user: { id: USER } }), { mode: 0o600 });const COOKIE = 'notessid=' + sid;let failures = 0, passes = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;let log = '';const srv = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, NOTES_PORT: String(PORT), NOTES_PUBLIC_URL: BASE, NOTES_STORAGE: join(W, 'data/storage/mpackdb'),NOTES_SESSIONS: join(W, 'sessions') + '/', NOTES_WATCH: '0', IDENT_URL: 'http://ident.test', IDENT_API_KEY: 'pk_rd', IDENT_API_SECRET: 'sk_rd' } });srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);let b = null;const api = async (path) => (await fetch(API + path, { headers: { cookie: COOKIE } })).json();const alive = async () => (await api('/api/notes')).notes.filter(n => !n.gone);try {for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }check('the session is the creator', (await api('/api/me')).user === USER);const live = await alive();console.log('live notes in the copy:', live.length);b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });const p = await b.newPage();p.__browser = b;await p.send('Network.enable');await p.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });const size = async (w, h) => { await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(300); };const shot = async (name) => { const { data } = await p.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(APP, '.scratch', `realdata-${name}.png`), Buffer.from(data, 'base64')); };const look = () => p.evaluate(`JSON.stringify((() => { const c = (s) => { const e = document.querySelector(s); if (!e) return null; const st = getComputedStyle(e); const r = e.getBoundingClientRect(); return { color: st.color, bg: st.backgroundColor, w: Math.round(r.width), h: Math.round(r.height), vis: r.width > 0 && st.display !== 'none' }; };return { list: c('note-list'), reader: c('note-reader'), header: c('application-header'), brand: c('application-header .brand'), selected: c('#notes a.selected'), item: c('#notes a'), md: c('md-editor'), ta: c('#notetext'), state: (document.getElementById('syncstate') || {}).textContent, overflow: document.documentElement.scrollWidth > innerWidth, mdDefined: !!document.querySelector('md-editor article') }; })())`);await size(1280, 900);await p.goto(BASE + '/');await p.waitFor('document.querySelectorAll("#notes a").length > 0', { timeout: 60000 });await sleep(1000);const shown = await p.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.getAttribute('href').slice(6))`);check(`all ${live.length} live notes are listed (by id)`, shown.length === live.length && live.every(n => shown.includes(n.id)), `${shown.length} shown`);await p.waitFor('!!navigator.serviceWorker.controller', { timeout: 30000 });// the note to edit: the newest one; open itconst target = shown[0];const before = (await api('/api/notes?id=' + target)).text;await p.click('#notes a');await p.waitFor(`location.pathname === '/note/${target}' && document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ${J(before)}`, { timeout: 30000 });await sleep(1500);console.log('look 1280 online:', await look()); await shot('1280-online');await size(390, 844); console.log('look 390 online:', await look()); await shot('390-online');await size(1280, 900);// Chrome offline: page + worker, then reload offlineconst conn = b.conn; const workers = [];for (const t of (await conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'service_worker')) {const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });await conn.send('Network.enable', {}, sessionId); workers.push(sessionId);}const offline = async (o) => { await p.setOffline(o); for (const s of workers) await conn.send('Network.emulateNetworkConditions', { offline: o, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s); };await offline(true);await p.goto(BASE + '/note/' + target);await p.waitFor(`!!window.__hl && document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ${J(before)}`, { timeout: 30000 });await sleep(1500);const offCount = await p.evaluate(`document.querySelectorAll('#notes a').length`);check(`offline reload: all ${live.length} notes still listed, the open note shows its text, no socket`, offCount === live.length && !(await p.evaluate('!!(window.__hl.socket && window.__hl.socket.readyState === 1)')), String(offCount));// MOBILE (mission 008): the offline pages at 390 px measured in the DOM: no visible element wider than 390 (shadow DOM// included), every visible tap target (a, button, input, textarea, select, [role=button]) at least 44 x 44 pxconst measure = (label) => p.evaluate(`JSON.stringify((() => { const wide = [], small = [], seen = [];const walk = (root) => { for (const e of root.querySelectorAll('*')) { if (e.shadowRoot) walk(e.shadowRoot);const r = e.getBoundingClientRect(); const st = getComputedStyle(e); if (!r.width || !r.height || st.display === 'none' || st.visibility === 'hidden') continue;const name = e.tagName.toLowerCase() + (e.id ? '#' + e.id : '') + (e.className && typeof e.className === 'string' ? '.' + e.className.trim().split(/\\s+/).join('.') : '');const scrolled = e.closest('nav') && /auto|scroll/.test(getComputedStyle(e.closest('nav')).overflowX); /* the phone toolbar is one row that scrolls inside its own box */if (!scrolled && (r.right > 390.5 || r.left < -0.5)) wide.push(name + ' ' + Math.round(r.left) + '..' + Math.round(r.right));if (e.matches('a, button, input:not([type=hidden]), textarea, select, [role=button], [contenteditable]') && (r.height < 43.5 || r.width < 43.5)) small.push(name + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + ' "' + (e.textContent || '').trim().slice(0, 20) + '"');if (e.matches('a, button, input:not([type=hidden]), textarea, select, [role=button], [contenteditable]')) seen.push(name); } };walk(document); return { scrollW: document.documentElement.scrollWidth, innerW: innerWidth, wide: wide.slice(0, 8), small: small.slice(0, 12), taps: seen.length, editor: !!document.querySelector('md-editor article > *') }; })())`).then(JSON.parse);await size(390, 844);for (const [what, url, ready] of [['note', BASE + '/note/' + target, `!!document.getElementById('notetext')`], ['list', BASE + '/', `document.querySelectorAll('#notes a').length > 0`]]) {await p.goto(url);try { await p.waitFor(`!!window.__hl && ${ready}`, { timeout: 30000 }); } catch (e) { console.log('DEBUG', what, await p.evaluate(`JSON.stringify({ path: location.pathname, hl: !!window.__hl, nt: !!document.getElementById('notetext'), body: document.body.innerText.slice(0, 300) })`)); throw e; }await sleep(2000);const m = await measure(what);console.log('390 offline ' + what + ':', J(m));check(`390 px offline, ${what}: the MdEditor block is drawn (surface built, no editor script any more)`, what === 'list' || m.editor, J(m));check(`390 px offline, ${what}: no element wider than 390 px, page scroll width ${m.scrollW}`, m.scrollW <= 390 && m.wide.length === 0, J(m.wide));check(`390 px offline, ${what}: ${m.taps} tap targets, all at least 44 x 44 px`, m.small.length === 0 && m.taps > 0, J(m.small));}await size(1280, 900);await p.goto(BASE + '/note/' + target);await p.waitFor(`!!window.__hl && document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ${J(before)}`, { timeout: 30000 });await sleep(1500);// real keys at the end of the text (the MdEditor block is in the page: nothing to load offline)await p.waitFor(`!!document.querySelector('md-editor article > *')`, { timeout: 30000 });const bx = await p.evaluate(`(() => { const r = document.querySelector('md-editor article').getBoundingClientRect(); return { x: r.left + 20, y: r.top + 10 }; })()`);for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await p.send('Input.dispatchMouseEvent', { type, x: bx.x, y: bx.y, button: 'left', clickCount: 1, buttons });await p.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });await p.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });const add = ' (offline edit, mission 007)';for (const ch of add) { await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); }await sleep(2500);console.log('look 1280 offline:', await look()); await shot('1280-offline');await size(390, 844); console.log('look 390 offline:', await look()); await shot('390-offline'); await size(1280, 900);const typed = await p.evaluate(`document.querySelector('#notetext input[name=text]').value`);check('offline: the edit is in the note, the server does not have it yet', typed === before + add && (await api('/api/notes?id=' + target)).text === before, J(typed.slice(-60)));await offline(false);let after = null;for (let i = 0; i < 120; i++) { after = (await api('/api/notes?id=' + target)).text; if (after === before + add) break; await sleep(250); }const live2 = await alive();check('back online: the offline edit synced into the same note (no copy, same count)', after === before + add && live2.length === live.length, J({ tail: (after || '').slice(-60), n: live2.length }));check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));} catch (e) {console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-1000));} finally {if (b) { try { await b.close(); } catch {} }try { srv.kill('SIGTERM'); } catch {}await sleep(1000);rmSync(W, { recursive: true, force: true });console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);process.exit(failures ? 1 : 0);}
Branches
Latest commits
- 4fb35a0enotes mobile: Delete note and the delete row exactly on the editor's edges; gate asserts 1 pxmre
- 91736270MN report and logmre
- 15667425notes: delete confirmation buttons at most 12rem wide on the desktopmre
- 8f7a6a95gate: MN phone checks (list header gutter, back gap, delete question)mre
- 90c73ed3notes mobile: back link gapmre
- 72bd4f83notes mobile: list header on the gutter, delete confirmation as a question + two equal buttons, Delete note under the editor edgemre
- ba1e73f8notes: a sent edit is done once the server's version is not older, so a second writer's text shows in the first tab; gate: two writers both waysmre
- c69ef9ebsync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
- 2eb783f5sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
- 4dd46dadsync-components: copy icons/icons.hl + README (F4); testsmre
- c92e4a0ftests/e2e-outside.mjs: real-Chrome E2E, a note pushed from another device while open, then typingmre
- 0516b4ccmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
- 38cc11ecmd-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
- 3e7e79f5reports/H1-hydrate.mdmre
- d98775e8tests/browser.mjs: wait for hydration before the clicks after a goto('/') (tables new note, phone sidebar)mre
- 1f3198b6tests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
- 39cf9fdfre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- db07aa84tests: short-id-switch ports from env (NOTES_SWITCH_IDENT_PORT/_PORT), defaults unchangedmre
- ef9f9feere-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- 5485467cdocker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre