@kaynooo/cli-page 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.js +276 -4
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -23,6 +23,7 @@ What `check` reports:
23
23
  - `overflow`: the page scrolls sideways; the up to three elements where it starts, with their right edge.
24
24
  - `console`: console errors and uncaught exceptions. `request`: requests that failed or answered 4xx/5xx. Both once per target, at the first width they show at.
25
25
  - `font`: text drawn in another font than its `font-family` asks for, naming the font Chromium drew it with (CDP `CSS.getPlatformFontsForNode`): a named family that is not available, or a generic one such as `system-ui` resolving to a monospace font.
26
+ - `contrast`: text under WCAG AA, 4.5:1 or 3:1 for large text, with both colours and the ratio (measured by `@kaynooo/audit-engine`); text over an image, a gradient or a filter cannot be measured and is left out.
26
27
  - `tap-target`: a control under 44px wide or tall below 600px wide, under 24px otherwise; a link inside a sentence is exempt, a checkbox counts its label.
27
28
  - `padding`: text touching an edge its box draws, a border side or a background unlike what is behind it.
28
29
  - `image`: an image that finished loading with nothing to draw. `layout-shift`: a cumulative layout shift score above 0.1, naming the element that moved most.
package/dist/cli.js CHANGED
@@ -1439,6 +1439,273 @@ var init_src = __esm(() => {
1439
1439
  init_workspace_root();
1440
1440
  });
1441
1441
 
