mirror of https://github.com/theNewDynamic/gohugo-theme-ananke.git

Patrick Kollitsch
10 hours ago c70b22c0c65d21fc25eda46a8182eb042da11da0
test(theme): enforce layered checks and fix accessibility

Move render scenarios into Node feature tests with DOM assertions, add browser, static, visual, and Lighthouse CI gates, and document recurring manual verification. Fix form names, content contrast, and mobile navigation layout shifts so the strict accessibility and performance checks pass.

Fixes #1005
Fixes #1006
Fixes #1007
Fixes #1008
Fixes #1010
Fixes #1011
Fixes #1013
Fixes #1015
Refs #1004
Refs #1009
Refs #1012
24 files modified
36 files added
6681 ■■■■■ changed files
.github/pull_request_template.md 3 ●●●●● patch | view | raw | blame | history
.github/workflows/quickstart.yml 2 ●●●●● patch | view | raw | blame | history
.github/workflows/tests.yml 152 ●●●●● patch | view | raw | blame | history
.gitignore 4 ●●●●● patch | view | raw | blame | history
CONTRIBUTING.md 7 ●●●●● patch | view | raw | blame | history
DESIGN.md 10 ●●●●● patch | view | raw | blame | history
assets/ananke/css/_styles.css 8 ●●●●● patch | view | raw | blame | history
biome.json 3 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-scripts.html 4 ●●●●● patch | view | raw | blame | history
layouts/_shortcodes/form-contact.html 8 ●●●●● patch | view | raw | blame | history
layouts/summary.html 2 ●●●●● patch | view | raw | blame | history
lighthouserc.cjs 28 ●●●●● patch | view | raw | blame | history
package-lock.json 4321 ●●●●● patch | view | raw | blame | history
package.json 19 ●●●●● patch | view | raw | blame | history
playwright.config.ts 3 ●●●●● patch | view | raw | blame | history
playwright.visual.config.ts 18 ●●●●● patch | view | raw | blame | history
scripts/test-hugo-quickstart.ts 849 ●●●●● patch | view | raw | blame | history
tests/README.md 103 ●●●●● patch | view | raw | blame | history
tests/catalog.yaml 14 ●●●●● patch | view | raw | blame | history
tests/coverage-gate.mjs 52 ●●●●● patch | view | raw | blame | history
tests/e2e/accessibility.spec.ts 27 ●●●●● patch | view | raw | blame | history
tests/e2e/copy-button.spec.ts 1 ●●●●● patch | view | raw | blame | history
tests/e2e/navigation.spec.ts 34 ●●●●● patch | view | raw | blame | history
tests/e2e/no-js.spec.ts 51 ●●●●● patch | view | raw | blame | history
tests/e2e/shortcodes.spec.ts 96 ●●●●● patch | view | raw | blame | history
tests/e2e/visual.spec.ts 16 ●●●●● patch | view | raw | blame | history
tests/fixtures/copy-code/content/example.md 7 ●●●●● patch | view | raw | blame | history
tests/fixtures/copy-code/copy-code.test.mjs 15 ●●●●● patch | view | raw | blame | history
tests/fixtures/copy-code/hugo.toml 4 ●●●●● patch | view | raw | blame | history
tests/fixtures/date-settings/date-settings.test.mjs 174 ●●●●● patch | view | raw | blame | history
tests/fixtures/header-deprecations/header-deprecations.test.mjs 52 ●●●●● patch | view | raw | blame | history
tests/fixtures/header-section/content/custom.md 7 ●●●●● patch | view | raw | blame | history
tests/fixtures/header-section/content/default.md 6 ●●●●● patch | view | raw | blame | history
tests/fixtures/header-section/header-section.test.mjs 19 ●●●●● patch | view | raw | blame | history
tests/fixtures/header-section/hugo.toml 2 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/content/cards/_index.md 3 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/content/cards/image.md 7 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/content/cards/plain.md 6 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/hugo.toml 2 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/images.toml 3 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/list-cards.test.mjs 32 ●●●●● patch | view | raw | blame | history
tests/fixtures/list-cards/plain.toml 3 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/shortcodes.md 24 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/hugo.toml 6 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/static/contact-submit/index.html 2 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/static/favicon.ico patch | view | raw | blame | history
tests/lychee.toml 5 ●●●●● patch | view | raw | blame | history
tests/manual-tests.md 58 ●●●●● patch | view | raw | blame | history
tests/quickstart.test.mjs 12 ●●●●● patch | view | raw | blame | history
tests/static/server.test.mjs 67 ●●●●● patch | view | raw | blame | history
tests/static/static-gates.test.mjs 41 ●●●●● patch | view | raw | blame | history
tests/support/check-links.mjs 22 ●●●●● patch | view | raw | blame | history
tests/support/check-markup.mjs 30 ●●●●● patch | view | raw | blame | history
tests/support/dev-server.mjs 27 ●●●●● patch | view | raw | blame | history
tests/support/pages.ts 8 ●●●●● patch | view | raw | blame | history
tests/support/prepare-site.mjs 57 ●●●●● patch | view | raw | blame | history
tests/testing-status.md 29 ●●●●● patch | view | raw | blame | history
tests/unit/build-diagnostics.test.mjs 41 ●●●●● patch | view | raw | blame | history
tests/unit/coverage-gate.test.mjs 67 ●●●●● patch | view | raw | blame | history
tsconfig.json 8 ●●●●● patch | view | raw | blame | history
.github/pull_request_template.md
@@ -1,3 +1,4 @@
<!-- markdownlint-disable MD041 -->
<!---
Add the issue number that is discussed and fixed by this PR (In the form
@@ -26,3 +27,5 @@
If testing of the new functionality is possible, please add tests.
-->
* [ ] Added or updated feature fixtures and tests, and registered parameters and shortcodes in `tests/catalog.yaml` (or explained why no tests are needed).
.github/workflows/quickstart.yml
@@ -50,7 +50,7 @@
      # so this gate actually exercises the code on the current branch / PR.
      - name: Run quickstart test (local working tree)
        run: |
          node scripts/test-hugo-quickstart.ts
          npm test
      # Additionally verify the documented submodule install against the published
      # theme, but only after merge to a release branch to avoid testing stale
.github/workflows/tests.yml
New file
@@ -0,0 +1,152 @@
name: Theme tests
on:
  push:
    branches: [development, main]
  pull_request:
  workflow_dispatch:
    inputs:
      update_visual_baselines:
        description: Generate visual baselines for review as an artifact
        type: boolean
        default: false
permissions:
  contents: read
jobs:
  browser:
    runs-on: ubuntu-latest
    container: mcr.microsoft.com/playwright:v1.65.1-noble
    env:
      HOME: /root
    steps:
      - name: Check out repository
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          persist-credentials: false
          submodules: false
      - name: Set up Node.js
        uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
        with:
          node-version: "24"
      - name: Set up Hugo
        uses: peaceiris/actions-hugo@2752ce1d29631191ea3f27c23495fa06139a5b78
        with:
          hugo-version: "latest"
          extended: true
      - name: Show tool versions
        run: |
          node --version
          npm --version
          git --version
          hugo version
      - name: Install dependencies
        run: npm ci
      - name: Check feature registration and gate tests
        run: npm run test:coverage-gate && npm run test:unit
      - name: Browser, accessibility, and no-JavaScript tests
        run: npm run test:e2e -- --workers=2
      - name: Compare visual baselines
        if: ${{ !inputs.update_visual_baselines }}
        run: npm run test:visual -- --workers=2
      - name: Generate visual baselines
        if: ${{ inputs.update_visual_baselines }}
        run: npm run test:visual -- --update-snapshots=all --workers=2
      - name: Upload test results and visual baselines
        if: always()
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
        with:
          name: browser-results
          path: |
            tests/.playwright/
            tests/visual-baselines/
          retention-days: 14
  static:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          persist-credentials: false
          submodules: false
      - name: Set up Node.js
        uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
        with:
          node-version: "24"
      - name: Set up Hugo
        uses: peaceiris/actions-hugo@2752ce1d29631191ea3f27c23495fa06139a5b78
        with:
          hugo-version: "latest"
          extended: true
      - name: Show tool versions
        run: |
          node --version
          npm --version
          git --version
          hugo version
      - name: Install dependencies
        run: npm ci
      - name: Install lychee
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh release download lychee-v0.24.2 --repo lycheeverse/lychee --pattern lychee-x86_64-unknown-linux-gnu.tar.gz --dir /tmp/lychee
          echo "1f4e0ef7f6554a6ed33dd7ac144fb2e1bbed98598e7af973042fc5cd43951c9a  /tmp/lychee/lychee-x86_64-unknown-linux-gnu.tar.gz" | sha256sum --check
          tar -xzf /tmp/lychee/lychee-x86_64-unknown-linux-gnu.tar.gz -C /tmp/lychee
          sudo install /tmp/lychee/lychee /usr/local/bin/lychee
      - name: Markup, internal links, and build diagnostics
        run: npm run test:static && npm run test:static:gates
  performance:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          persist-credentials: false
          submodules: false
      - name: Set up Node.js
        uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
        with:
          node-version: "24"
      - name: Set up Hugo
        uses: peaceiris/actions-hugo@2752ce1d29631191ea3f27c23495fa06139a5b78
        with:
          hugo-version: "latest"
          extended: true
      - name: Show tool versions
        run: |
          node --version
          npm --version
          git --version
          hugo version
      - name: Install dependencies
        run: npm ci
      - name: Performance, SEO, accessibility, and asset budgets
        run: npm run test:performance
      - name: Upload Lighthouse reports
        if: always()
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
        with:
          name: lighthouse-results
          path: |
            .lighthouseci/
            tests/.playwright/lighthouse/
          retention-days: 14
.gitignore
@@ -16,3 +16,7 @@
# Local posting credentials
/.env
# Generated test reports (visual baselines are tracked separately).
/tests/.playwright/
/.lighthouseci/
CONTRIBUTING.md
@@ -9,6 +9,7 @@
* [Branch strategy](#branch-strategy)
  * [Long-lived branches](#long-lived-branches)
  * [Branch naming](#branch-naming)
* [Tests](#tests)
* [Pull request workflow](#pull-request-workflow)
* [Circumventing git hooks](#circumventing-git-hooks)
* [Documentation contributions](#documentation-contributions)
@@ -96,6 +97,12 @@
git push --force-with-lease
```
## Tests
Run the relevant [theme test commands](tests/README.md) for each change and register changed parameters or shortcodes in `tests/catalog.yaml`. `npm test` uses the Node test runner and feature mini-sites; browser, static, visual, and Lighthouse checks have separate commands. The coverage gate checks registration and test paths, not complete behavioural coverage.
Follow [the manual testing guide](tests/manual-tests.md) after relevant UI changes and for release candidates. Record the tested commit, environment, scope, and findings in the pull request or release record. Initial screenshot approval establishes a starting point; changed screenshots and relevant accessibility behaviour need fresh review.
## Pull request workflow
1. Fork the repository and create a focused branch.
DESIGN.md
@@ -13,8 +13,8 @@
  text: "#555555"
  text-strong: "#111111"
  text-muted: "#777777"
  link: "#357EDD"
  link-hover: "#000000"
  link: "#00449E"
  link-hover: "#001B44"
  surface: "#FFFFFF"
  surface-subtle: "#F4F4F4"
  surface-raised: "#FFFFFF"
@@ -253,7 +253,7 @@
* **Primary (`#000000`)** is the default structural color for headers, navigation, footers, and primary submit actions.
* **Secondary (`#555555`)** maps to Tachyons `mid-gray` and is the default reading color for most text via the `text_color` parameter.
* **Tertiary (`#357EDD`)** maps to Tachyons `blue` and is available for links and accent states, though many theme links inherit black/gray and rely on `dim` or hover utilities.
* **Tertiary (`#357EDD`)** maps to Tachyons `blue` and is available for links and accent states, while content links use `dark-blue` and change to `navy` on hover or focus. Many structural links inherit black/gray and rely on `dim` or hover utilities.
* **Neutral (`#F4F4F4`)** maps to Tachyons `near-white` and is the default body background through `avenir bg-near-white`.
* **Surface (`#FFFFFF`)** is used by summary cards and content blocks.
* **Border (`#CCCCCC`)** maps to Tachyons `moon-gray`, used for low-contrast separators and bordered buttons.
@@ -311,7 +311,7 @@
Prefer Tachyons responsive suffixes (`-ns`, `-m`, `-l`) rather than custom media queries. Start single-column and progressively enhance at `not-small`, `medium`, and `large` breakpoints.
## Elevation & Depth
## Elevation & depth
The theme is deliberately flat. Depth is created with contrast, spacing, and hover transitions rather than shadows.
@@ -373,7 +373,7 @@
Preformatted blocks are dark (`#222222`) with light text (`#DDDDDD`), horizontal scrolling, `1.5em` padding, and a line height of `2`. Preserve overflow behavior so long code lines remain accessible.
## Do's and Don'ts
## Do's and don'ts
### Do
assets/ananke/css/_styles.css
@@ -14,10 +14,17 @@
  padding-left: 1rem;
}
/* Dark-blue links meet AA contrast on the theme's light surfaces. */
.nested-links a {
  color: #00449e;
  overflow-wrap: break-word;
}
.nested-links a:hover,
.nested-links a:focus {
  color: #001b44;
}
/* ------------------------------------------------------------------ *
 * Header navigation (see layouts/_partials/site-navigation.html)
 *
@@ -140,6 +147,7 @@
    border-top: 1px solid rgba(255, 255, 255, 0.2);
  }
  .ananke-js .ananke-nav:not(.ananke-nav-expanded) .ananke-nav-panel,
  .ananke-nav-collapsed .ananke-nav-panel {
    display: none;
  }
biome.json
@@ -5,7 +5,8 @@
    "includes": [
      "!!**/*.html",
      "!!assets/ananke/css/_tachyons.css",
      "!!assets/ananke/dist"
      "!!assets/ananke/dist",
      "!!scratch"
    ]
  }
}
layouts/_partials/site-scripts.html
@@ -93,6 +93,9 @@
  (function () {
    "use strict";
    // Apply the mobile layout before navigation markup can paint.
    document.documentElement.classList.add("ananke-js");
    // The toggle button of the open submenu. Only one submenu is open at a time.
    var openButton = null;
    var hoverCloseTimer = null;
@@ -134,6 +137,7 @@
      if (!nav) return;
      button.setAttribute("aria-expanded", expanded ? "true" : "false");
      nav.classList.toggle("ananke-nav-collapsed", !expanded);
      nav.classList.toggle("ananke-nav-expanded", expanded);
    }
    function enhanceHover(button) {
layouts/_shortcodes/form-contact.html
@@ -4,16 +4,16 @@
<form class="black-80 sans-serif" accept-charset="UTF-8" action="{{ .Get "action" }}" method="POST" role="form">
    <label class="{{ $.Scratch.Get "labelClasses" }}"  for="name">{{ lang.Translate "yourName" }}</label>
    <input type="text" id="name" name="name" class="{{ $.Scratch.Get "inputClasses" }}"  required placeholder=" "  aria-labelledby="name"/>
    <input type="text" id="name" name="name" class="{{ $.Scratch.Get "inputClasses" }}"  required placeholder=" "/>
    <label class="{{ $.Scratch.Get "labelClasses" }}" for="email">{{ lang.Translate "emailAddress" }}</label>
    <input type="email" id="email" name="email" class="{{ $.Scratch.Get "inputClasses" }}"  required placeholder=" "  aria-labelledby="email"/>
    <div class="requirements f6 gray glow i ph3 overflow-hidden">
    <input type="email" id="email" name="email" class="{{ $.Scratch.Get "inputClasses" }}"  required placeholder=" " aria-describedby="email-requirements"/>
    <div id="email-requirements" class="requirements f6 mid-gray glow i ph3 overflow-hidden">
      {{ lang.Translate "emailRequiredNote" }}
    </div>
    <label class="{{ $.Scratch.Get "labelClasses" }}" for="message">{{ lang.Translate "message" }}</label>
    <textarea id="message" name="message" class="{{ $.Scratch.Get "inputClasses" }} h4" aria-labelledby="message"></textarea>
    <textarea id="message" name="message" class="{{ $.Scratch.Get "inputClasses" }} h4"></textarea>
    <input class="db w-100 mv2 white pa3 bn hover-shadow hover-bg-black bg-animate bg-black" type="submit" value="{{ lang.Translate "send" }}" />
layouts/summary.html
@@ -1,7 +1,7 @@
{{ $show_date := partials.Include "func/ShowDate.html" (dict "page" . "key" "show_summary_date") }}
{{ $show_section_title := partials.Include "func/IsShown.html" (dict "page" . "key" "show_section_title") }}
<div class="w-100 mb4 nested-copy-line-height relative bg-white">
  <div class="mb3 pa4 gray overflow-hidden bg-white">
  <div class="mb3 pa4 mid-gray overflow-hidden bg-white">
    {{ if $show_section_title }}
      {{ with .CurrentSection.Title }}<span class="f6 db">{{ . }}</span>{{ end }}
    {{ end }}
lighthouserc.cjs
New file
@@ -0,0 +1,28 @@
module.exports = {
  ci: {
    collect: {
      startServerCommand: "node tests/support/dev-server.mjs",
      startServerReadyPattern: "Fixture site served",
      url: [
        "http://localhost:4321/",
        "http://localhost:4321/posts/",
        "http://localhost:4321/posts/hello/",
      ],
      numberOfRuns: 3,
      settings: { chromeFlags: "--no-sandbox" },
    },
    assert: {
      assertions: {
        "categories:performance": ["error", { minScore: 0.9 }],
        "categories:accessibility": ["error", { minScore: 1 }],
        "categories:seo": ["error", { minScore: 0.9 }],
        "resource-summary:script:size": ["error", { maxNumericValue: 16384 }],
        "resource-summary:stylesheet:size": [
          "error",
          { maxNumericValue: 32768 },
        ],
      },
    },
    upload: { target: "filesystem", outputDir: "tests/.playwright/lighthouse" },
  },
};
package-lock.json
Diff too large
package.json
@@ -31,10 +31,14 @@
    "@dnbhq/markdownlint-config": "2.0.0",
    "@dnbhq/release-config": "2.0.1",
    "@dnbhq/tsconfig": "0.1.6",
    "@iarna/toml": "2.2.5",
    "@lhci/cli": "0.16.1",
    "@playwright/test": "1.65.1",
    "@release-it/conventional-changelog": "12.0.2",
    "@types/node": "26.6.6",
    "cheerio": "1.2.0",
    "dotenv": "18.0.10",
    "html-validate": "11.21.1",
    "lint-staged": "17.6.1",
    "lockfile-lint": "5.1.0",
    "release-it": "21.1.2",
@@ -47,14 +51,14 @@
    "hook:commit": "lint-staged",
    "hook:push": "node -e \"process.exit(require('child_process').execSync('git branch --show-current').toString().trim() === 'main' ? 0 : 1)\" && node scripts/test-hugo-quickstart.ts || true",
    "lint:links": "lychee --config lychee.toml public",
    "lint:markdown": "markdownlint-cli2 --config ./node_modules/@dnbhq/markdownlint-config/.markdownlint-cli2.jsonc \"**/*.{md,mdx}\" \"#CHANGELOG.md\" \"#tests/.playwright/**\" \"#tests/fixtures/site/public/**\"",
    "lint:markdown:fix": "markdownlint-cli2 --config ./node_modules/@dnbhq/markdownlint-config/.markdownlint-cli2.jsonc --fix \"**/*.{md,mdx}\" \"#CHANGELOG.md\" \"#tests/.playwright/**\" \"#tests/fixtures/site/public/**\"",
    "lint:markdown": "markdownlint-cli2 --config ./node_modules/@dnbhq/markdownlint-config/.markdownlint-cli2.jsonc \"**/*.{md,mdx}\" \"#CHANGELOG.md\" \"#tests/.playwright/**\" \"#tests/fixtures/site/public/**\" \"#scratch/**\"",
    "lint:markdown:fix": "markdownlint-cli2 --config ./node_modules/@dnbhq/markdownlint-config/.markdownlint-cli2.jsonc --fix \"**/*.{md,mdx}\" \"#CHANGELOG.md\" \"#tests/.playwright/**\" \"#tests/fixtures/site/public/**\" \"#scratch/**\"",
    "lint:typescript": "tsc -p tsconfig.json --noEmit",
    "prepare": "simple-git-hooks install",
    "release": "release-it --config .release-it.ts",
    "release:pre": "release-it --preRelease=prerelease --config .release-it.ts",
    "server": "hugo server --environment documentation",
    "test": "node scripts/test-hugo-quickstart.ts",
    "test": "node --test tests/fixtures/*/*.test.mjs tests/unit/*.test.mjs tests/quickstart.test.mjs",
    "test:coverage-gate": "node tests/coverage-gate.mjs",
    "test:e2e": "playwright test",
    "test:e2e:ui": "playwright test --ui",
@@ -66,7 +70,14 @@
    "lint:lockfile": "lockfile-lint --path package-lock.json --validate-https --allowed-hosts npm",
    "lint": "npm run lint:code && npm run lint:lockfile && npm run lint:markdown && npm run lint:typescript",
    "check": "npm run lint && npm test && npm run test:coverage-gate",
    "lint:code:fix": "biome check --write"
    "lint:code:fix": "biome check --write",
    "test:static": "node tests/support/prepare-site.mjs && node tests/support/check-markup.mjs && node tests/support/check-links.mjs",
    "test:visual": "playwright test --config playwright.visual.config.ts",
    "test:performance": "lhci autorun",
    "test:unit": "node --test tests/unit/*.test.mjs",
    "test:fixtures": "node --test tests/fixtures/*/*.test.mjs",
    "test:watch": "node --test --watch tests/fixtures/*/*.test.mjs tests/unit/*.test.mjs",
    "test:static:gates": "node --test tests/static/*.test.mjs"
  },
  "cspell": {
    "version": "0.2",
playwright.config.ts
@@ -12,6 +12,7 @@
 * branch. See tests/support/dev-server.mjs.
 */
export default defineConfig({
  testIgnore: "**/visual.spec.ts",
  testDir: "./tests/e2e",
  outputDir: "./tests/.playwright/results",
  fullyParallel: true,
@@ -31,7 +32,7 @@
  webServer: {
    command: "node tests/support/dev-server.mjs",
    url: baseURL,
    reuseExistingServer: !isCI,
    reuseExistingServer: false,
    timeout: 120_000,
  },
});
playwright.visual.config.ts
New file
@@ -0,0 +1,18 @@
import { defineConfig } from "@playwright/test";
import config from "./playwright.config.ts";
export default defineConfig(config, {
  testIgnore: [],
  testMatch: "**/visual.spec.ts",
  snapshotPathTemplate:
    "{testDir}/../visual-baselines/{projectName}/{arg}{ext}",
  updateSnapshots: "none",
  use: { timezoneId: "UTC", locale: "en-GB", reducedMotion: "reduce" },
  expect: {
    toHaveScreenshot: {
      animations: "disabled",
      caret: "hide",
      maxDiffPixels: 0,
    },
  },
});
scripts/test-hugo-quickstart.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { constants } from "node:fs";
import {
@@ -16,6 +17,8 @@
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import TOML from "@iarna/toml";
import { load } from "cheerio";
/**
 * Absolute path to the theme repository root (the parent of `scripts/`).
@@ -71,11 +74,6 @@
  result: CommandResult;
}
interface HtmlAssertion {
  description: string;
  test: (html: string) => boolean;
}
const DEFAULT_OPTIONS: RoutineOptions = {
  projectName: "quickstart",
  themeSource: "local",
@@ -417,127 +415,35 @@
}
/**
 * Escape a string for safe use in a regular expression.
 *
 * @param value Raw string.
 * @returns Escaped string.
 */
function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
 * Assert that Hugo config contains the expected theme assignment somewhere in
 * the file, without requiring the whole config to match a fixed template.
 *
 * Accepts either single or double quotes, for example:
 * - theme = 'ananke'
 * - theme = "ananke"
 *
 * @param configPath Absolute config path.
 * @param themeName Expected theme name.
 * @throws Error when the config does not contain the expected theme line.
 * Check the configured theme using the TOML parser.
 */
async function assertThemeConfigured(
  configPath: string,
  themeName: string,
): Promise<void> {
  const config = await readTextFile(configPath);
  const themePattern = new RegExp(
    String.raw`^\s*theme\s*=\s*['"]${escapeRegExp(themeName)}['"]\s*$`,
    "m",
  );
  if (!themePattern.test(config)) {
    throw new Error(
      [
        "Strict assertion failed: theme configuration missing or incorrect.",
        `Config file: ${configPath}`,
        `Expected to find a line like: theme = '${themeName}'`,
        "Actual file contents:",
        config,
      ].join("\n\n"),
    );
  }
  assert.equal(TOML.parse(await readTextFile(configPath))["theme"], themeName);
}
/**
 * Return homepage assertions for the initial static build.
 *
 * @returns List of homepage assertions.
 */
function getHomepageAssertions(): HtmlAssertion[] {
  return [
    {
      description: "homepage contains an HTML document root",
      test: (html: string): boolean => /<html\b/i.test(html),
    },
    {
      description: "homepage contains a document title",
      test: (html: string): boolean => /<title>[\s\S]*?<\/title>/i.test(html),
    },
    {
      description: "homepage contains a body element",
      test: (html: string): boolean => /<body\b/i.test(html),
    },
    {
      description: "homepage contains at least one stylesheet reference",
      test: (html: string): boolean =>
        /<link\b[^>]*rel=["']stylesheet["'][^>]*>/i.test(html),
    },
    {
      description: "homepage contains at least one navigation-related landmark",
      test: (html: string): boolean => /<(nav|header)\b/i.test(html),
    },
    {
      description: "homepage contains theme-generated CSS class markers",
      test: (html: string): boolean =>
        /\b(ma[0-9]|pa[0-9]|bg-black|near-white|sans-serif)\b/i.test(html),
    },
    {
      description: "homepage contains a main content area",
      test: (html: string): boolean => /<(main|article|section)\b/i.test(html),
    },
  ];
}
/**
 * Assert that the generated homepage looks like a real themed render.
 *
 * @param homepagePath Absolute path to `public/index.html`.
 * @throws Error when one or more assertions fail.
 */
async function assertHomepageLooksValid(homepagePath: string): Promise<void> {
  const html = await readTextFile(homepagePath);
  const failures: string[] = [];
  if (html.trim().length === 0) {
    throw new Error(
      [
        "Strict assertion failed: generated homepage is empty.",
        `Homepage file: ${homepagePath}`,
      ].join("\n\n"),
  assert.ok(html.trim(), "Generated homepage must not be empty");
  const $ = load(html);
  for (const selector of [
    "html",
    "title",
    "body",
    'link[rel="stylesheet"]',
    "nav, header",
    "main, article, section",
  ]) {
    assert.ok($(selector).length, `Homepage missing ${selector}`);
  }
  assert.ok(
    $(".bg-black, .near-white, .sans-serif, .pa3, .ma0").length,
    "Homepage missing theme classes",
    );
  }
  for (const assertion of getHomepageAssertions()) {
    if (!assertion.test(html)) {
      failures.push(`- ${assertion.description}`);
    }
  }
  if (failures.length > 0) {
    throw new Error(
      [
        "Strict assertion failed: generated homepage did not match expected render checks.",
        `Homepage file: ${homepagePath}`,
        "Failed assertions:",
        ...failures,
      ].join("\n"),
    );
  }
}
/**
 * Extract the auto-generated date line from a Hugo content file with TOML frontmatter.
 *
@@ -615,74 +521,22 @@
 * @param pageHtml HTML from `public/foo/index.html`.
 */
function assertDraftPageRendered(pageHtml: string): void {
  const failures: string[] = [];
  if (!/<h2[^>]*>\s*Introduction\s*<\/h2>/i.test(pageHtml)) {
    failures.push("- heading 'Introduction' was not rendered as an h2 element");
  }
  if (!/<strong>\s*bold\s*<\/strong>/i.test(pageHtml)) {
    failures.push("- bold Markdown was not rendered as a <strong> element");
  }
  if (!/<em>\s*emphasized\s*<\/em>/i.test(pageHtml)) {
    failures.push("- emphasized Markdown was not rendered as an <em> element");
  }
  if (
    !/<a[^>]+href=["']https:\/\/gohugo\.io["'][^>]*>\s*Hugo\s*<\/a>/i.test(
      pageHtml,
    )
  ) {
    failures.push("- Markdown link was not rendered as an anchor element");
  }
  if (!/My First Post/i.test(pageHtml)) {
    failures.push("- post title was not visible on the rendered page");
  }
  if (failures.length > 0) {
    throw new Error(
      [
        "Strict assertion failed: draft page content was not rendered as expected.",
        "Failed assertions:",
        ...failures,
      ].join("\n"),
  const $ = load(pageHtml);
  assert.equal(
    $("h2").filter((_, element) => $(element).text().trim() === "Introduction")
      .length,
    1,
    );
  }
  assert.equal($("strong").text().trim(), "bold");
  assert.equal($("em").text().trim(), "emphasized");
  assert.equal($('a[href="https://gohugo.io"]').text().trim(), "Hugo");
  assert.ok($("h1").text().includes("My First Post"));
}
/**
 * Assert that the generated homepage reflects updated title and locale configuration.
 *
 * Locale is checked strictly on the `<html>` tag.
 *
 * @param homepageHtml HTML from `public/index.html`.
 */
function assertUpdatedConfigInOutput(homepageHtml: string): void {
  const failures: string[] = [];
  if (!/Ananke Test Quickstart/i.test(homepageHtml)) {
    failures.push(
      "- updated site title was not visible in the generated output",
    );
  }
  if (!/<html[^>]+lang=["']en-gb["'][^>]*>/i.test(homepageHtml)) {
    failures.push(
      "- updated locale 'en-gb' was not present in the <html lang=\"en-gb\"> tag",
    );
  }
  if (failures.length > 0) {
    throw new Error(
      [
        "Strict assertion failed: updated config was not reflected in the generated output.",
        "Failed assertions:",
        ...failures,
      ].join("\n"),
    );
  }
  const $ = load(homepageHtml);
  assert.ok($("body").text().includes("Ananke Test Quickstart"));
  assert.equal($("html").attr("lang"), "en-gb");
}
/**
@@ -700,7 +554,7 @@
  const homepageHtml = await readTextFile(homepagePath);
  if (/My First Post/i.test(homepageHtml)) {
  if (load(homepageHtml)("body").text().includes("My First Post")) {
    throw new Error(
      [
        "Strict assertion failed: draft post title was visible in the production homepage output.",
@@ -711,400 +565,12 @@
}
/**
 * Sentinel CSS class used to verify the configurable hero header spacing.
 *
 * Issue #504: the height of the hero header is controlled by the
 * `header_section_class` parameter. The value is unique so it can only appear in
 * the output when the front matter override is honoured.
 */
const HEADER_SECTION_CLASS_MARKER = "ananke-header-test-pv7";
/**
 * Default header section spacing rendered by `page-header.html` for a single
 * page with a featured image when `header_section_class` is not set.
 */
const DEFAULT_PAGE_HEADER_SECTION_CLASS = "tc-l pv6 ph3 ph4-ns";
/**
 * Create two single pages that exercise the configurable header section class:
 * one overrides `header_section_class` in front matter, the other relies on the
 * theme default. Both set `featured_image` so the hero header branch renders.
 *
 * @param contentDir Absolute path to the project `content` directory.
 */
async function writeHeaderSectionClassFixtures(
  contentDir: string,
): Promise<void> {
  const overridePage = [
    "+++",
    "title = 'Custom Header Height'",
    "featured_image = '/images/custom-hero.jpg'",
    `header_section_class = '${HEADER_SECTION_CLASS_MARKER} ph3 ph4-ns'`,
    "+++",
    "",
    "Body.",
    "",
  ].join("\n");
  const defaultPage = [
    "+++",
    "title = 'Default Header Height'",
    "featured_image = '/images/default-hero.jpg'",
    "+++",
    "",
    "Body.",
    "",
  ].join("\n");
  await writeTextFile(join(contentDir, "custom-header.md"), overridePage);
  await writeTextFile(join(contentDir, "default-header.md"), defaultPage);
}
/**
 * Assert that the configurable `header_section_class` parameter is honoured on
 * hero headers and that omitting it keeps the historical default spacing.
 *
 * @param projectRoot Absolute path to the temporary quickstart project.
 * @throws Error when the override is dropped, leaks, or the default changes.
 */
async function assertHeaderSectionClassConfigurable(
  projectRoot: string,
): Promise<void> {
  const failures: string[] = [];
  const overrideHtml = await readTextFile(
    join(projectRoot, "public", "custom-header", "index.html"),
  );
  const defaultHtml = await readTextFile(
    join(projectRoot, "public", "default-header", "index.html"),
  );
  if (!overrideHtml.includes(HEADER_SECTION_CLASS_MARKER)) {
    failures.push(
      `- custom 'header_section_class' value '${HEADER_SECTION_CLASS_MARKER}' was not applied to the hero header`,
    );
  }
  if (defaultHtml.includes(HEADER_SECTION_CLASS_MARKER)) {
    failures.push(
      "- custom 'header_section_class' value leaked onto a page that did not set it",
    );
  }
  if (!defaultHtml.includes(DEFAULT_PAGE_HEADER_SECTION_CLASS)) {
    failures.push(
      `- default header section spacing '${DEFAULT_PAGE_HEADER_SECTION_CLASS}' was missing when 'header_section_class' was not set`,
    );
  }
  if (failures.length > 0) {
    throw new Error(
      [
        "Strict assertion failed: configurable header section class did not behave as expected.",
        "Failed assertions:",
        ...failures,
      ].join("\n"),
    );
  }
}
/**
 * Markup only emitted by `summary-with-image.html` when a featured image is
 * rendered, used to detect that list cards switched to the image template.
 */
const LIST_CARD_IMAGE_MARKER = 'class="img"';
/**
 * Markup emitted by the summary templates when a card date is rendered.
 */
const SUMMARY_CARD_DATE_MARKER = "datetime=";
/**
 * Markup emitted by `summary.html` when the section title of a card is
 * rendered for the `cards` fixture section.
 */
const SUMMARY_CARD_SECTION_MARKER = '<span class="f6 db">Cards</span>';
/**
 * Create a content section whose list page exercises both the image and the
 * date behaviour of summary cards: one page has a featured image, the other
 * does not, and both carry an explicit date.
 *
 * @param contentDir Absolute path to the project `content` directory.
 */
async function writeListCardFixtures(contentDir: string): Promise<void> {
  const sectionDir = join(contentDir, "cards");
  await mkdir(sectionDir, { recursive: true });
  const sectionIndex = ["+++", "title = 'Cards'", "+++", "", ""].join("\n");
  const withImage = [
    "+++",
    "title = 'Card With Image'",
    "date = 2024-01-15T00:00:00Z",
    "featured_image = '/images/card-hero.jpg'",
    "+++",
    "",
    "Card body.",
    "",
  ].join("\n");
  const withoutImage = [
    "+++",
    "title = 'Card Without Image'",
    "date = 2024-02-20T00:00:00Z",
    "+++",
    "",
    "Card body.",
    "",
  ].join("\n");
  await writeTextFile(join(sectionDir, "_index.md"), sectionIndex);
  await writeTextFile(join(sectionDir, "with-image.md"), withImage);
  await writeTextFile(join(sectionDir, "without-image.md"), withoutImage);
}
/** Exercise date precedence through the actual single and summary templates. */
async function assertDateSettings(
  projectRoot: string,
  themeName: string,
): Promise<void> {
  type Settings = Record<string, boolean>;
  const cases: {
    label: string;
    site?: Settings;
    page?: Settings;
    cascade?: Settings;
    undated?: boolean;
    single: boolean;
    summary: boolean;
  }[] = [
    { label: "defaults", single: true, summary: true },
    {
      label: "shared site fallback",
      site: { show_date: false },
      single: false,
      summary: false,
    },
    {
      label: "specific site over shared site",
      site: { show_date: false, show_single_date: true },
      single: true,
      summary: false,
    },
    {
      label: "summary site override",
      site: { show_date: true, show_summary_date: false },
      single: true,
      summary: false,
    },
    {
      label: "page shared over specific site",
      site: { show_single_date: false, show_summary_date: false },
      page: { show_date: true },
      single: true,
      summary: true,
    },
    {
      label: "page shared false over site true",
      site: { show_single_date: true, show_summary_date: true },
      page: { show_date: false },
      single: false,
      summary: false,
    },
    {
      label: "specific page over shared page",
      page: { show_date: false, show_single_date: true },
      single: true,
      summary: false,
    },
    {
      label: "summary page over shared page",
      page: { show_date: true, show_summary_date: false },
      single: true,
      summary: false,
    },
    {
      label: "opposite independent settings",
      page: { show_single_date: false, show_summary_date: true },
      single: false,
      summary: true,
    },
    {
      label: "cascade over site",
      site: { show_summary_date: true },
      cascade: { show_summary_date: false },
      single: true,
      summary: false,
    },
    {
      label: "page over cascade",
      cascade: { show_single_date: false, show_summary_date: false },
      page: { show_single_date: true, show_summary_date: true },
      single: true,
      summary: true,
    },
    {
      label: "page map over cascade map",
      cascade: { show_summary_date: false },
      page: { show_date: true },
      single: true,
      summary: true,
    },
    {
      label: "undated page",
      page: { show_single_date: true, show_summary_date: true },
      undated: true,
      single: false,
      summary: false,
    },
  ];
  const settings = (values: Settings = {}): string[] =>
    Object.entries(values).map(([key, value]) => `${key} = ${String(value)}`);
  for (const variant of ["compact", "image", "post"]) {
    for (const test of cases) {
      const label = `${variant}: ${test.label}`;
      await writeTextFile(
        join(projectRoot, "hugo.toml"),
        [
          "baseURL = 'https://example.com/'",
          `theme = '${themeName}'`,
          "[params]",
          "mainSections = ['cards']",
          "[params.ananke.pages]",
          `show_list_images = ${String(variant === "image")}`,
          ...settings(test.site),
          "",
        ].join("\n"),
      );
      await writeTextFile(
        join(projectRoot, "content/cards/_index.md"),
        [
          "+++",
          "title = 'Cards'",
          ...(variant === "post" ? ["type = 'post'"] : []),
          ...(test.cascade
            ? ["[cascade.params.ananke]", ...settings(test.cascade)]
            : []),
          "+++",
          "",
        ].join("\n"),
      );
      for (const name of ["with-image", "without-image"]) {
        await writeTextFile(
          join(projectRoot, `content/cards/${name}.md`),
          [
            "+++",
            `title = '${name}'`,
            ...(test.undated ? [] : ["date = 2024-01-15T00:00:00Z"]),
            ...(variant === "post" ? ["type = 'post'"] : []),
            ...(name === "with-image"
              ? ["featured_image = '/images/card-hero.jpg'"]
              : []),
            ...(test.page ? ["[params.ananke]", ...settings(test.page)] : []),
            "+++",
            "",
            "Date setting fixture.",
            "",
          ].join("\n"),
        );
      }
      await executeHugoBuildStep(
        { name: label, command: "hugo", args: [], cwd: projectRoot },
        projectRoot,
      );
      const single = await readTextFile(
        join(projectRoot, "public/cards/with-image/index.html"),
      );
      if (single.includes('class="f6 mv4 dib tracked"') !== test.single) {
        throw new Error(`Single date assertion failed: ${label}`);
      }
      for (const path of ["cards/index.html", "index.html"]) {
        const html = await readTextFile(join(projectRoot, "public", path));
        const count = (html.match(/datetime="2024-01-15T00:00:00Z"/g) ?? [])
          .length;
        if (count !== (test.summary ? 2 : 0)) {
          throw new Error(
            `Summary date assertion failed: ${label}, ${path}, found ${count}`,
          );
        }
      }
    }
  }
}
/**
 * Assert that a list page renders summary cards with the expected image and
 * date behaviour.
 *
 * @param listHtml HTML from the rendered list page.
 * @param label Human-readable description of the configuration under test.
 * @param expectations Whether image cards and dates are expected in the output.
 * @throws Error when the rendered cards do not match the expectations.
 */
function assertListCardSummaries(
  listHtml: string,
  label: string,
  expectations: { images: boolean; dates: boolean; sectionTitles?: boolean },
): void {
  const failures: string[] = [];
  const hasImage = listHtml.includes(LIST_CARD_IMAGE_MARKER);
  const hasDate = listHtml.includes(SUMMARY_CARD_DATE_MARKER);
  const hasSectionTitle = listHtml.includes(SUMMARY_CARD_SECTION_MARKER);
  if (expectations.images && !hasImage) {
    failures.push(
      "- expected image summary cards but the list rendered no card image",
    );
  }
  if (!expectations.images && hasImage) {
    failures.push(
      "- image summary cards were rendered when 'ananke.pages.show_list_images' was not enabled",
    );
  }
  if (expectations.dates && !hasDate) {
    failures.push(
      "- expected summary card dates but none were rendered by default",
    );
  }
  if (!expectations.dates && hasDate) {
    failures.push(
      "- summary card dates were rendered when 'ananke.pages.show_date' was false",
    );
  }
  if (expectations.sectionTitles === true && !hasSectionTitle) {
    failures.push(
      "- expected summary card section titles but none were rendered by default",
    );
  }
  if (expectations.sectionTitles === false && hasSectionTitle) {
    failures.push(
      "- summary card section titles were rendered when 'ananke.pages.show_section_title' was false",
    );
  }
  if (failures.length > 0) {
    throw new Error(
      [
        `Strict assertion failed: list card summaries (${label}) did not behave as expected.`,
        "Failed assertions:",
        ...failures,
      ].join("\n"),
    );
  }
}
/**
 * Determine whether a directory is the work tree of a Git repository.
 *
 * @param path Absolute directory path.
 * @returns True when `path` is inside a Git work tree.
 */
async function isGitWorkTree(path: string): Promise<boolean> {
  const result = await runCommand(
    "git",
@@ -1142,6 +608,9 @@
        "--cached",
        "--others",
        "--exclude-standard",
        "--",
        ".",
        ":(exclude)scratch",
      ],
      themePath,
    );
@@ -1181,7 +650,7 @@
  // Fallback for a non-Git source directory: copy recursively while excluding
  // heavy or generated paths that would never ship with the theme.
  const excludedNames = new Set(["node_modules", "public", ".git"]);
  const excludedNames = new Set(["node_modules", "public", ".git", "scratch"]);
  await cp(themePath, destination, {
    recursive: true,
    filter: (source: string): boolean => {
@@ -1492,152 +961,6 @@
    await assertDraftHiddenInProduction(projectRoot, homepagePath);
    console.log("[OK ] Production build should exclude draft content");
    console.log("\n[RUN] Configurable hero header section class (issue #504)");
    await writeHeaderSectionClassFixtures(join(projectRoot, "content"));
    const headerSectionBuildStep: StepDefinition = {
      name: "Build site with configurable header section fixtures",
      command: "hugo",
      args: [],
      cwd: projectRoot,
      expectedFiles: [
        "public/custom-header/index.html",
        "public/default-header/index.html",
      ],
    };
    const headerSectionBuildReport = await executeHugoBuildStep(
      headerSectionBuildStep,
      projectRoot,
    );
    reports.push(headerSectionBuildReport);
    if (options.verbose) {
      console.log(
        `      ${formatCommand(headerSectionBuildStep.command, headerSectionBuildStep.args)}`,
      );
      console.log(
        `[OK ] ${headerSectionBuildStep.name} (${headerSectionBuildReport.result.durationMs} ms, exit ${String(headerSectionBuildReport.result.code)})`,
      );
      const trimmedOutput = headerSectionBuildReport.result.combined.trim();
      if (trimmedOutput) {
        console.log(trimmedOutput);
      }
    }
    await assertHeaderSectionClassConfigurable(projectRoot);
    console.log("[OK ] Configurable hero header section class (issue #504)");
    console.log("\n[RUN] List page image cards and summary dates (issue #217)");
    await writeListCardFixtures(join(projectRoot, "content"));
    const cardsListPath = join(projectRoot, "public", "cards", "index.html");
    // Default configuration: no image cards, but dates show by default.
    await writeTextFile(
      configPath,
      [
        "baseURL = 'https://example.com/'",
        "title = 'Ananke Test Quickstart'",
        `theme = '${options.themeName}'`,
        "",
      ].join("\n"),
    );
    const cardsDefaultBuildStep: StepDefinition = {
      name: "Build site with default summary cards",
      command: "hugo",
      args: [],
      cwd: projectRoot,
      expectedFiles: ["public/cards/index.html"],
    };
    const cardsDefaultBuildReport = await executeHugoBuildStep(
      cardsDefaultBuildStep,
      projectRoot,
    );
    reports.push(cardsDefaultBuildReport);
    assertListCardSummaries(await readTextFile(cardsListPath), "defaults", {
      images: false,
      dates: true,
      sectionTitles: true,
    });
    // Opt in to image cards and disable summary dates: images appear and the
    // dates disappear, proving the two settings are independent.
    await writeTextFile(
      configPath,
      [
        "baseURL = 'https://example.com/'",
        "title = 'Ananke Test Quickstart'",
        `theme = '${options.themeName}'`,
        "[params.ananke.pages]",
        "show_list_images = true",
        "show_date = false",
        "",
      ].join("\n"),
    );
    const cardsImagesBuildStep: StepDefinition = {
      name: "Build site with image cards and dates disabled",
      command: "hugo",
      args: [],
      cwd: projectRoot,
      expectedFiles: ["public/cards/index.html"],
    };
    const cardsImagesBuildReport = await executeHugoBuildStep(
      cardsImagesBuildStep,
      projectRoot,
    );
    reports.push(cardsImagesBuildReport);
    assertListCardSummaries(
      await readTextFile(cardsListPath),
      "image cards with dates disabled",
      { images: true, dates: false },
    );
    console.log("[OK ] List page image cards and summary dates (issue #217)");
    console.log(
      "\n[RUN] Hide summary card dates and section titles (issue #1109)",
    );
    await writeTextFile(
      configPath,
      [
        "baseURL = 'https://example.com/'",
        "title = 'Ananke Test Quickstart'",
        `theme = '${options.themeName}'`,
        "[params.ananke.pages]",
        "show_date = false",
        "show_section_title = false",
        "",
      ].join("\n"),
    );
    const cardsPlainBuildStep: StepDefinition = {
      name: "Build site with summary dates and section titles disabled",
      command: "hugo",
      args: [],
      cwd: projectRoot,
      expectedFiles: ["public/cards/index.html"],
    };
    const cardsPlainBuildReport = await executeHugoBuildStep(
      cardsPlainBuildStep,
      projectRoot,
    );
    reports.push(cardsPlainBuildReport);
    assertListCardSummaries(
      await readTextFile(cardsListPath),
      "dates and section titles disabled",
      { images: false, dates: false, sectionTitles: false },
    );
    console.log(
      "[OK ] Hide summary card dates and section titles (issue #1109)",
    );
    console.log("\n[RUN] Independent single and summary dates (issue #1112)");
    await assertDateSettings(projectRoot, options.themeName);
    console.log("[OK ] Independent single and summary dates (issue #1112)");
    console.log("\n[RUN] Deprecated header partial overrides (issue #1120)");
    await assertHeaderDeprecations(projectRoot, options.themeName);
    console.log("[OK ] Deprecated header partial overrides (issue #1120)");
    console.log("\nResult: PASS");
    if (options.keepOnSuccess) {
@@ -1675,102 +998,6 @@
}
/**
 * Assert the deprecation notice for overridden header partials (issue #1120).
 *
 * Builds the project three times: without an override (no notice), with a
 * project override of `site-navigation.html` (exactly one notice, and the
 * override renders), and with that notice in `ignoreLogs` (no notice).
 *
 * @param projectRoot Absolute path to the temporary quickstart project.
 * @param themeName Theme name used in the project configuration.
 * @throws Error when a notice is missing, repeated, or not suppressible.
 */
async function assertHeaderDeprecations(
  projectRoot: string,
  themeName: string,
): Promise<void> {
  const configPath = join(projectRoot, "hugo.toml");
  const overrideDir = join(projectRoot, "layouts", "_partials");
  const overridePath = join(overrideDir, "site-navigation.html");
  const notice = "ananke/DEPR";
  const marker = "deprecated-nav-override";
  const baseConfig = [
    "baseURL = 'https://example.com/'",
    "title = 'Ananke Test Quickstart'",
    `theme = '${themeName}'`,
  ];
  const build = async (label: string): Promise<string> => {
    await removePublicDir(projectRoot);
    const result = await runCommand("hugo", [], projectRoot);
    if (result.code !== 0) {
      throw new Error(`Build failed (${label}):\n${result.combined}`);
    }
    return result.combined;
  };
  const count = (output: string): number => output.split(notice).length - 1;
  const failures: string[] = [];
  await writeTextFile(configPath, [...baseConfig, ""].join("\n"));
  const plain = await build("no override");
  if (count(plain) !== 0) {
    failures.push("- a build without overrides printed a deprecation notice");
  }
  await mkdir(overrideDir, { recursive: true });
  await writeTextFile(overridePath, `<nav class="${marker}">custom</nav>\n`);
  try {
    const overridden = await build("site-navigation.html override");
    if (count(overridden) !== 1) {
      failures.push(
        `- expected exactly 1 deprecation notice for the override, got ${count(overridden)}`,
      );
    }
    if (
      !overridden.includes("overrides layouts/_partials/site-navigation.html")
    ) {
      failures.push("- the notice did not name site-navigation.html");
    }
    if (!overridden.includes("ananke-deprecated-site-navigation")) {
      failures.push("- the notice did not show its ignoreLogs id");
    }
    const homepage = await readTextFile(
      join(projectRoot, "public", "index.html"),
    );
    if (!homepage.includes(marker)) {
      failures.push(
        "- the project override of site-navigation.html did not render",
      );
    }
    await writeTextFile(
      configPath,
      [
        "ignoreLogs = ['ananke-deprecated-site-navigation']",
        ...baseConfig,
        "",
      ].join("\n"),
    );
    const suppressed = await build("override with ignoreLogs");
    if (count(suppressed) !== 0) {
      failures.push("- ignoreLogs did not suppress the deprecation notice");
    }
  } finally {
    await rm(overridePath, { force: true });
  }
  if (failures.length > 0) {
    throw new Error(
      [
        "Strict assertion failed: header deprecation notices did not behave as expected.",
        "Failed assertions:",
        ...failures,
      ].join("\n"),
    );
  }
}
/**
 * Main entry point.
 */
async function main(): Promise<void> {
tests/README.md
@@ -1,61 +1,76 @@
# Tests
# Theme tests
This directory holds the theme's automated tests. It is the proof-of-concept
for the testing system tracked in the testing epic.
The tests build against the local theme working tree, including uncommitted changes. No published theme download is needed, except for the optional submodule installation smoke test.
## Commands
Use Node.js 24 or later, a compatible Hugo, and `npm ci`. Install Chromium with `npx playwright install chromium`. Static link checks also require lychee 0.24.2.
| Command | Checks |
| --- | --- |
| `npm test` | Node test runner: feature mini-sites, gate regression tests, and the quickstart installation smoke test |
| `npm run test:fixtures` | Feature mini-sites with Cheerio DOM assertions |
| `npm run test:watch` | Node watch mode for feature and gate tests |
| `npm run test:e2e` | Browser interaction, axe, and no-JavaScript tests |
| `npm run test:coverage-gate` | Parameter and shortcode registration, and test file paths |
| `npm run test:static` | Build diagnostics, HTML validity, and offline internal links and fragments |
| `npm run test:visual` | Screenshots against reviewed CI baselines |
| `npm run test:performance` | Lighthouse budgets, with three runs per URL |
| `npm run test:quickstart` | Direct quickstart installation smoke test |
| `npm run test:quickstart:submodule` | Published submodule installation, which does not test local changes |
The watch command watches imported JavaScript test files. Restart it after changing Hugo templates or fixture content. Each test run rebuilds the affected mini-site.
## Layout
```text
tests/
├── fixtures/site/      # a minimal Hugo site that uses the theme
├── e2e/                # Playwright specs (E2E, accessibility, no-JS)
├── support/            # build-the-fixture + static-server helpers
├── catalog.yaml        # feature -> test manifest for the coverage gate
└── coverage-gate.mjs   # fails CI when a param/shortcode has no test
```
* `fixtures/<feature>/`: one mini-site and its co-located Node tests per migrated feature.
* `fixtures/site/`: the shared browser fixture, with home, list, single, taxonomy, terms, and 404 pages.
* `e2e/`: browser, accessibility, no-JavaScript, and visual tests.
* `support/prepare-site.mjs`: shared local-theme fixture builder.
* `catalog.yaml`: feature registration.
* `unit/`: regression tests for the coverage gate.
* `visual-baselines/`: reviewed screenshots generated in CI.
* `.playwright/`: ignored reports and screenshots.
The legacy build/HTML harness still lives at
`scripts/test-hugo-quickstart.ts` and is being migrated into this structure.
The fixture builder creates a temporary theme symlink and removes it after the build. It passes an explicit base URL, so a developer's `HUGO_BASEURL` cannot send tests to another server. `ANANKE_TEST_PORT` changes the browser server port. Lighthouse uses port 4321; run it separately from browser tests.
## Running
## Add or change a feature
```bash
# Browser end-to-end, accessibility, and progressive-enhancement (no-JS) tests.
# Builds the fixture site against the local theme working tree, serves it, and
# runs Playwright. Requires browsers: `npx playwright install chromium`.
npm run test:e2e
1. Add a fixture that exercises the behaviour. Use a feature mini-site for build and DOM checks, or the shared site for browser checks.
2. Add assertions for the rendered result and relevant interaction, accessibility, and no-JavaScript behaviour.
3. Register the parameter or shortcode in `catalog.yaml` with executable test file paths.
4. Run the relevant tests and `npm run test:coverage-gate`.
5. Update the separate documentation repository for user-facing theme changes.
# Feature -> test coverage gate: fails if an [ananke] param or a shortcode has
# no entry in tests/catalog.yaml.
npm run test:coverage-gate
The gate parses TOML and checks direct values in `[ananke]`, `[ananke.navigation]`, and `[ananke.navigation.classes]`, plus all theme shortcodes. A new unregistered parameter or shortcode fails. Missing, invalid, or out-of-repository test paths fail. Other nested tables remain outside this gate. A registration does not prove that assertions cover every behaviour. Stale entries produce warnings.
# Legacy quickstart build/assertion harness.
npm test
```
## Static checks
## How the fixture is built
Unexpected Hugo warnings, deprecations, and path warnings fail the shared fixture build. Two exact warnings are required for the intentionally invalid navigation fixtures (`unknown` and `invalid`); a missing or repeated warning also fails. The deprecated-header mini-site also requires its one expected deprecation warning and tests suppression. Other feature mini-sites allow no warnings.
`tests/support/prepare-site.mjs` creates a temporary themes directory with a
symlink to the repository root and runs Hugo against `tests/fixtures/site`, so
the suite always exercises the **current** theme code (including uncommitted
changes) without committing an absolute-path symlink. The built site is served
by `tests/support/dev-server.mjs`, which Playwright launches via
`webServer` in `playwright.config.ts`.
HTML validation uses `html-validate:standard` for validity rather than formatting preferences. Hugo's built-in `page/1/` redirects omit an explicit body. The gate checks their redirect metadata, supplies the implied body with the DOM parser, and validates the resulting document. Other pages are validated as emitted.
## Adding a test for a feature
Lychee checks local files and fragments offline. Absolute fixture URLs are mapped to files, so missing pages and assets fail without network access. External URLs are outside this gate. The contact form endpoint is a static test fixture and sends no messages.
When you add or change a feature:
## Visual baselines
1. If it has a config parameter or shortcode, add fixture content that
   exercises it under `tests/fixtures/site/`.
2. Add a spec under `tests/e2e/` (interaction, output, or accessibility).
3. Register it in `tests/catalog.yaml` so the coverage gate is satisfied.
Both CI generation and comparison use `mcr.microsoft.com/playwright:v1.65.1-noble`, matching the locked Playwright version. Update both when upgrading Playwright. The suite covers six page types at 375 and 1280 pixels. It fixes time and locale, reduces motion, disables animations, and waits for fonts.
The coverage gate (`npm run test:coverage-gate`) fails if a new `[ananke]`
parameter or shortcode is not listed in the catalog with at least one test, so
tests stay in sync with features.
1. Push the branch and run **Theme tests** with **Generate visual baselines for review as an artifact** enabled.
2. Download `browser-results` from that run and inspect every image.
3. Copy the generated `visual-baselines/` tree to `tests/visual-baselines/` and commit the reviewed images with the change.
4. Run CI normally to compare against those baselines.
## Accessibility note
Generate baselines in CI, not locally. Normal comparison uses `updateSnapshots: "none"`: missing baselines and pixel differences fail. Baseline generation uploads images for review; it does not commit or publish them. Initial CI comparisons will fail until reviewed baselines are added. Dark palette coverage can be added when that feature is available.
The axe suite catches roughly 30-40% of WCAG issues. It is a floor, not a
guarantee â€” pair it with manual keyboard and screen-reader checks.
## Lighthouse budgets
The proposed initial budgets in `lighthouserc.cjs` are performance â‰¥ 0.90, accessibility = 1.00, SEO â‰¥ 0.90, JavaScript â‰¤ 16 KiB, and CSS â‰¤ 32 KiB. Resource limits use Lighthouse's measured transfer bytes. The fixture server negotiates gzip for text responses, as a production static host normally does; it also supports uncompressed clients. The limits have not been lowered. Reports are saved locally and uploaded as CI artifacts. Uploads to a public Lighthouse server are disabled.
A local run with Hugo 0.170.0 and Playwright Chromium passed all nine runs: performance 1.00, accessibility 1.00, SEO 0.92–1.00, and CSS transfers of 15,478–15,921 bytes. Before the fixes, the server sent about 80–81 KB of uncompressed CSS, and mobile menu enhancement caused layout shifts near 0.45. Early mobile-menu styling reduced the measured shifts to about 0.03. The full Tachyons bundle is retained. These are local measurements; CI must establish its own results.
## Accessibility
Axe checks WCAG 2.2 AA rules across page types, but cannot establish full conformance. Use the [manual testing guide](manual-tests.md) as well. The contrast defects tracked in [#1015](https://github.com/gohugo-ananke/ananke/issues/1015) are fixed, and all page-type audits require zero violations. The suite includes the contact form and checks content links on hover and keyboard focus.
See [the issue status and remaining work](testing-status.md).
tests/catalog.yaml
@@ -4,8 +4,8 @@
# listed here with at least one test reference, or `npm run test:coverage-gate`
# fails. This forces a test to accompany each new or changed feature.
#
# `tests` entries are free-form references (spec files or fixture folders) for
# humans; the gate only checks that the key is present and has a non-empty list.
# `tests` entries must name existing executable spec or quickstart files.
# This checks registration and paths, not whether assertions cover every behaviour.
params:
  ananke.responsive_image_widths:
@@ -15,7 +15,7 @@
  ananke.show_categories:
    tests: ["scripts/test-hugo-quickstart.ts"]
  ananke.copy_code:
    tests: ["tests/e2e/copy-button.spec.ts"]
    tests: ["tests/e2e/copy-button.spec.ts", "tests/fixtures/copy-code/copy-code.test.mjs"]
  ananke.navigation.submenu_mode:
    tests: ["tests/e2e/navigation-modes.spec.ts"]
  ananke.navigation.classes.nav:
@@ -44,9 +44,11 @@
    tests: ["tests/e2e/navigation.spec.ts"]
shortcodes:
  edit-page:
    tests: ["tests/e2e/shortcodes.spec.ts"]
  form-contact:
    tests: ["scripts/test-hugo-quickstart.ts"] # TODO: add a dedicated form-contact test
    tests: ["tests/e2e/shortcodes.spec.ts"]
  page-index:
    tests: ["scripts/test-hugo-quickstart.ts"] # TODO: add a dedicated page-index test
    tests: ["tests/e2e/shortcodes.spec.ts"]
  since:
    tests: ["scripts/test-hugo-quickstart.ts"] # TODO: add a dedicated since test
    tests: ["tests/e2e/shortcodes.spec.ts"]
tests/coverage-gate.mjs
@@ -16,13 +16,14 @@
 * here (not the deep [ananke.social.networks.*] catalog). Widen GATED_TABLES
 * as the gate matures.
 */
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import TOML from "@iarna/toml";
import { parse } from "yaml";
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "..");
const repoRoot = resolve(process.argv[2] || join(here, ".."));
/** Tables in config/_default/params.toml whose direct keys are gated. */
const GATED_TABLES = [
@@ -37,18 +38,15 @@
    join(repoRoot, "config", "_default", "params.toml"),
    "utf8",
  );
  const config = TOML.parse(toml);
  const keys = new Set();
  let table = null;
  for (const raw of toml.split("\n")) {
    const line = raw.trim();
    if (line.startsWith("[")) {
      const name = line.slice(1, -1).trim();
      table = GATED_TABLES.includes(name) ? name : null;
      continue;
  for (const table of GATED_TABLES) {
    const values = table.split(".").reduce((node, key) => node?.[key], config);
    for (const [key, value] of Object.entries(values || {})) {
      if (value === null || typeof value !== "object" || Array.isArray(value)) {
        keys.add(`${table}.${key}`);
    }
    if (!table || line === "" || line.startsWith("#")) continue;
    const eq = line.indexOf("=");
    if (eq > 0) keys.add(`${table}.${line.slice(0, eq).trim()}`);
    }
  }
  return keys;
}
@@ -73,13 +71,39 @@
  return out;
}
const catalog = parse(readFileSync(join(here, "catalog.yaml"), "utf8")) || {};
const catalog =
  parse(readFileSync(join(repoRoot, "tests", "catalog.yaml"), "utf8")) || {};
const params = collectAnankeParams();
const shortcodes = collectShortcodes();
const catParams = catalogued(catalog.params);
const catShortcodes = catalogued(catalog.shortcodes);
const errors = [];
for (const section of [catalog.params, catalog.shortcodes]) {
  for (const [feature, entry] of Object.entries(section || {})) {
    for (const ref of entry?.tests || []) {
      if (typeof ref !== "string") {
        errors.push(`${feature}: test reference must be a path string`);
        continue;
      }
      const path = resolve(repoRoot, ref);
      const local = relative(repoRoot, path);
      if (
        isAbsolute(ref) ||
        local.startsWith("..") ||
        local.split(/[\\/]/).includes("scratch") ||
        !(
          /\.(spec|test)\.(ts|mjs)$/.test(ref) ||
          ref === "scripts/test-hugo-quickstart.ts"
        )
      ) {
        errors.push(`${feature}: invalid test path '${ref}'`);
      } else if (!existsSync(path) || !statSync(path).isFile()) {
        errors.push(`${feature}: test file '${ref}' does not exist`);
      }
    }
  }
}
for (const p of params) {
  if (!catParams.has(p))
    errors.push(`param '${p}' has no test in tests/catalog.yaml`);
tests/e2e/accessibility.spec.ts
@@ -13,6 +13,7 @@
  "section list": "/posts/",
  "single page": "/posts/hello/",
  "standalone page": "/about/",
  "shortcode page with contact form": "/shortcodes/",
  "custom header layout": "/header-layout/",
  "taxonomy terms": "/tags/",
  "taxonomy term": "/tags/alpha/",
@@ -21,26 +22,10 @@
const TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
/**
 * Page types with a known, tracked WCAG AA contrast failure (Tachyons `gray`
 * #777 on summary cards and single-page bylines). Marked as expected failures
 * so the suite is green while the bug is open; when #1015 is fixed these will
 * start passing and Playwright will flag the stale annotation for removal.
 */
const KNOWN_FAILURES = new Set([
  "section list",
  "single page",
  "taxonomy terms",
  "taxonomy term",
]);
for (const [name, path] of Object.entries(PAGES)) {
  test(`${name} has no automatically detectable a11y violations`, async ({
    page,
  }) => {
    if (KNOWN_FAILURES.has(name)) {
      test.fail(true, "Known WCAG AA contrast issue, tracked in #1015");
    }
    await page.goto(path);
    const results = await new AxeBuilder({ page }).withTags(TAGS).analyze();
    expect(results.violations).toEqual([]);
@@ -95,3 +80,13 @@
    .analyze();
  expect(results.violations).toEqual([]);
});
for (const state of ["focus", "hover"] as const) {
  test(`content links retain AA contrast on ${state}`, async ({ page }) => {
    await page.goto("/posts/hello/");
    const link = page.locator('main a[href="/tags/alpha/"]').first();
    await link[state]();
    const results = await new AxeBuilder({ page }).withTags(TAGS).analyze();
    expect(results.violations).toEqual([]);
  });
}
tests/e2e/copy-button.spec.ts
@@ -7,6 +7,7 @@
    await page.goto(POST);
    // Exactly one fenced block on this page â†’ one .code-block wrapper.
    await expect(page.locator(".code-block")).toHaveCount(1);
    await expect(page.locator("article p code")).toHaveText("code");
    // Inline `code` lives outside a .code-block wrapper.
    await expect(page.locator(".code-block code")).toHaveCount(1);
  });
tests/e2e/navigation.spec.ts
@@ -349,3 +349,37 @@
    if (box) expect(box.x + box.width).toBeLessThanOrEqual(320);
  });
});
test("mobile navigation is collapsed before DOMContentLoaded", async ({
  page,
  baseURL,
}) => {
  await page.setViewportSize({ width: 375, height: 800 });
  let release: () => void = () => {};
  const deferredScript = new Promise<void>((resolve) => {
    release = resolve;
  });
  await page.route("**/__deferred-fixture.js", async (route) => {
    await deferredScript;
    await route.fulfill({ contentType: "text/javascript", body: "" });
  });
  await page.route(new URL("/", baseURL).href, async (route) => {
    const response = await route.fetch();
    const html = (await response.text()).replace(
      "</head>",
      '<script defer src="/__deferred-fixture.js"></script></head>',
    );
    await route.fulfill({ response, body: html });
  });
  try {
    await page.goto("/", { waitUntil: "commit" });
    await expect(page.locator(".ananke-nav-brand")).toBeVisible();
    expect(await page.evaluate(() => document.readyState)).not.toBe("complete");
    await expect(page.locator(".ananke-nav-panel")).toBeHidden();
  } finally {
    release();
  }
  await page.waitForLoadState("domcontentloaded");
  await page.getByRole("button", { name: "Menu", exact: true }).click();
  await expect(page.locator(".ananke-nav-panel")).toBeVisible();
});
tests/e2e/no-js.spec.ts
New file
@@ -0,0 +1,51 @@
import { expect, test } from "@playwright/test";
test.use({ javaScriptEnabled: false });
for (const width of [375, 1280]) {
  test(`navigation and code selection work without JavaScript at ${width}px`, async ({
    page,
  }) => {
    await page.setViewportSize({ width, height: 800 });
    await page.goto("/");
    await page
      .locator("header nav")
      .getByRole("link", { name: "Hello World", exact: true })
      .click();
    await expect(page).toHaveURL(/\/posts\/hello\/$/);
    await expect(page.locator(".code-copy")).toBeHidden();
    await page.locator("pre code").selectText();
    expect(
      await page.evaluate(() => window.getSelection()?.toString()),
    ).toContain("copy_code = true");
    await page
      .locator("header nav")
      .getByRole("link", { name: "Tags", exact: true })
      .click();
    await expect(page).toHaveURL(/\/tags\/$/);
    await page.locator("main").getByRole("link", { name: /alpha/i }).click();
    await expect(page).toHaveURL(/\/tags\/alpha\/$/);
  });
}
test("contact form keeps its accessible fields without JavaScript", async ({
  page,
}) => {
  await page.goto("/shortcodes/");
  const form = page.locator("main form");
  await form
    .getByRole("textbox", { name: "Your Name", exact: true })
    .fill("Test visitor");
  const email = form.getByRole("textbox", {
    name: "Email Address",
    exact: true,
  });
  await email.fill("visitor@example.com");
  await expect(email).toHaveAccessibleDescription(
    "An email address is required.",
  );
  await form
    .getByRole("textbox", { name: "Message", exact: true })
    .fill("Fixture message");
  await expect(form.getByRole("button", { name: "Send" })).toBeVisible();
});
tests/e2e/shortcodes.spec.ts
New file
@@ -0,0 +1,96 @@
import { expect, test } from "@playwright/test";
test.beforeEach(async ({ page }) => {
  await page.goto("/shortcodes/");
});
test("form-contact renders fields, labels, and the configured action", async ({
  page,
}) => {
  const form = page.locator("main form");
  await expect(form).toHaveAttribute("action", "/contact-submit/");
  await expect(form).toHaveAttribute("method", "POST");
  await expect(form.locator('label[for="name"]')).toHaveText("Your Name");
  await expect(form.locator('label[for="email"]')).toHaveText("Email Address");
  await expect(form.locator('label[for="message"]')).toHaveText("Message");
  await expect(
    form.getByRole("textbox", { name: "Your Name", exact: true }),
  ).toHaveAttribute("required", "");
  await expect(
    form.getByRole("textbox", { name: "Email Address", exact: true }),
  ).toHaveAttribute("type", "email");
  await expect(
    form.getByRole("textbox", { name: "Message", exact: true }),
  ).toBeVisible();
  await expect(
    form.getByRole("textbox", { name: "Email Address", exact: true }),
  ).toHaveAccessibleDescription("An email address is required.");
  await expect(form.getByRole("button", { name: "Send" })).toBeVisible();
});
test("since accepts positional, named, and front matter versions", async ({
  page,
}) => {
  for (const version of ["2.18.0", "2.19.0", "2.17.0"]) {
    await expect(
      page.locator("main span").filter({ hasText: `since ${version}` }),
    ).toBeVisible();
  }
});
test("page-index links to regular pages", async ({ page }) => {
  await page
    .locator("main")
    .getByRole("link", { name: "Hello World", exact: true })
    .click();
  await expect(page).toHaveURL(/\/posts\/hello\/$/);
});
test("edit-page resolves configured, positional, and named branches", async ({
  page,
}) => {
  const links = page
    .locator("main")
    .getByRole("link", { name: "Improve this page on GitHub" });
  await expect(links).toHaveCount(3);
  for (const [index, branch] of [
    "main",
    "development",
    "test-branch",
  ].entries()) {
    await expect(links.nth(index)).toHaveAttribute(
      "href",
      `https://github.com/gohugo-ananke/ananke/edit/${branch}/content/shortcodes.md`,
    );
    await expect(links.nth(index)).toHaveAttribute("rel", "noopener");
  }
});
test("form fields work with keyboard labels and native validation", async ({
  page,
}) => {
  const form = page.locator("main form");
  const name = form.getByRole("textbox", { name: "Your Name", exact: true });
  const email = form.getByRole("textbox", {
    name: "Email Address",
    exact: true,
  });
  const message = form.getByRole("textbox", { name: "Message", exact: true });
  await form.locator('label[for="name"]').click();
  await expect(name).toBeFocused();
  await name.fill("Test visitor");
  await page.keyboard.press("Tab");
  await expect(email).toBeFocused();
  await email.fill("invalid");
  expect(
    await email.evaluate(
      (element: HTMLInputElement) => element.validity.typeMismatch,
    ),
  ).toBe(true);
  await email.fill("visitor@example.com");
  await page.keyboard.press("Tab");
  await expect(message).toBeFocused();
  await message.fill("Fixture message");
  await page.keyboard.press("Tab");
  await expect(form.getByRole("button", { name: "Send" })).toBeFocused();
});
tests/e2e/visual.spec.ts
New file
@@ -0,0 +1,16 @@
import { expect, test } from "@playwright/test";
import { pageTypes } from "../support/pages.ts";
for (const [name, path] of Object.entries(pageTypes)) {
  for (const width of [375, 1280]) {
    test(`${name} at ${width}px`, async ({ page }) => {
      await page.setViewportSize({ width, height: 900 });
      await page.clock.setFixedTime(new Date("2026-01-10T12:00:00Z"));
      await page.goto(path);
      await page.evaluate(() => document.fonts.ready);
      await expect(page).toHaveScreenshot(`${name}-${width}.png`, {
        fullPage: true,
      });
    });
  }
}
tests/fixtures/copy-code/content/example.md
New file
@@ -0,0 +1,7 @@
---
title: Code without a copy button
---
```toml
copy_code = false
```
tests/fixtures/copy-code/copy-code.test.mjs
New file
@@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { load } from "cheerio";
import { buildFixtureSite } from "../../support/prepare-site.mjs";
const source = dirname(fileURLToPath(import.meta.url));
test("copy_code=false disables the site-wide code wrapper and button (#986)", () => {
  const output = buildFixtureSite({ source });
  const $ = load(readFileSync(join(output, "example/index.html"), "utf8"));
  assert.equal($(".code-copy, .code-block").length, 0);
  assert.match($("pre code").text(), /copy_code = false/);
});
tests/fixtures/copy-code/hugo.toml
New file
@@ -0,0 +1,4 @@
title = "Copy code fixture"
theme = "ananke"
[params.ananke]
copy_code = false
tests/fixtures/date-settings/date-settings.test.mjs
New file
@@ -0,0 +1,174 @@
import assert from "node:assert/strict";
import {
  mkdirSync,
  mkdtempSync,
  readFileSync,
  rmSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { load } from "cheerio";
import { buildFixtureSite } from "../../support/prepare-site.mjs";
const cases = [
  { label: "defaults", single: true, summary: true },
  {
    label: "shared site fallback",
    site: { show_date: false },
    single: false,
    summary: false,
  },
  {
    label: "specific site over shared site",
    site: { show_date: false, show_single_date: true },
    single: true,
    summary: false,
  },
  {
    label: "summary site override",
    site: { show_date: true, show_summary_date: false },
    single: true,
    summary: false,
  },
  {
    label: "page shared over specific site",
    site: { show_single_date: false, show_summary_date: false },
    page: { show_date: true },
    single: true,
    summary: true,
  },
  {
    label: "page shared false over site true",
    site: { show_single_date: true, show_summary_date: true },
    page: { show_date: false },
    single: false,
    summary: false,
  },
  {
    label: "specific page over shared page",
    page: { show_date: false, show_single_date: true },
    single: true,
    summary: false,
  },
  {
    label: "summary page over shared page",
    page: { show_date: true, show_summary_date: false },
    single: true,
    summary: false,
  },
  {
    label: "opposite independent settings",
    page: { show_single_date: false, show_summary_date: true },
    single: false,
    summary: true,
  },
  {
    label: "cascade over site",
    site: { show_summary_date: true },
    cascade: { show_summary_date: false },
    single: true,
    summary: false,
  },
  {
    label: "page over cascade",
    cascade: { show_single_date: false, show_summary_date: false },
    page: { show_single_date: true, show_summary_date: true },
    single: true,
    summary: true,
  },
  {
    label: "page map over cascade map",
    cascade: { show_summary_date: false },
    page: { show_date: true },
    single: true,
    summary: true,
  },
  {
    label: "undated page",
    page: { show_single_date: true, show_summary_date: true },
    undated: true,
    single: false,
    summary: false,
  },
];
const settings = (values = {}) =>
  Object.entries(values).map(([key, value]) => `${key} = ${value}`);
for (const variant of ["compact", "image", "post"]) {
  for (const scenario of cases) {
    test(`${variant}: ${scenario.label} (#1112)`, () => {
      const source = mkdtempSync(join(tmpdir(), "ananke-date-settings-"));
      try {
        mkdirSync(join(source, "content/cards"), { recursive: true });
        writeFileSync(
          join(source, "hugo.toml"),
          [
            'theme = "ananke"',
            'title = "Date fixture"',
            "[params]",
            'mainSections = ["cards"]',
            "[params.ananke.pages]",
            `show_list_images = ${variant === "image"}`,
            ...settings(scenario.site),
            "",
          ].join("\n"),
        );
        writeFileSync(
          join(source, "content/cards/_index.md"),
          [
            "+++",
            'title = "Cards"',
            ...(variant === "post" ? ['type = "post"'] : []),
            ...(scenario.cascade
              ? ["[cascade.params.ananke]", ...settings(scenario.cascade)]
              : []),
            "+++",
            "",
          ].join("\n"),
        );
        for (const name of ["with-image", "without-image"]) {
          writeFileSync(
            join(source, `content/cards/${name}.md`),
            [
              "+++",
              `title = "${name}"`,
              ...(scenario.undated ? [] : ["date = 2024-01-15T00:00:00Z"]),
              ...(variant === "post" ? ['type = "post"'] : []),
              ...(name === "with-image"
                ? ['featured_image = "/images/card.jpg"']
                : []),
              ...(scenario.page
                ? ["[params.ananke]", ...settings(scenario.page)]
                : []),
              "+++",
              "",
              "Date setting fixture.",
              "",
            ].join("\n"),
          );
        }
        const output = buildFixtureSite({ source });
        for (const name of ["with-image", "without-image"]) {
          const $ = load(
            readFileSync(join(output, `cards/${name}/index.html`), "utf8"),
          );
          assert.equal(
            $("time.f6.mv4.dib.tracked").length,
            scenario.single ? 1 : 0,
          );
        }
        for (const file of ["cards/index.html", "index.html"]) {
          const $ = load(readFileSync(join(output, file), "utf8"));
          assert.equal(
            $('time[datetime="2024-01-15T00:00:00Z"]').length,
            scenario.summary ? 2 : 0,
            file,
          );
        }
      } finally {
        rmSync(source, { recursive: true, force: true });
      }
    });
  }
}
tests/fixtures/header-deprecations/header-deprecations.test.mjs
New file
@@ -0,0 +1,52 @@
import assert from "node:assert/strict";
import {
  mkdirSync,
  mkdtempSync,
  readFileSync,
  rmSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { load } from "cheerio";
import { buildFixtureSite } from "../../support/prepare-site.mjs";
test("header override deprecation is emitted once and can be suppressed (#1120)", () => {
  const source = mkdtempSync(join(tmpdir(), "ananke-header-override-"));
  const config = 'theme = "ananke"\ntitle = "Header override"\n';
  try {
    writeFileSync(join(source, "hugo.toml"), config);
    let output = "";
    const onOutput = (log) => {
      output = log;
    };
    buildFixtureSite({ source, onOutput });
    assert.doesNotMatch(output, /ananke\/DEPR/);
    const partials = join(source, "layouts/_partials");
    mkdirSync(partials, { recursive: true });
    writeFileSync(
      join(partials, "site-navigation.html"),
      '<nav class="fixture-deprecated-nav">Custom navigation</nav>',
    );
    const destination = buildFixtureSite({
      source,
      onOutput,
      expectedWarnings: [
        /^ananke\/DEPR Your project overrides layouts\/_partials\/site-navigation\.html\. Overriding the header partials is deprecated/,
      ],
    });
    assert.equal(output.split("ananke/DEPR").length - 1, 1);
    assert.match(output, /ananke-deprecated-site-navigation/);
    const $ = load(readFileSync(join(destination, "index.html"), "utf8"));
    assert.equal($("nav.fixture-deprecated-nav").length, 1);
    writeFileSync(
      join(source, "hugo.toml"),
      `ignoreLogs = ["ananke-deprecated-site-navigation"]\n${config}`,
    );
    buildFixtureSite({ source, onOutput });
    assert.doesNotMatch(output, /ananke\/DEPR/);
  } finally {
    rmSync(source, { recursive: true, force: true });
  }
});
tests/fixtures/header-section/content/custom.md
New file
@@ -0,0 +1,7 @@
---
title: custom header
featured_image: /images/header.jpg
header_section_class: fixture-custom-height ph3
---
Body.
tests/fixtures/header-section/content/default.md
New file
@@ -0,0 +1,6 @@
---
title: default header
featured_image: /images/header.jpg
---
Body.
tests/fixtures/header-section/header-section.test.mjs
New file
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { load } from "cheerio";
import { buildFixtureSite } from "../../support/prepare-site.mjs";
const source = dirname(fileURLToPath(import.meta.url));
test("header_section_class overrides only its page (#504)", () => {
  const output = buildFixtureSite({ source });
  const custom = load(readFileSync(join(output, "custom/index.html"), "utf8"));
  const defaults = load(
    readFileSync(join(output, "default/index.html"), "utf8"),
  );
  assert.equal(custom("header .fixture-custom-height").length, 1);
  assert.equal(defaults("header .fixture-custom-height").length, 0);
  assert.equal(defaults("header .tc-l.pv6.ph3.ph4-ns").length, 1);
});
tests/fixtures/header-section/hugo.toml
New file
@@ -0,0 +1,2 @@
title = "Header fixture"
theme = "ananke"
tests/fixtures/list-cards/content/cards/_index.md
New file
@@ -0,0 +1,3 @@
---
title: Cards
---
tests/fixtures/list-cards/content/cards/image.md
New file
@@ -0,0 +1,7 @@
---
title: image card
date: 2026-01-01
featured_image: /images/card.jpg
---
Card summary.
tests/fixtures/list-cards/content/cards/plain.md
New file
@@ -0,0 +1,6 @@
---
title: plain card
date: 2026-01-01
---
Card summary.
tests/fixtures/list-cards/hugo.toml
New file
@@ -0,0 +1,2 @@
title = "Cards fixture"
theme = "ananke"
tests/fixtures/list-cards/images.toml
New file
@@ -0,0 +1,3 @@
[params.ananke.pages]
show_list_images = true
show_date = false
tests/fixtures/list-cards/list-cards.test.mjs
New file
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { load } from "cheerio";
import { buildFixtureSite } from "../../support/prepare-site.mjs";
const source = dirname(fileURLToPath(import.meta.url));
for (const [name, config, images, dates, sectionTitles] of [
  ["defaults", "hugo.toml", 0, 2, 2],
  ["image cards without dates", "hugo.toml,images.toml", 1, 0, 0],
  [
    "plain cards without dates or section titles",
    "hugo.toml,plain.toml",
    0,
    0,
    0,
  ],
]) {
  test(`list cards: ${name} (#217, #1109)`, () => {
    const output = buildFixtureSite({ source, config });
    const $ = load(readFileSync(join(output, "cards/index.html"), "utf8"));
    assert.equal($("main img.img").length, images);
    assert.equal($("main time[datetime]").length, dates);
    assert.equal(
      $("main span.f6.db").filter((_, el) => $(el).text() === "Cards").length,
      sectionTitles,
    );
    assert.equal($("main h1 a").length, 2);
  });
}
tests/fixtures/list-cards/plain.toml
New file
@@ -0,0 +1,3 @@
[params.ananke.pages]
show_date = false
show_section_title = false
tests/fixtures/site/content/shortcodes.md
New file
@@ -0,0 +1,24 @@
---
title: Shortcode fixtures
since: 2.17.0
---
## Contact
{{< form-contact action="/contact-submit/" >}}
## Versions
{{< since "2.18.0" >}}
{{< since version="2.19.0" >}}
{{< since >}}
## Page index
{{< page-index >}}
## Edit links
{{< edit-page >}}
{{< edit-page "development" >}}
{{< edit-page branch="test-branch" >}}
tests/fixtures/site/hugo.toml
@@ -9,6 +9,8 @@
[params]
mainSections = ["posts"]
description = "A local fixture for Ananke theme rendering, accessibility, and performance tests."
favicon = "/favicon.ico"
[params.ananke]
show_recent_posts = true
@@ -74,3 +76,7 @@
name = "About"
pageRef = "/about/"
weight = 20
[params.ananke.shortcodes.edit_page]
repo_url = "https://github.com/gohugo-ananke/ananke"
branch = "main"
tests/fixtures/site/static/contact-submit/index.html
New file
@@ -0,0 +1,2 @@
<!doctype html>
<html lang="en"><head><title>Fixture form endpoint</title></head><body><p>Test endpoint. No message is sent.</p></body></html>
tests/fixtures/site/static/favicon.ico
Binary files differ
tests/lychee.toml
New file
@@ -0,0 +1,5 @@
# Offline fixture checks remap the site's absolute HTTP URLs to files.
# External URLs are left to the separate site/documentation link audits.
no_progress = true
include_fragments = "anchor-only"
index_files = ["index.html"]
tests/manual-tests.md
New file
@@ -0,0 +1,58 @@
# Manual tests
Manual checks recur when a change can affect their result. A successful check applies to the tested commit, environment, and scope; it is not permanent accessibility or visual approval. Run the automated suites first. Unchecked items have not been verified.
## When to run them
| Trigger | Manual work |
| --- | --- |
| First setup of this suite | Review the initial CI-generated screenshots and run the full accessibility checklist to establish a recorded starting point. |
| Navigation, content structure, form, code-copy, CSS, or layout changes | Repeat the affected keyboard, screen-reader, contrast, zoom, and no-JavaScript checks on the changed page types. |
| Release candidate | Run a representative keyboard and screen-reader smoke test across home, list, single, terms, taxonomy, and 404 pages; review unresolved findings before release. |
| Browser or assistive-technology changes that affect supported users | Repeat representative navigation, reading-order, and form checks in the changed environment. |
| Intended visual change, browser upgrade, font change, or capture-environment change | Review the screenshot differences and approve replacement baselines generated in CI. |
| A new page type or viewport enters the visual suite | Review its first CI-generated baseline. |
## Visual baseline review
Initial baseline approval is a one-time setup step for that baseline set. Screenshot comparisons run automatically in CI after that. Human review recurs when a difference is intentional or when the capture environment changes; an unchanged screenshot does not need a fresh manual review on every run.
Generate baseline images with the workflow described in [the visual baseline guide](README.md#visual-baselines). Check page content, navigation, responsive layout, clipping, overlap, focus appearance where captured, and unexpected missing elements at each viewport. Record the CI run and reviewed commit. Review the actual differences before accepting replacement images; do not update baselines only to silence a failure.
## Accessibility checklist
Use the checks below for the affected scope. A release smoke test covers representative pages and interactions; a substantial navigation or layout change warrants the full checklist.
* [ ] Navigate each page type using only Tab, Shift+Tab, Enter, Space, and Escape. Confirm logical focus order, visible focus, and no keyboard traps.
* [ ] Open and close desktop submenus and the mobile menu. Confirm focus returns to the correct control, and expanded states are announced.
* [ ] Read home, list, single, terms, taxonomy, and 404 pages with a screen reader. Check document language, page titles, heading order, landmarks, link names, and reading order.
* [ ] Confirm form controls have useful accessible names, instructions, required states, and understandable validation feedback.
* [ ] Check code copying and feedback with keyboard and screen reader. Confirm code can be selected when JavaScript is disabled.
* [ ] Disable JavaScript. Follow primary and child navigation links, read content, and check that hidden enhancement controls leave no empty stops.
* [ ] Check text at 200% zoom and reflow at 320 CSS pixels. Confirm content remains readable without unnecessary horizontal scrolling.
* [ ] Check contrast for normal text, large text, focus indicators, controls, and text on featured images. Test hover, focus, selected, and disabled states.
* [ ] Check meaningful image alternatives and confirm decorative images do not add noise.
* [ ] Check pointer target size, mobile orientation, reduced motion, and forced colours.
The automated suite now requires zero violations, including contrast and form labels. This does not mean these manual checks have passed. Record any manual defects separately.
## Record a result
Put results in the pull request or release record, and link any defects. Keep the checklist as the procedure rather than checking it off permanently. Use this template:
```text
Date:
Tested commit:
Tester:
Scope and page types:
Browser and version:
Operating system and version:
Screen reader or other assistive technology and version:
Viewport and zoom:
Checks completed:
Result: passed / failed / not run
Findings and issue links:
Screenshots or CI run:
```
Axe results and accessible-name assertions do not replace a person using a screen reader. Leave manual checks marked as not run until that work is done.
tests/quickstart.test.mjs
New file
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { test } from "node:test";
test("documented quickstart installs and builds the local theme", () => {
  const result = spawnSync(
    process.execPath,
    ["scripts/test-hugo-quickstart.ts"],
    { encoding: "utf8" },
  );
  assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
});
tests/static/server.test.mjs
New file
@@ -0,0 +1,67 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { get } from "node:http";
import { test } from "node:test";
import { gunzipSync } from "node:zlib";
import { load } from "cheerio";
function request(url, encoding) {
  return new Promise((resolve, reject) => {
    get(url, { headers: { "Accept-Encoding": encoding } }, (response) => {
      const chunks = [];
      response.on("data", (chunk) => chunks.push(chunk));
      response.on("end", () =>
        resolve({
          status: response.statusCode,
          headers: response.headers,
          body: Buffer.concat(chunks),
        }),
      );
      response.on("error", reject);
    }).on("error", reject);
  });
}
test("fixture hosting negotiates gzip without changing content", {
  timeout: 15_000,
}, async (t) => {
  const server = spawn(process.execPath, ["tests/support/dev-server.mjs"], {
    env: { ...process.env, ANANKE_TEST_PORT: "0" },
    stdio: ["ignore", "pipe", "pipe"],
  });
  t.after(async () => {
    server.kill();
    await once(server, "exit");
  });
  const origin = await new Promise((resolve, reject) => {
    let log = "";
    server.on("error", reject);
    server.stdout.on("data", (chunk) => {
      log += chunk;
      const match = log.match(
        /Fixture site served at (http:\/\/localhost:\d+\/)/,
      );
      if (match) resolve(match[1]);
    });
    server.once("exit", (code) =>
      reject(new Error(`Fixture server exited ${code}: ${log}`)),
    );
  });
  const html = await request(origin, "identity");
  assert.equal(html.status, 200);
  const $ = load(html.body.toString());
  const stylesheet = new URL(
    $('link[rel="stylesheet"]').first().attr("href"),
    origin,
  );
  const plain = await request(stylesheet, "identity");
  const gzip = await request(stylesheet, "br, gzip");
  assert.equal(gzip.headers["content-encoding"], "gzip");
  assert.equal(gzip.headers.vary, "Accept-Encoding");
  assert.deepEqual(gunzipSync(gzip.body), plain.body);
  assert.ok(gzip.body.length < plain.body.length);
  const excluded = await request(stylesheet, "gzip;q=0, identity");
  assert.equal(excluded.headers["content-encoding"], undefined);
  assert.deepEqual(excluded.body, plain.body);
});
tests/static/static-gates.test.mjs
New file
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
function check(script, html) {
  const root = mkdtempSync(join(tmpdir(), "ananke-static-gate-"));
  try {
    writeFileSync(join(root, "index.html"), html);
    return spawnSync(process.execPath, [script, root], { encoding: "utf8" });
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
}
test("invalid markup fails the markup gate", () => {
  const result = check(
    "tests/support/check-markup.mjs",
    '<!doctype html><html lang="en"><head><title>Invalid</title></head><body><ul><p>Invalid list child</p></ul></body></html>',
  );
  assert.equal(result.status, 1);
  assert.match(result.stderr, /element-permitted-content/);
});
test("missing internal files fail the link gate", () => {
  const result = check(
    "tests/support/check-links.mjs",
    '<a href="http://localhost:4321/missing/">Missing page</a>',
  );
  assert.equal(result.status, 2);
  assert.match(result.stdout + result.stderr, /File not found/);
});
test("missing fragments fail the link gate", () => {
  const result = check(
    "tests/support/check-links.mjs",
    '<a href="#missing">Missing anchor</a>',
  );
  assert.equal(result.status, 2);
  assert.match(result.stdout + result.stderr, /[Ff]ragment/);
});
tests/support/check-links.mjs
New file
@@ -0,0 +1,22 @@
import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
const root = resolve(process.argv[2] || "tests/fixtures/site/public");
const port = process.env.ANANKE_TEST_PORT || 4321;
const result = spawnSync(
  "lychee",
  [
    "--config",
    "tests/lychee.toml",
    "--offline",
    "--root-dir",
    root,
    "--remap",
    `^http://localhost:${port}/(.*) ${pathToFileURL(root).href}/$1`,
    `${root}/**/*.html`,
  ],
  { stdio: "inherit" },
);
if (result.error) throw result.error;
process.exitCode = result.status ?? 1;
tests/support/check-markup.mjs
New file
@@ -0,0 +1,30 @@
import assert from "node:assert/strict";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { load } from "cheerio";
import { HtmlValidate } from "html-validate";
const validator = new HtmlValidate({ extends: ["html-validate:standard"] });
let count = 0;
async function validate(dir) {
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) await validate(path);
    else if (entry.name.endsWith(".html")) {
      let source = readFileSync(path, "utf8");
      // Hugo's built-in pagination redirects omit <body>. Verify the redirect
      // and supply its implied empty body before validating the document.
      if (/[/\\]page[/\\]1[/\\]index.html$/.test(path)) {
        const $ = load(source);
        assert.equal($("meta[http-equiv=refresh]").length, 1, path);
        assert.ok($("link[rel=canonical]").attr("href"), path);
        source = $.html();
      }
      const report = await validator.validateString(source, path);
      assert.ok(report.valid, JSON.stringify(report.results, null, 2));
      count++;
    }
  }
}
await validate(process.argv[2] || "tests/fixtures/site/public");
console.log(`Markup gate passed: ${count} HTML files.`);
tests/support/dev-server.mjs
@@ -9,6 +9,7 @@
import { createReadStream, existsSync, statSync } from "node:fs";
import { createServer } from "node:http";
import { extname, join, normalize } from "node:path";
import { createGzip } from "node:zlib";
import { buildFixtureSite } from "./prepare-site.mjs";
const PORT = Number(process.env.ANANKE_TEST_PORT || 4321);
@@ -22,6 +23,9 @@
  ".xml": "application/xml; charset=utf-8",
  ".txt": "text/plain; charset=utf-8",
  ".woff2": "font/woff2",
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".ico": "image/x-icon",
};
const root = buildFixtureSite();
@@ -54,9 +58,28 @@
    "Content-Type",
    TYPES[extname(filePath)] || "application/octet-stream",
  );
  createReadStream(filePath).pipe(res);
  // Match normal static hosting: negotiate compression for text assets.
  const compressible = /\.(?:html|css|js|json|svg|xml|txt)$/.test(filePath);
  const encodings = (req.headers["accept-encoding"] || "").split(",");
  const gzip = encodings.some((entry) => {
    const [name, quality] = entry.trim().split(";");
    return (
      name === "gzip" &&
      (!quality || Number(quality.trim().replace(/^q=/, "")) > 0)
    );
  });
  if (compressible) res.setHeader("Vary", "Accept-Encoding");
  const stream = createReadStream(filePath);
  if (compressible && gzip) {
    res.setHeader("Content-Encoding", "gzip");
    stream.pipe(createGzip()).pipe(res);
  } else {
    stream.pipe(res);
  }
});
server.listen(PORT, () => {
  console.log(`Fixture site served at http://localhost:${PORT}/`);
  console.log(
    `Fixture site served at http://localhost:${server.address().port}/`,
  );
});
tests/support/pages.ts
New file
@@ -0,0 +1,8 @@
export const pageTypes = {
  home: "/",
  list: "/posts/",
  single: "/posts/hello/",
  terms: "/tags/",
  taxonomy: "/tags/alpha/",
  "404": "/404.html",
};
tests/support/prepare-site.mjs
@@ -13,40 +13,83 @@
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { stripVTControlCharacters } from "node:util";
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "..", "..");
const siteDir = resolve(here, "..", "fixtures", "site");
const publicDir = join(siteDir, "public");
export function buildFixtureSite() {
export function buildFixtureSite(options = {}) {
  const source = options.source || siteDir;
  const destination = options.destination || join(source, "public");
  const expectedModes = source === siteDir ? ["unknown", "invalid"] : [];
  const themesDir = mkdtempSync(join(tmpdir(), "ananke-test-themes-"));
  try {
    symlinkSync(repoRoot, join(themesDir, "ananke"), "dir");
    rmSync(publicDir, { recursive: true, force: true });
    rmSync(destination, { recursive: true, force: true });
    const result = spawnSync(
      "hugo",
      [
        "--source",
        siteDir,
        source,
        "--themesDir",
        themesDir,
        "--destination",
        publicDir,
        destination,
        "--baseURL",
        `http://localhost:${process.env.ANANKE_TEST_PORT || 4321}/`,
        "--environment",
        "production",
        "--printPathWarnings",
        "--logLevel",
        "warn",
        ...(options.config ? ["--config", options.config] : []),
      ],
      { stdio: "inherit" },
      { encoding: "utf8" },
    );
    const output = `${result.stdout || ""}\n${result.stderr || ""}`;
    process.stdout.write(output);
    if (result.error) throw result.error;
    const expectedWarnings =
      options.expectedWarnings ||
      expectedModes.map(
        (mode) =>
          `[ananke] Invalid ananke.navigation.submenu_mode "${mode}"; using split. Choose split, hover, click, or toplevel.`,
      );
    checkDiagnostics(output, expectedWarnings);
    options.onOutput?.(output);
    if (result.status !== 0) {
      throw new Error(`hugo build failed with code ${result.status}`);
    }
  } finally {
    rmSync(themesDir, { recursive: true, force: true });
  }
  return publicDir;
  return destination;
}
export function checkDiagnostics(output, expectedWarnings = []) {
  const warnings = stripVTControlCharacters(output)
    .split("\n")
    .filter((line) => /^(?:WARN|DEPRECATED)\s/.test(line));
  const matches = (line, expected) => {
    const message = line.replace(/^(?:WARN|DEPRECATED)\s+/, "");
    return typeof expected === "string"
      ? message === expected
      : expected.test(message);
  };
  for (const expected of expectedWarnings) {
    if (warnings.filter((line) => matches(line, expected)).length !== 1) {
      throw new Error(`Expected exactly one fixture warning: ${expected}`);
    }
  }
  const unexpected = warnings.filter(
    (line) => !expectedWarnings.some((expected) => matches(line, expected)),
  );
  if (unexpected.length) {
    throw new Error(
      `Unexpected Hugo warnings/deprecations:\n${unexpected.join("\n") || output}`,
    );
  }
}
// Allow running directly: `node tests/support/prepare-site.mjs`
tests/testing-status.md
New file
@@ -0,0 +1,29 @@
# Testing issue status
This is an implementation record for the open `type:tests` reports. Local validation does not establish that a GitHub Actions run passed. No issues have been closed.
| Issue | Implemented | Remaining work or blocker |
| --- | --- | --- |
| [#1004](https://github.com/gohugo-ananke/ananke/issues/1004) | Layered testing commands and CI configuration | Complete the child issues below |
| [#1005](https://github.com/gohugo-ananke/ananke/issues/1005) | Node runner, standard reporter, watch command, Cheerio assertions, and feature mini-sites for #504, #217, #1109, copy disablement, date precedence, and header deprecations | First remote CI run |
| [#1006](https://github.com/gohugo-ananke/ananke/issues/1006) | Local build/serve harness, pinned Playwright container CI job, shared page-type data, and report artifacts | First remote CI run |
| [#1007](https://github.com/gohugo-ananke/ananke/issues/1007) | Axe across page types including the contact form, contrast fixes, zero-violation assertions, CI, and manual checklist | Manual checklist requires human checks; first remote CI run |
| [#1008](https://github.com/gohugo-ananke/ananke/issues/1008) | No-JavaScript navigation, submenu, image, copy-control, and code-selection tests at mobile and desktop sizes | First remote CI run |
| [#1009](https://github.com/gohugo-ananke/ananke/issues/1009) | Six page types at two viewports, deterministic capture settings, comparison gate, and CI baseline artifact workflow | Generate, review, and commit the first CI baselines; establish stability in that container |
| [#1010](https://github.com/gohugo-ananke/ananke/issues/1010) | Lighthouse CI, score and asset budgets, reports, and CI job | All nine local runs pass the unchanged budgets; first remote CI run |
| [#1011](https://github.com/gohugo-ananke/ananke/issues/1011) | HTML validity, offline links and fragments, diagnostic assertions, and CI job | First remote CI run; external link availability is outside this deterministic gate |
| [#1012](https://github.com/gohugo-ananke/ananke/issues/1012) | TOML parsing, executable-path validation, mutation tests, missing edit-page registration, CI, documentation, and PR checkbox | Other nested parameter tables remain outside the declared gate scope |
| [#1013](https://github.com/gohugo-ananke/ananke/issues/1013) | Copy wrapper, inline-code exclusion, copy feedback and clipboard, no-JavaScript rendering, site-wide disablement, and real shortcode tests | Continue the backfill queue below |
## Backfill queue
* Home content alignment, recent posts, and categories: dedicated DOM assertions for each setting and disabled state.
* Header layout and hooks: widen parameter registration to nested configuration once behaviour-specific tests exist.
* Social follow/share settings and network definitions: output, accessible names, escaping, and no-JavaScript checks.
* Since and edit-page shortcodes: configured targets, repository formats, empty input, warning cases, and missing source files.
## Decisions and acceptance still needed
Contrast, native form labels, and email instructions are now covered by passing axe, accessible-name, keyboard, and browser-validation checks. The mobile menu is collapsed before DOMContentLoaded when JavaScript is available, while no-JavaScript navigation stays expanded. The fixture server negotiates gzip and has tests for compressed, uncompressed, and explicitly refused gzip responses. Lighthouse passes all nine local runs with the original score and transfer budgets.
Remote CI still needs to run. Visual baselines must be generated in CI and reviewed by a person. The manual accessibility checklist also requires human checks; automated checks do not establish full conformance.
tests/unit/build-diagnostics.test.mjs
New file
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { checkDiagnostics } from "../support/prepare-site.mjs";
test("clean diagnostics pass", () => checkDiagnostics("Total in 20 ms\n"));
test("unexpected path warnings fail", () => {
  assert.throws(
    () => checkDiagnostics("WARN  Duplicate target path /posts/\n"),
    /Unexpected Hugo/,
  );
});
test("unexpected deprecations fail", () => {
  assert.throws(
    () => checkDiagnostics("WARN  Feature is deprecated\n"),
    /Unexpected Hugo/,
  );
});
test("expected diagnostics are required exactly once", () => {
  checkDiagnostics("WARN  Intentional warning\n", ["Intentional warning"]);
  assert.throws(
    () => checkDiagnostics("", ["Intentional warning"]),
    /exactly one/,
  );
  assert.throws(
    () =>
      checkDiagnostics(
        "WARN  Intentional warning\nWARN  Intentional warning\n",
        ["Intentional warning"],
      ),
    /exactly one/,
  );
});
test("expected diagnostics cannot hide another warning", () => {
  assert.throws(
    () =>
      checkDiagnostics("WARN  Intentional warning\nWARN  Unexpected\n", [
        "Intentional warning",
      ]),
    /Unexpected Hugo/,
  );
});
tests/unit/coverage-gate.test.mjs
New file
@@ -0,0 +1,67 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { test } from "node:test";
const gate = resolve("tests/coverage-gate.mjs");
function runFixture({
  params = "",
  shortcode = false,
  reference = "tests/e2e/example.spec.ts",
  makeTest = true,
} = {}) {
  const root = mkdtempSync(join(tmpdir(), "ananke-coverage-gate-"));
  const write = (file, content) => {
    mkdirSync(dirname(join(root, file)), { recursive: true });
    writeFileSync(join(root, file), content);
  };
  try {
    write(
      "config/_default/params.toml",
      `[ananke]\nexisting = true\n${params}`,
    );
    write(
      "tests/catalog.yaml",
      `params:\n  ananke.existing:\n    tests: ["${reference}"]\n`,
    );
    mkdirSync(join(root, "layouts/_shortcodes"), { recursive: true });
    if (shortcode) write("layouts/_shortcodes/new.html", "<p>new</p>");
    if (makeTest)
      write("tests/e2e/example.spec.ts", "// fixture test reference\n");
    return spawnSync(process.execPath, [gate, root], { encoding: "utf8" });
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
}
test("registered features pass", () => assert.equal(runFixture().status, 0));
test("an unregistered parameter fails", () => {
  const result = runFixture({ params: "new = false\n" });
  assert.equal(result.status, 1);
  assert.match(result.stderr, /ananke.new.*has no test/);
});
test("an unregistered shortcode fails", () => {
  const result = runFixture({ shortcode: true });
  assert.equal(result.status, 1);
  assert.match(result.stderr, /shortcode 'new'.*has no test/);
});
test("a deleted test fails", () => {
  const result = runFixture({ makeTest: false });
  assert.equal(result.status, 1);
  assert.match(result.stderr, /does not exist/);
});
test("a reference outside the repository fails", () => {
  const result = runFixture({ reference: "../example.spec.ts" });
  assert.equal(result.status, 1);
  assert.match(result.stderr, /invalid test path/);
});
test("multiline arrays and commented table headers cannot bypass the gate", () => {
  const result = runFixture({
    params: '[ananke.navigation] # comment\nnew = [\n  "one",\n  "two",\n]\n',
  });
  assert.equal(result.status, 1);
  assert.match(result.stderr, /ananke.navigation.new.*has no test/);
});
tsconfig.json
@@ -7,5 +7,11 @@
    "declarationMap": true,
    "jsx": "react-jsx"
  },
  "include": ["**/*.ts", "scripts/**/*"]
  "include": ["**/*.ts", "scripts/**/*"],
  "exclude": [
    "node_modules",
    "scratch",
    "tests/.playwright",
    "tests/fixtures/**/public"
  ]
}