Automated QA · Zero-Dependency Node 18+ CLI (31.9 KB)

Foldable Website Test CLI for Node.js & CI

Quick Answer · CI/CD Layout Gate

foldcheck.mjs is a free, single-file foldable website test runner and automated responsive website checker for Node.js 18+. With zero npm dependencies or headless browser installs, it scans built HTML/CSS or staging URLs across 8 flagship folding phones (32 simulated viewports), exports reviewable CSS patches (--fix-css) or AI prompts (--ai), and fails pull requests on high-severity layout regressions.

Who This Command-Line Checker Is Built For

Frontend & DevOps

CI/CD Pull-Request Gates

Run sub-second layout checks in GitHub Actions or GitLab CI without provisioning heavy Chromium or Playwright runners.

E-Commerce Teams

Theme Release Guards

Verify built Shopify, headless commerce, or checkout templates before deploying promotions or seasonal banners.

Agencies & QA

Batch Client Audits

Emit structured --json or --md reports across all 32 simulated viewports for repeatable client sign-off.

AI Developers

Terminal Fix Loops

Pipe --ai output straight into Claude Code, Cursor, or Gemini CLI to fix overflowing containers automatically.

Interactive Command Builder


        
      

GitHub Actions & Pre-Deploy Release Gate

Commit the script under scripts/foldcheck.mjs and fail builds whenever high-severity overflow or zoom-locking slips into a pull request:

name: Foldable Layout Gate
on: [pull_request]
jobs:
  foldable-qa:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: node scripts/foldcheck.mjs ./dist/index.html --all-devices --fail-on high --md

All 12 Automated Audit Rules & Severity Levels

Every static check maps 1-to-1 to our 12-point iPhone Duo website checklist and uses the same penalty rubric as the live browser studio:

RuleSeverityWhat the Checker Flags
viewport-metahighMissing viewport tag, fixed pixel width=, or zoom locking (user-scalable=no)
horizontal-overflowhighFixed containers wider than cover (356–466px) or split panes (372–459px)
fixed-width-elementshighHardcoded pixel width or min-width breaking responsive reflow
unresponsive-mediahighFixed-width images, videos, SVGs, iframes, or unwrapped wide tables
touch-targetsmediumButtons, inputs, or nav controls sized under 44×44 CSS px
crease-obstructionmediumCentered modals or primary CTAs straddling the unfolded center fold crease
sticky-occlusionmediumSticky/fixed bars exceeding 22% of compact cover or landscape height
split-screen-crampingmediumNon-wrapping flex rows or missing min-width: 0 in Split View panes
tiny-typographylowReadable text declarations smaller than 12px
viewport-fit-safe-arealowFixed edge bars missing viewport-fit=cover or env(safe-area-inset-*)
hardcoded-100vhlowBare 100vh without dynamic 100dvh / 100svh pairing
csr-thin-shellinfoClient-rendered SPA shells requiring built SSR HTML or hydrated DOM inspection

CLI vs. Browser Studio vs. DevTools Inspector

Use this command-line foldable website test tool on every pull request for instant source-level gating and --fix-css / --ai generation. Pair it with the 3D browser simulator for visual inspection across 32 viewports, the no-device testing guide for Safari 27.1 breakpoints, and the In-Page DevTools Inspector for authenticated or client-rendered SPAs.

Complete Single-File Node.js Source

Zero npm dependencies, readable ESM source for Node.js 18+. Download via the top button or inspect every line below before adding to your codebase.

Inspect full ESM CLI source (31.9 KB · Node 18+)
#!/usr/bin/env node
/**
 * FoldCheck CLI — Zero-dependency Foldable Website Layout Auditor (Node 18+)
 * Simulated CSS viewports for 8 official Apple, Samsung, and Huawei foldables (32 postures).
 * Usage:
 *   node foldcheck.mjs <file-or-url> [--device iphone-duo] [--state cover] [--all-states] [--all-devices]
 *                      [--md | --ai | --json] [--fail-on high|medium|low]
 */

import fs from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';

const VERSION = '1.1.0';
const MAX_BYTES = 2 * 1024 * 1024;
const FETCH_TIMEOUT_MS = 10000;

