notes
All repositories: gitoria
10.2 KB
// tests/e2e-outside.mjs (F3, MdEditor outside value): END TO END in lisbeth's real Chrome (ssh -L <cdp>:127.0.0.1:9223 lisbeth, and -R <app-port> so Chrome// reaches http://<E2E_HOST|127.0.0.1>:<app-port>), real mouse and key events, on a COPY of a deploy backup. A note with a table is open; ANOTHER DEVICE// (an API save with the same login) changes a cell and adds a line; the open editor must show it, and the keys typed next (click the cell, End, "5")// must continue from the NEW text: saved `20` + `5` = `205` (the old editor wrote back its stale `2` + `5` = `25`).// node tests/e2e-outside.mjs prepare <label> <backup.tgz> <app-port> → copies the backup, makes a session, prints the env for the server (start it OUTSIDE the lisbeth lock)// node tests/e2e-outside.mjs run <label> <backup.tgz> <app-port> <cdp-port> <shots-dir> (one tab, navigated; put back to about:blank; the server is already up)import { spawn, execFileSync } from 'node:child_process';import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'node:fs';import { createHash, randomBytes } from 'node:crypto';import { join, resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';const [MODE, LABEL, tgz, portArg, cdpArg, shots] = process.argv.slice(2);const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const PORT = Number(portArg), CDP = Number(cdpArg);const BASE = `http://${process.env.E2E_HOST || '127.0.0.1'}:${PORT}`, API = `http://127.0.0.1:${PORT}`;const W = join(APP, '.scratch/e2e-outside-' + LABEL);const USER = '0muh6o5a3kkd';if (MODE === 'prepare') {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 sid0 = randomBytes(16).toString('hex'), now0 = Date.now();writeFileSync(join(W, 'sessions', createHash('sha256').update(sid0).digest('hex')), JSON.stringify({ created: now0, data: { tag: 'e2e' }, handled: [], id: sid0, seen: now0, user: { id: USER } }), { mode: 0o600 });writeFileSync(join(W, 'sid'), sid0);console.log(`cd ${APP} && NOTES_PORT=${PORT} NOTES_PUBLIC_URL=${BASE} NOTES_STORAGE=${W}/data/storage/mpackdb NOTES_SESSIONS=${W}/sessions/ NOTES_WATCH=0 IDENT_URL=http://ident.test IDENT_API_KEY=pk_e2e IDENT_API_SECRET=sk_e2e ./bin/hybriel project.hl`);process.exit(0);}mkdirSync(shots, { recursive: true });const sid = readFileSync(join(W, 'sid'), 'utf8');let failures = 0, passes = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} [${LABEL}] ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;function connect(url) {return new Promise((ok, no) => {const ws = new WebSocket(url); let n = 0; const pend = new Map();ws.addEventListener('message', (m) => { const d = JSON.parse(m.data); if (d.id && pend.has(d.id)) { const p = pend.get(d.id); pend.delete(d.id); d.error ? p.no(new Error(d.error.message)) : p.ok(d.result); } });ws.addEventListener('open', () => ok({ ws, send: (method, params = {}) => new Promise((ok2, no2) => { const id = ++n; pend.set(id, { ok: ok2, no: no2 }); ws.send(J({ id, method, params })); }) }));ws.addEventListener('error', () => no(new Error('ws error ' + url)));});}const get = async (path) => (await fetch(`http://127.0.0.1:${CDP}${path}`)).json();const hdr = { cookie: 'notessid=' + sid, 'content-type': 'application/json' };const api = async (path) => (await fetch(API + path, { headers: hdr })).json();const post = async (b) => (await fetch(API + '/api/notes', { method: 'POST', headers: hdr, body: J(b) })).json();let page = null, tabUrlBefore = null;const ev = async (expr) => { const r = await page.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error('evaluate: ' + (r.exceptionDetails.exception && r.exceptionDetails.exception.description || r.exceptionDetails.text)); return r.result.value; };const waitFor = async (expr, label, timeout = 40000) => { const t0 = Date.now(); for (;;) { let v = false; try { v = await ev(expr); } catch {} if (v) return v; if (Date.now() - t0 > timeout) throw new Error('waitFor timed out: ' + label); await sleep(250); } };const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(shots, `${LABEL}-${name}.png`), Buffer.from(data, 'base64')); };const size = async (w, h) => { await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(400); };const click = async (x, y) => { for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await page.send('Input.dispatchMouseEvent', { type, x: Math.round(x), y: Math.round(y), button: 'left', clickCount: 1, buttons }); await sleep(150); };const clickSel = async (sel) => { const r = await ev(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const q = e.getBoundingClientRect(); return { x: q.left + q.width / 2, y: q.top + q.height / 2 }; })()`); if (!r) throw new Error('no ' + sel); await click(r.x, r.y); };const key = async (k, code, vk) => { await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await sleep(60); };const type = async (s) => { for (const ch of s) { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); } await sleep(80); };const value = () => ev(`(() => { const i = document.querySelector('#notetext input[name=text]'); return i ? i.value : null; })()`);const shown = () => ev(`(() => { const a = document.querySelector('md-editor article'); return a ? a.innerText : null; })()`);const TEXT1 = '# Outside E2E\n\n| Item | Qty |\n|:---|---:|\n| milk | 2 |\n| bread | 1 |\n';const TEXT2 = '# Outside E2E\n\n| Item | Qty |\n|:---|---:|\n| milk | 20 |\n| bread | 1 |\n\nChanged on another device\n';try {for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }check('the copy: the session is the creator', (await api('/api/me')).user === USER);const pages = (await get('/json/list')).filter(t => t.type === 'page');const tabs = pages.filter(t => t.url === 'about:blank');if (!tabs.length) tabs.push(...pages.filter(t => t.url.startsWith('http://127.0.0.1:') || t.url.startsWith('http://localhost:')).slice(0, 1));if (!tabs.length) throw new Error('no existing about:blank tab');tabUrlBefore = tabs[0].url;page = await connect(tabs[0].webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${CDP}`));for (const m of ['Page.enable', 'Runtime.enable', 'Network.enable']) await page.send(m);await page.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });let n = 0;for (const [W_, H_] of [[390, 844], [1280, 900]]) {const tag = String(W_);await size(W_, H_);const local = 'lf3' + tag + Date.now().toString(16);const r1 = await post({ op: 'save', id: '', local, text: TEXT1, base: 0, at: Date.now() });check(`${tag}: the note is saved (${r1.id})`, !!r1.id, J(r1));await page.send('Page.navigate', { url: BASE + '/note/' + r1.id }); await sleep(300); await page.send('Page.bringToFront');await waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated', 60000);await waitFor(`!!document.querySelector('md-editor article table')`, 'the note and its table', 60000); await sleep(800);check(`${tag}: the open note shows qty 2`, /milk\s+2\b/.test(await shown()), J(await shown()));await shot(`${tag}-1-open`);// ANOTHER DEVICE changes the note: the page gets it as a pushconst r2 = await post({ op: 'save', id: r1.id, local, text: TEXT2, base: r1.edited, at: Date.now() });check(`${tag}: the other device's save is taken (${J(r2).slice(0, 80)})`, r2.text === TEXT2, J(r2));await waitFor(`((document.querySelector('#notetext input[name=text]') || {}).value || '').includes('Changed on another device')`, 'the field follows the push', 90000);await sleep(1500);const sh = await shown();check(`${tag}: the editor surface shows the pushed text (qty 20, the new line)`, /milk\s+20\b/.test(sh) && sh.includes('Changed on another device'), J(sh));await shot(`${tag}-2-after-push`);// the first edit: click in the Qty cell of milk, End, type 5const cell = await ev(`(() => { const c = [...document.querySelectorAll('md-editor article td')].find(t => t.textContent.trim() === '20' || t.textContent.trim() === '2'); if (!c) return null; c.scrollIntoView({ block: 'center' }); const q = c.getBoundingClientRect(); return { x: q.left + q.width / 2, y: q.top + q.height / 2 }; })()`);if (!cell) throw new Error('no qty cell');await click(cell.x, cell.y); await key('End', 'End', 35); await type('5'); await sleep(300);const v = await value();check(`${tag}: the field holds 205 (the first edit started from the new text), not 25 — ${J(v)}`, /\| milk +\| +205 +\|/.test(v) && v.includes('Changed on another device'), J(v));await shot(`${tag}-3-typed`);let saved = null;for (let i = 0; i < 60 && !saved; i++) { const t = (await api('/api/notes?id=' + r1.id)).text; if (/\| milk +\| +205 +\|/.test(t || '')) saved = t; else await sleep(500); }check(`${tag}: the server keeps 205 and the other device's line`, !!saved && saved.includes('Changed on another device'), J((await api('/api/notes?id=' + r1.id)).text));n++;}} catch (e) { failures++; console.log('FAIL crashed — ' + e.message); try { console.log('field', J(await value()), 'shown', J(await shown())); await shot('crash'); } catch {} }finally {try { if (page) { await page.send('Emulation.clearDeviceMetricsOverride'); await page.send('Page.navigate', { url: 'about:blank' }); page.ws.close(); } } catch {}console.log(`${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);}
Branches
Latest commits
- eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
- 3537cf7eMerge branch 'vendor-day59' into mainAtlas
- c13d188b|||PR Vendor Hybriel day59Atlas
- 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
- ae1075b2Preserve rejected drafts during note ID adoptionAtlas
- 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
- 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
- 649cef37|||PR Vendor Hybriel day56Atlas
- aadd0abcMerge branch 'hl-standard-2' into mainAtlas
- 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
- 617ee8c0Merge branch 'hl-standard' into mainAtlas
- 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
- 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
- 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
- d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
- 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
- d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
- 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
- 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre