gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita2e343aea2e343aeident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mrea2e343ae/tests/browser.mjs

58.2 KB

  1. // tests/browser.mjs — THE GATE of notes.worldapi.org (tickets notes#1: sidebar + Markdown editor; notes#2: offline + sync;
  2. // notes#4: offline and sync in pure Hybriel — hl:web's own worker, kept state per user and queue; Chrome offline through CDP).
  3. // Its own notes server on its own storage, its OWN ident (a copy of ident's code without .env — codes go to a mail
  4. // sink, tests/identkit.mjs), real headless Chromes for everything visible. `*.notes.test` is mapped to 127.0.0.1
  5. // inside Chrome (--host-resolver-rules) so ident and the app are the same site, as on worldapi.org.
  6. //
  7. // node tests/browser.mjs (NOTES_GATE_PORT server, default 8702; NOTES_GATE_IDENT_PORT, default 8701;
  8. // NOTES_GATE_CHROME "8713-8719" = Chrome debug ports)
  9. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  10. // NOTES_GATE_SOFT=1 (old code only: waits do not stop the gate), NOTES_GATE_DEBUG=1 (a crash dumps both devices' state).
  11. // NOTES_GATE_UNTIL=<section> stops after that section (offline, outage, conflict, delete, …) while working on the gate.
  12. import { spawn } from 'node:child_process';
  13. import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
  14. import { dirname, join, resolve } from 'node:path';
  15. import { fileURLToPath } from 'node:url';
  16. import { launchBrowser } from './cdp.mjs';
  17. import { startIdent } from './identkit.mjs';
  18. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  19. const HERE = dirname(fileURLToPath(import.meta.url));
  20. const APP = resolve(HERE, '..');
  21. const BIN = join(APP, 'bin/hybriel');
  22. const PORT = Number(process.env.NOTES_GATE_PORT || 8702);
  23. const IDENT_PORT = Number(process.env.NOTES_GATE_IDENT_PORT || 8701);
  24. const API = `http://127.0.0.1:${PORT}`;
  25. const BASE = `http://notes.test:${PORT}`;
  26. const IDENT_B = `http://ident.notes.test:${IDENT_PORT}`;
  27. const [CH_FROM, CH_TO] = (process.env.NOTES_GATE_CHROME || '8703-8709').split('-').map(Number);
  28. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.notes.test 127.0.0.1, MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=' + `http://notes.test:${PORT}`; // a service worker needs a secure origin (https on worldapi.org)
  29. const SCRATCH = join(APP, '.scratch');
  30. const STORE = join(SCRATCH, 'gate-store');
  31. const IDENT_DIR = process.env.NOTES_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  32. rmSync(STORE, { recursive: true, force: true });
  33. mkdirSync(STORE, { recursive: true });
  34. // IW (creator 2026-10-24, "you removed the ident widget from all sites"): ident's <ident-selector> stands in the header, VISIBLE, top right — signed
  35. // out and signed in, on the phone and on the desktop. Returns 'ok' or what is wrong (hidden by an ancestor, no box, outside the viewport, not in the
  36. // header, not on the right, covered by something else).
  37. const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';
  38. for (let e = s; e && e !== document.documentElement; e = e.parentElement) { const c = getComputedStyle(e); if (c.display === 'none') return 'display:none on ' + e.tagName; if (c.visibility === 'hidden') return 'visibility:hidden on ' + e.tagName; if (+c.opacity === 0) return 'opacity 0 on ' + e.tagName; }
  39. const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();
  40. if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;
  41. if (b.left < 0 || b.top < 0 || b.right > innerWidth + 0.5 || b.bottom > innerHeight) return 'outside the viewport ' + JSON.stringify([b.left, b.top, b.right, b.bottom]);
  42. if (b.top < h.top - 1 || b.bottom > h.bottom + 1) return 'not inside the header row ' + JSON.stringify([b.top, b.bottom, h.top, h.bottom]);
  43. if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;
  44. const top = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2); if (!top || !top.closest('ident-selector')) return 'covered by ' + (top && top.tagName);
  45. return 'ok'; })()`;
  46. let failures = 0, passes = 0;
  47. function check(label, ok, detail = '') {
  48. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  49. if (ok) passes++; else failures++;
  50. }
  51. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  52. const J = JSON.stringify;
  53. let log = '';
  54. let server = null, ident = null;
  55. const browsers = [];
  56. function startServer(extraEnv = {}) {
  57. log += '\n==== notes server start\n';
  58. server = spawn(BIN, ['project.hl'], {
  59. cwd: APP,
  60. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_STORAGE: join(STORE, 'mpackdb'), NOTES_SESSIONS: join(STORE, 'sessions') + '/', NOTES_WATCH: '0',
  61. NOTES_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...extraEnv },
  62. stdio: ['ignore', 'pipe', 'pipe'],
  63. });
  64. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  65. }
  66. async function serverUp() {
  67. for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/'); if (r.ok) return; } catch {} await sleep(250); }
  68. throw new Error('notes did not come up\n' + log);
  69. }
  70. async function stopServer() {
  71. if (!server) return;
  72. try { server.kill('SIGTERM'); } catch {}
  73. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  74. server = null;
  75. }
  76. const SLOW = Number(process.env.NOTES_GATE_SLOW || 3);
  77. // NOTES_GATE_SOFT=1: a wait that times out is logged and the gate goes on (the checks decide) — to run this gate against
  78. // OLD code and see which checks fail there; never for a real gate run
  79. const SOFT = process.env.NOTES_GATE_SOFT === '1';
  80. function patient(page) {
  81. const waitFor = page.waitFor.bind(page);
  82. page.waitFor = (expr, o = {}) => SOFT
  83. ? waitFor(expr, { ...o, timeout: o.timeout || 10000 }).catch((e) => { console.log('note (soft): ' + e.message); return false; })
  84. : waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  85. const goto = page.goto.bind(page);
  86. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  87. return page;
  88. }
  89. // a page of a NEW Chrome (own cookies), or — given `like` — another tab of the same Chrome (same login)
  90. async function newPage(like = null) {
  91. if (like) return patient(await like.__browser.newPage());
  92. const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  93. browsers.push(b);
  94. const p = patient(await b.newPage());
  95. p.__browser = b;
  96. return p;
  97. }
  98. async function viewport(page, width, height) {
  99. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  100. await sleep(250);
  101. }
  102. async function shot(page, name) {
  103. await page.send('Page.bringToFront');
  104. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  105. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  106. }
  107. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  108. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });
  109. const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);
  110. const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);
  111. const subjects = (page) => page.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.textContent)`);
  112. const UNTIL = process.env.NOTES_GATE_UNTIL || '';
  113. const until = (name) => { if (UNTIL === name) throw Object.assign(new Error('stopped after ' + name), { until: true }); };
  114. const visible = (page, sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  115. async function identSignIn(page, email) {
  116. await page.goto(IDENT_B + '/');
  117. await page.waitForSelector('#email');
  118. await hydrated(page);
  119. await page.type('#email', email);
  120. await page.click('#sendcode');
  121. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  122. await hydrated(page);
  123. await page.type('#code', ident.lastCode(email));
  124. await page.click('#verify');
  125. await page.waitForSelector('#signout, #menusignout', { timeout: 10000 });
  126. }
  127. // the plain LOGIN LINK (ident's /login with the app key and the callback — the header has no button for it since 2026-10-24, the selector is the way
  128. // in, but the old way is still served): opened as the button's link did → ident's "choose an identity" → back
  129. let LOGIN_URL = null;
  130. async function buttonLogin(page) {
  131. await page.goto(LOGIN_URL);
  132. await page.waitForSelector('#chooselist', { timeout: 10000 });
  133. await hydrated(page);
  134. await page.click('#chooselist li:nth-child(1) .choose');
  135. }
  136. // ---- REAL clicks and keys into the editor's shadow DOM (as in tickets' gate) ----------------------------
  137. const mdR = (expr) => `(() => { const r = document.querySelector('#notetext md-editor'); if (!r) return null; return (${expr}); })()`;
  138. const CTRL = 2;
  139. async function mdClick(page, sel) {
  140. const bx = await page.evaluate(mdR(`(() => { const el = r.querySelector(${J(sel)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const q = el.getBoundingClientRect(); return { x: q.left, y: q.top, w: q.width, h: q.height }; })()`));
  141. if (!bx || !bx.w) throw new Error('mdClick: ' + sel + ' is not laid out');
  142. const x = Math.round(bx.x + bx.w / 2), y = Math.round(bx.y + bx.h / 2);
  143. for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await page.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, buttons });
  144. await sleep(80);
  145. }
  146. async function mdPress(page, key, mods = 0) {
  147. const K = { Enter: [13, 'Enter', '\r'], End: [35, 'End'], Tab: [9, 'Tab'] }[key];
  148. const [vk, code, text] = K;
  149. const t = text && !(mods & CTRL) ? text : undefined;
  150. await page.send('Input.dispatchKeyEvent', { type: t ? 'keyDown' : 'rawKeyDown', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, ...(t ? { text: t, unmodifiedText: t } : {}) });
  151. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk });
  152. await sleep(30);
  153. }
  154. async function mdType(page, text) {
  155. for (const ch of text) {
  156. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  157. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  158. }
  159. await sleep(60);
  160. }
  161. const taVal = (page) => page.evaluate(`document.querySelector('#notetext input[name=text]').value`);
  162. // the block builds the surface's content once the page is live (a 100 ms animation, no mount event): wait for it, or a click lands in an empty surface
  163. const editorReady = (page, label) => page.waitFor(mdR(`!!r.querySelector('md-editor article > *')`), { label });
  164. const emitFace = async (event, payload, cookie) => {
  165. const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });
  166. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  167. return { status: r.status, raw: t, value: j && j.value };
  168. };
  169. // ---- CHROME OFFLINE (notes#4): CDP cuts the page AND its service worker. An open WebSocket survives the cut
  170. // (report 005), so every offline check first RELOADS offline: the page boots from hl:web's worker, no socket opens.
  171. async function workerSessions(page) {
  172. const conn = page.__browser.conn;
  173. page.__workers = page.__workers || new Map();
  174. const { targetInfos } = await conn.send('Target.getTargets');
  175. for (const t of targetInfos) {
  176. if (t.type === 'service_worker' && !page.__workers.has(t.targetId)) {
  177. const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  178. await conn.send('Network.enable', {}, sessionId);
  179. page.__workers.set(t.targetId, sessionId);
  180. }
  181. }
  182. return [...page.__workers.values()];
  183. }
  184. async function setOffline(page, off) {
  185. await page.setOffline(off);
  186. for (const s of await workerSessions(page)) await page.__browser.conn.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s);
  187. }
  188. const socketOpen = (page) => page.evaluate('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)');
  189. const booted = (page, label) => page.waitFor('!!window.__hl', { label });
  190. // what hl:web keeps in this browser (IndexedDB `hl-offline`: `state`, `queue`) and the worker's documents
  191. const keptCopy = (page) => page.evaluate(`(async () => {
  192. const dbs = (await indexedDB.databases()).map(d => d.name);
  193. // every database of this origin, every store (hl:web's \`hl-offline\` and anything else, e.g. the old notes-<user>)
  194. let state = [], queue = [];
  195. for (const name of dbs) {
  196. const db = await new Promise((ok, no) => { const r = indexedDB.open(name); r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error); });
  197. const all = (st) => new Promise((ok) => { try { const r = db.transaction(st, 'readonly').objectStore(st).getAll(); r.onsuccess = () => ok(r.result); r.onerror = () => ok([]); } catch (e) { ok([]); } });
  198. for (const st of [...db.objectStoreNames]) { const rows = await all(st); if (name === 'hl-offline' && st === 'queue') queue = rows; else state.push({ db: name, store: st, rows }); }
  199. db.close();
  200. }
  201. const docs = [];
  202. for (const k of await caches.keys()) { const c = await caches.open(k); for (const r of await c.keys()) { const res = await c.match(r); if ((res.headers.get('content-type') || '').includes('text/html')) docs.push({ cache: k, path: new URL(r.url).pathname, html: await res.text() }); } }
  203. return { dbs, state: JSON.stringify(state), queue: queue.length, queueText: JSON.stringify(queue), docs };
  204. })()`);
  205. // the editor: <md-editor>'s own surface when the element is defined, else the plain textarea it wraps — real keys either way
  206. const mdDefined = (page) => page.evaluate(`!!document.querySelector('#notetext md-editor article')`);
  207. async function typeAtEnd(page, text) {
  208. if (await mdDefined(page)) {
  209. await editorReady(page, 'editor');
  210. await mdClick(page, 'md-editor article');
  211. await mdPress(page, 'End', CTRL);
  212. } else {
  213. await page.click('#notetext');
  214. await mdPress(page, 'End', CTRL);
  215. }
  216. await mdType(page, text);
  217. }
  218. try {
  219. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  220. const alice = await ident.signIn('[email protected]');
  221. await ident.signIn('[email protected]');
  222. const APPKEY = await ident.registerApp(alice, 'notes (gate)', [BASE]);
  223. LOGIN_URL = `${IDENT_B}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`;
  224. check('ident: our own ident runs (a copy without .env), notes is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  225. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  226. await serverUp();
  227. // ---- signed out -------------------------------------------------------------------------------------
  228. let html = await (await fetch(API + '/')).text();
  229. check('signed out: the page only asks to log in (no list, no editor, no notes)', /Log in with ident/.test(html) && !/id="newnote"|<note-list|<md-editor|id="notesapp"/.test(html), html.slice(html.indexOf('<body')).slice(0, 300));
  230. // mission 015 (route marker, hybriel#197): the menu's one item "Notes" (href /) is marked in the SERVER's html on every page: the list, a note, the login failure
  231. for (const pg of ['/', '/note/abc123def456', '/login/failed']) {
  232. const h = await (await fetch(API + pg)).text();
  233. const links = [...h.matchAll(/<a [^>]*href="\/"[^>]*>Notes/g)].map(m => m[0]);
  234. check(`server html ${pg}: the menu marks Notes (aria-current=page, class current), in both menus, before any script`, links.length >= 2 && links.every(l => /aria-current="page"/.test(l) && /class="current"/.test(l)), J(links));
  235. }
  236. let r = await fetch(API + '/login/callback', { redirect: 'manual' });
  237. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  238. r = await fetch(API + '/api/notes');
  239. check('signed out: the notes API answers 401', r.status === 401);
  240. r = await (await fetch(API + '/api/me')).json();
  241. check('signed out: /api/me says nobody', r.user === null, J(r));
  242. // ---- log in with ident (the button flow) on device A ----------------------------------------------------
  243. const a = await newPage();
  244. globalThis.__debugPages = { A: a };
  245. await viewport(a, 1280, 900);
  246. await identSignIn(a, '[email protected]');
  247. await a.goto(BASE + '/');
  248. await hydrated(a);
  249. check('signed out (browser): the selector stands in the header and NOTHING beside it (no second "Log in with ident" button); no "New note"', await has(a, '#selector') && !(await has(a, '#loginbutton')) && !(await has(a, 'a[href*="/login?key="]')) && !(await has(a, '#newnote')));
  250. for (const [w, h] of [[390, 844], [1280, 900]]) {
  251. await viewport(a, w, h);
  252. check(`IW ${w}px signed out: ident's selector stands visible at the top right of the header`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok', await a.evaluate(SELECTOR_IN_HEADER));
  253. }
  254. await viewport(a, 1280, 900);
  255. await buttonLogin(a);
  256. await a.waitForSelector('#newnote', { timeout: 15000 });
  257. check('login: alice sees her (empty) list and "New note"', (await txt(a, '#empty')) !== null && (await subjects(a)).length === 0 && await has(a, '#logout'));
  258. for (const [w, h] of [[390, 844], [1280, 900]]) {
  259. await viewport(a, w, h);
  260. check(`IW ${w}px signed in: ident's selector stands visible at the top right of the header and shows it is logged in`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await a.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)), await a.evaluate(SELECTOR_IN_HEADER));
  261. await a.click('button.user-toggle');
  262. await a.waitFor('document.querySelector("#user-menu").matches(":popover-open")', { label: 'user menu' });
  263. check(`IW ${w}px signed in: Log out is reachable (the user menu opens by a real click and shows it, 44 px high, inside the screen)`, await a.evaluate('(() => { const b = document.querySelector("#logout").getBoundingClientRect(); return b.width > 0 && b.height >= 44 && b.bottom <= innerHeight && b.right <= innerWidth; })()'));
  264. await a.evaluate('document.querySelector("#user-menu").hidePopover()');
  265. }
  266. await viewport(a, 1280, 900);
  267. const cookieOf = async (page) => (await page.cookies([BASE])).filter(c => c.name === 'notessid').map(c => 'notessid=' + c.value)[0];
  268. const cookieA = await cookieOf(a);
  269. const apiGet = async (path, cookie) => { const x = await fetch(API + path, { headers: { cookie } }); return { status: x.status, json: await x.json().catch(() => null) }; };
  270. const apiPost = async (body, cookie) => { const x = await fetch(API + '/api/notes', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: typeof body === 'string' ? body : J(body) }); return { status: x.status, json: await x.json().catch(() => null) }; };
  271. const serverNotes = async (cookie) => {
  272. const list = (await apiGet('/api/notes', cookie)).json.notes.filter(n => !n.gone);
  273. const out = [];
  274. for (const n of list) out.push({ ...n, text: (await apiGet('/api/notes?id=' + n.id, cookie)).json.text });
  275. return out;
  276. };
  277. const untilServer = async (cookie, pred, label) => {
  278. for (let i = 0; i < 80; i++) { const ns = await serverNotes(cookie); if (pred(ns)) return ns; await sleep(250); }
  279. throw new Error('server never showed: ' + label + ' ' + J(await serverNotes(cookie)));
  280. };
  281. // the page has synced when its socket is open and nothing waits in hl:web's queue (the replay is done)
  282. const synced = async (page, label) => {
  283. await page.waitFor('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)', { label: label + ' (socket)', timeout: 20000 });
  284. for (let i = 0; i < 120; i++) { if ((await keptCopy(page)).queue === 0) return true; await sleep(250); }
  285. console.log('note: ' + label + ': the queue never emptied'); // the checks after this decide
  286. return false;
  287. };
  288. const keptPaths = (page) => page.evaluate(`(async () => { const out = []; for (const k of await caches.keys()) { if (!k.startsWith('hl-shell-')) continue; const c = await caches.open(k); for (const r of await c.keys()) out.push(new URL(r.url).pathname); } return out.sort().join(' '); })()`);
  289. const shellKept = async (page) => { for (let i = 0; i < 80; i++) { if (/(^| )\/( |$)/.test(await keptPaths(page))) return true; await sleep(250); } console.log('note: the page was never kept by hl:web: ' + await keptPaths(page)); return false; };
  290. await a.waitFor('!!navigator.serviceWorker.controller', { label: 'page controlled by a service worker' });
  291. await shellKept(a);
  292. const kp = await keptPaths(a);
  293. check("offline: hl:web's worker keeps the page document and the shell (runtime, client half, stylesheet, page modules)",
  294. /(^| )\/( |$)/.test(kp) && /\/__hl\/hl-runtime\.js/.test(kp) && /\/__hl\/web\/client\.js/.test(kp) && /\/__hl\/app\.css/.test(kp) && /\/components\/notes\.hl/.test(kp), kp);
  295. // ---- THE INSTALLABLE APP (mission 046): hl:web's own manifest from project.hl appIcons, and since notes#4 its own
  296. // generated service worker too (`offline = [Notes]`): notes' /sw.js and /notes-offline.js are gone.
  297. const pwaHtml = await (await fetch(API + '/')).text();
  298. const mhref = (pwaHtml.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  299. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header token `darker`)',
  300. mhref === '/__hl/manifest.webmanifest' && pwaHtml.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  301. && pwaHtml.includes('<link rel="icon" href="/icons/favicon.svg">') && pwaHtml.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), pwaHtml.slice(0, 900));
  302. const mres = await fetch(API + mhref);
  303. const man = await mres.json();
  304. check('pwa: the manifest is served as application/manifest+json: name "notes", start_url /, scope /, display standalone, the token colours',
  305. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'notes' && man.short_name === 'notes' && man.start_url === '/' && man.scope === '/'
  306. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  307. const iconOk = [];
  308. for (const ic of man.icons || []) {
  309. const ir = await fetch(API + ic.src);
  310. const buf = Buffer.from(await ir.arrayBuffer());
  311. iconOk.push(ir.ok && ic.type === 'image/png' && buf.readUInt32BE(16) === Number(ic.sizes.split('x')[0]) && buf.readUInt32BE(20) === Number(ic.sizes.split('x')[1]));
  312. }
  313. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  314. iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(pu => ['192x192', '512x512'].every(sz => man.icons.some(i => i.purpose === pu && i.sizes === sz))), J(man.icons) + ' ' + J(iconOk));
  315. const touch = await fetch(API + '/icons/apple-touch-icon.png');
  316. const touchBytes = Buffer.from(await touch.arrayBuffer());
  317. const fav = await fetch(API + '/icons/favicon.svg');
  318. const favText = await fav.text();
  319. const ico = await fetch(API + '/favicon.ico');
  320. const icoBytes = Buffer.from(await ico.arrayBuffer());
  321. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in notes yellow, /favicon.ico a real icon file',
  322. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#dcdcaa')
  323. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  324. const am = await a.send('Page.getAppManifest');
  325. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));
  326. const inst = await a.send('Page.getInstallabilityErrors');
  327. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  328. const regs = await a.evaluate(`navigator.serviceWorker.getRegistrations().then(rs => rs.map(r => new URL(r.scope).pathname + ' ' + new URL((r.active || r.waiting || r.installing).scriptURL).pathname).join(','))`);
  329. check("pwa: exactly one service worker — hl:web's generated /__hl/sw.js for scope /, it controls the page; /sw.js and /notes-offline.js are gone (404)",
  330. regs === '/ /__hl/sw.js' && new URL(await a.evaluate('navigator.serviceWorker.controller.scriptURL')).pathname === '/__hl/sw.js'
  331. && (await fetch(API + '/sw.js')).status === 404 && (await fetch(API + '/notes-offline.js')).status === 404, regs);
  332. const pageJs = await a.evaluate(`[...document.scripts].map(x => x.src ? new URL(x.src).pathname : 'inline').join(' ')`);
  333. check('no hand-written notes JavaScript on the page: only hl:web, ident and login.js (no md-editor.js: the Hybriel MdEditor block draws the editor)', !/notes-offline|\/sw\.js|md-editor/.test(pageJs), pageJs);
  334. check('mission 010: /md-editor.js is gone (404) and no <md-editor> custom element is defined — the block\'s <md-editor> is plain Hybriel', (await fetch(API + '/md-editor.js')).status === 404 && !(await a.evaluate(`!!customElements.get('md-editor')`)), pageJs);
  335. // ---- new note: heading and text; saved on the server ------------------------------------------------------
  336. await a.click('#newnote');
  337. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'the new note is open' });
  338. await a.waitForSelector('#notetext');
  339. await editorReady(a, 'editor on the new note');
  340. check('new note: opens on the right, the sidebar lists it as "Untitled note"', (await subjects(a)).join('|') === 'Untitled note' && await visible(a, 'note-list') && await visible(a, 'note-editor'), J(await subjects(a)));
  341. await mdClick(a, 'md-editor article');
  342. await mdType(a, '# Groceries');
  343. await mdPress(a, 'Enter');
  344. await mdType(a, 'milk and bread');
  345. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'sidebar shows the heading as the subject' });
  346. const t1 = await taVal(a);
  347. check('editor: "# " became a heading, the textarea holds the Markdown', t1 === '# Groceries\n\nmilk and bread' || t1 === '# Groceries\nmilk and bread', J(t1));
  348. check('editor: the heading is formatted (h1 in the editor)', await a.evaluate(mdR(`!!r.querySelector('md-editor article h1')`)));
  349. let sn = await untilServer(cookieA, ns => ns.length === 1 && /^# Groceries/.test(ns[0].text) && /milk and bread$/.test(ns[0].text), 'Groceries');
  350. check('online: the note reached the server, which gave it its own id', /^[0-9a-z]{12}$/.test(sn[0].id), J(sn));
  351. await a.waitFor(`location.pathname === '/note/${sn[0].id}'`, { label: 'the address follows the server id' });
  352. const firstUrl = '/note/' + sn[0].id;
  353. await shot(a, 'desktop-one-note');
  354. // ---- a second note; the edited one goes to the top ------------------------------------------------------------
  355. await a.click('#newnote');
  356. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'second note' });
  357. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'the second note is empty' });
  358. await editorReady(a, 'editor on the second note');
  359. await mdClick(a, 'md-editor article');
  360. await mdType(a, 'Zebra facts');
  361. await a.waitFor(`document.querySelector('#notes a').textContent === 'Zebra facts'`, { label: 'Zebra on top' });
  362. check('sidebar: two notes, the newest edited on top', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  363. await untilServer(cookieA, ns => ns.length === 2, 'two notes');
  364. await a.click(`#notes a[href="${firstUrl}"]`);
  365. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'Groceries text loaded' });
  366. check('sidebar click: the note opens on the right with its text', location_ok(await a.evaluate('location.pathname'), firstUrl));
  367. function location_ok(x, y) { return x === y; }
  368. // ---- device B (another browser, same login) gets the notes -------------------------------------------------------
  369. const b = await newPage();
  370. globalThis.__debugPages.B = b;
  371. await viewport(b, 1280, 900);
  372. await identSignIn(b, '[email protected]');
  373. await b.goto(BASE + '/');
  374. await hydrated(b);
  375. await buttonLogin(b);
  376. await b.waitForSelector('#newnote', { timeout: 15000 });
  377. await b.waitFor(`document.querySelectorAll('#notes a').length === 2`, { label: 'device B pulled the notes' });
  378. check('second device: the same two notes appear after login', (await subjects(b)).join('|') === 'Zebra facts|Groceries', J(await subjects(b)));
  379. await b.goto(BASE + firstUrl);
  380. await b.waitForSelector('#notetext');
  381. await b.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'B opened Groceries by its address' });
  382. check('second device: a note address opens the note', true);
  383. const cookieB = await cookieOf(b);
  384. await shellKept(b);
  385. // ---- CHROME OFFLINE on A (notes#4): CDP cuts the page and its worker, then the page is RELOADED offline ---------------
  386. await setOffline(a, true);
  387. await a.goto(BASE + firstUrl);
  388. await booted(a, 'offline: the page boots from the worker');
  389. await a.waitForSelector('#notetext', { timeout: 20000 });
  390. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'offline: the note opens from the browser copy' });
  391. check('offline: the page reloads with no network and shows the note and the list', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  392. check('chrome offline (new): the reload really is offline — the page booted from the worker and has no socket', !(await socketOpen(a)) && await a.evaluate('navigator.onLine === false'));
  393. await sleep(1500);
  394. check('chrome offline (new): the MdEditor block is there offline (it is in the page itself — no script file to keep)', await mdDefined(a), 'no md-editor article offline');
  395. await typeAtEnd(a, ' and eggs');
  396. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'offline edit moves the note to the top' });
  397. await a.click('#newnote');
  398. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'offline: new note' });
  399. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'offline: the new note is empty' });
  400. await typeAtEnd(a, 'Written offline');
  401. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline'`, { label: 'offline note in the list' });
  402. const saysOffline = await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'the page says it is offline' }).then(() => true, () => false);
  403. check('offline: the sidebar says the changes are kept here', saysOffline, J(await txt(a, '#syncstate')));
  404. await sleep(2500);
  405. const waiting = await keptCopy(a);
  406. const onServer = (await serverNotes(cookieA)).map(n => n.text);
  407. check('chrome offline (new): the edit and the new note wait in the browser (hl:web queue) — the server has neither yet',
  408. waiting.queue >= 2 && /and eggs/.test(waiting.queueText) && /Written offline/.test(waiting.queueText) && !onServer.some(t => /and eggs|Written offline/.test(t)), J({ q: waiting.queue, onServer }));
  409. await a.goto(BASE + '/');
  410. await booted(a, 'offline / boots');
  411. await a.waitForSelector('#notes a');
  412. await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'offline / says it is offline' });
  413. check('offline: a reload of / with no network opens the shell (header, brand, logout, the list) and says it is offline (mission 046)',
  414. (await txt(a, 'application-header .brand')) === 'notes' && await has(a, '#logout') && await has(a, 'note-list') && /Offline/.test(await txt(a, '#syncstate')));
  415. await viewport(a, 390, 844);
  416. await shot(a, 'pwa-phone-offline');
  417. await viewport(a, 1280, 900);
  418. check('offline: after another reload the offline edits are all there', (await subjects(a)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(a)));
  419. await a.click('#notes li:nth-child(2) a');
  420. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('milk and bread and eggs')`, { label: 'the offline edit is in the note' });
  421. check('offline: the edited text survived the reload', true);
  422. until('offline');
  423. // ---- back online: it reaches the server, and device B --------------------------------------------------------------
  424. await setOffline(a, false);
  425. sn = await untilServer(cookieA, ns => ns.length === 3 && ns.some(n => /milk and bread and eggs$/.test(n.text)) && ns.some(n => n.text === 'Written offline'), 'the offline edits');
  426. check('back online: the offline edit and the offline note reached the server', sn.filter(n => n.text === 'Written offline').length === 1, J(sn));
  427. await synced(a, 'A back online');
  428. await a.waitFor(`[...document.querySelectorAll('#notes a')].length === 3 && [...document.querySelectorAll('#notes a')].every(x => !/\\/note\\/l/.test(x.getAttribute('href')))`, { label: 'the offline note got a server id' });
  429. check('back online: the offline note now has a server id', true);
  430. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B got the offline note' });
  431. await b.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('and eggs')`, { label: 'B shows the edit in the open note' });
  432. check('second device: sees the edit made offline on the first (open note refreshed) and the new note', (await subjects(b)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(b)));
  433. until('online');
  434. // ---- the same note edited on two devices while both are offline: nothing is lost -----------------------------------
  435. await b.click('#notes li:nth-child(3) a');
  436. await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'B opened Zebra' });
  437. await a.click('#notes li:nth-child(3) a');
  438. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'A opened Zebra' });
  439. await stopServer();
  440. await typeAtEnd(a, ' on A');
  441. await sleep(1200);
  442. await typeAtEnd(b, ' on B');
  443. await sleep(300);
  444. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  445. await serverUp();
  446. await synced(a, 'A after the outage');
  447. await synced(b, 'B after the outage');
  448. sn = await untilServer(cookieA, ns => ns.length === 4, 'the conflict copy');
  449. const texts = sn.map(n => n.text);
  450. check('conflict: the later edit (B) is the note, the other (A) is kept as a copy — nothing lost', texts.includes('Zebra facts on B') && texts.some(t => t.startsWith('Zebra facts on A') && /kept as a copy/.test(t)), J(texts));
  451. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  452. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  453. check('conflict: both devices end with the same four notes', (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  454. until('conflict');
  455. // mission 014 (hybriel#196): "Delete note" is pressed ONCE and the question must open and stay open >= 0.5 s. (Mission 012 pressed
  456. // again when it closed by itself; the cause was notes.hl open() setting `asking = false` only after the awaited flush(0) ack.)
  457. const openAsk = async (page, label) => {
  458. const shown = `document.querySelector('#deleteyes').getBoundingClientRect().width > 0`;
  459. await page.click('#delete');
  460. await page.waitFor(shown, { label: label + ' opens' });
  461. const t0 = Date.now();
  462. while (Date.now() - t0 < 500) {
  463. if (!(await page.evaluate(shown))) throw new Error('the delete question closed by itself within 0.5 s: ' + label);
  464. await sleep(50);
  465. }
  466. return 1;
  467. };
  468. // ---- delete on A reaches B -------------------------------------------------------------------------------------------------
  469. await a.click('#notes li:nth-child(1) a');
  470. await a.waitFor(`!!document.getElementById('notetext')`, { label: 'A opened a note to delete' });
  471. const doomed = await a.evaluate('document.querySelector("#notetext input[name=text]").value');
  472. check('delete: the question is hidden until "Delete note" is clicked', !(await visible(a, '#deleteyes')));
  473. await openAsk(a, 'delete question');
  474. await a.click('#deleteno');
  475. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width === 0`, { label: 'kept' });
  476. check('delete: "Keep" changes nothing', (await subjects(a)).length === 4);
  477. await openAsk(a, 'delete question again');
  478. await a.click('#deleteyes');
  479. await a.waitFor(`location.pathname === '/' && document.querySelectorAll('#notes a').length === 3`, { label: 'back to the list, one note less' });
  480. check('delete: the note is gone from the list and the page is the list again', await has(a, '#pick'));
  481. await untilServer(cookieA, ns => ns.length === 3 && !ns.some(n => n.text === doomed), 'the delete');
  482. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B follows the delete' });
  483. check('delete: the other device follows', true);
  484. until('delete');
  485. // ---- NEW (notes#4): one device OFFLINE (Chrome, reloaded offline), the other online, the same note ----------------------
  486. const pickNote = async (page, subject) => {
  487. await page.evaluate(`[...document.querySelectorAll('#notes a')].find(x => x.textContent === ${J(subject)}).scrollIntoView()`);
  488. const i = await page.evaluate(`[...document.querySelectorAll('#notes a')].findIndex(x => x.textContent === ${J(subject)})`);
  489. await page.click(`#notes li:nth-child(${i + 1}) a`);
  490. };
  491. await pickNote(a, 'Written offline');
  492. await a.waitFor(`location.pathname.startsWith('/note/') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A opened "Written offline"' });
  493. const splitUrl = await a.evaluate('location.pathname');
  494. await setOffline(a, true);
  495. await a.goto(BASE + splitUrl);
  496. await booted(a, 'A offline again');
  497. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A offline: the note' });
  498. await typeAtEnd(a, ' / A offline');
  499. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline / A offline'`, { label: 'A offline: typed' });
  500. await sleep(2000);
  501. await pickNote(b, 'Written offline');
  502. await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'B opened it' });
  503. await typeAtEnd(b, ' / B online');
  504. await untilServer(cookieA, ns => ns.some(n => n.text === 'Written offline / B online'), 'B online save');
  505. check('one offline (new): while A is offline, B\'s online edit reaches the server and A\'s does not',
  506. !(await serverNotes(cookieA)).some(n => /A offline/.test(n.text)) && (await keptCopy(a)).queue >= 1);
  507. await setOffline(a, false);
  508. sn = await untilServer(cookieA, ns => ns.length === 4, 'the copy of the offline edit');
  509. const split = sn.map(n => n.text);
  510. check('one offline (new): back online, the later edit (B) is the note and A\'s offline edit is kept as a copy — nothing lost',
  511. split.includes('Written offline / B online') && split.some(t => t.startsWith('Written offline / A offline') && /kept as a copy/.test(t)), J(split));
  512. await synced(a, 'A back after the split');
  513. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  514. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  515. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline / B online'`, { label: 'A shows the winner in its editor' });
  516. check('one offline (new): both devices list the same four notes; A\'s editor now shows the winning text',
  517. (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  518. until('split');
  519. // ---- NEW (N1): TWO WRITERS on one note, both ways, by real keys: what B types must reach A as surely as A's reaches B ------------
  520. // (before the fix, tab A kept its own already-sent edit laid over the server's list, so B's text never showed in A)
  521. const twoPath = await a.evaluate('location.pathname');
  522. await b.goto(BASE + twoPath);
  523. await b.waitFor(`!!document.querySelector('#notetext md-editor article > *')`, { label: 'two writers: B opened the note' });
  524. await editorReady(a, 'two writers: A editor');
  525. const typeAt = async (page, mark) => { await mdClick(page, 'article'); await mdPress(page, 'End', CTRL); await mdType(page, mark); };
  526. let twoOk = true, twoWhy = '';
  527. for (let i = 1; i <= 3 && twoOk; i++) {
  528. for (const [src, dst, who, mark] of [[a, b, 'A', ` +a${i}`], [b, a, 'B', ` +b${i}`]]) {
  529. await typeAt(src, mark);
  530. try { await dst.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith(${J(mark)})`, { label: `two writers: ${who}'s ${mark} reaches the other tab`, timeout: 8000 }); }
  531. catch (e) { twoOk = false; twoWhy = `${who} typed ${mark}, the other tab shows …${(await taVal(dst)).slice(-30)}`; break; }
  532. }
  533. }
  534. check('two writers: text typed in tab B reaches tab A, and A\'s reaches B (3 rounds each way)', twoOk, twoWhy);
  535. await sleep(1500);
  536. const finalA = await taVal(a), finalB = await taVal(b);
  537. check('two writers: both tabs end with the same text holding every typed mark', finalA === finalB && [1, 2, 3].every(i => finalA.includes(` +a${i}`) && finalA.includes(` +b${i}`)), J(finalA.slice(-60)) + J(finalB.slice(-60)));
  538. await a.goto(BASE + twoPath);
  539. await editorReady(a, 'two writers: A reloaded');
  540. check('two writers: after a reload nothing is lost', (await taVal(a)).endsWith(' +b3') && (await taVal(a)).includes(' +a3'), J((await taVal(a)).slice(-40)));
  541. until('twowriters');
  542. // ---- somebody else sees nothing of it ----------------------------------------------------------------------------------------
  543. const bob = await newPage();
  544. await viewport(bob, 1280, 900);
  545. await identSignIn(bob, '[email protected]');
  546. await bob.goto(BASE + '/');
  547. await hydrated(bob);
  548. await buttonLogin(bob);
  549. await bob.waitForSelector('#newnote', { timeout: 15000 });
  550. await sleep(800);
  551. check('another user: an empty list', (await subjects(bob)).length === 0);
  552. const cookieBob = await cookieOf(bob);
  553. const alicePick = (await serverNotes(cookieA))[0];
  554. const aliceId = alicePick.id;
  555. check("another user: alice's note is not in bob's API", (await apiGet('/api/notes?id=' + aliceId, cookieBob)).status === 404 && (await apiGet('/api/notes', cookieBob)).json.notes.length === 0);
  556. await apiPost({ op: 'save', id: aliceId, local: '', text: 'hacked', base: 0, at: 1 }, cookieBob);
  557. await apiPost({ op: 'delete', id: aliceId, base: 0 }, cookieBob);
  558. check("another user: saving over / deleting alice's note does not touch it", (await serverNotes(cookieA)).some(n => n.id === aliceId && n.text === alicePick.text));
  559. check('a note over the size limit is refused, not cut', (await apiPost({ op: 'save', id: '', local: 'x1', text: 'x'.repeat(200001), base: 0, at: 1 }, cookieA)).status === 400);
  560. check('the API refuses invalid JSON and wrong fields with 400', (await apiPost('{nope', cookieA)).status === 400 && (await apiPost({ op: 'save', id: 5 }, cookieA)).status === 400 && (await apiPost({ op: 'zap' }, cookieA)).status === 400);
  561. // a retried push (the answer was lost) does not make a second note
  562. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  563. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  564. check('a push repeated after a lost answer makes no second note', (await serverNotes(cookieA)).filter(n => n.text === 'retry me').length === 1);
  565. // ---- MARKDOWN TABLES (notes#5): a table TYPED with real keys becomes a real <table>; a line with pipes stays text --------
  566. await a.goto(BASE + '/');
  567. await a.waitForSelector('#newnote');
  568. await hydrated(a); // the server-rendered button is clickable before the client mounts: that click is lost
  569. await a.click('#newnote');
  570. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'tables: new note' });
  571. await editorReady(a, 'tables: editor');
  572. await mdClick(a, 'md-editor article');
  573. await mdType(a, 'Shopping table');
  574. await mdPress(a, 'Enter');
  575. await mdType(a, 'a | b stays text');
  576. await mdPress(a, 'Enter');
  577. await mdType(a, '| Item | Qty | Note \\| x |');
  578. await mdPress(a, 'Enter');
  579. await mdType(a, '|:---|:---:|---:|');
  580. await mdPress(a, 'Enter');
  581. await mdType(a, '**milk**');
  582. await mdPress(a, 'Tab');
  583. await mdType(a, '`2`');
  584. await mdPress(a, 'Tab');
  585. await mdType(a, 'a|b');
  586. await mdPress(a, 'Enter');
  587. await mdType(a, 'bread');
  588. await mdPress(a, 'Tab');
  589. await mdType(a, '1');
  590. await mdPress(a, 'Tab');
  591. await mdType(a, 'Donaudampfschifffahrtsgesellschaftskapitaenswitwenrentenversicherung');
  592. await mdPress(a, 'Enter');
  593. await mdPress(a, 'Enter');
  594. await mdType(a, 'after the table');
  595. const tableOf = (page) => page.evaluate(mdR(`(() => {
  596. const t = r.querySelector('md-editor article table'); if (!t) return null;
  597. const cell = (c) => ({ text: c.textContent, html: c.innerHTML, align: c.getAttribute('data-align') || '', css: getComputedStyle(c).textAlign });
  598. return { head: [...t.querySelectorAll('thead th')].map(cell), rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell)),
  599. ps: [...r.querySelectorAll('md-editor article > p')].map(p => p.textContent), order: [...r.querySelector('md-editor article').children].map(e => e.tagName).join(' ') };
  600. })()`));
  601. const tableOk = (t) => !!t && t.head.map(c => c.text).join('/') === 'Item/Qty/Note | x'
  602. && t.head.map(c => c.align + ':' + c.css).join(' ') === 'left:left center:center right:right'
  603. && t.rows.length === 2 && /^<strong>milk<\/strong>\u200b?$/.test(t.rows[0][0].html) && /^<code>2<\/code>\u200b?$/.test(t.rows[0][1].html) && t.rows[0][2].text === 'a|b'
  604. && t.rows[1].map(c => c.text).join('/').startsWith('bread/1/Donaudampf') && t.rows[1][1].css === 'center';
  605. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('after the table')`, { label: 'tables: typed to the end' });
  606. let tb = await tableOf(a);
  607. check('tables: typed header + delimiter + rows became a <table> (th, aligned left/center/right, bold + code cells, a typed pipe in a cell, \\| in the header)', tableOk(tb), J(tb));
  608. check('tables: the line with pipes stays a paragraph, text before and after the table too',
  609. !!tb && tb.ps.join('/') === 'Shopping table/a | b stays text/after the table' && tb.order === 'P P TABLE P', J(tb && [tb.ps, tb.order]));
  610. const md = await taVal(a);
  611. const mdLines = md.split('\n');
  612. const reparsed = mdLines.map(l => l === '' ? '' : l.startsWith('|') ? 'T' : 'p').join('').replace(/T+/g, 'T' + mdLines.filter(l => l.startsWith('|')).length);
  613. check('tables: the note is GitHub Markdown — pipe rows, `:---`/`:-:`/`--:`, escaped pipes, bold/code kept',
  614. /^\| Item +\| Qty +\| Note \\\| x +\|$/.test(mdLines.find(l => l.startsWith('| Item')) || '') && /^\| :-+ \| :-+: \| -+: \|$/.test(mdLines.find(l => /^\| :-/.test(l)) || '')
  615. && /\| \*\*milk\*\* +\| `2` +\| a\\\|b +\|/.test(md) && reparsed === 'ppT4p', J(md) + ' ' + reparsed);
  616. const tableNote = await untilServer(cookieA, ns => ns.some(n => n.text === md), 'the table note');
  617. const tableId = tableNote.find(n => n.text === md).id;
  618. await a.goto(BASE + '/note/' + tableId);
  619. await a.waitForSelector('#notetext');
  620. await editorReady(a, 'tables: reopened');
  621. await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: table after reload' });
  622. tb = await tableOf(a);
  623. check('tables: reopened from the server the note shows the same table, the text is unchanged', tableOk(tb) && (await taVal(a)) === md, J(tb));
  624. await viewport(a, 1280, 900);
  625. await shot(a, 'tables-desktop');
  626. await viewport(a, 390, 844);
  627. await sleep(300);
  628. const scroll = await a.evaluate(mdR(`(() => { const t = r.querySelector('md-editor article table'); const box = r.querySelector('md-editor article').getBoundingClientRect(); const q = t.getBoundingClientRect(); return { sw: t.scrollWidth, cw: t.clientWidth, inBox: q.right <= box.right + 1, ov: getComputedStyle(t).overflowX }; })()`));
  629. check('tables: on a phone the wide table scrolls inside its box, the page does not scroll sideways',
  630. scroll.sw > scroll.cw && scroll.inBox && /auto|scroll/.test(scroll.ov) && await noOverflow(a), J(scroll));
  631. await shot(a, 'tables-phone');
  632. const phoneEd = await a.evaluate(mdR(`(() => { const nav = r.querySelector('nav'); const bs = [...r.querySelectorAll('nav button')].map(x => x.getBoundingClientRect()); const q = r.getBoundingClientRect(); const tx = r.querySelector('article'); return { editorW: Math.round(q.width), viewW: innerWidth, small: bs.filter(x => x.width > 0 && (x.width < 43.5 || x.height < 43.5)).length, buttons: bs.length, fs: parseFloat(getComputedStyle(tx).fontSize), files: [...r.querySelectorAll('nav button')].some(x => /file/i.test(x.textContent) && x.getBoundingClientRect().width > 0) }; })()`));
  633. check('mission 010 (phone, 390): the editor fits the screen, every toolbar button is >= 44 px, the text is >= 16 px, no File button (files="off", the notes have no uploads)',
  634. phoneEd.editorW <= phoneEd.viewW && phoneEd.buttons > 0 && phoneEd.small === 0 && phoneEd.fs >= 16 && !phoneEd.files, J(phoneEd));
  635. await viewport(a, 1280, 900);
  636. // a cell edited in place: only that cell changes in the Markdown
  637. await mdClick(a, 'md-editor article tbody tr:first-child td:nth-child(2)');
  638. await mdPress(a, 'End');
  639. await mdType(a, '0');
  640. await a.waitFor(`document.querySelector('#notetext input[name=text]').value !== ${J(md)}`, { label: 'tables: cell edit' });
  641. const md2 = await taVal(a);
  642. const outside = (t) => t.split('\n').filter(l => !l.startsWith('|')).join('\n');
  643. const cellNow = (/\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2) || [])[1] ? 'code:' + /\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2)[1] : null;
  644. check('tables: typing in a cell changes that cell (`2` → `20`), the text around the table stays byte for byte', cellNow === 'code:20' && outside(md2) === outside(md) && md2.split('\n').filter(l => l.startsWith('|')).length === 4, J(md2));
  645. // offline: the table renders from the browser copy with the server gone
  646. await untilServer(cookieA, ns => ns.some(n => n.text === md2), 'the cell edit');
  647. await synced(a, 'tables: saved');
  648. await stopServer();
  649. await a.goto(BASE + '/note/' + tableId);
  650. await a.waitForSelector('#notetext', { timeout: 20000 });
  651. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === ${J(md2)}`, { label: 'tables: offline text' });
  652. await sleep(1500);
  653. tb = null;
  654. if (await mdDefined(a)) {
  655. await editorReady(a, 'tables: offline');
  656. await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: offline table' });
  657. tb = await tableOf(a);
  658. }
  659. check('tables: offline (server stopped) the note opens from the browser copy with the table', !!tb && tb.rows.length === 2 && tb.rows[0][1].text === '20' && (await taVal(a)) === md2, tb ? J(tb) : 'no <md-editor> offline (Hybriel gap, report 007); the text itself is there: ' + ((await taVal(a)) === md2));
  660. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  661. await serverUp();
  662. await synced(a, 'tables: after the outage');
  663. // ---- phone and desktop layout ----------------------------------------------------------------------------------------------------
  664. await a.goto(BASE + '/');
  665. await a.waitForSelector('#notes a');
  666. await hydrated(a); // the sidebar links are server-rendered too
  667. await viewport(a, 390, 844);
  668. check('phone: the list alone, no note', await visible(a, 'note-list') && !(await visible(a, 'note-reader')) && await noOverflow(a));
  669. await shot(a, 'phone-list');
  670. // MN (mobile audit): the list header stands on the 16 px gutter like the rows' text, not on the screen edge
  671. const hdr = await a.evaluate(`(() => { const h = document.querySelector('note-list h1').getBoundingClientRect(), b = document.querySelector('#newnote').getBoundingClientRect(), r = document.querySelector('#notes a').getBoundingClientRect(); return { h1: Math.round(h.left), btnGap: Math.round(innerWidth - b.right), rowText: Math.round(r.left + parseFloat(getComputedStyle(document.querySelector('#notes a')).paddingLeft)) }; })()`);
  672. check('MN phone list: "Notes" and "New note" stand on the 16 px gutter (same left edge as the row text, not 4 px from the screen edge)', hdr.h1 >= 14 && hdr.btnGap >= 14 && Math.abs(hdr.h1 - hdr.rowText) <= 2, J(hdr));
  673. await a.click('#notes a');
  674. await a.waitForSelector('#notetext');
  675. await editorReady(a, 'phone editor');
  676. check('phone: the opened note replaces the list, with a way back', !(await visible(a, 'note-list')) && await visible(a, 'note-editor') && await visible(a, '.back') && await noOverflow(a));
  677. await shot(a, 'phone-note');
  678. // MN: back link close to the editor; "Delete note" under the editor's edge; the delete question on its own line with two equal buttons
  679. const g1 = await a.evaluate(`(() => { const q = (x) => document.querySelector(x).getBoundingClientRect(); return { gap: Math.round(q('#notetext').top - q('a.back').bottom), delLeft: q('#delete').left, edLeft: q('#notetext').left, backLeft: q('a.back').left }; })()`);
  680. check('MN phone note: the gap between "All notes" and the editor is <= 20 px, "Delete note" button left edge = editor left edge = All notes left edge', g1.gap <= 20 && Math.abs(g1.delLeft - g1.edLeft) <= 1 && Math.abs(g1.backLeft - g1.edLeft) <= 1, J(g1));
  681. await a.click('#delete');
  682. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display !== 'none'`, { label: 'delete question open' });
  683. const g2 = await a.evaluate(`(() => { const q = (x) => document.querySelector(x).getBoundingClientRect(); const t = document.querySelector('#deleteask ask-text').getBoundingClientRect(); return { qLeft: t.left, edLeft: q('#notetext').left, edRight: q('#notetext').right, rowLeft: q('#deleteyes').left, rowRight: q('#deleteno').right, qBottom: Math.round(t.bottom), yesTop: Math.round(q('#deleteyes').top), noTop: Math.round(q('#deleteno').top), yesW: Math.round(q('#deleteyes').width), noW: Math.round(q('#deleteno').width), yesH: Math.round(q('#deleteyes').height), noH: Math.round(q('#deleteno').height) }; })()`);
  684. check('MN phone delete question: text on the editor edge, then Delete and Keep side by side, equal, >= 44 px, below the text',
  685. Math.abs(g2.qLeft - g2.edLeft) <= 1 && Math.abs(g2.rowLeft - g2.edLeft) <= 1 && Math.abs(g2.rowRight - g2.edRight) <= 1 && g2.yesTop >= g2.qBottom - 1 && Math.abs(g2.yesTop - g2.noTop) <= 1 && Math.abs(g2.yesW - g2.noW) <= 2 && g2.yesW >= 100 && g2.yesH >= 43 && g2.noH >= 43 && await noOverflow(a), J(g2));
  686. await shot(a, 'phone-delete-ask');
  687. await a.click('#deleteno');
  688. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display === 'none'`, { label: 'delete question closed' });
  689. await a.click('.back');
  690. await a.waitFor(`location.pathname === '/' && document.querySelector('note-list').getBoundingClientRect().width > 0`, { label: 'phone: back to the list' });
  691. check('phone: "All notes" brings the list back', await visible(a, 'note-list') && !(await visible(a, 'note-reader')));
  692. await viewport(a, 1280, 900);
  693. await a.click('#notes a');
  694. await editorReady(a, 'desktop editor');
  695. check('desktop: list and note side by side, no "All notes" link', await visible(a, 'note-list') && await visible(a, 'note-editor') && !(await visible(a, '.back')) && await noOverflow(a));
  696. await shot(a, 'desktop-two');
  697. // ---- log out: the browser forgets the notes ---------------------------------------------------------------------------------------
  698. // mission 011: Log out is in the theme's user menu (the icon at the header's right end opens it)
  699. await a.click('button.user-toggle');
  700. await a.waitFor(`document.querySelector('#user-menu').matches(':popover-open')`, { label: 'user menu open' });
  701. await a.click('#logout');
  702. await a.waitForSelector('#loginhint');
  703. check('log out: the notes are gone from the page, the login hint shows', !(await has(a, '#notes')) && await has(a, '#loginhint'));
  704. await sleep(1500);
  705. const after = await keptCopy(a);
  706. const leak = (x) => /Groceries|milk and bread|Zebra facts|Written offline/.test(x);
  707. check("log out: this browser deleted its copy of the notes (hl:web's kept state, queue and kept documents)",
  708. !leak(after.state) && after.queue === 0 && !after.docs.some(d => leak(d.html)), J({ state: after.state.slice(0, 300), q: after.queue, docs: after.docs.map(d => d.path + (leak(d.html) ? ' LEAK' : '')) }));
  709. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  710. } catch (e) {
  711. if (process.env.NOTES_GATE_DEBUG) { for (const b of browsers) { try { for (const t of (await b.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page')) console.log('DEBUG page', t.url); } catch {} } }
  712. for (const [name, dp] of Object.entries(globalThis.__debugPages || {})) if (process.env.NOTES_GATE_DEBUG) { try { console.log('DEBUG ' + name, await dp.evaluate(`JSON.stringify({ path: location.pathname, hrefs: [...document.querySelectorAll('#notes a')].map(a => a.getAttribute('href') + ' ' + a.textContent), sock: window.__hl && window.__hl.socket && window.__hl.socket.readyState, sync: (document.getElementById('syncstate')||{}).textContent })`), JSON.stringify(await keptCopy(dp)).slice(0, 1500)); console.log(dp.dumpConsole().split('\n').filter(l => !/debug|ERR_INTERNET|ERR_FAILED/.test(l)).slice(-40).join('\n')); } catch (x) { console.log('debug failed', x); } }
  713. if (e && e.until) { console.log('---- ' + e.message + ' (NOTES_GATE_UNTIL)'); failures += 0; } else {
  714. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  715. failures++;
  716. console.log(log.slice(-1500));
  717. }
  718. } finally {
  719. for (const b of browsers) { try { await b.close(); } catch {} }
  720. await stopServer();
  721. if (ident) await ident.stop();
  722. console.log(`${passes} passed, ${failures} failed`);
  723. process.exit(failures ? 1 : 0);
  724. }

Branches

Latest commits

  • a2e343aeident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b96c7f70theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 6140e6a0sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • cb7e6469deploy: security gate (tests/security.mjs)mre
  • 774bf34bnotes security: CSRF guard on /api/notes, new session at login, Secure cookie, uploadMax 0, login rate limit, nosniff, face payload check; tests/security.mjs; SN reportmre
  • ef18a68fsync components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
  • c37488b1MN report: alignment updatemre
  • 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