返回 CodeWhale
docs-ia.test.ts
根目录 / web / lib / docs-ia.test.ts
1 /**
2 * Information-architecture contracts: docs-map registration, sitemap and
3 * hreflang preservation, navigation parity across breakpoints and locales,
4 * and the accessibility hooks (skip link, labelled nav, aria-current).
5 *
6 * These are deterministic source/unit contracts in the same style as
7 * public-copy.test.ts: they read the real sources and assert structure, so a
8 * future IA change fails here first instead of drifting silently.
9 */
10 import { existsSync, readFileSync } from "node:fs";
11 import { describe, expect, it } from "vitest";
12 import buildSitemap from "../app/sitemap";
13 import { DOC_TOPICS, docTopicHref, getTopic } from "./docs-map";
14 import { docsTopicIsCurrent } from "./docs-navigation";
15 import { FOUNDER_SWITCHES } from "./founder-switches";
16 import { locales } from "./i18n/config";
17 import { contentLocalesForPath } from "./i18n/content-locales";
18 import { getChrome, getHome } from "./i18n/dictionaries";
19 import {
20 currentNavHref,
21 footerDocsLinks,
22 footerLegalLinks,
23 footerProductLinks,
24 footerProjectLinks,
25 navLinks as buildNavLinks,
26 signInLink,
27 } from "./i18n/links";
28 import { SITE_URL } from "./page-meta";
29 import { siteCss } from "./site-css";
30
31 const webRoot = new URL("../", import.meta.url);
32 const repoRoot = new URL("../../", import.meta.url);
33
34 function webText(path: string): string {
35 return readFileSync(new URL(path, webRoot), "utf8");
36 }
37
38 const sitemapEntries = buildSitemap();
39 const nav = webText("components/nav.tsx");
40 const navLinks = webText("components/nav-links.tsx");
41 const mobileMenu = webText("components/mobile-menu.tsx");
42 const footer = webText("components/footer.tsx");
43 const localeLayout = webText("app/[locale]/layout.tsx");
44 const css = siteCss();
45
46 describe("docs-map registration", () => {
47 it("registers the guide and vocabulary topics as first-party pages", () => {
48 const guide = getTopic("guide");
49 const vocabulary = getTopic("vocabulary");
50 expect(guide?.hasPage).toBe(true);
51 expect(vocabulary?.hasPage).toBe(true);
52 expect(vocabulary?.category).toBe("reference");
53 expect(docTopicHref(guide!, "en")).toBe("/en/docs/guide");
54 expect(docTopicHref(vocabulary!, "zh")).toBe("/zh/docs/vocabulary");
55 expect(docsTopicIsCurrent(vocabulary!, "en", "/en/docs/vocabulary")).toBe(true);
56 });
57
58 it("keeps every docs topic repo source on disk", () => {
59 for (const topic of DOC_TOPICS) {
60 const sources = Array.isArray(topic.repoSource) ? topic.repoSource : [topic.repoSource];
61 for (const source of sources) {
62 expect(existsSync(new URL(source, repoRoot)), `${topic.id}: ${source}`).toBe(true);
63 }
64 }
65 });
66
67 it("keeps topic labels and descriptions bilingual", () => {
68 for (const topic of DOC_TOPICS) {
69 for (const pair of [topic.label, topic.description]) {
70 expect(pair.en.trim().length, `${topic.id} en`).toBeGreaterThan(0);
71 expect(pair.zh.trim().length, `${topic.id} zh`).toBeGreaterThan(0);
72 }
73 }
74 });
75 });
76
77 describe("sitemap and hreflang preservation", () => {
78 it("indexes every first-party docs page", () => {
79 for (const topic of DOC_TOPICS) {
80 if (!topic.hasPage) continue;
81 const path = topic.sitePath ? `/${topic.sitePath}` : `/docs/${topic.slug}`;
82 expect(
83 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en${path}`),
84 path,
85 ).toBe(true);
86 }
87 expect(
88 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en/docs/guide`),
89 ).toBe(true);
90 expect(
91 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en/docs/vocabulary`),
92 ).toBe(true);
93 });
94
95 it("keeps sitemap and hreflang output aligned with real translation coverage", () => {
96 // Home and Computer Use have 18 locales; install and the source catalogue are English.
97 // Other page bodies ship English and Chinese.
98 expect(sitemapEntries.filter(entry => entry.url.endsWith("/install")).map(entry => entry.url))
99 .toEqual([`${SITE_URL}/en/install`]);
100 expect(sitemapEntries.some(entry => entry.url.endsWith("/pricing"))).toBe(false);
101 for (const path of ["/app", "/plugins", "/computer-use", "/legal/terms", "/legal/privacy"]) {
102 expect(
103 sitemapEntries.some((entry) => entry.url === `${SITE_URL}/en${path}`),
104 path,
105 ).toBe(true);
106 }
107 for (const [path, expectedLocales] of [
108 ["/", locales],
109 ["/docs/guide", ["en", "zh"]],
110 ["/computer-use", locales],
111 ["/install", ["en"]],
112 ["/docs", ["en", "zh"]],
113 ] as const) {
114 const suffix = path === "/" ? "" : path;
115 const entry = sitemapEntries.find(
116 (candidate) => candidate.url === `${SITE_URL}/en${suffix}`,
117 );
118 expect(entry, path).toBeDefined();
119 expect(Object.keys(entry?.alternates?.languages ?? {}), path).toEqual([
120 ...expectedLocales,
121 ]);
122 }
123 for (const path of ["/product", "/features", "/signin", "/admin", "/auth/callback", "/community", "/feed", "/roadmap", "/digest", "/runtime", "/constitution", "/enterprise", "/download", "/desktop"]) {
124 expect(sitemapEntries.some((entry) => new RegExp(`^/[^/]+${path}$`).test(new URL(entry.url).pathname)), path).toBe(false);
125 }
126 expect(sitemapEntries.every((entry) => entry.lastModified instanceof Date && Number.isFinite(entry.lastModified.getTime()))).toBe(true);
127 });
128
129 it("lists the Ratatui index but not its component pages, which stay reachable", () => {
130 const expectedUrls = contentLocalesForPath("/ratatui").map((locale) => `${SITE_URL}/${locale}/ratatui`);
131 const entries = sitemapEntries.filter(
132 (entry) => new URL(entry.url).pathname.split("/")[2] === "ratatui",
133 );
134 expect(entries.map((entry) => entry.url)).toEqual(expectedUrls);
135 expect(new Set(sitemapEntries.map((entry) => entry.url)).size).toBe(sitemapEntries.length);
136 expect(existsSync(new URL("app/[locale]/ratatui/[component]/page.tsx", webRoot))).toBe(true);
137 });
138
139 it("keeps the new docs pages on the shared metadata helper", () => {
140 for (const route of ["guide", "vocabulary"]) {
141 const page = webText(`app/[locale]/docs/${route}/page.tsx`);
142 expect(page, route).toContain('import { buildPageMetadata } from "@/lib/page-meta"');
143 expect(page, route).toContain(`path: "/docs/${route}"`);
144 }
145 });
146
147 it("keeps sign-in out of the sitemap and redirects account creation", () => {
148 expect(existsSync(new URL("app/[locale]/signin/page.tsx", webRoot))).toBe(true);
149 const entry = webText("components/public-account-entry.tsx");
150 expect(entry).toContain("<WhalePose");
151 expect(entry).toContain("installLocally");
152 expect(webText("app/[locale]/signin/page.tsx")).toContain("<PublicAccountEntry locale={locale} />");
153 expect(webText("app/[locale]/signup/page.tsx")).toContain('permanentRedirect(`/${locale}/signin`)');
154 expect(sitemapEntries.some((entry) => entry.url.endsWith("/signup"))).toBe(false);
155 expect(sitemapEntries.some((entry) => entry.url.endsWith("/docs/computers"))).toBe(false);
156 expect(webText("app/[locale]/docs/computers/page.tsx")).toContain('permanentRedirect(`/${locale}/docs/fleet`)');
157 expect(nav).not.toContain("APP_LOGIN_URL");
158 expect(nav).not.toContain("APP_SIGNUP_URL");
159 });
160 });
161
162 describe("navigation parity and accessibility", () => {
163 it("keeps desktop and mobile navigation on one shared link set", () => {
164 // Both surfaces consume the same `links` prop from nav.tsx — assert the
165 // wiring rather than duplicating the arrays.
166 expect(nav).toContain("<NavLinks links={links} primaryAria={chrome.navPrimaryAria} />");
167 expect(nav).toContain("links={links}");
168 expect(mobileMenu).toContain("links.map");
169 expect(mobileMenu).toContain("signIn.href");
170 expect(nav).toContain("FOUNDER_SWITCH_VALUES.accountSignInOffered");
171 expect(FOUNDER_SWITCHES.accountSignInOffered.value).toBe(false);
172 expect(navLinks).toContain("links.map");
173 // One generator feeds both surfaces — no per-locale hardcoded arrays.
174 expect(nav).toContain("navLinks(locale, chrome)");
175 expect(nav).not.toMatch(/const (EN|ZH)_LINKS/);
176 // The primary strip replaces the compact menu at lg, with icon-only
177 // controls leaving room for translated labels (see nav-hit-target.test).
178 // Wrapping is the escape valve for a translated strip that outgrows the
179 // row; the row gap stays tight so a second row does not double the
180 // sticky header's height.
181 expect(navLinks).toContain(
182 'className="hidden lg:flex min-w-0 shrink items-center gap-x-5 gap-y-1 flex-wrap"',
183 );
184 // One label per destination: no companion labels on either surface.
185 expect(navLinks).not.toContain("secondary");
186 expect(mobileMenu).not.toContain("secondary");
187 expect(mobileMenu).toContain('className="nav-icon-button lg:hidden"');
188 expect(nav).toContain("paper-install-cta hidden lg:inline-flex");
189 // A fixed descendant of the blurred sticky header uses the header as its
190 // containing block and collapses. The open sheet must live at body scope.
191 expect(mobileMenu).toContain('import { createPortal } from "react-dom"');
192 expect(mobileMenu).toContain("createPortal(<div");
193 expect(mobileMenu).toContain("document.body");
194 expect(mobileMenu).toContain("element.inert = true");
195 expect(mobileMenu).toContain('if (e.key !== "Tab") return');
196 expect(mobileMenu).toContain('window.matchMedia("(min-width: 1024px)")');
197 expect(mobileMenu).toContain("if (event.matches) closeImmediately()");
198 // Locale handlers are shared so a regional tag cannot nest
199 // (`/ja/pt-BR/...`); the theme control is site-wide, never route-gated.
200 expect(webText("components/locale-switcher.tsx")).toContain("replacePathLocale(pathname, code)");
201 expect(webText("components/theme-toggle.tsx")).not.toContain("isDocsPath");
202 expect(webText("middleware.ts")).toContain("pathLocale(pathname)");
203 });
204
205 it("keeps nav link paths in exact locale-swap parity for every routed locale", () => {
206 // The hardcoded /en/ and /zh/ arrays are gone; assert the generated set
207 // directly, across every routed locale rather than only two of them.
208 const reference = buildNavLinks("en", getChrome("en")).map((l) =>
209 l.href.replace(/^\/en\//, ""),
210 );
211 expect(reference).toEqual(["docs", "models", "plugins", "app", "changelog", "contribute"]);
212 for (const locale of locales) {
213 const links = buildNavLinks(locale, getChrome(locale));
214 expect(
215 links.map((l) => l.href.replace(new RegExp(`^/${locale}/`), "")),
216 `${locale} nav routes`,
217 ).toEqual(reference);
218 for (const link of [...links, signInLink(locale, getChrome(locale))]) {
219 expect(link.href.startsWith(`/${locale}/`), `${locale} ${link.href}`).toBe(true);
220 expect(link.label.trim().length, `${locale} empty nav label`).toBeGreaterThan(0);
221 }
222 }
223 });
224
225 it("keeps footer link paths in exact locale-swap parity for every routed locale", () => {
226 const reference = [
227 ...footerProductLinks("en", getChrome("en")),
228 ...footerDocsLinks("en", getChrome("en")),
229 ].map((l) => l.href.replace(/^\/en\//, ""));
230 expect(reference).toContain("computer-use");
231 expect(reference).toContain("docs/guide");
232 expect(reference).toContain("faq");
233 for (const locale of locales) {
234 const product = [
235 ...footerProductLinks(locale, getChrome(locale)),
236 ...footerDocsLinks(locale, getChrome(locale)),
237 ];
238 expect(
239 product.map((l) => l.href.replace(new RegExp(`^/${locale}/`), "")),
240 `${locale} footer product routes`,
241 ).toEqual(reference);
242 const project = footerProjectLinks(locale, getChrome(locale));
243 expect(project.map((l) => l.href), `${locale} footer project routes`).toEqual([
244 "https://github.com/codewhale-hq/CodeWhale",
245 `/${locale}/contribute`,
246 "https://discord.gg/37gfS3ksug",
247 `/${locale}/merch`,
248 "https://github.com/codewhale-hq/CodeWhale/blob/main/LICENSE",
249 ]);
250 const legal = footerLegalLinks(locale, getChrome(locale), "Usage");
251 expect(legal.map((l) => l.href), `${locale} footer legal`).toEqual([
252 `/${locale}/legal/terms`,
253 `/${locale}/legal/privacy`,
254 `/${locale}/legal/privacy#usage-counting`,
255 "https://github.com/codewhale-hq/CodeWhale/blob/main/.github/SECURITY.md",
256 ]);
257 // Labels come from the dictionary, not hardcoded English, so every
258 // routed locale renders the footer legal links in its own language.
259 expect(legal.map((l) => l.label), `${locale} footer legal labels`).toEqual([
260 getChrome(locale).footerTerms,
261 getChrome(locale).footerPrivacy,
262 "Usage",
263 getChrome(locale).footerSecurity,
264 ]);
265 }
266 });
267
268 it("labels the primary nav and marks the current page accessibly", () => {
269 expect(navLinks).toContain("aria-label={primaryAria}");
270 expect(getChrome("en").navPrimaryAria).toBe("Primary");
271 expect(getChrome("zh").navPrimaryAria).toBe("主导航");
272 expect(navLinks).toContain('aria-current={isActive ? "page" : undefined}');
273 expect(mobileMenu).toContain('aria-current={isActive ? "page" : undefined}');
274 expect(mobileMenu).toContain('aria-expanded={open}');
275 expect(mobileMenu).toContain('aria-controls="mobile-menu"');
276 expect(mobileMenu).toContain('role="dialog"');
277 });
278
279 it("marks exactly one nav link as the current page on a nested route", () => {
280 // `/xx/docs` and `/xx/docs/guide` are both nav links, so the plain
281 // prefix test both surfaces used marked two links `aria-current="page"`
282 // on the guide route — and drew the nav underline under both.
283 for (const locale of locales) {
284 const links = [
285 ...buildNavLinks(locale, getChrome(locale)),
286 { href: `/${locale}/docs/guide`, label: getChrome(locale).footerGuide },
287 ];
288 const guide = `/${locale}/docs/guide`;
289 const naive = links.filter(
290 (l) => guide === l.href || guide.startsWith(`${l.href}/`),
291 );
292 expect(naive.length, `${locale} ancestor+page collision`).toBeGreaterThan(1);
293 expect(currentNavHref(links, guide), `${locale} current nav link`).toBe(guide);
294 // A route that is not itself a nav link still resolves to its section.
295 expect(
296 currentNavHref(links, `/${locale}/docs/configuration`),
297 `${locale} section fallback`,
298 ).toBe(`/${locale}/docs`);
299 expect(currentNavHref(links, `/${locale}`), `${locale} home`).toBeNull();
300 }
301 // Both surfaces resolve the current page through the shared helper
302 // rather than repeating the prefix test that collided.
303 expect(navLinks).toContain("currentNavHref(links, pathname)");
304 expect(mobileMenu).toContain("currentNavHref(signIn ? [...links, signIn] : links, pathname)");
305 expect(navLinks).not.toContain("pathname.startsWith(");
306 expect(mobileMenu).not.toContain("pathname.startsWith(");
307 });
308
309 it("ships a keyboard-reachable skip link to the main landmark", () => {
310 expect(localeLayout).toContain('href="#main-content"');
311 expect(localeLayout).toContain('className="skip-link"');
312 expect(localeLayout).toContain('<main id="main-content">');
313 expect(css).toContain(".skip-link:focus-visible");
314 });
315
316 it("keeps the docs trail on the docs-map registry", () => {
317 const docsLayout = webText("app/[locale]/docs/layout.tsx");
318 const docsMap = webText("lib/docs-map.ts");
319 expect(docsMap).toContain("sidebar, breadcrumbs, and drift/parity checks");
320 expect(docsMap).toContain("export const DOC_CATEGORY_LABELS");
321 expect(docsLayout).toContain("<DocsBreadcrumb locale={locale} />");
322 expect(css).toContain(".docs-breadcrumb");
323 });
324
325 it("keeps responsive breakpoints for the getting-started steps", () => {
326 // 4-up grid by default, 2-up at the tablet breakpoint, 1-up on phones —
327 // the same responsive ladder as the existing workflow steps.
328 expect(css).toMatch(/\.gs-steps\s*\{[^}]*repeat\(4, minmax\(0, 1fr\)\)/);
329 expect(css).toMatch(
330 /@media \(max-width: 760px\)[\s\S]*?\.gs-steps\s*\{[^}]*repeat\(2, minmax\(0, 1fr\)\)/,
331 );
332 expect(css).toMatch(
333 /@media \(max-width: 520px\)[\s\S]*?\.gs-steps\s*\{\s*grid-template-columns: 1fr/,
334 );
335 });
336
337 it("keeps the footer discovery links alongside the pinned legal links", () => {
338 // The link sets moved to lib/i18n/links.ts, so assert the rendered
339 // contract for en AND zh rather than scraping literals out of the TSX.
340 for (const locale of ["en", "zh"]) {
341 const docs = footerDocsLinks(locale, getChrome(locale)).map((l) => l.href);
342 expect(docs, `${locale} footer docs`).toContain(`/${locale}/docs/guide`);
343 expect(docs, `${locale} footer docs`).toContain(`/${locale}/faq`);
344 }
345 const license = footerProjectLinks("en", getChrome("en")).at(-1);
346 expect(license).toEqual({
347 label: "MIT license",
348 href: "https://github.com/codewhale-hq/CodeWhale/blob/main/LICENSE",
349 });
350 // zh gets the footer legal labels from its dictionary, not English.
351 expect(footerLegalLinks("zh", getChrome("zh"), "使用数据").map((l) => l.label).slice(0, 2)).toEqual([
352 "服务条款",
353 "隐私政策",
354 ]);
355 expect(footer).toContain("footerProductLinks(locale, chrome)");
356 expect(footer).toContain("footerDocsLinks(locale, chrome)");
357 expect(footer).toContain("footerProjectLinks(locale, chrome)");
358 expect(footer).toContain("footerLegalLinks(locale, chrome,");
359 });
360 });
361
362 describe("homepage integration", () => {
363 const homepage = webText("app/[locale]/page.tsx");
364
365 it("names the published release and never the source version", () => {
366 expect(homepage).toContain("facts.latestPublishedRelease");
367 expect(homepage).not.toContain("facts.version");
368 expect(getHome("en").installNote).toContain("{version}");
369 });
370 });
371
371 lines TYPESCRIPT