LifeMate — Personal, Family & Learning Companion

design/mobile-accessibility-v2
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
cjs 572 lines 38.5 KB
Raw
1 #!/usr/bin/env node
2 'use strict';
3
4 // Design-only checks: static fixtures, no application server or real identity.
5 // Every result below is measured in the launched Chromium process. This does
6 // not attest Safari, assistive technology, an installed PWA, or a real device.
7 const { chromium } = require('playwright');
8 const fs = require('node:fs');
9 const path = require('node:path');
10 const assert = require('node:assert/strict');
11
12 const packageRoot = path.resolve(__dirname, '..');
13 const base = new URL(process.env.DESIGN_BASE_URL || 'http://127.0.0.1:8772/LifeGuide-preview.html');
14 const receiptPath = path.resolve(process.env.DESIGN_RECEIPT || path.join(packageRoot, 'exports/verification.json'));
15 const screenshotsDir = path.join(path.dirname(receiptPath), 'screenshots');
16 const requestedWidths = [320, 360, 390];
17 const themes = ['calm', 'bright'];
18 const systemStates = ['normal', 'empty', 'loading', 'error', 'offline', 'conflict', 'session', 'rate-limit'];
19 const requiredMain = ['home', 'plan', 'courses', 'lesson', 'quiz', 'focus', 'family', 'reminders', 'settings', 'parent-home', 'report'];
20 const label = 'طرح تعاملی با داده ساختگی';
21 const started = new Date().toISOString();
22
23 const report = {
24 schemaVersion: 2,
25 scope: 'LifeGuide-Design-v2: static, fictional, interactive design only',
26 status: 'FAIL',
27 startedAt: started,
28 command: 'NODE_PATH=/opt/codex/runtimes/codex-primary-runtime/dependencies/node/node_modules node tools/check.cjs',
29 baseUrl: base.origin + base.pathname,
30 browser: null,
31 matrices: { widths: requestedWidths, themes, fontScale: [1, 2], systemStates },
32 checks: [],
33 failures: [],
34 measurements: {
35 auditedLayouts: 0, visibleTextNodes: 0, touchTargets: 0,
36 minimumFontPx: null, minimumContrast: null, minimumTargetWidthPx: null,
37 minimumTargetHeightPx: null, worstContrast: null, minimumFont: null,
38 bidi: [],
39 },
40 screenshots: [],
41 runtimeErrors: [],
42 failedStaticRequests: [],
43 externalRequests: [],
44 forbiddenRequests: [],
45 unverified: {
46 safari: 'UNVERIFIED: Safari has not been run.',
47 realDevice: 'UNVERIFIED: no physical Android/iPhone/iPad test has been performed.',
48 iranReachability: 'UNVERIFIED: this local static check does not measure access from Iran.',
49 videoPlayback: 'UNVERIFIED: no approved video source or real video playback is included.',
50 studentUsability: 'UNVERIFIED: the ten-minute student test script has not been conducted.',
51 backendAndPersistence: 'UNVERIFIED and outside scope: no server, sending, saving, or real authentication.',
52 },
53 };
54 const failureKeys = new Set();
55 function fail(check, details) {
56 const key = `${check}:${JSON.stringify(details)}`;
57 if (!failureKeys.has(key)) {
58 failureKeys.add(key);
59 report.failures.push({ check, ...details });
60 }
61 }
62 function checked(check, details = {}) {
63 report.checks.push({ check, status: 'VERIFIED', result: 'PASS', ...details });
64 }
65 function safeRequest(url) {
66 try { const parsed = new URL(url); return parsed.origin + parsed.pathname; }
67 catch { return 'unparseable-url'; }
68 }
69 function writeReport() {
70 report.finishedAt = new Date().toISOString();
71 report.passed = report.failures.length === 0 && report.checks.length > 0;
72 report.status = report.passed ? 'VERIFIED_DESIGN_ONLY' : 'FAIL';
73 report.failureCount = report.failures.length;
74 fs.mkdirSync(path.dirname(receiptPath), { recursive: true });
75 fs.writeFileSync(receiptPath, JSON.stringify(report, null, 2) + '\n');
76 }
77
78 // This function runs inside Chromium so measurements use actual computed
79 // styles, browser line boxes and glyph positions, rather than token guesses.
80 function auditLayout({ expectedScreen, expectedState, expectedTheme, fontScale, requiredLabel }) {
81 const problems = [];
82 const stats = { textCount: 0, targetCount: 0, minimumFont: null, minimumContrast: null, minimumTargetWidth: null, minimumTargetHeight: null, fontSamples: [] };
83 const phone = document.querySelector('.phone');
84 const rectOf = (element) => {
85 const r = element.getBoundingClientRect();
86 return { x: +r.x.toFixed(2), y: +r.y.toFixed(2), width: +r.width.toFixed(2), height: +r.height.toFixed(2) };
87 };
88 const selector = (element) => {
89 if (!element) return '(missing)';
90 if (element.id) return '#' + element.id;
91 const qa = element.getAttribute('data-qa');
92 if (qa) return '[data-qa="' + qa + '"]';
93 const classes = [...element.classList].slice(0, 3).map(c => '.' + c).join('');
94 return element.tagName.toLowerCase() + classes;
95 };
96 const visible = (element) => {
97 if (!(element instanceof Element)) return false;
98 for (let current = element; current; current = current.parentElement) {
99 const s = getComputedStyle(current);
100 if (s.display === 'none' || s.visibility === 'hidden' || s.visibility === 'collapse' || Number(s.opacity) === 0 || current.hidden) return false;
101 }
102 return !!element.getClientRects().length;
103 };
104 const parseColor = (color) => {
105 if (color === 'transparent') return [0, 0, 0, 0];
106 const parts = color.match(/^rgba?\(([^)]+)\)$/);
107 if (!parts) throw new Error('Unsupported computed color: ' + color);
108 const nums = parts[1].split(/[\s,/]+/).filter(Boolean).map(Number);
109 if (nums.length < 3 || nums.some(n => !Number.isFinite(n))) throw new Error('Invalid computed color: ' + color);
110 return [nums[0], nums[1], nums[2], nums[3] ?? 1];
111 };
112 const over = (front, back) => {
113 const alpha = front[3] + back[3] * (1 - front[3]);
114 if (alpha === 0) return [0, 0, 0, 0];
115 return [0, 1, 2].map(i => (front[i] * front[3] + back[i] * back[3] * (1 - front[3])) / alpha).concat(alpha);
116 };
117 const luminance = (color) => {
118 const c = color.slice(0, 3).map(v => {
119 const s = v / 255;
120 return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
121 });
122 return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
123 };
124 const contrast = (front, back) => {
125 const a = luminance(front), b = luminance(back);
126 return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
127 };
128 const contrastFor = (element, foreground) => {
129 const chain = [];
130 for (let current = element; current; current = current.parentElement) chain.push(current);
131 let bg = [255, 255, 255, 1];
132 for (const ancestor of chain.reverse()) {
133 const style = getComputedStyle(ancestor);
134 if (style.backgroundImage !== 'none') throw new Error('Text contrast with a background image/gradient requires a pixel audit: ' + selector(ancestor));
135 if (Number(style.opacity) !== 1) throw new Error('Text contrast with ancestor opacity requires a layer audit: ' + selector(ancestor));
136 bg = over(parseColor(style.backgroundColor), bg);
137 }
138 const fg = over(parseColor(foreground), bg);
139 return { ratio: contrast(fg, bg), foreground: fg.map((n, i) => i < 3 ? +n.toFixed(2) : n), background: bg.map((n, i) => i < 3 ? +n.toFixed(2) : n) };
140 };
141 if (!phone) return { problems: [{ type: 'missing-phone' }], stats };
142 for (const [attribute, expected] of [['data-screen', expectedScreen], ['data-state', expectedState], ['data-theme', expectedTheme]]) {
143 if (phone.getAttribute(attribute) !== expected) problems.push({ type: 'wrong-route', attribute, expected, actual: phone.getAttribute(attribute) });
144 }
145 const labels = [...phone.querySelectorAll('.prototype-label')].filter(visible);
146 if (labels.length !== 1 || labels[0].textContent.trim() !== requiredLabel) problems.push({ type: 'prototype-label', count: labels.length });
147 if (!phone.querySelector('main.screen-content')) problems.push({ type: 'missing-main-landmark' });
148 if (phone.querySelector('.home-menu-card')) problems.push({ type: 'removed-home-menu-card-still-present' });
149 const nav = phone.querySelector('.bottom-nav');
150 if (nav && nav.querySelectorAll('button').length > 5) problems.push({ type: 'too-many-bottom-destinations', count: nav.querySelectorAll('button').length });
151 if (document.querySelector('form')) problems.push({ type: 'real-form-present' });
152 for (const input of document.querySelectorAll('input,textarea,[contenteditable]')) {
153 if (input.matches('input[type="checkbox"],input[type="radio"]')) continue;
154 if (input.isContentEditable || !input.readOnly && !input.disabled) problems.push({ type: 'editable-personal-value', selector: selector(input) });
155 if (input.matches('input[type="tel"],input[type="email"]')) problems.push({ type: 'real-identity-field-type', selector: selector(input), inputType: input.type });
156 }
157 if (expectedScreen === 'home' && ['normal', 'offline', 'error'].includes(expectedState)) {
158 const tasks = phone.querySelectorAll('[data-qa="today-task"]');
159 if (tasks.length < 3 || tasks.length > 4) problems.push({ type: 'home-task-count', count: tasks.length, expected: 'three or four tasks' });
160 if (phone.querySelectorAll('[data-qa="task-start"]').length !== tasks.length) problems.push({ type: 'home-task-action-missing' });
161 if (!phone.querySelector('[role="progressbar"][aria-valuenow]')) problems.push({ type: 'home-progress-missing' });
162 if (!phone.querySelector('header [data-action="go:reminders"]') || !phone.querySelector('header [data-action="go:student-report"]')) problems.push({ type: 'home-header-destination-missing' });
163 }
164 if (['empty', 'loading', 'error', 'offline', 'conflict', 'session', 'rate-limit'].includes(expectedState)) {
165 const stateElement = phone.querySelector(`[data-qa="state-${expectedState}"]`);
166 if (!stateElement || !visible(stateElement)) problems.push({ type: 'state-content-missing', expectedState });
167 else if (expectedState !== 'loading' && !stateElement.textContent.trim()) problems.push({ type: 'state-without-text-label', expectedState });
168 if (expectedState === 'loading' && (!stateElement?.matches('[aria-busy="true"]') || phone.querySelectorAll('.skeleton').length < 2)) problems.push({ type: 'loading-skeleton-missing' });
169 if (expectedState === 'error' && !phone.querySelector('button[data-action="state:normal"]')) problems.push({ type: 'retry-control-missing' });
170 if (expectedState === 'offline' && phone.querySelectorAll('[data-qa="queued-list"] li').length < 1) problems.push({ type: 'offline-queue-list-missing' });
171 if (expectedState === 'conflict' && (!phone.querySelector('button[data-action="resolve:local"]') || !phone.querySelector('button[data-action="resolve:other"]'))) problems.push({ type: 'conflict-choice-missing' });
172 if (expectedState === 'session' && !phone.querySelector('button[data-action="go:welcome"]')) problems.push({ type: 'session-reentry-missing' });
173 if (expectedState === 'rate-limit' && (!/[۴4][۲2][۹9]/.test(stateElement?.textContent || '') || !phone.querySelector('button:disabled'))) problems.push({ type: 'rate-limit-cooldown-missing' });
174 }
175 if (expectedScreen === 'otp' && ['wrong', 'expired', 'cooldown'].includes(expectedState)) {
176 const alert = phone.querySelector('[role="alert"]');
177 const expectedWord = { wrong: 'اشتباه', expired: 'منقضی', cooldown: 'ثانیه' }[expectedState];
178 if (!alert?.textContent.includes(expectedWord)) problems.push({ type: 'otp-state-message-missing', expectedState });
179 if (expectedState === 'cooldown' && !phone.querySelector('button[data-action="noop"]:disabled')) problems.push({ type: 'otp-resend-not-disabled-during-cooldown' });
180 }
181 if (document.documentElement.scrollWidth > innerWidth + 1) problems.push({ type: 'document-horizontal-overflow', scrollWidth: document.documentElement.scrollWidth, viewportWidth: innerWidth });
182
183 const bodyElements = [phone, ...phone.querySelectorAll('*')];
184 for (const element of bodyElements) {
185 if (!visible(element) || !(element instanceof HTMLElement)) continue;
186 // Native controls expose internal scrolling metrics unrelated to layout.
187 // Their actual outer bounds and targets are still audited below.
188 if (!['INPUT', 'TEXTAREA', 'SELECT', 'OPTION'].includes(element.tagName) && element.clientWidth > 0 && element.scrollWidth > element.clientWidth + 1) {
189 problems.push({ type: 'element-horizontal-overflow', selector: selector(element), clientWidth: element.clientWidth, scrollWidth: element.scrollWidth, rect: rectOf(element) });
190 }
191 }
192
193 const textAudit = (element, text, rectangles) => {
194 const style = getComputedStyle(element);
195 const font = parseFloat(style.fontSize);
196 const sample = text.replace(/\s+/g, ' ').trim().slice(0, 100);
197 const location = { selector: selector(element), text: sample, rect: rectOf(element), fontSizePx: +font.toFixed(3) };
198 stats.textCount++;
199 stats.fontSamples.push({ selector: location.selector, text: sample, fontSizePx: font });
200 if (!stats.minimumFont || font < stats.minimumFont.value) stats.minimumFont = { value: font, ...location };
201 // A 200% root font must actually enlarge every text item; fixed px sizes
202 // cannot silently pass by merely remaining above 12px.
203 if (font < 12 * fontScale - 0.02) problems.push({ type: 'font-below-minimum', requiredPx: 12 * fontScale, ...location });
204 try {
205 const measured = contrastFor(element, style.color);
206 if (!stats.minimumContrast || measured.ratio < stats.minimumContrast.value) stats.minimumContrast = { value: measured.ratio, ...location, ...measured };
207 if (measured.ratio < 4.5 - 0.001) problems.push({ type: 'text-contrast', required: 4.5, ratio: +measured.ratio.toFixed(4), ...location, foreground: measured.foreground, background: measured.background });
208 } catch (error) { problems.push({ type: 'unmeasurable-contrast', ...location, message: error.message }); }
209 // Hidden/clip overflow may cut text permanently. Scrollable ancestors are
210 // deliberately allowed: their offscreen text can be reached by scrolling.
211 for (let ancestor = element; ancestor && phone.contains(ancestor); ancestor = ancestor.parentElement) {
212 const ancestorStyle = getComputedStyle(ancestor);
213 const clipsX = ['hidden', 'clip'].includes(ancestorStyle.overflowX);
214 const clipsY = ['hidden', 'clip'].includes(ancestorStyle.overflowY);
215 if (!clipsX && !clipsY) continue;
216 // A phone frame legitimately bounds an independently scrollable main.
217 if (ancestor === phone && element.closest('main.screen-content')) continue;
218 const ancestorRect = ancestor.getBoundingClientRect();
219 for (const r of rectangles) {
220 if (r.width < 0.1 || r.height < 0.1) continue;
221 if (clipsX && (r.left < ancestorRect.left - 1.5 || r.right > ancestorRect.right + 1.5) || clipsY && (r.top < ancestorRect.top - 2 || r.bottom > ancestorRect.bottom + 2)) {
222 problems.push({ type: 'clipped-text', ...location, clippingAncestor: selector(ancestor), clippingRect: rectOf(ancestor), textRect: { x: +r.x.toFixed(2), y: +r.y.toFixed(2), width: +r.width.toFixed(2), height: +r.height.toFixed(2) } });
223 break;
224 }
225 }
226 }
227 };
228 const walker = document.createTreeWalker(phone, NodeFilter.SHOW_TEXT);
229 while (walker.nextNode()) {
230 const node = walker.currentNode, element = node.parentElement;
231 if (!node.textContent.trim() || !element || !visible(element) || element.closest('script,style,template,option')) continue;
232 const range = document.createRange(); range.selectNodeContents(node);
233 const rectangles = [...range.getClientRects()];
234 if (!rectangles.some(r => r.width > 0.1 && r.height > 0.1)) continue;
235 textAudit(element, node.textContent, rectangles);
236 }
237 // A native input's current value and placeholder have no DOM Text node.
238 for (const control of phone.querySelectorAll('input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]),textarea,select')) {
239 if (!visible(control)) continue;
240 const content = control.tagName === 'SELECT' ? control.selectedOptions[0]?.textContent : (control.value || control.placeholder);
241 if (content) textAudit(control, content, []);
242 if (control.matches('input[type="email"],input[type="tel"]') && !control.readOnly && !control.disabled) problems.push({ type: 'editable-real-identity-field', selector: selector(control) });
243 }
244 const targets = phone.querySelectorAll('button,input:not([type="hidden"]),select,textarea,a[href],[role="button"],[role="switch"],[role="tab"],summary');
245 for (const target of targets) {
246 if (!visible(target)) continue;
247 const rect = target.getBoundingClientRect(), description = { selector: selector(target), text: (target.getAttribute('aria-label') || target.textContent || target.getAttribute('name') || '').trim().slice(0, 100), rect: rectOf(target), disabled: target.matches(':disabled') };
248 stats.targetCount++;
249 if (!stats.minimumTargetWidth || rect.width < stats.minimumTargetWidth.value) stats.minimumTargetWidth = { value: rect.width, ...description };
250 if (!stats.minimumTargetHeight || rect.height < stats.minimumTargetHeight.value) stats.minimumTargetHeight = { value: rect.height, ...description };
251 if (rect.width < 48 - 0.1 || rect.height < 48 - 0.1) problems.push({ type: 'touch-target', requiredWidthPx: 48, requiredHeightPx: 48, ...description });
252 }
253 return { problems, stats };
254 }
255
256 function updateMeasurements(audit, context) {
257 const m = report.measurements, s = audit.stats;
258 m.auditedLayouts++;
259 m.visibleTextNodes += s.textCount;
260 m.touchTargets += s.targetCount;
261 if (s.minimumFont && (m.minimumFontPx === null || s.minimumFont.value < m.minimumFontPx)) {
262 m.minimumFontPx = +s.minimumFont.value.toFixed(3); m.minimumFont = { ...context, ...s.minimumFont };
263 }
264 if (s.minimumContrast && (m.minimumContrast === null || s.minimumContrast.value < m.minimumContrast)) {
265 m.minimumContrast = +s.minimumContrast.value.toFixed(6); m.worstContrast = { ...context, ...s.minimumContrast };
266 }
267 if (s.minimumTargetWidth && (m.minimumTargetWidthPx === null || s.minimumTargetWidth.value < m.minimumTargetWidthPx)) m.minimumTargetWidthPx = +s.minimumTargetWidth.value.toFixed(3);
268 if (s.minimumTargetHeight && (m.minimumTargetHeightPx === null || s.minimumTargetHeight.value < m.minimumTargetHeightPx)) m.minimumTargetHeightPx = +s.minimumTargetHeight.value.toFixed(3);
269 for (const problem of audit.problems) fail(problem.type, { ...context, ...problem });
270 }
271
272 async function navigate(page, screen, state = 'normal', theme = 'calm', fontScale = 1) {
273 await page.evaluate(async ({ screen, state, theme, fontScale }) => {
274 document.documentElement.style.fontSize = `${16 * fontScale}px`;
275 await Promise.resolve(window.LifeGuideDesign.navigate(screen, state, theme));
276 await document.fonts.ready;
277 await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
278 }, { screen, state, theme, fontScale });
279 }
280
281 async function checkBidi(page) {
282 await page.setViewportSize({ width: 390, height: 1000 });
283 await navigate(page, 'math-bidi');
284 const evidence = await page.evaluate(() => {
285 const examples = ['−۳', '−۱۰', '۷ + (−۳)', '½'];
286 const characterRect = (element, index) => {
287 const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
288 let offset = index;
289 while (walker.nextNode()) {
290 const node = walker.currentNode;
291 if (offset < node.length) {
292 const range = document.createRange(); range.setStart(node, offset); range.setEnd(node, offset + 1);
293 const r = range.getBoundingClientRect();
294 return { left: +r.left.toFixed(3), right: +r.right.toFixed(3), top: +r.top.toFixed(3), bottom: +r.bottom.toFixed(3) };
295 }
296 offset -= node.length;
297 }
298 return null;
299 };
300 return examples.map(example => {
301 const element = [...document.querySelectorAll('bdi.math[dir="ltr"][data-math]')].find(e => e.dataset.math === example);
302 if (!element) return { example, passed: false, reason: 'missing bdi.math[dir=ltr] fixture' };
303 const text = element.textContent.trim();
304 const minusIndex = text.indexOf('−');
305 const minus = minusIndex < 0 ? null : characterRect(element, minusIndex);
306 const followingDigit = minusIndex < 0 ? null : characterRect(element, minusIndex + 1);
307 const style = getComputedStyle(element);
308 const passed = text === example && style.direction === 'ltr' && /isolate/.test(style.unicodeBidi) && (minusIndex < 0 || minus && followingDigit && minus.left < followingDigit.left && Math.abs(minus.top - followingDigit.top) < 2);
309 return { example, text, direction: style.direction, unicodeBidi: style.unicodeBidi, minus, followingDigit, passed };
310 });
311 });
312 report.measurements.bidi = evidence;
313 for (const item of evidence) if (!item.passed) fail('bidi-minus-before-digit', item);
314 fs.mkdirSync(screenshotsDir, { recursive: true });
315 const filename = path.join(screenshotsDir, 'bidi-math-390.png');
316 // Expand only this evidence capture, so all four mandatory examples are
317 // visible together instead of being cut by the phone's scroll viewport.
318 await page.locator('.phone').evaluate(phone => {
319 Object.assign(phone.style, { height: 'auto', maxHeight: 'none', minHeight: '0', overflow: 'visible' });
320 Object.assign(phone.querySelector('main.screen-content').style, { height: 'auto', maxHeight: 'none', minHeight: '0', flex: 'none', overflow: 'visible' });
321 });
322 await page.locator('.phone').screenshot({ path: filename });
323 report.screenshots.push(path.relative(path.dirname(receiptPath), filename));
324 if (evidence.every(item => item.passed)) checked('bidi: mandatory LTR islands and minus glyph left of following digit', { examples: evidence.length, screenshot: path.relative(path.dirname(receiptPath), filename), screenshotMode: '390px phone width, expanded scroll content to show every example together' });
325 }
326
327 async function checkNavigation(page, screens) {
328 await page.setViewportSize({ width: 390, height: 844 });
329 await navigate(page, 'home');
330 const homeButtons = await page.locator('.phone .bottom-nav button').count();
331 assert.ok(homeButtons > 0 && homeButtons <= 5, 'Student bottom navigation must contain one to five destinations.');
332 const visited = [];
333 for (let index = 0; index < homeButtons; index++) {
334 await navigate(page, 'home');
335 const button = page.locator('.phone .bottom-nav button').nth(index);
336 const name = (await button.textContent()).trim();
337 await button.click();
338 const destination = await page.locator('.phone').getAttribute('data-screen');
339 assert.ok(screens.some(screen => screen.id === destination), 'Bottom navigation must open an existing screen.');
340 visited.push({ name, destination });
341 }
342 assert.equal(new Set(visited.map(v => v.destination)).size, homeButtons, 'Bottom destinations must not all route to the same fixture.');
343 await navigate(page, 'parent-home');
344 const parentButtons = await page.locator('.phone .bottom-nav button').count();
345 assert.ok(parentButtons > 0 && parentButtons <= 5, 'Parent bottom navigation must contain one to five destinations.');
346 for (let index = 0; index < parentButtons; index++) {
347 await navigate(page, 'parent-home');
348 await page.locator('.phone .bottom-nav button').nth(index).click();
349 assert.equal(await page.locator('.phone').getAttribute('data-role'), 'parent', 'Parent navigation must not impersonate the child.');
350 }
351 for (const action of ['go:parent-reminders', 'go:report', 'go:parent-settings']) {
352 await navigate(page, 'parent-home');
353 await page.locator(`.phone header button[data-action="${action}"]`).click();
354 assert.equal(await page.locator('.phone').getAttribute('data-role'), 'parent', 'Parent header must not enter a child account.');
355 }
356 await navigate(page, 'parent-settings');
357 await page.locator('.phone button[data-action="go:parent-account-actions"]').click();
358 assert.equal(await page.locator('.phone').getAttribute('data-role'), 'parent');
359 for (const destination of ['parent-leave-family', 'parent-export-data', 'parent-delete-account']) {
360 await navigate(page, 'parent-account-actions');
361 await page.locator(`.phone button[data-action="go:${destination}"]`).click();
362 assert.equal(await page.locator('.phone').getAttribute('data-role'), 'parent', 'Parent account management must remain in the parent role.');
363 await page.locator('.phone button[data-action^="confirm:"]').click();
364 assert.equal(await page.locator('.phone').getAttribute('data-screen'), 'parent-confirm-action');
365 await page.locator('.phone input[type="checkbox"]').check();
366 await page.locator('.phone button[data-action="go:parent-action-preview"]').click();
367 assert.equal(await page.locator('.phone').getAttribute('data-role'), 'parent');
368 }
369 checked('clickable student navigation and separate parent navigation', { studentDestinations: visited, parentDestinationCount: parentButtons });
370 }
371
372 async function checkStateInteractions(page, screens) {
373 const actions = [];
374 await page.setViewportSize({ width: 390, height: 844 });
375 for (const screen of screens) {
376 for (const state of screen.states || ['normal']) {
377 if (!['error', 'empty', 'offline', 'conflict', 'session', 'rate-limit'].includes(state)) continue;
378 const variants = state === 'conflict' ? ['resolve:local', 'resolve:other'] : [state === 'session' ? 'go:welcome' : 'state:normal'];
379 for (const action of variants) {
380 await navigate(page, screen.id, state);
381 // The component gallery intentionally contains its own error-banner
382 // sample as well as the page's error state. Both retry controls have
383 // identical semantics; exercise the first actual state control.
384 await page.locator(`.phone button[data-action="${action}"]`).first().click();
385 const after = await page.locator('.phone').getAttribute('data-state');
386 assert.equal(after, 'normal', `${screen.id}/${state}/${action} must leave the error/system state.`);
387 assert.equal(await page.locator('.phone').getAttribute('data-screen'), state === 'session' ? 'welcome' : screen.id);
388 if (state === 'conflict') assert.match(await page.locator('.phone .toast').textContent(), /هیچ همگام‌سازی واقعی/);
389 actions.push({ screen: screen.id, state, action, result: 'PASS' });
390 }
391 }
392 }
393 for (const state of ['wrong', 'expired']) {
394 await navigate(page, 'otp', state);
395 await page.locator('.phone button[data-action="state:cooldown"]').click();
396 assert.equal(await page.locator('.phone').getAttribute('data-state'), 'cooldown');
397 assert.equal(await page.locator('.phone button[data-action="noop"]').isDisabled(), true);
398 await page.locator('.phone button[data-action="state:normal"]').click();
399 assert.equal(await page.locator('.phone').getAttribute('data-state'), 'normal');
400 actions.push({ screen: 'otp', state, action: 'resend cooldown -> simulated expiry -> normal', result: 'PASS' });
401 }
402 checked('retry, explicit conflict choices, offline reconnect, session re-entry, rate-limit and OTP cooldown controls change their fixture states', { actionCount: actions.length, actions });
403 }
404
405 async function checkQuiz(page) {
406 await navigate(page, 'quiz');
407 const answers = page.locator('[data-qa="quiz-answer"]');
408 if (!await answers.count()) {
409 fail('quiz-interaction', { message: 'Missing [data-qa=quiz-answer] interactive options.' }); return;
410 }
411 for (let question = 0; question < 10; question++) {
412 assert.ok(await answers.count() >= 2, 'Each question needs at least two possible answers.');
413 await answers.first().click();
414 const next = page.locator('[data-qa="quiz-next"]');
415 await next.click();
416 }
417 const result = page.locator('[data-qa="quiz-result"]');
418 await result.waitFor({ state: 'visible' });
419 const resultText = (await result.textContent()).trim();
420 assert.ok(resultText.length > 0, 'The quiz must display its fictional score.');
421 const review = page.locator('[data-qa="quiz-review"]');
422 if (await review.count()) { await review.click(); assert.ok(await page.locator('[data-qa="answer-review"]').count() > 0, 'Answer review must show responses.'); }
423 const retry = page.locator('[data-qa="quiz-retry"]');
424 await retry.click();
425 assert.ok(await page.locator('[data-qa="quiz-answer"]').count() >= 2, 'Retry must return to quiz questions.');
426 checked('ten fictional quiz questions, displayed score, answer review and retry', { questionCount: 10, resultText });
427 }
428
429 async function checkBoard(page, expectedFrames) {
430 await page.setViewportSize({ width: 1800, height: 1200 });
431 await page.goto(new URL('?board=1', base).href, { waitUntil: 'networkidle' });
432 await page.evaluate(() => document.fonts.ready);
433 const board = await page.evaluate(requiredLabel => {
434 const phones = [...document.querySelectorAll('.phone')];
435 return phones.map(phone => ({ screen: phone.dataset.screen, state: phone.dataset.state, theme: phone.dataset.theme, label: phone.querySelector('.prototype-label')?.textContent.trim(), height: phone.getBoundingClientRect().height, overflow: [...phone.querySelectorAll('main.screen-content')].map(main => ({ scrollHeight: main.scrollHeight, clientHeight: main.clientHeight })) }));
436 }, label);
437 assert.ok(board.length >= 20, 'Complete board must contain at least twenty visible design frames.');
438 assert.equal(board.length, expectedFrames.length, 'Board must render every declared board frame.');
439 assert.ok(board.every(frame => frame.label === label), 'Every board frame must retain the fictional-design label.');
440 checked('full board has every declared frame and design label', { frameCount: board.length, minimumRequired: 20, frames: board });
441 }
442
443 async function main() {
444 let browser;
445 try {
446 assert.ok(['http:', 'https:'].includes(base.protocol), 'Use a local static HTTP(S) server.');
447 assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname), 'This design checker only opens a loopback static server; no live site is allowed.');
448 browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium', headless: true, args: ['--no-sandbox'] });
449 report.browser = await browser.version();
450 const context = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'fa-IR' });
451 await context.route('**/*', async route => {
452 const request = route.request(), url = new URL(request.url());
453 if (!['http:', 'https:'].includes(url.protocol)) return route.continue();
454 if (url.origin !== base.origin) { report.externalRequests.push(safeRequest(request.url())); return route.abort('blockedbyclient'); }
455 if (!['GET', 'HEAD'].includes(request.method()) || ['xhr', 'fetch', 'websocket', 'eventsource', 'ping'].includes(request.resourceType())) {
456 report.forbiddenRequests.push({ url: safeRequest(request.url()), method: request.method(), resourceType: request.resourceType() });
457 return route.abort('blockedbyclient');
458 }
459 return route.continue();
460 });
461 const page = await context.newPage();
462 page.on('pageerror', error => report.runtimeErrors.push(error.message));
463 page.on('response', response => {
464 if (response.status() >= 400 && new URL(response.url()).origin === base.origin) report.failedStaticRequests.push({ url: safeRequest(response.url()), status: response.status() });
465 });
466 page.on('requestfailed', request => {
467 if (new URL(request.url()).origin === base.origin) report.failedStaticRequests.push({ url: safeRequest(request.url()), failure: request.failure()?.errorText || 'failed' });
468 });
469 page.on('websocket', socket => report.forbiddenRequests.push({ url: safeRequest(socket.url()), resourceType: 'websocket' }));
470 await page.goto(base.href, { waitUntil: 'networkidle' });
471 await page.evaluate(() => document.fonts.ready);
472 const contract = await page.evaluate(() => {
473 const design = window.LifeGuideDesign;
474 if (!design || !Array.isArray(design.screens) || typeof design.navigate !== 'function' || typeof design.reset !== 'function' || !Array.isArray(design.boardFrames)) return null;
475 return { screens: design.screens, boardFrames: design.boardFrames };
476 });
477 assert.ok(contract, 'window.LifeGuideDesign must expose screens, boardFrames, navigate() and reset().');
478 assert.ok(contract.screens.length >= 20, 'Screen inventory must include at least twenty distinct screens.');
479 assert.equal(new Set(contract.screens.map(s => s.id)).size, contract.screens.length, 'Screen IDs must be unique.');
480 for (const id of requiredMain) assert.ok(contract.screens.some(screen => screen.id === id), 'Missing required main screen: ' + id);
481 checked('public design inspection contract and screen inventory', { screenCount: contract.screens.length, boardFrameCount: contract.boardFrames.length });
482 await navigate(page, 'lesson');
483 assert.equal(await page.locator('.phone video,.phone iframe,.phone object,.phone embed').count(), 0, 'Without an approved source the default lesson must not load a video/embed.');
484 checked('default lesson has no video/embed source', { realVideoPlayback: 'UNVERIFIED' });
485 const themeEvidence = [];
486 for (const theme of themes) {
487 await navigate(page, 'home', 'normal', theme);
488 themeEvidence.push(await page.locator('.phone').evaluate(element => ({ theme: element.dataset.theme, primary: getComputedStyle(element).getPropertyValue('--primary').trim(), canvas: getComputedStyle(element).getPropertyValue('--canvas').trim(), bottomDestinations: [...element.querySelectorAll('.bottom-nav button')].map(button => button.textContent.trim()) })));
489 }
490 assert.notEqual(themeEvidence[0].primary + themeEvidence[0].canvas, themeEvidence[1].primary + themeEvidence[1].canvas, 'The two visual directions must actually change appearance.');
491 assert.deepEqual(themeEvidence[0].bottomDestinations, themeEvidence[1].bottomDestinations, 'Visual directions must keep the same navigation structure.');
492 checked('two visibly distinct directions retain the same navigation structure', { themes: themeEvidence });
493
494 const layouts = [];
495 for (const screen of contract.screens) {
496 const states = [...new Set([...(screen.states || ['normal']), ...(requiredMain.includes(screen.id) || screen.main ? systemStates : [])])];
497 for (const state of states) layouts.push({ screen: screen.id, state });
498 }
499 const initialFailureCount = report.failures.length;
500 const normalFonts = new Map();
501 for (const width of requestedWidths) {
502 await page.setViewportSize({ width, height: 844 });
503 for (const theme of themes) {
504 for (const fontScale of [1, 2]) {
505 for (const { screen, state } of layouts) {
506 const auditContext = { screen, state, theme, viewportWidthPx: width, fontScale };
507 try {
508 await navigate(page, screen, state, theme, fontScale);
509 const audit = await page.evaluate(auditLayout, { expectedScreen: screen, expectedState: state, expectedTheme: theme, fontScale, requiredLabel: label });
510 updateMeasurements(audit, auditContext);
511 const fontKey = `${width}:${theme}:${screen}:${state}`;
512 if (fontScale === 1) normalFonts.set(fontKey, audit.stats.fontSamples);
513 else {
514 const originalFonts = normalFonts.get(fontKey) || [];
515 for (let index = 0; index < originalFonts.length; index++) {
516 const original = originalFonts[index], enlarged = audit.stats.fontSamples[index];
517 if (!enlarged || original.selector !== enlarged.selector || original.text !== enlarged.text) {
518 fail('font-200-percent-coverage', { ...auditContext, message: 'Text changed between normal and enlarged layouts; cannot attest scaling.', original, enlarged });
519 break;
520 }
521 if (enlarged.fontSizePx < original.fontSizePx * 2 - 0.05) fail('font-did-not-enlarge-200-percent', { ...auditContext, selector: original.selector, text: original.text, originalPx: original.fontSizePx, enlargedPx: enlarged.fontSizePx });
522 }
523 }
524 } catch (error) { fail('layout-evaluation', { ...auditContext, message: error.message }); }
525 }
526 }
527 }
528 console.log(`Measured width ${width}px: ${report.measurements.auditedLayouts} layouts; ${report.failures.length} cumulative failures.`);
529 }
530 if (report.failures.length === initialFailureCount) checked('rendered text >=12px, measured contrast >=4.5:1, targets >=48x48, no horizontal overflow or hidden text at 100% and 200%', { layouts: report.measurements.auditedLayouts, minimumFontPx: report.measurements.minimumFontPx, minimumContrast: report.measurements.minimumContrast, widths: requestedWidths, themes });
531
532 for (const [name, action] of [
533 ['bidi', () => checkBidi(page)],
534 ['navigation', () => checkNavigation(page, contract.screens)],
535 ['system-state-interactions', () => checkStateInteractions(page, contract.screens)],
536 ['quiz', () => checkQuiz(page)],
537 ['board', () => checkBoard(page, contract.boardFrames)],
538 ]) {
539 console.log(`Running interaction check: ${name}`);
540 try { await action(); } catch (error) { fail(name, { message: error.message }); }
541 }
542 // An already loaded prototype must still change screens with all network
543 // disabled, but this is not evidence of production offline synchronization.
544 try {
545 await page.goto(base.href, { waitUntil: 'networkidle' });
546 await context.setOffline(true);
547 await navigate(page, 'home');
548 await page.locator('.phone .bottom-nav button').nth(1).click();
549 assert.notEqual(await page.locator('.phone').getAttribute('data-screen'), 'home');
550 await context.setOffline(false);
551 checked('already loaded fixture remains locally navigable without network', { limitation: 'Not a PWA/service-worker/server-sync acceptance test.' });
552 } catch (error) { fail('offline-design-navigation', { message: error.message }); await context.setOffline(false); }
553 if (report.runtimeErrors.length) fail('javascript-runtime-errors', { errors: report.runtimeErrors });
554 if (report.failedStaticRequests.length) fail('failed-local-static-assets', { requests: report.failedStaticRequests });
555 if (report.externalRequests.length) fail('external-network-requests', { urls: [...new Set(report.externalRequests)] });
556 if (report.forbiddenRequests.length) fail('server-or-authentication-connection', { requests: report.forbiddenRequests });
557 if (!report.runtimeErrors.length && !report.externalRequests.length && !report.forbiddenRequests.length && !report.failedStaticRequests.length) checked('no JavaScript errors, failed static assets, external requests, or server/authentication traffic', { javascriptErrors: 0, failedStaticRequests: 0, externalRequests: 0, forbiddenRequests: 0 });
558 } catch (error) {
559 fail('checker-fatal-error', { message: error.message });
560 } finally {
561 if (browser) await browser.close();
562 writeReport();
563 console.log(JSON.stringify({ status: report.status, checksPassed: report.checks.length, measuredLayouts: report.measurements.auditedLayouts, failures: report.failureCount, minimumFontPx: report.measurements.minimumFontPx, minimumContrast: report.measurements.minimumContrast, receipt: receiptPath }, null, 2));
564 if (!report.passed) {
565 console.error(JSON.stringify(report.failures.slice(0, 20), null, 2));
566 process.exitCode = 1;
567 }
568 }
569 }
570
571 module.exports = { auditLayout };
572 if (require.main === module) main();