1442
+ // ../../node_modules/.bun/@kaynooo+audit-engine@0.1.1/node_modules/@kaynooo/audit-engine/src/inpage.ts
1443
+ function install() {
1444
+ if (window.__audit)
1445
+ return;
1446
+ window.__audit = {
1447
+ cssPath(el) {
1448
+ const parts = [];
1449
+ for (let node = el;node && node !== document.documentElement; node = node.parentElement) {
1450
+ if (node.id && document.querySelectorAll(`#${CSS.escape(node.id)}`).length === 1) {
1451
+ parts.unshift(`#${CSS.escape(node.id)}`);
1452
+ break;
1453
+ }
1454
+ const tag = node.localName;
1455
+ const siblings = node.parentElement ? [...node.parentElement.children].filter((child) => child.localName === tag) : [];
1456
+ parts.unshift(siblings.length > 1 ? `${tag}:nth-of-type(${siblings.indexOf(node) + 1})` : tag);
1457
+ }
1458
+ return parts.join(" > ");
1459
+ },
1460
+ snippet(el) {
1461
+ return (/^<[^>]*>/.exec(el.outerHTML)?.[0] ?? `<${el.localName}>`).slice(0, 200);
1462
+ },
1463
+ ownText(el) {
1464
+ let text = "";
1465
+ for (const node of el.childNodes) {
1466
+ if (node.nodeType === Node.TEXT_NODE)
1467
+ text += node.textContent ?? "";
1468
+ }
1469
+ return text.replace(/\s+/g, " ").trim();
1470
+ },
1471
+ visible(el) {
1472
+ const style = getComputedStyle(el);
1473
+ const rect = el.getBoundingClientRect();
1474
+ return style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) > 0 && rect.width > 0 && rect.height > 0;
1475
+ }
1476
+ };
1477
+ }
1478
+ async function installHelpers(page) {
1479
+ await page.evaluate(install);
1480
+ }
1481
+
1482
+ // ../../node_modules/.bun/@kaynooo+audit-engine@0.1.1/node_modules/@kaynooo/audit-engine/src/contrast.ts
1483
+ function measure(cap) {
1484
+ const helpers = window.__audit;
1485
+ const canvas = document.createElement("canvas");
1486
+ canvas.width = 1;
1487
+ canvas.height = 1;
1488
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
1489
+ const viaCanvas = (value) => {
1490
+ if (!ctx)
1491
+ return null;
1492
+ ctx.fillStyle = "#000";
1493
+ ctx.fillStyle = value;
1494
+ const onBlack = ctx.fillStyle;
1495
+ ctx.fillStyle = "#fff";
1496
+ ctx.fillStyle = value;
1497
+ if (ctx.fillStyle !== onBlack)
1498
+ return null;
1499
+ ctx.clearRect(0, 0, 1, 1);
1500
+ ctx.fillRect(0, 0, 1, 1);
1501
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data;
1502
+ return [r, g, b, a / 255];
1503
+ };
1504
+ const parse = (value) => {
1505
+ if (!value || value === "transparent")
1506
+ return [0, 0, 0, 0];
1507
+ const match = /^rgba?\(([^)]+)\)$/.exec(value);
1508
+ if (match) {
1509
+ const parts = (match[1] ?? "").split(/[\s,/]+/).filter(Boolean).map((part) => Number.parseFloat(part));
1510
+ return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0, parts[3] ?? 1];
1511
+ }
1512
+ return viaCanvas(value);
1513
+ };
1514
+ const over = (top, bottom) => {
1515
+ const a = top[3];
1516
+ return [top[0] * a + bottom[0] * (1 - a), top[1] * a + bottom[1] * (1 - a), top[2] * a + bottom[2] * (1 - a), 1];
1517
+ };
1518
+ const luminance = (rgb) => {
1519
+ const channel = (value) => {
1520
+ const c = value / 255;
1521
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
1522
+ };
1523
+ return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);
1524
+ };
1525
+ const ratio = (a, b) => {
1526
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
1527
+ return (hi + 0.05) / (lo + 0.05);
1528
+ };
1529
+ const css = (rgb) => `rgb(${Math.round(rgb[0])}, ${Math.round(rgb[1])}, ${Math.round(rgb[2])})`;
1530
+ const MEDIA = new Set(["IMG", "PICTURE", "VIDEO", "CANVAS", "IFRAME", "OBJECT", "EMBED", "svg"]);
1531
+ const isMedia = (node) => MEDIA.has(node.tagName);
1532
+ const solid = (style) => {
1533
+ if (style.backgroundImage && style.backgroundImage !== "none")
1534
+ return "background-image";
1535
+ if (style.filter && style.filter !== "none")
1536
+ return "filter";
1537
+ if (style.mixBlendMode && style.mixBlendMode !== "normal")
1538
+ return "blend-mode";
1539
+ return Number.parseFloat(style.opacity) < 1 ? "opacity" : null;
1540
+ };
1541
+ const pseudoBackground = (node) => {
1542
+ for (const which of ["::before", "::after"]) {
1543
+ const style = getComputedStyle(node, which);
1544
+ if (!style.content || style.content === "none" || style.position !== "absolute" && style.position !== "fixed")
1545
+ continue;
1546
+ if (!(Number.parseFloat(style.zIndex) < 0))
1547
+ continue;
1548
+ if (style.top !== "0px" || style.right !== "0px" || style.bottom !== "0px" || style.left !== "0px")
1549
+ continue;
1550
+ if (style.backgroundImage && style.backgroundImage !== "none")
1551
+ return "background-image";
1552
+ const color = parse(style.backgroundColor);
1553
+ if (color && color[3] > 0)
1554
+ return color;
1555
+ }
1556
+ return null;
1557
+ };
1558
+ const ground = (() => {
1559
+ const probe = document.createElement("div");
1560
+ probe.style.backgroundColor = "Canvas";
1561
+ document.documentElement.append(probe);
1562
+ const color = parse(getComputedStyle(probe).backgroundColor);
1563
+ probe.remove();
1564
+ return color && color[3] === 1 ? color : [255, 255, 255, 1];
1565
+ })();
1566
+ const compose = (stack) => {
1567
+ const layers = [];
1568
+ for (const node of stack) {
1569
+ if (isMedia(node))
1570
+ return "media";
1571
+ const style = getComputedStyle(node);
1572
+ const reason = solid(style);
1573
+ if (reason)
1574
+ return reason;
1575
+ const pseudo = pseudoBackground(node);
1576
+ if (typeof pseudo === "string")
1577
+ return pseudo;
1578
+ if (pseudo) {
1579
+ layers.push(pseudo);
1580
+ if (pseudo[3] === 1)
1581
+ break;
1582
+ }
1583
+ const color = parse(style.backgroundColor);
1584
+ if (color && color[3] > 0) {
1585
+ layers.push(color);
1586
+ if (color[3] === 1)
1587
+ break;
1588
+ }
1589
+ }
1590
+ let base = ground;
1591
+ for (const layer of layers.toReversed())
1592
+ base = over(layer, base);
1593
+ return base;
1594
+ };
1595
+ const textRect = (el) => {
1596
+ const range = document.createRange();
1597
+ for (const child of el.childNodes) {
1598
+ if (child.nodeType !== Node.TEXT_NODE || (child.textContent ?? "").trim() === "")
1599
+ continue;
1600
+ range.selectNodeContents(child);
1601
+ for (const rect of range.getClientRects()) {
1602
+ if (rect.width > 0 && rect.height > 0)
1603
+ return rect;
1604
+ }
1605
+ }
1606
+ return null;
1607
+ };
1608
+ const background = (el) => {
1609
+ let rect = textRect(el);
1610
+ if (!rect)
1611
+ return "offscreen";
1612
+ if (rect.top < 0 || rect.bottom > innerHeight) {
1613
+ scrollTo({ top: scrollY + rect.top + rect.height / 2 - innerHeight / 2, left: scrollX, behavior: "instant" });
1614
+ rect = textRect(el);
1615
+ }
1616
+ if (!rect)
1617
+ return "offscreen";
1618
+ const x = rect.left + rect.width / 2;
1619
+ const y = rect.top + rect.height / 2;
1620
+ if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight)
1621
+ return "offscreen";
1622
+ const stack = document.elementsFromPoint(x, y);
1623
+ const index = stack.indexOf(el);
1624
+ if (index === -1) {
1625
+ if (getComputedStyle(el).pointerEvents !== "none")
1626
+ return "covered";
1627
+ const chain = [];
1628
+ for (let node = el;node; node = node.parentElement)
1629
+ chain.push(node);
1630
+ return compose(chain);
1631
+ }
1632
+ for (const front of stack.slice(0, index)) {
1633
+ if (el.contains(front) || front.contains(el))
1634
+ continue;
1635
+ const style = getComputedStyle(front);
1636
+ if (isMedia(front) || style.backgroundImage && style.backgroundImage !== "none" || (parse(style.backgroundColor)?.[3] ?? 0) > 0)
1637
+ return "covered";
1638
+ }
1639
+ return compose(stack.slice(index));
1640
+ };
1641
+ const inactive = (el) => el.closest(':disabled, [aria-disabled="true"], [inert]') !== null;
1642
+ const startX = scrollX;
1643
+ const startY = scrollY;
1644
+ const report = { checked: 0, failures: [], undecidable: [], truncated: false };
1645
+ try {
1646
+ for (const el of document.body.querySelectorAll("*"))
1647
+ check(el);
1648
+ } finally {
1649
+ scrollTo({ top: startY, left: startX, behavior: "instant" });
1650
+ }
1651
+ return report;
1652
+ function undecided(item) {
1653
+ if (report.undecidable.length < cap)
1654
+ report.undecidable.push(item);
1655
+ else
1656
+ report.truncated = true;
1657
+ }
1658
+ function check(el) {
1659
+ const text = helpers.ownText(el);
1660
+ if (!text || !helpers.visible(el) || inactive(el))
1661
+ return;
1662
+ const box = el.getBoundingClientRect();
1663
+ if (box.width <= 1 || box.height <= 1)
1664
+ return;
1665
+ const style = getComputedStyle(el);
1666
+ const fill = style.webkitTextFillColor && style.webkitTextFillColor !== style.color ? style.webkitTextFillColor : style.color;
1667
+ const fg = parse(fill);
1668
+ if (!fg)
1669
+ return;
1670
+ const base = { selector: helpers.cssPath(el), snippet: helpers.snippet(el), text: text.slice(0, 120) };
1671
+ if (el instanceof SVGElement) {
1672
+ undecided({ ...base, fg: style.fill, reason: "svg" });
1673
+ return;
1674
+ }
1675
+ if (fg[3] === 0) {
1676
+ undecided({ ...base, fg: fill, reason: "gradient-text" });
1677
+ return;
1678
+ }
1679
+ report.checked++;
1680
+ const bg = background(el);
1681
+ if (typeof bg === "string") {
1682
+ undecided({ ...base, fg: css(fg), reason: bg });
1683
+ return;
1684
+ }
1685
+ const color = fg[3] < 1 ? over(fg, bg) : fg;
1686
+ const size = Number.parseFloat(style.fontSize) || 16;
1687
+ const large = size >= 24 || Number.parseInt(style.fontWeight, 10) >= 700 && size >= 18.66;
1688
+ const required = large ? 3 : 4.5;
1689
+ const measured = ratio(color, bg);
1690
+ if (measured >= required)
1691
+ return;
1692
+ if (style.textShadow && style.textShadow !== "none") {
1693
+ undecided({ ...base, fg: css(color), reason: "text-shadow" });
1694
+ return;
1695
+ }
1696
+ if (report.failures.length >= cap) {
1697
+ report.truncated = true;
1698
+ return;
1699
+ }
1700
+ report.failures.push({ ...base, fg: css(color), bg: css(bg), ratio: Math.floor(measured * 100) / 100, required, large });
1701
+ }
1702
+ }
1703
+ async function measureContrast(page, options = {}) {
1704
+ await installHelpers(page);
1705
+ return page.evaluate(measure, options.cap ?? 200);
1706
+ }
1707
+ var init_contrast = () => {};
1708
+
1442
1709
  // src/inpage.ts
