Calculators that show their working. A programmatic-SEO calculator site: static output, no database, a few labelled ad slots per page. The rules the project is built under are in CLAUDE.md, the plan is in plan/, and the live progress tracker is docs/status.html (open it straight from disk).
Astro 7 (static output), TypeScript strict, Tailwind CSS 4 via @tailwindcss/vite, one React island (@astrojs/react), decimal.js for all numeric output, zod for input validation, KaTeX rendered at build time, Vitest, and Playwright with axe-core for browser tests. TypeScript is version 7. Hosting is Cloudflare Pages (live at https://opuscalculator.com since 27 Nov 2026). Needs Node 22.23.4 or newer. The repository is public.
| Command | Action |
|---|---|
npm install |
Install dependencies. Afterwards check git diff package-lock.json (see Release flow). |
npm run dev |
Dev server at localhost:4321 |
npm run typecheck |
astro sync then tsc --noEmit (.astro files are not type-checked) |
npm test |
Vitest, all test files |
npm run build |
astro build to dist/, then verify-dist, which fails the build on any bad sitemap URL or link to an unpublished page |
npm run verify |
Lockfile guard, type check, tests and build (the build also checks links, the bundle budget and security). Green before every push. |
npm run count |
Calculators per category and cohort, live count, closest pair of intros, quality-gate failures with reasons |
npm run audit |
Crawls dist/: orphan pages, pages with fewer than 3 inbound links, sitemap-only pages, links to unpublished pages |
npm run indexation |
Weekly: ask Search Console about every published URL, write indexation.csv (needs SEARCH_CONSOLE_CREDENTIALS; -- --mock file.csv is a dry run) |
npm run gate |
Evaluate the promotion gate from indexation.csv and write src/config/promotion-gate.json |
npm run dashboard |
Render reports/indexation.html, a local file (never deploy it) |
npm run prune |
List pages with 0 impressions and 0 clicks for 90 days; -- --write adds them to src/config/pruned.json |
npm run preview |
Serve dist/ locally |
npm run a11y |
After a build: axe-core, reflow, keyboard and live-region checks in Chrome; fails on any violation |
npm run e2e |
After a build: Playwright specs that assert exact numbers (-- --project=chromium for one browser) |
npm run visual |
After a build: 12 screenshot comparisons (Chromium, Windows baselines) |
npm run audit:prelaunch |
After a build: the pre-launch checks; -- --base https://opuscalculator.com runs them on a deployed site |
npm run lighthouse |
After a build: Lighthouse on 5 random published pages (3 mobile, 2 desktop); -- --base URL for a deployed site; fails under 90 on mobile |
npm run prelaunch |
Lists the facts only the owner can supply (jurisdiction, legal read-through, reviewers) |
count, audit and the build's verify-dist read the cohort flags like the build does, so run them with the same flags the build used (for example COHORT_2_PUBLISHED=true npm run audit after a build with that flag), or live pages will be reported as unpublished.
src/calculators/ one TypeScript config per hand-written calculator (definition, formula and copy)
src/generators/ programmatic configs: each file default-exports a function returning CalculatorConfig[]
src/content/categories/ hub copy, one file per category (800 to 1,200 words each)
src/lib/ registry, quality gate, SEO and JSON-LD, hubs, sitemaps, linking, audit, indexation and pruning logic, spec helper, helpers
functions/ Cloudflare Pages Function: 410 Gone for deleted pages, 401 for /admin without an Access token
src/components/ widget (React island), layouts A/B/C, ad slot, disclaimer, header currency and theme controls
src/content/ category hub copy, YMYL disclaimers and reviewers
src/config/ rollout flags, promotion gate, pruned and gone lists, site facts (jurisdiction, mailboxes)
src/styles/ tokens.css, the one source of design tokens
src/pages/ home, calculators/[slug], categories/[category], about, policy and legal pages, 404, 500, sitemap endpoints
public/ favicon, social image, robots.txt and _headers (security headers)
scripts/ count-calculators, link-audit, verify-dist, check-security, check-bundle-size, a11y, prelaunch-audit, check-lockfile, run.mjs (runs a .ts script through Vite)
tests/ calculator tests plus registry, generator, layout, widget, SEO, currency, security, design-token and audit tests; tests/e2e and tests/visual are Playwright
docs/status.html progress tracker; `/docs-sync` keeps it current
docs/ also: ui-demo.html (approved look), DISTRIBUTION.md, ACCESSIBILITY_AUDIT.md, adr/, INCIDENT_RUNBOOK.md, ROLLBACK.md, RUNBOOK_ONCALL.md
plan/ the build plan (Prompts and Appendices)
- Create
src/calculators/<slug>.tsthat default-exports aCalculatorConfig(seesrc/lib/types.tsand any existing file, for examplepercentage-calculator.ts).calculate()must be pure, usedecimal.jsthroughsrc/lib/decimal.tsandsrc/lib/format.ts, and return formatted strings. - Add
tests/calculators/<slug>.test.tswith the default case, at least three more known answers and a decimal-precision assertion. - Leave
publish: falseuntil it passesvalidateForIndexing()(intro of at least 150 words, intro not too similar to another, 3 or more FAQ entries that are not duplicated on other pages, purecalculate(), unique slug). The registry excludes a calculator that fails and logs why. Unpublished calculators have no page and are never linked or put in a sitemap. - To publish, set
publish: true. The page is built at/calculators/<slug>/and its category hub lists it. It is live only if the flag for its tier's cohort is on (Tier 1 is on by default).
- Create
src/generators/<name>.tswhose default export is a function returningCalculatorConfig[]. Most generators exportSPECS(a list ofSpecobjects: copy, inputs, formula, scenarios and at least 3 known answers inchecks) and map them withdefineCalculatorfromsrc/lib/spec.ts;tests/generators/specs.test.tsthen tests every spec automatically. The registry picks it up automatically. Put shared helpers insrc/lib/(for examplegen-utils.ts), not insrc/generators/, because every file there is treated as a generator.units.tsis the working example. - Set
publish: true, atier(2 or 3: cohort N is tier N, a working assumption, see open question 12.4 in the tracker) and asubCluster(the group on the category hub and the source of sibling links). Slugs must not collide with a hand-written page; the registry throws on a duplicate. - Every generated config must pass the quality gate. The gate compares distinct words in intros (Jaccard, limit 0.3), so templated copy needs per-page content (numbers, unit facts) and several phrasings per sentence slot; copy chosen by
pick()orhash32()fromsrc/lib/gen-utils.tsis stable between builds. - Add a test file under
tests/generators/(seeunits.test.ts): counts, unique slug/title/description/h1, known values, and thatregistry.excludedis empty. Runnpm run countto see totals and the closest pair.
sitemap-index.xml lists sitemap-pages.xml (home and hubs), sitemap-tier1.xml and sitemap-tier{2,3}-<category>.xml, each split at 50,000 URLs, containing published URLs only. They come from src/lib/sitemaps.ts and two endpoints in src/pages/. public/robots.txt allows the named crawlers and disallows ?sort=, ?filter= and ?page=. Discovery is sitemaps plus internal links only; Google's Indexing API is not used (CLAUDE.md rule 8).
Each hub's copy lives in src/content/categories/<category>.ts. A hub renders only when its category has a published calculator, and a hub with calculators but under 800 words of analysis fails the build. Sub-clusters, the "most used" blurbs and the decision guide are keyed by calculator slug in the same file and show only for published calculators; generated pages are grouped by their own subCluster.
Cohort 2 may publish only when cohort 1 is above 40% indexed and at least 20% of its pages have organic clicks; cohort 3 likewise against cohort 2 (CLAUDE.md rule 5). src/config/rollout.ts fails the build if COHORT_2_PUBLISHED or COHORT_3_PUBLISHED is true without a fresh, allowing src/config/promotion-gate.json.
- After the site is deployed and verified in Search Console, run
npm run buildthennpm run indexationevery week (setSEARCH_CONSOLE_CREDENTIALSon your own machine; never commit it). Runnpm run dashboardto read the result. - When you want to promote, run
npm run gate. If it says ALLOWED, commit the changedpromotion-gate.jsonin a pull request, then set the flag in Cloudflare Pages. The gate file expires after 14 days. PROMOTION_GATE_SKIP=local-onlylets you build with the flags on for testing on your own machine; it is ignored on CI and Cloudflare Pages.
Pruning and deleting: npm run prune -- --write records pages for noindex (they stay linked). To delete a page, add its path to src/config/gone.json; the Cloudflare Pages Function in functions/ then answers 410 (not yet tested on Cloudflare).
| Variable | Purpose |
|---|---|
COHORT_1_PUBLISHED |
Defaults to true. Read in src/config/rollout.ts. |
COHORT_2_PUBLISHED |
Defaults to false. Do not set it until the promotion gate is met (CLAUDE.md rule 5). |
COHORT_3_PUBLISHED |
Defaults to false. |
PLAUSIBLE_DOMAIN |
If set, the base layout adds one Plausible script tag. Unset means no analytics. |
NODE_VERSION |
Cloudflare Pages only: set to 22. |
PUBLIC_ADS_DISABLED |
true turns every ad slot back into an empty placeholder (the kill switch). The ad network ids are in src/config/ads.ts. |
SEARCH_CONSOLE_CREDENTIALS |
Service account JSON for npm run indexation. Your machine only; never committed. |
SEARCH_CONSOLE_SITE |
Search Console property, default https://opuscalculator.com/. |
PROMOTION_GATE_SKIP |
local-only skips the promotion gate for a test build; ignored on CI and Cloudflare. |
.env.example lists every variable the code reads, names only; never put a real value in it. Anything prefixed PUBLIC_ is visible to every visitor. The flags are applied by isPublished() in src/lib/registry.ts: a page is live when publish is true and its tier's flag is on, and rollout.ts refuses to start a build that turns on cohort 2 or 3 without the promotion gate. The canonical host is written in astro.config.mjs and src/lib/seo.ts, not read from the environment.
Connected and live since 27 Nov 2026 (tracker items 9.6 to 9.10). The project opuscalculator uses exactly these settings; use them again if you ever recreate it:
| Setting | Value |
|---|---|
| Production branch | main |
| Framework preset | None (or Astro; the build command below is what counts) |
| Build command | npm run build (runs astro build, then verify-dist, the bundle budget and the security check, and fails on any of them) |
| Build output directory | dist |
| Root directory | leave blank |
| Environment variables | COHORT_1_PUBLISHED=true, COHORT_2_PUBLISHED=false, COHORT_3_PUBLISHED=false, PLAUSIBLE_DOMAIN=opuscalculator.com (only after you choose the analytics tool, tracker 12.9), NODE_VERSION=22 |
- The
functions/folder is picked up automatically.dist/_routes.json, written by the build, sends only/admin/*and the gone paths to it, so every other request is a plain static file. public/_headersbecomes the response headers (security headers and long caching for hashed assets).SITE_URLappears in the plan's Appendix A but nothing reads it: the address is written inastro.config.mjsandsrc/lib/seo.ts. Setting it on Cloudflare does nothing.- Cloudflare bills build minutes. With the repository public you can turn off preview builds for branches other than
main(Settings, Builds, Branch control) if you do not use previews. - Do not fill in
src/config/ads.tsuntil an ad network is approved (12.11) and/privacy, the CSP andpublic/ads.txtare updated for it:docs/ADS_SETUP.mdhas the steps. - The custom domain is
opuscalculator.com(CNAME @toopuscalculator.pages.dev).www.opuscalculator.comis not a Pages domain: a Cloudflare Single Redirect rule named "Redirect www to apex" (request URL*://www.*, targethttps://${2}, 301) sends every www request to the same path on the apex, and thewwwDNS record must stay proxied for the rule to apply. - If a page shows old registrar or parking content after a DNS change, purge the cache (Caching, Configuration, Purge Everything). Cloudflare cached the parking
robots.txtfor 4 hours on 27 Nov.
After the first deploy, run the checks that cannot run before it: npm run audit:prelaunch -- --base https://opuscalculator.com --sample 20, and curl -I on /, on a made-up URL (must be 404) and on /admin/ (must be 401 or the Access login).
https://opuscalculator.com/mcp is a read-only Model Context Protocol server (stateless, plain HTTP: POST one JSON-RPC message, get one JSON reply). Tools: list_calculators, describe_calculator and calculate. calculate runs the same decimal.js code and the same zod validators as the page, so the numbers match; a test checks that for every calculator. It stores nothing and calls no other service.
- How it is built.
npm run buildrunsscripts/build-mcp.ts. It writes an entry with one loader per calculator published in this build, then bundles it withsrc/mcp/protocol.tsinto.mcp/(generated, git-ignored; 48 KB gzipped with the 5 live calculators, about 570 KB with all 1,156; the build fails above 2.4 MB, because a Worker may be 3 MB compressed). A calculator is built the first time it is asked for and then kept, so the Function starts in a few milliseconds. (The first version built all 1,171 calculators at startup and Cloudflare refused it: "Script startup exceeded CPU time limit".)functions/mcp.tsis the thin HTTP shell, anddist/_routes.jsonsends only/admin/*,/mcpand the gone paths to Functions. - Known limit when cohorts 2 and 3 publish. A generator file builds all of its calculators in one call, and the heaviest took 100 to 370 ms in a cold Node run (
finance,units,finance-2,math; the build prints them). On a Workers plan with a 10 ms CPU limit that first call per file could be refused; later calls are cached. Today all 5 published calculators are hand-written and cheap. Before promoting cohort 2, check the Workers plan and measure/mcpon a preview. - Which calculators exist. Only those in
/calculators.json, written by the same build as the site. A calculator that is not published cannot be listed, described or run.verify-distfails if that file and the built pages disagree. - Limits. 16 KB request body, 100 characters per value, 40 inputs, and a best-effort 60 requests a minute per address that lives in one isolate's memory (a speed bump, not a guarantee). For a hard limit add a Cloudflare rate limiting rule for
/mcp(Security, WAF, Rate limiting rules): that is a dashboard setting for the owner. - Try it.
curl -s https://opuscalculator.com/mcp -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"calculate","arguments":{"slug":"bmi-calculator","inputs":{"weight":85}}}}' - Privacy.
/privacydescribes the endpoint; change it in the same pull request as any change to what the endpoint records.
There is no deployed admin page yet: the indexation dashboard is rendered locally (npm run dashboard, tracker 12.10). If you decide to deploy one, put Cloudflare Access in front of it first:
- Cloudflare dashboard, Zero Trust, Access, Applications, Add an application, Self-hosted.
- Application domain
opuscalculator.com, pathadmin/*. - Add a policy: action Allow, include your email address (One-time PIN login needs nothing else).
- Save, then test:
curl -I https://opuscalculator.com/admin/indexationwithout a token must answer 401 or redirect to the Access login. A signed-in browser must reach the page.
functions/_middleware.ts is a second lock: it answers 401 to any /admin/ request that has no Cloudflare Access token, so removing the Access rule by mistake fails closed. It checks that a token is present; verifying its signature would need your Access team domain and audience tag.
public/_headers sets HSTS (preload), nosniff, Referrer-Policy, Permissions-Policy, X-Frame-Options: DENY and a Content-Security-Policy. The only third party in the CSP is https://plausible.io. To add one (an ad network, an error monitor), add exactly its hosts to the CSP and to KNOWN_HOSTS in scripts/check-security.ts with the reason, and update /privacy; the build fails if you forget either.
npm run build also fails if a secret value or credential shape (private key, service-account JSON, AWS, Anthropic, GitHub or Slack token) appears in dist/, or if a PUBLIC_ variable has a secret-looking name. .env.example lists every variable the code reads (names only). npm audit --audit-level=high must pass.
All of these need a build first and use the Google Chrome already installed (Playwright's chrome channel), so there is nothing to download. Set CHROME_PATH to use another.
npm run a11y: axe-core on 8 pages in light and dark plus the widget's error state (zero violations of any impact), no sideways scroll at 320 and 640 px, the keyboard tab order (skip link first, no trap, the ad slot never focused), and the live-region timing. The tab-order tables are written toreports/a11y/; the audit of 23 Nov is indocs/ACCESSIBILITY_AUDIT.md.npm run e2e: one spec per Tier 1 calculator intests/e2e/, typing inputs and asserting the exact rendered numbers, each with an axe scan.-- --project=chromiumruns one browser. Firefox, WebKit and mobile Safari neednpx playwright install firefox webkitonce.npm run visual: 12 screenshots (layouts A, B and C, light and dark, desktop and mobile) against baselines intests/visual/layouts.spec.ts-snapshots/. The baselines are Windows renderings; on another system runnpm run visual -- --update-snapshotsonce and review the images.- Every calculator page has a toolbar (share, cite, share result, clear all changes, a preferred-source link on Google, embed code), built once in the shared template. Embeddable copies live at
/embed/<slug>/(noindex, canonical to the real page); only/embed/*may be framed, set in its own block ofpublic/_headers.verify-distfails the build if a calculator page lacks a control or its embed page. npm run lighthouse: Lighthouse 12 (fetched withnpxat run time, not a dependency) on 5 random pages from the sitemaps, 3 mobile and 2 desktop, on the installed Chrome; the local server compresses with Brotli and caches like Cloudflare Pages. It fails if a mobile page scores under 90 for performance.-- --base https://opuscalculator.comruns it on a deployed site, which is the run that counts for launch. It has not yet been proven end to end.npm run audit:prelaunch: the pre-launch checks (200 and 404, sitemaps, links, one h1 and canonical and JSON-LD, the default result in the raw HTML, the ad slot below the fold).-- --base https://opuscalculator.comruns it on a deployed site.E2E_BASE_URL=https://<preview>.pages.dev npm run e2eruns the E2E suite against a deployed preview instead of the local build.
Any calculator that shows money can show any of 31 currencies. USD is the default; the header selector (and the "Change" link in each widget) changes it. Only the symbol and number format change, never the typed amounts. The choice is kept in localStorage (opus-currency); with no choice the currency is detected from Cloudflare's country (/cdn-cgi/trace) or the browser language (never the geolocation prompt, and not on localhost). The server HTML always ships the calculator's own currency. In code: src/lib/currency.ts, currency-of.ts, currency-store.ts and fmtCurrency in src/lib/format.ts. Do not hardcode $ in a new calculator.
The theme follows the system and can be set with the header toggle (opus-theme). All colours and sizes come from src/styles/tokens.css; a test fails on a raw hex, px or rem value in a component. docs/ui-demo.html is the approved visual reference. node scripts/make-brand-assets.mjs regenerates the favicon and the social image.
Neither error monitoring nor uptime checks exist, because both need accounts (tracker 18.4 and 18.5).
- Uptime: in UptimeRobot or Better Stack create three monitors:
https://opuscalculator.com/,https://opuscalculator.com/calculators/bmi-calculator/andhttps://opuscalculator.com/sitemap-index.xml, each every 60 seconds from 3 regions, alerting your email after 2 consecutive failures. - Errors: the plan names Sentry (
tracesSampleRate0.1, no session replay, source maps at build, the DSN inSENTRY_DSN). Add it only whenSENTRY_DSNis set, add the Sentry host to the CSP andKNOWN_HOSTS, and name it in/privacy. - Incidents:
docs/INCIDENT_RUNBOOK.md,docs/ROLLBACK.mdanddocs/RUNBOOK_ONCALL.md.
GitHub, Settings, Branches, Add rule for main: require status checks to pass (the single check job), require linear history, and block force pushes. Do not require approving reviews: with one maintainer you cannot approve your own pull requests. Merge with squash.
npm run prelaunch lists them: the governing jurisdiction in src/config/site.ts, a legal read-through of /privacy, /terms and /dmca (then legalReviewed = true), the three mailboxes (hello@, dmca@, access@opuscalculator.com), the contacts in docs/RUNBOOK_ONCALL.md, and the privacy page matching the real analytics and ad network.
main is never pushed to. Every change goes: branch, code and tests, npm run verify green locally, one commit, one push, open the PR, wait for CI (gh pr checks --watch), squash-merge if CI is green. Docs changes are batched into one docs-sync-YYYY-MM-DD PR, and that PR (no CI runs on it) and any PR that edits .github/workflows are merged by the owner, not by CI. CI runs on pull requests to main only and ignores docs paths. Never commit secrets: claude-toggle.bat holds an API key and is git-ignored. If your npm is configured for a private registry, npm install can write its URLs into package-lock.json; npm run verify fails on that, and the fix is to rewrite those URLs to https://registry.npmjs.org/.