Compare commits

..
Author SHA1 Message Date
chrnx 6e78fce659 chore: version to CalVer 26.7.0-beta.0
CI / build (pull_request) Successful in 18s
Aligns website with the org-wide CalVer scheme; every package's first tag is v26.7.0-beta.0 (no production yet).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 15:00:16 -05:00
chrnx deac98a63c Merge pull request 'ci: build gate + promote + release workflows (two-forge)' (#1) from chore/ci-workflows into main
CI / build (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 7s
2026-07-18 18:53:56 +00:00
chrnx f65fc3742c ci: bump Node to 22 (Astro 7 requires >=22.12)
CI / build (pull_request) Successful in 19s
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 13:51:08 -05:00
chrnx 92815796e6 ci: add build gate + promote + release workflows (two-forge)
CI / build (pull_request) Failing after 24s
ci.yml: astro build on PR/push to main. promote.yml (Gitea-only): mirror main + tags to Expressive-Tea/green-tea-site. release.yml (GitHub-only): on a v* tag, build and attach dist as a .tar.gz to the GitHub release for the cPanel deploy.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 13:47:50 -05:00
chrnx f52d493ea1 docs(blog): honest benchmarks — what a real network does to "faster"
Over two real machines the throughput race compresses and the server sits idle; the runtime-agnostic edge (Bun/Deno ~1.6x Node, same app) is the part no Node-only framework can show; and the O(n^2) I found and fixed in my own pipeline while stress-testing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 19:09:39 -05:00
chrnx 731631ecd5 feat(site): email launch-list capture with a PHP/MySQL endpoint
A signup form in the closing section posts to subscribe.php (ships in the build): PDO/MySQL, honeypot, idempotent insert, optional mail() notify. DB creds live in a gitignored config kept above the web root; schema and setup in server/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 19:09:39 -05:00
chrnx 7f4b6c3092 feat(site): sharpen the hero, intent-keyword titles, and a beta FAQ
Hero H1 leads with the differentiator (a graph, not a middleware chain) instead of three adjectives; page titles carry search-intent keywords; a beta-scoped FAQ answers production-readiness, Express migration, performance and dependency questions; the footer credits the Expressive Tea Team.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 19:09:39 -05:00
chrnx af376a26b4 feat(site): add a How-it-compares table so the difference lands
The landing explained what Green Tea is but never set it beside Express,
Fastify, or NestJS — so 'it's different' was told, not shown, and it read
like one more framework. The core README already carries an honest
comparison; this lifts its most load-bearing rows (pipeline model, does
req.user exist, seeing the pipeline, real-time, runtimes, deps) into a
curated four-column table with the Green Tea column lit.

Responsive: the table scrolls inside its own overflow-x container so the
page body never scrolls sideways on mobile. Copy is pulled from the
verified README rows — nothing new claimed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:35:59 -05:00
chrnx e083f244c0 docs(site): sell real-time and the graph honestly
Two claims a skeptic would catch. RealTime still said 'return an
AsyncIterable' with no mention of declaring the transport — the same
implicit-return the framework now rejects with TransportMismatchError; the
honest version (declare the transport, the contract is never a surprise)
sells harder anyway. And GraphNotChain's 'no one else has the graph' invited
the obvious 'Angular and Nest have a DI graph' — so say the real,
unrefutable thing: they resolve a graph of services, this resolves your
request pipeline. Same fix in the founder post.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:16:47 -05:00
chrnx 482bbab0ae docs(site): move to green-tea.expressive-tea.io, docs at /docs
The site hangs off the expressive-tea.io cPanel now, not the placeholder
.dev domain. Docs live at /docs on the same subdomain (a separate build,
not a nested sub-subdomain), so every cross-link to the docs points there.
robots.txt sitemap and the README deploy steps follow — cPanel upload, two
folders, one cert.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:13:18 -05:00
chrnx f274a7cbe7 docs(site): point at the real GitHub org, and admit what the edge can't do
Green Tea ships under the Expressive-Tea org — the framework it grew out
of lives there, and the founder story the launch post tells is easier to
follow when both are in the same house. The green-tea-dev placeholder was
never going to exist.

RunsEverywhere claimed the same src/ runs everywhere, full stop. It
doesn't: the edge has no filesystem, so file-backed views and static
serving don't go. A landing page that oversells gets found out on day
one, and this project's whole pitch is that it tells you the truth.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 09:36:57 -05:00
chrnx e3cb7f1d90 chore: untrack internal specs and SDD ledger (gitignored)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 21:18:01 -05:00
chrnx c349dbd514 fix: post date off-by-one and inconsistent placeholder links
Post/blog-index dates formatted pubDate in the local timezone, so a
UTC-midnight date like 2026-07-10 rendered as July 9 anywhere west
of UTC. Format with timeZone: 'UTC' to match the stored date.

Also normalizes the npm package to @green-tea/core everywhere (Header
and Footer still pointed at @expressive-tea/core) and settles on a
single GitHub placeholder (https://github.com/green-tea-dev/green-tea)
across Header, Footer, Hero, and HonestBeta — documented in the README
as unconfirmed until launch. Docs CTAs in Hero and HonestBeta now open
in a new tab with rel="noopener noreferrer", matching Header/Footer.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 19:21:26 -05:00
chrnx 383c859666 polish: 404 page, branded OG image, robots.txt, README
Rounds out the site for launch: a calm branded 404 (with the graph
motif and a way back home), a proper 1200x630 OG/Twitter card so
shared links look right, robots.txt pointing at the sitemap, and a
README covering local dev and the manual Cloudflare Pages deploy
flow (no deploy CI is configured).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 19:21:18 -05:00
chrnx ca7cfab246 content(blog): launch post — why I rebuilt my framework
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 19:15:24 -05:00
chrnx 4f131eba43 feat(blog): content collection, index, post layout, RSS
Adds the blog system ahead of the launch post: a zod-typed `blog`
content collection (content layer glob loader), a card-list index
with a calm empty state, the post route/layout with reading time,
and an RSS feed — all wired to the existing Base shell and palette.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 19:11:19 -05:00
chrnx 479a3012c4 feat: landing page — the pitch (graph, runtime-agnostic, real-time, batteries)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 19:02:25 -05:00
chrnx 0969882f97 chore: scaffold Astro site + brand shell (header, footer, layout, motif)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 18:52:47 -05:00
chrnx c064791675 docs: site design + implementation plan
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 18:48:25 -05:00
5 changed files with 0 additions and 658 deletions

No files matched your search

-3
View File
@@ -11,9 +11,6 @@ node_modules/
.superpowers/ .superpowers/
.specs/ .specs/
# isolated feature worktrees
.worktrees/
# environment variables # environment variables
.env .env
.env.production .env.production
@@ -1,72 +0,0 @@
# SEO and performance improvement design
Date: 2026-08-02
## Goal
Make the public site easier for search engines to understand and faster on a cold mobile load. Preserve the current visual design, static Astro architecture, and two-forge release flow.
## Baseline
Lighthouse 13 measured the deployed home page at 96 performance, 96 accessibility, 100 best practices, and 100 SEO on mobile. The desktop scores were 95, 96, 100, and 100. Mobile FCP and LCP were 2.3 seconds, TBT was 0 milliseconds, and CLS was 0.001.
The audit found five material gaps:
- Google Fonts blocks rendering and accounts for about 990 milliseconds of estimated savings.
- Hashed CSS and SVG assets have no explicit browser cache lifetime.
- HTTP serves a second working copy instead of redirecting to HTTPS.
- Pages lack product and article structured data.
- Two text treatments fail WCAG color contrast checks.
The sitemap, canonical URLs, robots file, HTTPS pages, and real 404 status already work.
## Design
### Metadata and structured data
Extend `Base.astro` with explicit page type, robots, publication metadata, and JSON-LD inputs. The home page will describe Green Tea as a software application and website. Blog posts will emit `BlogPosting` data, `og:type=article`, publication and modification dates, author, and tags. The 404 page will emit `noindex, follow`.
Keep canonical URLs derived from `Astro.site`. Serialize structured data from trusted build-time objects and render it as an `application/ld+json` script.
### Font delivery and accessibility
Remove the Google Fonts stylesheet from the page and unused Starlight brand imports from the marketing site's global CSS. Host only the WOFF2 files required for Zen Maru Gothic weights 500 and 700 under `public/fonts`, declare them with `font-display: swap`, and preload only the heading face needed above the fold.
Adjust the muted runtime caveat and syntax-comment colors until Lighthouse reports sufficient contrast. Do not change layout, spacing, copy, or component structure.
### Apache behavior
Add `public/.htaccess` so Astro copies it to `dist/.htaccess`. It will:
- redirect HTTP requests to the same HTTPS URL;
- assign a long immutable cache lifetime to hashed `/_astro/` assets;
- assign shorter cache lifetimes to fonts and static images;
- enable compression when the host provides `mod_deflate` or `mod_brotli`;
- avoid changing routes or the existing 404 behavior.
Every directive that depends on an optional Apache module will use an `IfModule` guard. The release must remain compatible with the current cPanel Apache host.
### Release boundary
GitHub remains the only forge that packages a production artifact. `.github/workflows/release.yml` already restricts its package job to `github.com` and creates `green-tea-site-<tag>.tar.gz` with `tar -C dist .`, which includes dotfiles.
Add a release validation step after the build that fails unless `dist/.htaccess` exists. Gitea will continue to run the shared build gate and promotion workflow, but it will not package or publish a release artifact.
## Verification
Run a clean production build and verify:
- `dist/.htaccess` exists and appears in a locally created tar listing;
- every indexable page has one canonical URL, description, and valid JSON-LD;
- the 404 page has `noindex, follow`;
- the sitemap lists only indexable public pages;
- no generated page requests Google Fonts;
- internal production links return expected statuses;
- Lighthouse mobile and desktop improve or hold their baseline scores;
- Lighthouse reports no automated SEO or contrast failures.
The final report will separate local build results from behavior that requires the new artifact to be deployed on Apache.
## Non-goals
This change will not redesign the site, add analytics, create keyword-stuffed copy, submit the site to Search Console, modify the documentation build under `/docs`, or create release archives in Gitea.
@@ -1,366 +0,0 @@
# SEO and Performance Improvements Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Improve search-engine metadata, remove the render-blocking font dependency, fix automated contrast failures, and ship Apache redirects and caching inside the GitHub release artifact.
**Architecture:** Keep Astro's static output and extend the existing base layout with typed metadata and build-time JSON-LD. Vendor the two Latin WOFF2 font files, copy Apache configuration from `public/`, and verify generated HTML with a dependency-free Node script. Preserve the shared Gitea/GitHub build gate while keeping production packaging exclusive to GitHub.
**Tech Stack:** Astro 7, TypeScript, plain CSS, Node.js assertions, Apache `.htaccess`, GitHub Actions, Lighthouse 13.
---
### Task 1: Add a failing generated-site verifier
**Files:**
- Create: `scripts/verify-build.mjs`
- Modify: `package.json`
**Step 1: Create the verifier**
Write a Node script that reads `dist/index.html`, `dist/404.html`, the blog index, and every generated blog post. Use `node:assert/strict` to require:
- one canonical URL and one meta description per HTML page;
- parseable JSON-LD on the home page and each blog post;
- `SoftwareApplication` in the home JSON-LD graph;
- `BlogPosting`, article Open Graph metadata, dates, and author on each post;
- `noindex, follow` on the 404 page;
- no reference to `fonts.googleapis.com` or `fonts.gstatic.com`;
- a generated `dist/.htaccess` file.
The script should end with `Verified generated SEO and deploy metadata.` and exit nonzero on the first failed assertion.
**Step 2: Add build-check scripts**
Add these entries to `package.json`:
```json
"check": "npm run build && npm run verify:build",
"verify:build": "node scripts/verify-build.mjs"
```
**Step 3: Run the verifier against the current build**
Run: `npm run build && npm run verify:build`
Expected: FAIL because the current output has no JSON-LD and no `dist/.htaccess`.
**Step 4: Commit the failing verifier**
```bash
git add package.json scripts/verify-build.mjs
git commit -m "test: verify generated SEO metadata"
```
### Task 2: Add typed global and home-page SEO metadata
**Files:**
- Modify: `src/layouts/Base.astro`
- Modify: `src/pages/index.astro`
**Step 1: Extend the base layout contract**
Add these optional props:
```ts
type OpenGraphType = 'website' | 'article';
type StructuredData = Record<string, unknown>;
interface Props {
title?: string;
description?: string;
image?: string;
ogType?: OpenGraphType;
robots?: string;
publishedTime?: Date;
updatedTime?: Date;
author?: string;
tags?: string[];
structuredData?: StructuredData;
}
```
Default `ogType` to `website` and `robots` to `index, follow`. Convert the canonical and image URLs to strings before using them in metadata.
Emit:
```astro
<meta name="robots" content={robots} />
<meta property="og:type" content={ogType} />
{
ogType === 'article' && (
<>
{publishedTime && <meta property="article:published_time" content={publishedTime.toISOString()} />}
{updatedTime && <meta property="article:modified_time" content={updatedTime.toISOString()} />}
{author && <meta property="article:author" content={author} />}
{tags?.map((tag) => <meta property="article:tag" content={tag} />)}
</>
)
}
{structuredData && (
<script
type="application/ld+json"
set:html={JSON.stringify(structuredData).replace(/</g, '\\u003c')}
/>
)}
```
Keep the existing title, description, canonical, Open Graph image, Twitter card, RSS, favicon, and generator metadata.
**Step 2: Add home-page JSON-LD**
In `src/pages/index.astro`, construct a single `@context` object with an `@graph` containing:
- a `WebSite` node with the canonical URL, name, and page description;
- a `SoftwareApplication` node with name, description, application category, cross-platform operating system, canonical URL, repository URL, MIT license URL, and a zero-price `Offer`.
Pass that object through `structuredData` on `<Base>`.
**Step 3: Build and inspect the home page**
Run: `npm run build`
Expected: PASS. `dist/index.html` contains one canonical tag, `robots=index, follow`, and parseable JSON-LD containing `WebSite` and `SoftwareApplication`.
**Step 4: Commit global and home metadata**
```bash
git add src/layouts/Base.astro src/pages/index.astro
git commit -m "feat: add structured product metadata"
```
### Task 3: Add article metadata and exclude the 404 page
**Files:**
- Modify: `src/layouts/Post.astro`
- Modify: `src/pages/404.astro`
**Step 1: Construct article JSON-LD**
In `Post.astro`, derive absolute canonical and hero-image URLs from `Astro.url.pathname` and `Astro.site`. Create a `BlogPosting` object containing:
```ts
const structuredData = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: title,
description,
image: absoluteHeroImage,
datePublished: pubDate.toISOString(),
dateModified: (updatedDate ?? pubDate).toISOString(),
author: { '@type': 'Person', name: author },
publisher: { '@type': 'Organization', name: 'Expressive Tea Team' },
mainEntityOfPage: canonicalURL,
keywords: tags?.join(', '),
};
```
Pass `ogType="article"`, dates, author, tags, and `structuredData` to `Base`.
**Step 2: Mark the 404 page for exclusion**
Pass `robots="noindex, follow"` to `Base` in `src/pages/404.astro`.
**Step 3: Build and inspect posts and 404 output**
Run: `npm run build`
Expected: PASS. Each post contains article metadata and parseable `BlogPosting` JSON-LD. `dist/404.html` contains `noindex, follow` and no indexable structured-data entity.
**Step 4: Commit article and 404 metadata**
```bash
git add src/layouts/Post.astro src/pages/404.astro
git commit -m "feat: describe blog posts to search engines"
```
### Task 4: Self-host the heading font and fix contrast
**Files:**
- Create: `public/fonts/zen-maru-gothic-latin-500.woff2`
- Create: `public/fonts/zen-maru-gothic-latin-700.woff2`
- Create: `public/fonts/OFL.txt`
- Modify: `src/layouts/Base.astro`
- Modify: `src/styles/global.css`
- Modify: `src/components/sections/RunsEverywhere.astro`
- Modify: `src/components/sections/SeeIt.astro`
**Step 1: Vendor the exact Latin font files**
Download the Google Fonts v19 Latin WOFF2 assets and the Zen Maru Gothic OFL license. Record and verify these SHA-256 hashes:
```text
2c5953da616e5e6dcad34ae8b744f7e759f1647c041389681fa2360908508d55 zen-maru-gothic-latin-500.woff2
9d65f92a3e11edcef9d73694b5b73cb6888243aee54e8034b162eb368c6ff3ed zen-maru-gothic-latin-700.woff2
```
**Step 2: Declare local font faces**
Remove `@import './brand.css';` from `src/styles/global.css`. Add two `@font-face` rules using the local files, `font-style: normal`, weights 500 and 700, `font-display: swap`, and the Latin unicode range supplied by Google Fonts.
The detached `src/styles/brand.css` belongs to the separate Starlight docs theme and must not load in this marketing build.
**Step 3: Remove the external font connection**
Delete the Google Fonts preconnect and stylesheet tags from `Base.astro`. Add one preload:
```astro
<link
rel="preload"
href="/fonts/zen-maru-gothic-latin-700.woff2"
as="font"
type="font/woff2"
crossorigin
/>
```
**Step 4: Fix both Lighthouse contrast findings**
Remove `opacity: 0.75` from `.runs__caveat` so it inherits the accessible `--dim` color at full opacity. Change the Astro `Code` theme in `SeeIt.astro` from `github-dark` to `github-dark-high-contrast`.
**Step 5: Build and check output dependencies**
Run: `npm run build && ! rg 'fonts\\.(googleapis|gstatic)\\.com' dist`
Expected: PASS. The font files exist under `dist/fonts`, and no generated page references Google-hosted fonts.
**Step 6: Commit font and contrast changes**
```bash
git add public/fonts src/layouts/Base.astro src/styles/global.css \
src/components/sections/RunsEverywhere.astro src/components/sections/SeeIt.astro
git commit -m "perf: self-host heading fonts"
```
### Task 5: Ship Apache behavior in the static build
**Files:**
- Create: `public/.htaccess`
**Step 1: Add the canonical HTTPS redirect**
Use `mod_rewrite` under `IfModule`. When `%{HTTPS}` is not `on`, redirect with status 301 to `https://green-tea.expressive-tea.io%{REQUEST_URI}`. Use `NE` and `L` flags.
**Step 2: Add guarded caching and compression**
Under guarded `mod_expires` and `mod_headers` blocks:
- cache fingerprinted CSS, JavaScript, SVG, and image assets for one year with `immutable`;
- cache WOFF2 files for one year;
- cache ordinary images and icons for seven days;
- mark HTML as immediately stale with `public, max-age=0, must-revalidate`.
Use `mod_deflate` for HTML, CSS, JavaScript, JSON, XML, SVG, and plain text. Do not add rewrites for Astro routes.
**Step 3: Verify Astro copies the dotfile**
Run: `npm run check`
Expected: PASS and print `Verified generated SEO and deploy metadata.` Confirm `test -f dist/.htaccess` exits zero.
**Step 4: Commit Apache configuration**
```bash
git add public/.htaccess
git commit -m "perf: ship Apache caching and HTTPS redirect"
```
### Task 6: Keep packaging exclusive to GitHub and enforce the artifact contract
**Files:**
- Modify: `.github/workflows/ci.yml`
- Modify: `.github/workflows/release.yml`
**Step 1: Run generated-output checks in the shared build gate**
Replace `npm run build` with `npm run check` in `ci.yml`. This check may run on GitHub and Gitea; it creates no release artifact.
**Step 2: Verify the release archive in the GitHub-only job**
Keep the existing job condition:
```yaml
if: ${{ github.server_url == 'https://github.com' }}
```
Replace the release build command with `npm run check`. After packaging, add:
```yaml
- name: Verify package contents
run: tar -tzf "green-tea-site-${{ github.ref_name }}.tar.gz" | grep -Fx './.htaccess'
```
Do not change `.github/workflows/promote.yml` and do not add a Gitea artifact job.
**Step 3: Inspect the workflow diff**
Run: `git diff --check && git diff -- .github/workflows/ci.yml .github/workflows/release.yml`
Expected: both workflows use `npm run check`; only `release.yml` contains `tar`, `softprops/action-gh-release`, and the `github.com` job guard.
**Step 4: Commit workflow verification**
```bash
git add .github/workflows/ci.yml .github/workflows/release.yml
git commit -m "ci: verify the GitHub release artifact"
```
### Task 7: Run final build and Lighthouse verification
**Files:**
- Modify if needed: files changed in Tasks 1-6
**Step 1: Run repository checks**
Run:
```bash
npm run check
git diff --check
```
Expected: both commands pass.
**Step 2: Reproduce the GitHub archive locally**
Run:
```bash
tar -czf /tmp/green-tea-site-seo-audit.tar.gz -C dist .
tar -tzf /tmp/green-tea-site-seo-audit.tar.gz | grep -Fx './.htaccess'
```
Expected: `./.htaccess`.
**Step 3: Serve the production build**
Run: `npm run preview -- --host 127.0.0.1`
Keep the preview process running for the next two steps.
**Step 4: Run mobile Lighthouse**
Run Lighthouse 13 against `http://127.0.0.1:4321/` with mobile simulated throttling and JSON output.
Expected: 100 SEO, 100 best practices, no color-contrast failure, no Google Fonts request, TBT of 0 milliseconds, and performance at or above the deployed baseline of 96 when measured under equivalent settings.
**Step 5: Run desktop Lighthouse**
Run Lighthouse 13 with the desktop preset.
Expected: 100 SEO, 100 best practices, no color-contrast failure, and performance at or above the deployed baseline of 95 when measured under equivalent settings.
**Step 6: Inspect generated metadata and Git state**
Run:
```bash
rg -n 'application/ld\\+json|article:published_time|noindex, follow' dist/index.html dist/blog dist/404.html
git status --short --branch
```
Expected: all metadata is present and only intentional changes remain.
**Step 7: Commit any verification-driven correction**
If Lighthouse required a correction, stage only that correction and commit it with a focused message. Do not create an empty verification commit.
-2
View File
@@ -8,8 +8,6 @@
"scripts": { "scripts": {
"dev": "astro dev", "dev": "astro dev",
"build": "astro build", "build": "astro build",
"check": "npm run build && npm run verify:build",
"verify:build": "node scripts/verify-build.mjs",
"preview": "astro preview", "preview": "astro preview",
"astro": "astro" "astro": "astro"
}, },
-215
View File
@@ -1,215 +0,0 @@
import assert from 'node:assert/strict';
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
const distDir = resolve('dist');
function readHtml(filePath) {
assert.ok(existsSync(filePath), `Missing generated HTML: ${relative(distDir, filePath)}`);
return readFileSync(filePath, 'utf8');
}
function tags(html, tagName) {
return html.match(new RegExp(`<${tagName}\\b[^>]*>`, 'gi')) ?? [];
}
function attribute(tag, name) {
const match = tag.match(
new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'),
);
return match?.[1] ?? match?.[2] ?? match?.[3];
}
function metaTags(html, attributeName, attributeValue) {
return tags(html, 'meta').filter(
(tag) => attribute(tag, attributeName)?.toLowerCase() === attributeValue.toLowerCase(),
);
}
function verifyPageMetadata({ label, html }) {
const canonicals = tags(html, 'link').filter((tag) =>
attribute(tag, 'rel')
?.toLowerCase()
.split(/\s+/)
.includes('canonical'),
);
assert.equal(canonicals.length, 1, `${label} must have exactly one canonical URL`);
const canonicalUrl = attribute(canonicals[0], 'href');
assert.ok(canonicalUrl, `${label} canonical URL must not be empty`);
let parsedCanonical;
assert.doesNotThrow(
() => {
parsedCanonical = new URL(canonicalUrl);
},
`${label} canonical URL must be valid`,
);
assert.ok(
['https:', 'http:'].includes(parsedCanonical.protocol),
`${label} canonical URL must use HTTP or HTTPS`,
);
const descriptions = metaTags(html, 'name', 'description');
assert.equal(descriptions.length, 1, `${label} must have exactly one meta description`);
assert.ok(attribute(descriptions[0], 'content')?.trim(), `${label} meta description must not be empty`);
}
function findGeneratedTextAssets(directory) {
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const entryPath = join(directory, entry.name);
if (entry.isDirectory()) return findGeneratedTextAssets(entryPath);
return entry.isFile() && /\.(?:html|css)$/i.test(entry.name) ? [entryPath] : [];
});
}
function parseJsonLd(html, label) {
const scripts = [];
const scriptPattern = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
let match;
while ((match = scriptPattern.exec(html)) !== null) {
if (attribute(`<script${match[1]}>`, 'type')?.toLowerCase() === 'application/ld+json') {
scripts.push(match[2]);
}
}
assert.ok(scripts.length > 0, `${label} must have parseable JSON-LD`);
return scripts.map((source, index) => {
try {
return JSON.parse(source);
} catch (error) {
assert.fail(`${label} JSON-LD script ${index + 1} is invalid: ${error.message}`);
}
});
}
function findNodesByType(value, expectedType, matches = []) {
if (Array.isArray(value)) {
for (const item of value) findNodesByType(item, expectedType, matches);
return matches;
}
if (value === null || typeof value !== 'object') return matches;
const types = Array.isArray(value['@type']) ? value['@type'] : [value['@type']];
if (types.includes(expectedType)) matches.push(value);
for (const item of Object.values(value)) findNodesByType(item, expectedType, matches);
return matches;
}
function requireValidDate(value, message) {
assert.equal(typeof value, 'string', `${message} must be a string`);
assert.match(
value,
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,
`${message} must use ISO-8601 UTC format`,
);
const parsedDate = new Date(value);
assert.ok(!Number.isNaN(parsedDate.valueOf()), `${message} must be a valid date`);
assert.equal(parsedDate.toISOString(), value, `${message} must not normalize an impossible date`);
}
function requireSingleMeta(html, label, property, expectedContent) {
const matching = metaTags(html, 'property', property);
assert.equal(matching.length, 1, `${label} must have exactly one ${property} meta tag`);
if (expectedContent !== undefined) {
assert.equal(
attribute(matching[0], 'content')?.toLowerCase(),
expectedContent.toLowerCase(),
`${label} ${property} must be ${expectedContent}`,
);
} else {
assert.ok(attribute(matching[0], 'content')?.trim(), `${label} ${property} must not be empty`);
}
return matching[0];
}
assert.ok(existsSync(distDir), 'Missing generated dist directory');
const generatedTextAssets = findGeneratedTextAssets(distDir);
const htmlPages = generatedTextAssets
.filter((filePath) => filePath.toLowerCase().endsWith('.html'))
.map((filePath) => ({
label: relative(distDir, filePath),
path: filePath,
html: readHtml(filePath),
}));
assert.ok(htmlPages.length > 0, 'Expected at least one generated HTML page');
for (const page of htmlPages) verifyPageMetadata(page);
function requirePage(relativePath, label) {
const page = htmlPages.find((candidate) => candidate.label === relativePath);
assert.ok(page, `Missing generated ${label}: ${relativePath}`);
return { ...page, label };
}
const home = requirePage('index.html', 'home page');
const notFound = requirePage('404.html', '404 page');
requirePage(join('blog', 'index.html'), 'blog index');
const postPages = htmlPages
.map((page) => ({ ...page, route: page.label.replaceAll('\\', '/') }))
.filter(
(page) =>
page.route.startsWith('blog/') &&
page.route.endsWith('/index.html') &&
page.route !== 'blog/index.html',
)
.map((page) => ({
...page,
label: `blog post ${page.route.slice('blog/'.length, -'/index.html'.length)}`,
}));
assert.ok(postPages.length > 0, 'Expected at least one generated blog post');
const homeJsonLd = parseJsonLd(home.html, home.label);
assert.ok(
findNodesByType(homeJsonLd, 'SoftwareApplication').length > 0,
'home page JSON-LD must contain SoftwareApplication',
);
for (const post of postPages) {
const jsonLd = parseJsonLd(post.html, post.label);
const blogPostings = findNodesByType(jsonLd, 'BlogPosting');
assert.equal(blogPostings.length, 1, `${post.label} JSON-LD must contain one BlogPosting`);
const [blogPosting] = blogPostings;
requireValidDate(blogPosting.datePublished, `${post.label} BlogPosting datePublished`);
requireValidDate(blogPosting.dateModified, `${post.label} BlogPosting dateModified`);
assert.equal(typeof blogPosting.author, 'object', `${post.label} BlogPosting author must be an object`);
assert.ok(
!Array.isArray(blogPosting.author) && blogPosting.author !== null,
`${post.label} BlogPosting author must be an object`,
);
assert.ok(
typeof blogPosting.author.name === 'string' && blogPosting.author.name.trim(),
`${post.label} BlogPosting author.name must not be empty`,
);
requireSingleMeta(post.html, post.label, 'og:type', 'article');
const publishedTime = requireSingleMeta(post.html, post.label, 'article:published_time');
requireSingleMeta(post.html, post.label, 'article:author');
requireValidDate(
attribute(publishedTime, 'content'),
`${post.label} article:published_time content`,
);
}
const robots = metaTags(notFound.html, 'name', 'robots');
assert.equal(robots.length, 1, '404 page must have exactly one robots meta tag');
assert.equal(
attribute(robots[0], 'content')?.toLowerCase(),
'noindex, follow',
'404 page robots metadata must be noindex, follow',
);
for (const assetPath of generatedTextAssets) {
const source = readFileSync(assetPath, 'utf8');
for (const forbiddenHost of ['fonts.googleapis.com', 'fonts.gstatic.com']) {
assert.ok(
!source.toLowerCase().includes(forbiddenHost),
`${relative(distDir, assetPath)} must not reference ${forbiddenHost}`,
);
}
}
assert.ok(existsSync(join(distDir, '.htaccess')), 'Missing generated dist/.htaccess');
assert.ok(statSync(join(distDir, '.htaccess')).isFile(), 'Generated dist/.htaccess must be a file');
console.log('Verified generated SEO and deploy metadata.');