export const DEVICES = {
  'iphone-duo': {
    id: 'iphone-duo',
    name: 'iPhone Duo',
    states: {
      cover: { width: 466, height: 678, foldAxis: null },
      inner: { width: 890, height: 626, foldAxis: 'vertical' },
      split: { width: 442, height: 626, foldAxis: null },
      landscape: { width: 626, height: 890, foldAxis: 'horizontal' }
    }
  },
  'z-fold-8': {
    id: 'z-fold-8',
    name: 'Galaxy Z Fold 8',
    states: {
      cover: { width: 436, height: 689, foldAxis: null },
      inner: { width: 924, height: 698, foldAxis: 'vertical' },
      split: { width: 459, height: 698, foldAxis: null },
      landscape: { width: 698, height: 924, foldAxis: 'horizontal' }
    }
  },
  'z-fold-7': {
    id: 'z-fold-7',
    name: 'Galaxy Z Fold 7',
    states: {
      cover: { width: 412, height: 960, foldAxis: null },
      inner: { width: 750, height: 832, foldAxis: 'vertical' },
      split: { width: 372, height: 832, foldAxis: null },
      landscape: { width: 832, height: 750, foldAxis: 'horizontal' }
    }
  },
  'z-flip-7': {
    id: 'z-flip-7',
    name: 'Galaxy Z Flip 7',
    states: {
      cover: { width: 361, height: 300, foldAxis: null },
      inner: { width: 411, height: 960, foldAxis: 'horizontal' },
      split: { width: 411, height: 474, foldAxis: null },
      landscape: { width: 960, height: 411, foldAxis: 'vertical' }
    }
  },
  'mate-x8': {
    id: 'mate-x8',
    name: 'Huawei Mate X8',
    states: {
      cover: { width: 412, height: 889, foldAxis: null },
      inner: { width: 851, height: 881, foldAxis: 'vertical' },
      split: { width: 423, height: 881, foldAxis: null },
      landscape: { width: 881, height: 851, foldAxis: 'horizontal' }
    }
  },
  'mate-x7': {
    id: 'mate-x7',
    name: 'Huawei Mate X7',
    states: {
      cover: { width: 393, height: 889, foldAxis: null },
      inner: { width: 804, height: 879, foldAxis: 'vertical' },
      split: { width: 399, height: 879, foldAxis: null },
      landscape: { width: 879, height: 804, foldAxis: 'horizontal' }
    }
  },
  'mate-xt': {
    id: 'mate-xt',
    name: 'Huawei Mate XT',
    states: {
      cover: { width: 360, height: 797, foldAxis: null },
      inner: { width: 1137, height: 797, foldAxis: 'vertical' },
      split: { width: 565, height: 797, foldAxis: null },
      landscape: { width: 797, height: 1137, foldAxis: 'horizontal' }
    }
  },
  'pura-x': {
    id: 'pura-x',
    name: 'Huawei Pura X',
    states: {
      cover: { width: 356, height: 356, foldAxis: null },
      inner: { width: 480, height: 771, foldAxis: 'horizontal' },
      split: { width: 480, height: 382, foldAxis: null },
      landscape: { width: 771, height: 480, foldAxis: 'vertical' }
    }
  }
};

const SEVERITY_RANK = { high: 3, medium: 2, low: 1, info: 0 };

const RULE_META = {
  'viewport-meta': { severity: 'high', penalty: 12, title: 'Viewport meta missing or zoom-locked' },
  'horizontal-overflow': { severity: 'high', penalty: 14, title: 'Horizontal overflow beyond simulated viewport' },
  'fixed-width-elements': { severity: 'high', penalty: 10, title: 'Rigid pixel widths wider than active pane' },
  'unresponsive-media': { severity: 'high', penalty: 8, title: 'Unconstrained media or wide tables' },
  'touch-targets': { severity: 'medium', penalty: 6, title: 'Interactive touch targets below 44x44px' },
  'crease-obstruction': { severity: 'medium', penalty: 6, title: 'Primary control or modal straddles fold crease' },
  'sticky-occlusion': { severity: 'medium', penalty: 6, title: 'Fixed or sticky bar exceeds 22% of viewport height' },
  'split-screen-cramping': { severity: 'medium', penalty: 6, title: 'Split-screen / cover pane reflow cramping' },
  'tiny-typography': { severity: 'low', penalty: 2, title: 'Sub-12px typography hurts cover readability' },
  'viewport-fit-safe-area': { severity: 'low', penalty: 2, title: 'Fixed edge UI missing viewport-fit=cover / safe-area' },
  'hardcoded-100vh': { severity: 'low', penalty: 2, title: 'Bare 100vh without 100dvh/100svh fallback' },
  'csr-thin-shell': { severity: 'info', penalty: 0, title: 'Client-rendered JS shell detected' }
};