1443
1710
  async function source(file) {
1444
1711
  let code = sources.get(file);
@@ -1710,6 +1977,10 @@ function listen(page, into) {
1710
1977
  into.push({ kind: "request", message: `${response.request().method()} ${shortUrl(response.url())} answered ${response.status()}` });
1711
1978
  });
1712
1979
  }
1980
+ async function contrastFindings(page) {
1981
+ const { failures } = await measureContrast(page);
1982
+ return failures.map(({ selector, fg, bg, ratio, required }) => ({ kind: "contrast", selector, message: `${fg} on ${bg}, ${ratio.toFixed(2)}:1, needs ${required}:1` }));
1983
+ }
1713
1984
  async function check(args) {
1714
1985
  const { values, positionals } = parse(args, USAGE, OPTIONS, {
1715
1986
  positionals: ["<file|url>..."],
@@ -1756,7 +2027,7 @@ async function check(args) {
1756
2027
  shots.push({ target: target.label, width, path: file });
1757
2028
  if (!values.json)
1758
2029
  console.log(path(file));
1759
- const found = [...heard, ...await inPage(page, "measure", "measureDom", width < PHONE_WIDTH), ...skipped.has("font") ? [] : await fontFindings(page)];
2030
+ const found = [...heard, ...await inPage(page, "measure", "measureDom", width < PHONE_WIDTH), ...skipped.has("font") ? [] : await fontFindings(page), ...skipped.has("contrast") ? [] : await contrastFindings(page)];
1760
2031
  await context.close();
1761
2032
  for (const finding of found) {
1762
2033
  const key = `${finding.kind}|${finding.selector ?? ""}|${finding.message}`;
@@ -1785,18 +2056,19 @@ async function check(args) {
1785
2056
  }
1786
2057
  var KINDS, ONCE, URL_CAP = 160, EXITS, USAGE, OPTIONS;
1787
2058
  var init_check = __esm(() => {
2059
+ init_contrast();
1788
2060
  init_src();
1789
2061
  init_browser();
1790
2062
  init_fonts();
1791
2063
  init_inpage();
1792
2064
  init_report2();
1793
- KINDS = ["redirect", "overflow", "console", "request", "font", "tap-target", "padding", "image", "layout-shift"];
1794
- ONCE = new Set(["redirect", "console", "request", "font"]);
2065
+ KINDS = ["redirect", "overflow", "console", "request", "font", "contrast", "tap-target", "padding", "image", "layout-shift"];
2066
+ ONCE = new Set(["redirect", "console", "request", "font", "contrast"]);
1795
2067
  EXITS = [[0, "nothing found"], [1, "a defect was found"], [2, "a usage error, or a target that would not load"]];
1796
2068
  USAGE = `page check <file|url>...
1797
2069
 
1798
2070
  Opens each HTML file or URL in a local Chromium at every width, writes a full-page PNG per width (next to a file as <name>-<width>.png, into --out, or the cache folder for a URL) and prints its path, then one line per defect: <target> <width>px <kind> <selector>: <measure>.
1799
- Kinds: redirect (the page landed elsewhere, a login page say, so what follows is about that page), overflow (the page scrolls sideways; the elements where it starts), console (errors and uncaught exceptions), request (failed, or answered 4xx/5xx), font (text drawn in another font than its stack asks for, naming the one drawn), tap-target (under 44px below ${PHONE_WIDTH}px wide, under 24px otherwise; a link inside a sentence is exempt), padding (text touching the border or background edge of its box), image (did not load), layout-shift (a score above 0.1).
2071
+ Kinds: redirect (the page landed elsewhere, a login page say, so what follows is about that page), overflow (the page scrolls sideways; the elements where it starts), console (errors and uncaught exceptions), request (failed, or answered 4xx/5xx), font (text drawn in another font than its stack asks for, naming the one drawn), contrast (text under WCAG AA, 4.5:1 or 3:1 for large text; text over an image, a gradient or a filter is left out), tap-target (under 44px below ${PHONE_WIDTH}px wide, under 24px otherwise; a link inside a sentence is exempt), padding (text touching the border or background edge of its box), image (did not load), layout-shift (a score above 0.1).
1800
2072
  It never starts or builds an app: give it a file or a URL already served. A page behind a login takes --cookie, -H or --storage-state; a header goes to the target's origin alone.
1801
2073
  Chromium comes from PAGE_CHROMIUM, ~/.cache/ms-playwright or /usr/bin, never downloaded.
1802
2074
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-page",
3
3
  "type": "module",
4
- "version": "0.0.2",
4
+ "version": "0.0.3",
5
5
  "description": "page: shoots HTML files or URLs at several widths in a local Chromium and reports their layout defects one line each, or diffs a built page against its mockup.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -38,6 +38,7 @@
38
38
  "page": "$npm_execpath src/cli.ts"
39
39
  },
40
40
  "dependencies": {
41
+ "@kaynooo/audit-engine": "0.1.1",
41
42
  "playwright-core": "1.64.1"
42
43
  },
43
44
  "devDependencies": {