function stripCssComments(css) {
  return css.replace(/\/\*[\s\S]*?\*\//g, '');
}

function evalMediaCondition(cond, width, height) {
  const parts = cond.split(/\band\b/i).map((s) => s.trim());
  for (const part of parts) {
    let m;
    if ((m = part.match(/\(\s*max-width\s*:\s*([\d.]+)px\s*\)/i))) {
      if (!(width <= parseFloat(m[1]))) return false;
    } else if ((m = part.match(/\(\s*min-width\s*:\s*([\d.]+)px\s*\)/i))) {
      if (!(width >= parseFloat(m[1]))) return false;
    } else if ((m = part.match(/\(\s*max-height\s*:\s*([\d.]+)px\s*\)/i))) {
      if (!(height <= parseFloat(m[1]))) return false;
    } else if ((m = part.match(/\(\s*min-height\s*:\s*([\d.]+)px\s*\)/i))) {
      if (!(height >= parseFloat(m[1]))) return false;
    } else if (/print/i.test(part)) {
      return false;
    }
  }
  return true;
}

function parseDeclarations(block) {
  const decls = {};
  const list = [];
  for (const raw of block.split(';')) {
    const idx = raw.indexOf(':');
    if (idx === -1) continue;
    const prop = raw.slice(0, idx).trim().toLowerCase();
    const val = raw.slice(idx + 1).trim();
    if (!prop || !val) continue;
    decls[prop] = val;
    list.push({ prop, val });
  }
  return { decls, list };
}

function parseCssRules(cssText, width, height) {
  const clean = stripCssComments(cssText);
  const rules = [];
  let i = 0;
  const len = clean.length;

  function readBlock() {
    let depth = 1;
    let start = i;
    while (i < len && depth > 0) {
      if (clean[i] === '{') depth++;
      else if (clean[i] === '}') depth--;
      i++;
    }
    return clean.slice(start, i - 1);
  }

  while (i < len) {
    while (i < len && /\s/.test(clean[i])) i++;
    if (i >= len) break;
    const start = i;
    while (i < len && clean[i] !== '{' && clean[i] !== ';') i++;
    if (i >= len) break;
    if (clean[i] === ';') {
      i++;
      continue;
    }
    const prelude = clean.slice(start, i).trim();
    i++; // consume '{'
    const body = readBlock();

    if (prelude.startsWith('@media')) {
      const cond = prelude.replace(/^@media\s*/i, '').trim();
      if (evalMediaCondition(cond, width, height)) {
        rules.push(...parseCssRules(body, width, height));
      }
    } else if (prelude.startsWith('@')) {
      // ignore @keyframes, @font-face, etc.
    } else {
      const { decls, list } = parseDeclarations(body);
      for (const selector of prelude.split(',').map((s) => s.trim()).filter(Boolean)) {
        rules.push({ selector, decls, list });
      }
    }
  }
  return rules;
}

function pxValue(val) {
  if (!val) return null;
  const m = String(val).trim().match(/^([\d.]+)px$/i);
  return m ? parseFloat(m[1]) : null;
}

function extractInlineStyles(html) {
  const entries = [];
  const tagRe = /<([a-z0-9-]+)([^>]*?)\sstyle\s*=\s*(["'])([\s\S]*?)\3([^>]*)>/gi;
  let m;
  while ((m = tagRe.exec(html))) {
    const tag = m[1].toLowerCase();
    const attrs = `${m[2]} ${m[5]}`;
    const idMatch = attrs.match(/\bid\s*=\s*["']([^"']+)["']/i);
    const clsMatch = attrs.match(/\bclass\s*=\s*["']([^"']+)["']/i);
    const selector = idMatch
      ? `${tag}#${idMatch[1]}`
      : clsMatch
      ? `${tag}.${clsMatch[1].trim().split(/\s+/)[0]}`
      : tag;
    const { decls, list } = parseDeclarations(m[4]);
    entries.push({ tag, selector, attrs, decls, list });
  }
  return entries;
}

function buildEffectiveMap(rules) {
  const map = new Map();
  for (const r of rules) {
    const prev = map.get(r.selector) || { decls: {}, list: [] };
    map.set(r.selector, {
      decls: { ...prev.decls, ...r.decls },
      list: [...prev.list, ...r.list]
    });
  }
  return map;
}

export function auditHtml(html, deviceId = 'iphone-duo', stateId = 'cover', sourceLabel = 'input.html') {
  const device = DEVICES[deviceId] || DEVICES['iphone-duo'];
  const state = device.states[stateId] || device.states.cover;
  const { width, height, foldAxis } = state;

  const issues = [];
  const styleBlocks = [];
  const styleRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
  let sm;
  while ((sm = styleRe.exec(html))) styleBlocks.push(sm[1]);

  const rawCss = styleBlocks.join('\n');
  const activeRules = parseCssRules(rawCss, width, height);
  const effectiveBySelector = buildEffectiveMap(activeRules);
  const inlineStyles = extractInlineStyles(html);

  const allStyledEntries = [
    ...[...effectiveBySelector.entries()].map(([selector, data]) => ({ selector, ...data })),
    ...inlineStyles
  ];

  const addIssue = (id, detail, selectors = [], fix = '') => {
    const meta = RULE_META[id];
    issues.push({
      id,
      severity: meta.severity,
      penalty: meta.penalty,
      title: meta.title,
      detail,
      selectors: [...new Set(selectors)].slice(0, 5),
      fix
    });
  };

  // 1. Viewport meta
  const vpMatch = html.match(/<meta\b[^>]*name\s*=\s*["']viewport["'][^>]*>/i);
  const vpContent = vpMatch ? (vpMatch[0].match(/content\s*=\s*["']([^"']*)["']/i)?.[1] || '') : '';
  if (!vpMatch) {
    addIssue(
      'viewport-meta',
      'No <meta name="viewport"> tag found; foldable browsers will fall back to desktop scaling.',
      ['head'],
      'Add <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">.'
    );
  } else {
    const problems = [];
    if (!/width\s*=\s*device-width/i.test(vpContent)) problems.push('missing width=device-width');
    if (/user-scalable\s*=\s*(no|0)/i.test(vpContent)) problems.push('user-scalable=no locks zoom');
    if (/maximum-scale\s*=\s*1(\.0+)?(?:\D|$)/i.test(vpContent)) problems.push('maximum-scale=1 blocks zoom');
    if (problems.length) {
      addIssue(
        'viewport-meta',
        `Viewport meta issue: ${problems.join('; ')}.`,
        ['meta[name="viewport"]'],
        'Use content="width=device-width, initial-scale=1, viewport-fit=cover".'
      );
    }
  }

  // 2 & 3. Rigid pixel widths & horizontal overflow
  const rigidOversized = [];
  const overflowSelectors = [];
  let maxDetectedWidth = width;
  const globalBoxClip = allStyledEntries.some(
    (e) => /^(html|body|html,\s*body)$/.test(e.selector) && /hidden|clip/i.test(e.decls['overflow-x'] || '')
  );

  for (const entry of allStyledEntries) {
    const w = pxValue(entry.decls['width']);
    const minW = pxValue(entry.decls['min-width']);
    const maxW = entry.decls['max-width'];
    const constrainedByMax = maxW && (/^100%/.test(maxW) || (pxValue(maxW) !== null && pxValue(maxW) <= width));
    if (w !== null && w > width && !constrainedByMax) {
      rigidOversized.push(`${entry.selector} (width: ${w}px)`);
      overflowSelectors.push(entry.selector);
      if (w > maxDetectedWidth) maxDetectedWidth = w;
    }
    if (minW !== null && minW > width) {
      rigidOversized.push(`${entry.selector} (min-width: ${minW}px)`);
      overflowSelectors.push(entry.selector);
      if (minW > maxDetectedWidth) maxDetectedWidth = minW;
    }
  }

  // Check fixed HTML attribute widths on tables/divs
  const htmlWidthRe = /<(table|div|section|main|header)\b[^>]*\bwidth\s*=\s*["']?(\d+)(?:px)?["']?[^>]*>/gi;
  let hw;
  while ((hw = htmlWidthRe.exec(html))) {
    const w = parseInt(hw[2], 10);
    if (w > width) {
      rigidOversized.push(`${hw[1].toLowerCase()}[width="${w}"]`);
      overflowSelectors.push(hw[1].toLowerCase());
      if (w > maxDetectedWidth) maxDetectedWidth = w;
    }
  }

  if (maxDetectedWidth > width && !globalBoxClip) {
    addIssue(
      'horizontal-overflow',
      `Estimated content width (${Math.round(maxDetectedWidth)}px) overflows ${width}px simulated viewport by ${Math.round(maxDetectedWidth - width)}px.`,
      overflowSelectors,
      'Replace fixed pixel widths with width: 100% + max-width, and wrap wide tables in overflow-x: auto.'
    );
  }
  if (rigidOversized.length) {
    addIssue(
      'fixed-width-elements',
      `Found ${rigidOversized.length} rigid pixel width declaration(s) exceeding ${width}px: ${rigidOversized.slice(0, 3).join(', ')}.`,
      overflowSelectors,
      'Use width: min(100%, <cap>px) or fluid CSS Grid/Flexbox tracks.'
    );
  }

  // 4. Unresponsive media / tables
  const hasResponsiveImgRule = allStyledEntries.some(
    (e) => /\b(img|video|iframe|svg)\b/i.test(e.selector) && /100%/.test(e.decls['max-width'] || '')
  );
  const mediaOffenders = [];
  const mediaRe = /<(img|video|iframe|svg)\b([^>]*)>/gi;
  let mm;
  while ((mm = mediaRe.exec(html))) {
    const tag = mm[1].toLowerCase();
    const attrs = mm[2];
    const attrW = attrs.match(/\bwidth\s*=\s*["']?(\d+)(?:px)?["']?/i);
    const styleW = attrs.match(/style\s*=\s*["'][^"']*width\s*:\s*([\d.]+)px/i);
    const hasMaxW = /max-width\s*:\s*100%/i.test(attrs);
    const w = styleW ? parseFloat(styleW[1]) : attrW ? parseFloat(attrW[1]) : null;
    if (w !== null && w > width && !hasMaxW && !hasResponsiveImgRule) {
      mediaOffenders.push(`${tag}[width=${Math.round(w)}]`);
    }
  }
  const hasTable = /<table\b/i.test(html);
  if (hasTable) {
    const tableOverflowCss = allStyledEntries.some(
      (e) => /table/i.test(e.selector) && /auto|scroll/i.test(e.decls['overflow-x'] || e.decls['overflow'] || '')
    );
    const tableWide = allStyledEntries.some(
      (e) => /table/i.test(e.selector) && ((pxValue(e.decls['width']) || 0) > width || (pxValue(e.decls['min-width']) || 0) > width)
    );
    if (tableWide && !tableOverflowCss) {
      mediaOffenders.push('table');
    }
  }
  if (mediaOffenders.length) {
    addIssue(
      'unresponsive-media',
      `Media or table elements exceed ${width}px without fluid constraints: ${mediaOffenders.slice(0, 3).join(', ')}.`,
      mediaOffenders,
      'Add img, video, svg, iframe { max-width: 100%; height: auto; } and wrap tables in overflow-x: auto.'
    );
  }

  // 5. Touch targets (< 44px on buttons, nav links, inputs)
  const smallTargets = [];
  for (const entry of allStyledEntries) {
    if (/(button|\.btn|\.nav-link|nav\s+a|input|select|\.icon-btn|\.chip)/i.test(entry.selector)) {
      const h = pxValue(entry.decls['height']);
      const w = pxValue(entry.decls['width']);
      const minH = pxValue(entry.decls['min-height']);
      if ((h !== null && h < 40 && !(minH !== null && minH >= 44)) || (w !== null && w < 40)) {
        smallTargets.push(`${entry.selector} (${w ? w + 'w' : ''}${w && h ? 'x' : ''}${h ? h + 'h' : ''}px)`);
      }
    }
  }
  if (smallTargets.length) {
    addIssue(
      'touch-targets',
      `Detected ${smallTargets.length} interactive control style(s) under 44x44px: ${smallTargets.slice(0, 3).join(', ')}.`,
      smallTargets.map((s) => s.split(' ')[0]),
      'Set min-height: 44px; min-width: 44px on buttons, inputs, and navigation links.'
    );
  }

  // 6. Fold crease obstruction (Inner / Landscape unfolded states only)
  if (foldAxis) {
    const creaseOffenders = [];
    for (const entry of allStyledEntries) {
      const isControlOrModal = /(modal|dialog|cta|btn-primary|floating|fab|center-action|crease)/i.test(entry.selector);
      const isCenteredFixed =
        /fixed|absolute/i.test(entry.decls['position'] || '') &&
        (/50%/.test(entry.decls['left'] || '') || /translateX\(-50%\)/i.test(entry.decls['transform'] || '') || /50%/.test(entry.decls['top'] || ''));
      if (isControlOrModal && isCenteredFixed) {
        creaseOffenders.push(entry.selector);
      }
    }
    if (creaseOffenders.length) {
      addIssue(
        'crease-obstruction',
        `Centered overlay/CTA (${creaseOffenders.slice(0, 3).join(', ')}) crosses the ${foldAxis} fold crease at ${Math.round((foldAxis === 'vertical' ? width : height) / 2)}px.`,
        creaseOffenders,
        'Align dialogs and primary CTAs into either the left or right pane using a 2-column grid with a >= 32px center gutter.'
      );
    }
  }

  // 7. Sticky / fixed occlusion (> 22% viewport height)
  let totalFixedHeight = 0;
  const fixedBarSelectors = [];
  for (const entry of allStyledEntries) {
    if (/^(fixed|sticky)$/i.test(entry.decls['position'] || '')) {
      const h = pxValue(entry.decls['height']) || pxValue(entry.decls['min-height']);
      if (h !== null && h >= 48) {
        totalFixedHeight += h;
        fixedBarSelectors.push(`${entry.selector} (${h}px)`);
      }
    }
  }
  if (totalFixedHeight > height * 0.22) {
    const pct = Math.round((totalFixedHeight / height) * 100);
    addIssue(
      'sticky-occlusion',
      `Fixed/sticky chrome totals ${Math.round(totalFixedHeight)}px (${pct}% of ${height}px viewport height), exceeding the 22% budget.`,
      fixedBarSelectors.map((s) => s.split(' ')[0]),
      'Collapse sticky headers below 64px or switch position: static on short viewports (@media (max-height: 500px)).'
    );
  }

  // 8. Split-screen / cover cramping (narrow widths <= 420px)
  if (width <= 420) {
    const cramped = [];
    for (const entry of allStyledEntries) {
      const isNowrapFlex =
        /flex/i.test(entry.decls['display'] || '') &&
        /nowrap/i.test(entry.decls['flex-wrap'] || '');
      const isClippedNowrap =
        /nowrap/i.test(entry.decls['white-space'] || '') &&
        /hidden/i.test(entry.decls['overflow'] || entry.decls['overflow-x'] || '') &&
        !/ellipsis/i.test(entry.decls['text-overflow'] || '');
      const multiColGrid =
        /grid/i.test(entry.decls['display'] || '') &&
        /repeat\(\s*([3-9]|\d{2,})/i.test(entry.decls['grid-template-columns'] || '');
      if (isNowrapFlex || isClippedNowrap || multiColGrid) {
        cramped.push(entry.selector);
      }
    }
    if (cramped.length) {
      addIssue(
        'split-screen-cramping',
        `Detected ${cramped.length} non-wrapping or multi-column rule(s) prone to cramping at ${width}px: ${cramped.slice(0, 3).join(', ')}.`,
        cramped,
        'Allow flex-wrap: wrap, set min-width: 0 on flex children, and stack grids to 1 column below 480px.'
      );
    }
  }

  // 9. Tiny typography (< 12px)
  const tinyText = [];
  for (const entry of allStyledEntries) {
    const fs = pxValue(entry.decls['font-size']);
    if (fs !== null && fs > 0 && fs < 12) {
      tinyText.push(`${entry.selector} (${fs}px)`);
    }
  }
  if (tinyText.length) {
    addIssue(
      'tiny-typography',
      `Sub-12px font size detected: ${tinyText.slice(0, 3).join(', ')}.`,
      tinyText.map((s) => s.split(' ')[0]),
      'Keep readable text at >= 12px (16px recommended for body prose).'
    );
  }

  // 10. Viewport-fit safe area (when fixed edge bars exist)
  const hasFixedEdgeBar = allStyledEntries.some((e) => /^(fixed|sticky)$/i.test(e.decls['position'] || ''));
  const hasViewportFit = /viewport-fit\s*=\s*cover/i.test(vpContent);
  const hasSafeAreaInset = /safe-area-inset/i.test(rawCss) || /safe-area-inset/i.test(html);
  if (hasFixedEdgeBar && (!hasViewportFit || !hasSafeAreaInset)) {
    addIssue(
      'viewport-fit-safe-area',
      'Fixed/sticky navigation present without viewport-fit=cover and env(safe-area-inset-*) padding.',
      ['meta[name="viewport"]'],
      'Add viewport-fit=cover to the viewport meta and pad fixed bars with env(safe-area-inset-top/bottom).'
    );
  }

  // 11. Hardcoded 100vh without dvh/svh fallback
  const vhOffenders = [];
  for (const entry of allStyledEntries) {
    const vhProps = entry.list.filter((d) => /^(height|min-height|max-height)$/.test(d.prop));
    const usesBare100vh = vhProps.some((d) => /\b100vh\b/i.test(d.val));
    const usesDynamicVh = vhProps.some((d) => /\b100(dvh|svh)\b/i.test(d.val));
    if (usesBare100vh && !usesDynamicVh) {
      vhOffenders.push(entry.selector);
    }
  }
  if (vhOffenders.length) {
    addIssue(
      'hardcoded-100vh',
      `Bare 100vh without 100dvh/100svh fallback on: ${vhOffenders.slice(0, 3).join(', ')}.`,
      vhOffenders,
      'Pair height/min-height: 100vh with a 100dvh declaration for smooth cover-to-inner transitions.'
    );
  }

  // 12. CSR / JS thin shell detection
  const bodyOnly = html
    .replace(/<script\b[\s\S]*?<\/script>/gi, ' ')
    .replace(/<style\b[\s\S]*?<\/style>/gi, ' ')
    .replace(/<[^>]+>/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();
  const wordCount = bodyOnly ? bodyOnly.split(/\s+/).length : 0;
  const scriptCount = (html.match(/<script\b/gi) || []).length;
  const hasSpaRoot = /id\s*=\s*["'](root|app|__next|__nuxt)["']/i.test(html);
  if (hasSpaRoot && wordCount < 40 && scriptCount >= 2) {
    addIssue(
      'csr-thin-shell',
      `Captured only ${wordCount} words alongside ${scriptCount} script tags and a client mount root. Static fetch sees only the HTML shell.`,
      ['body'],
      'Save the rendered DOM from DevTools or audit a server-rendered build.'
    );
  }

  const totalPenalty = issues.reduce((acc, it) => acc + it.penalty, 0);
  const score = Math.max(0, 100 - totalPenalty);
  const actionableIssues = issues.filter((i) => i.severity !== 'info');
  const statusText = actionableIssues.length === 0 ? `Clean at ${width}px` : `${actionableIssues.length} issue(s) at ${width}px`;

  return {
    tool: 'FoldCheck CLI',
    version: VERSION,
    source: sourceLabel,
    device: { id: device.id, name: device.name },
    state: stateId,
    viewport: { width, height, foldAxis, simulated: true },
    score,
    statusText,
    issueCount: actionableIssues.length,
    issues
  };
}

function formatTextReport(results) {
  const lines = [];
  for (const r of results) {
    lines.push(`\nFoldCheck · ${r.device.name} (${r.state}, simulated ${r.viewport.width}x${r.viewport.height})`);
    lines.push(`Source: ${r.source}`);
    lines.push(`Score:  ${r.score}/100  [${r.statusText}]`);
    lines.push('-'.repeat(64));
    if (r.issues.length === 0) {
      lines.push('  PASS  No foldable layout issues detected.');
    } else {
      for (const issue of r.issues) {
        lines.push(`  [${issue.severity.toUpperCase()}] ${issue.title} (-${issue.penalty})`);
        lines.push(`         ${issue.detail}`);
        if (issue.fix) lines.push(`         Fix: ${issue.fix}`);
      }
    }
  }
  return lines.join('\n') + '\n';
}

function formatMarkdown(results) {
  const lines = ['# FoldCheck Audit Report (Simulated Viewports)', ''];
  lines.push('| Device | State | Simulated CSS | Score | Status |');
  lines.push('|---|---|---|---:|---|');
  for (const r of results) {
    lines.push(`| ${r.device.name} | ${r.state} | ${r.viewport.width}x${r.viewport.height} | ${r.score}/100 | ${r.statusText} |`);
  }
  for (const r of results) {
    lines.push('', `## ${r.device.name} — ${r.state} (${r.viewport.width}x${r.viewport.height}) · ${r.score}/100`, '');
    if (r.issues.length === 0) {
      lines.push('- Clean: 0 issues detected.');
    } else {
      for (const it of r.issues) {
        lines.push(`- **[${it.severity.toUpperCase()}] ${it.title}** (\`${it.id}\`): ${it.detail}`);
        if (it.fix) lines.push(`  - Fix: ${it.fix}`);
      }
    }
  }
  return lines.join('\n') + '\n';
}

function formatAiPrompt(results) {
  const failing = results.filter((r) => r.issues.length > 0);
  if (!failing.length) {
    return `FoldCheck simulated audit passed with 100/100 across ${results.length} viewport(s) for ${results[0]?.source}. No CSS fixes needed.\n`;
  }
  const lines = [
    'Fix the following foldable web layout issues identified by FoldCheck (simulated CSS viewports).',
    'Preserve existing visual branding while making layouts fluid across cover, unfolded inner, split-screen, and landscape widths.',
    ''
  ];
  for (const r of failing) {
    lines.push(`### Target: ${r.device.name} ${r.state} (${r.viewport.width}x${r.viewport.height} CSS px) — Current score ${r.score}/100`);
    for (const it of r.issues) {
      const sel = it.selectors.length ? ` | Selectors: ${it.selectors.join(', ')}` : '';
      lines.push(`- [${it.severity.toUpperCase()}] ${it.id}: ${it.detail}${sel}`);
      if (it.fix) lines.push(`  Recommended CSS/HTML change: ${it.fix}`);
    }
    lines.push('');
  }
  lines.push('Return minimal, production-ready HTML/CSS diffs and explain how each change prevents overflow or fold-crease clipping.');
  return lines.join('\n') + '\n';
}

function formatFixCss(results) {
  const issueMap = new Map();
  for (const r of results) {
    for (const it of r.issues) {
      if (it.severity === 'info') continue;
      const prev = issueMap.get(it.id) || new Set();
      for (const s of it.selectors) prev.add(s);
      issueMap.set(it.id, prev);
    }
  }
  const cleanSel = (id, fallback) => {
    const valid = [...(issueMap.get(id) || [])].filter((s) => s && !/^(head|style|meta|html|body)$/i.test(s) && !/\[/.test(s));
    return valid.length ? valid.join(', ') : fallback;
  };
  const out = [
    `/* FoldCheck CLI Auto-Generated web Repair Patch (v${VERSION}) */`,
    '*, *::before, *::after { box-sizing: border-box; }',
    'html, body { max-width: 100%; overflow-x: clip; }'
  ];
  if (issueMap.has('horizontal-overflow') || issueMap.has('fixed-width-elements')) {
    const merged = new Set([...(issueMap.get('horizontal-overflow') || []), ...(issueMap.get('fixed-width-elements') || [])]);
    const valid = [...merged].filter((s) => s && !/^(head|style|meta|html|body)$/i.test(s) && !/\[/.test(s));
    out.push(`${valid.length ? valid.join(', ') : 'main, section, header'} { max-width: 100% !important; width: 100% !important; min-width: 0 !important; }`);
  }
  if (issueMap.has('unresponsive-media')) {
    out.push('img, svg, video, iframe { max-width: 100% !important; height: auto !important; }');
    out.push('table { display: block; width: 100% !important; max-width: 100% !important; overflow-x: auto; }');
  }
  if (issueMap.has('touch-targets')) {
    out.push(`${cleanSel('touch-targets', 'button, nav a, input, select')} { min-width: 44px !important; min-height: 44px !important; width: auto !important; height: auto !important; }`);
  }
  if (issueMap.has('crease-obstruction')) {
    out.push(`@media (min-width: 680px) { ${cleanSel('crease-obstruction', '.modal, aside')} { left: auto !important; right: 1.5rem !important; transform: none !important; max-width: calc(50vw - 32px) !important; } }`);
  }
  if (issueMap.has('sticky-occlusion') || issueMap.has('viewport-fit-safe-area')) {
    const sel = cleanSel('sticky-occlusion', 'header, .fixed-header');
    out.push(`${sel} { height: auto !important; max-height: 76px !important; padding-top: max(0.5rem, env(safe-area-inset-top)) !important; }`);
    out.push(`@media (max-height: 500px) { ${sel} { position: static !important; } }`);
  }
  if (issueMap.has('split-screen-cramping')) {
    const sel = cleanSel('split-screen-cramping', 'nav, .nav-links, .pricing-grid');
    out.push(`${sel} { flex-wrap: wrap !important; white-space: normal !important; min-width: 0 !important; }`);
    out.push(`@media (max-width: 680px) { ${sel} { grid-template-columns: 1fr !important; } }`);
  }
  if (issueMap.has('tiny-typography')) {
    out.push(`${cleanSel('tiny-typography', 'small, .caption')} { font-size: max(13px, 0.875rem) !important; }`);
  }
  if (issueMap.has('hardcoded-100vh')) {
    out.push('main, .hero, .hero-panel { min-height: 100dvh !important; }');
  }
  return out.join('\n') + '\n';
}

async function readSource(target) {
  if (target === '-') {
    const chunks = [];
    for await (const chunk of process.stdin) chunks.push(chunk);
    return { html: Buffer.concat(chunks).toString('utf8'), label: 'stdin' };
  }
  if (/^https?:\/\//i.test(target)) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
    try {
      const res = await fetch(target, {
        signal: controller.signal,
        headers: { 'user-agent': `FoldCheck-CLI/${VERSION} (+https://foldcheck.com/cli)` }
      });
      if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${target}`);
      const buf = Buffer.from(await res.arrayBuffer());
      if (buf.length > MAX_BYTES) throw new Error(`Response exceeded ${MAX_BYTES} byte limit`);
      return { html: buf.toString('utf8'), label: target };
    } finally {
      clearTimeout(timer);
    }
  }
  const fullPath = path.resolve(target);
  const html = await fs.readFile(fullPath, 'utf8');
  return { html, label: target };
}

function printHelp() {
  console.log(`FoldCheck CLI v${VERSION} — Simulated Foldable Website Auditor

Usage:
  node foldcheck.mjs <file.html | https://url | -> [options]

Options:
  --device <id>       iphone-duo (default), z-fold-8, z-fold-7, z-flip-7,
                      mate-x8, mate-x7, mate-xt, pura-x
  --state <name>      cover (default), inner, split, landscape
  --all-states        Audit all 4 states for the chosen device
  --all-devices       Audit all 8 devices x 4 states (32 simulated viewports)
  --md                Output Markdown report
  --ai                Output copy-paste AI fix prompt
  --fix-css           Output auto-generated foldcheck-patch.css repair sheet
  --json              Output JSON report
  --fail-on <level>   Exit with code 1 on severity >= high | medium | low
  -v, --version       Show CLI version
  -h, --help          Show this help
`);
}

async function main() {
  const args = process.argv.slice(2);
  if (args.length === 0 || args.includes('-h') || args.includes('--help')) {
    printHelp();
    process.exit(0);
  }
  if (args.includes('-v') || args.includes('--version')) {
    console.log(VERSION);
    process.exit(0);
  }

  let target = null;
  let deviceId = 'iphone-duo';
  let stateId = 'cover';
  let allStates = false;
  let allDevices = false;
  let format = 'text';
  let failOn = null;

  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg === '--device') deviceId = args[++i];
    else if (arg === '--state') stateId = args[++i];
    else if (arg === '--all-states') allStates = true;
    else if (arg === '--all-devices') allDevices = true;
    else if (arg === '--md') format = 'md';
    else if (arg === '--ai') format = 'ai';
    else if (arg === '--fix-css') format = 'fix-css';
    else if (arg === '--json') format = 'json';
    else if (arg === '--fail-on') failOn = (args[++i] || '').toLowerCase();
    else if (!arg.startsWith('-') || arg === '-') target = arg;
  }

  if (!target) {
    console.error('Error: missing input file or URL. Run with --help for usage.');
    process.exit(2);
  }
  if (!DEVICES[deviceId]) {
    console.error(`Error: unknown device "${deviceId}". Valid: ${Object.keys(DEVICES).join(', ')}`);
    process.exit(2);
  }

  const { html, label } = await readSource(target);
  const targets = [];

  if (allDevices) {
    for (const dev of Object.keys(DEVICES)) {
      for (const st of ['cover', 'inner', 'split', 'landscape']) targets.push([dev, st]);
    }
  } else if (allStates) {
    for (const st of ['cover', 'inner', 'split', 'landscape']) targets.push([deviceId, st]);
  } else {
    targets.push([deviceId, stateId]);
  }

  const results = targets.map(([d, s]) => auditHtml(html, d, s, label));

  if (format === 'json') {
    console.log(JSON.stringify(results.length === 1 ? results[0] : { results }, null, 2));
  } else if (format === 'md') {
    process.stdout.write(formatMarkdown(results));
  } else if (format === 'ai') {
    process.stdout.write(formatAiPrompt(results));
  } else if (format === 'fix-css') {
    process.stdout.write(formatFixCss(results));
  } else {
    process.stdout.write(formatTextReport(results));
  }

  if (failOn && SEVERITY_RANK[failOn] !== undefined) {
    const threshold = SEVERITY_RANK[failOn];
    const breached = results.some((r) => r.issues.some((it) => SEVERITY_RANK[it.severity] >= threshold));
    if (breached) process.exit(1);
  }
}

const invokedDirectly =
  process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname);

if (invokedDirectly) {
  main().catch((err) => {
    console.error(`FoldCheck error: ${err.message}`);
    process.exit(2);
  });
}

Recommended Automated Testing Resources

Frequently Asked Questions

Does the CLI require npm install, Puppeteer, or Playwright?

No. The standalone 31.9 KB ESM script uses only built-in Node.js 18+ modules. Commit it into your repository and run it immediately in local terminals or CI containers.

Does the CLI automatically overwrite my CSS or HTML files?

No—that is deliberate. Blind codemods often hide overflow bugs with overflow-x: hidden. Instead, --fix-css prints a reviewable CSS patch and --ai generates a targeted prompt for Cursor, Claude Code, or Gemini.

How do I fail a GitHub Actions pull request on layout regressions?

Pass --fail-on high (or --fail-on medium for stricter teams) alongside --all-states or --all-devices. The script exits with status code 1 whenever any finding meets or exceeds your threshold.

Can the CLI check React, Vue, Next.js, or Shopify templates?

Yes. Because it performs a fast static scan without launching a browser, point it at your built static/SSR HTML output (such as ./dist/index.html) or a live staging URL. For purely client-rendered SPAs, combine with Playwright HTML dumps or our DevTools Inspector.

Which report formats does the command-line tool export?

Choose readable terminal output by default, --md for Markdown PR comments, --json for CI dashboards, --fix-css for targeted CSS patches, and --ai for ready-to-paste AI fix prompts.