From f0cc108fe94d9d1f9d3e0fbca9ff0e46a1f8e515 Mon Sep 17 00:00:00 2001 From: FreeDEX <101082494+YaMaiDay@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:04:58 +0800 Subject: [PATCH] Optimize docs loading and maintenance workflows --- .github/actions/validate-docs/action.yml | 42 ++ .github/workflows/docs-check.yml | 28 +- .github/workflows/docs-publish.yml | 28 +- CONTRIBUTING.md | 8 + README.md | 10 +- fern/card-effects.js | 28 +- fern/docs-interface.js | 19 +- fern/language-modal.js | 22 +- fern/seo-structured-data.js | 65 +-- scripts/check-customer-support.mjs | 10 +- scripts/check-docs-interface.mjs | 14 + scripts/check-navigation-icons.test.mjs | 18 +- scripts/check-translations.mjs | 17 +- scripts/check-workflows-translations.test.mjs | 532 +++++++++++------- scripts/check-workflows.test.mjs | 185 ++++-- scripts/documentation-pages.mjs | 34 ++ scripts/generate-translations.mjs | 73 +-- scripts/polish-core-translations.mjs | 2 +- scripts/preview-prediction.mjs | 5 +- scripts/test-fixture-paths.mjs | 15 + tests/browser/regression.test.mjs | 160 ++++++ 21 files changed, 870 insertions(+), 445 deletions(-) create mode 100644 .github/actions/validate-docs/action.yml create mode 100644 scripts/documentation-pages.mjs create mode 100644 scripts/test-fixture-paths.mjs diff --git a/.github/actions/validate-docs/action.yml b/.github/actions/validate-docs/action.yml new file mode 100644 index 00000000..cc46e5cf --- /dev/null +++ b/.github/actions/validate-docs/action.yml @@ -0,0 +1,42 @@ +name: Validate docs +description: Run documentation and browser checks on the checked-out revision. +inputs: + fern-token: + description: Fern token for authenticated checks, when available. + required: false + +runs: + using: composite + steps: + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: npm + cache-dependency-path: | + package-lock.json + tests/browser/package-lock.json + + - name: Install dependencies + shell: bash + run: npm ci + + - name: Validate documentation + shell: bash + run: npm run check + env: + FERN_TOKEN: ${{ inputs.fern-token }} + + - name: Install browser regression dependencies + shell: bash + run: npm ci --prefix tests/browser --ignore-scripts + + - name: Install regression browsers + shell: bash + working-directory: tests/browser + # CI launches Chromium headlessly without a channel. WebKit is still installed. + run: npm run install:browsers -- --with-deps --only-shell + + - name: Verify browser interactions + shell: bash + run: npm run browser:check diff --git a/.github/workflows/docs-check.yml b/.github/workflows/docs-check.yml index d7418308..473929c4 100644 --- a/.github/workflows/docs-check.yml +++ b/.github/workflows/docs-check.yml @@ -22,29 +22,7 @@ jobs: - name: Check out repository uses: actions/checkout@v5 - - name: Set up Node.js - uses: actions/setup-node@v6 + - name: Validate docs and browser interactions + uses: ./.github/actions/validate-docs with: - node-version: 22 - cache: npm - cache-dependency-path: | - package-lock.json - tests/browser/package-lock.json - - - name: Install dependencies - run: npm ci - - - name: Validate documentation - run: npm run check - env: - FERN_TOKEN: ${{ secrets.FERN_TOKEN }} - - - name: Install browser regression dependencies - run: npm ci --prefix tests/browser --ignore-scripts - - - name: Install regression browsers - working-directory: tests/browser - run: npm run install:browsers -- --with-deps - - - name: Verify browser interactions - run: npm run browser:check + fern-token: ${{ secrets.FERN_TOKEN }} diff --git a/.github/workflows/docs-publish.yml b/.github/workflows/docs-publish.yml index 23802884..18e9372b 100644 --- a/.github/workflows/docs-publish.yml +++ b/.github/workflows/docs-publish.yml @@ -20,32 +20,10 @@ jobs: - name: Check out repository uses: actions/checkout@v5 - - name: Set up Node.js - uses: actions/setup-node@v6 + - name: Validate docs and browser interactions + uses: ./.github/actions/validate-docs with: - node-version: 22 - cache: npm - cache-dependency-path: | - package-lock.json - tests/browser/package-lock.json - - - name: Install dependencies - run: npm ci - - - name: Validate documentation - run: npm run check - env: - FERN_TOKEN: ${{ secrets.FERN_TOKEN }} - - - name: Install browser regression dependencies - run: npm ci --prefix tests/browser --ignore-scripts - - - name: Install regression browsers - working-directory: tests/browser - run: npm run install:browsers -- --with-deps - - - name: Verify browser interactions - run: npm run browser:check + fern-token: ${{ secrets.FERN_TOKEN }} # Both gates above must pass; avoid repeating the local prepublish hook. - name: Publish to Fern production diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9c9e565b..715c2521 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,11 +18,19 @@ Documentation source files live under: - `fern/docs.yml` for English navigation, tabs, redirects, and site configuration - `fern/translations//` for locales handled by Fern's native localization +List every English source page in `fern/docs.yml` navigation. Generation and +validation use that list directly when pages are added or retired. + English is the source of truth. If an English page changes, regenerate the affected locales with `npm run translations:generate -- --locales=`. For a deliberate manual translation, refresh its source hash with `npm run translations:refresh-manifest -- --locales=`. +Incremental generation reuses an existing navigation overlay once its English +navigation has been cached. Review navigation changes when the English tabs or +sidebar change, or run `npm run translations:generate -- --labels-only --locales=` +to regenerate navigation labels explicitly. + After translation generation, run `npm run translations:polish`. The repository checks verify all 20 public locales, canonical URLs, internal links, code samples, and locale configuration. diff --git a/README.md b/README.md index 68f96b7e..a97635f3 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ The public Trading Widget `v1` runtime was checked at version `1.8.0` on English and Simplified Chinese are reviewed together. The other 18 locales use machine-assisted translation with code, links, identifiers and structure checks; -these checks do not substitute for native-language editorial review. The current -navigation has 158 unique pages per locale. +these checks do not substitute for native-language editorial review. The English +navigation defines the page list for all locales. ## Local Development @@ -160,9 +160,9 @@ On Linux, append `-- --with-deps` to the browser installation command to install the required system packages. See [Playwright's CI setup](https://playwright.dev/docs/ci). The regular `npm run check` remains available without downloading browsers. The **Docs checks** workflow runs both documentation and browser checks for pull -requests and pushes to `main`, using the same Node.js version and browser commands -as the publication workflow. Documentation checks run first so a failure stops -the job before browser installation. +requests and pushes to `main`. It shares the [validation action](.github/actions/validate-docs/action.yml) +with the publication workflow. Documentation checks run first so a failure stops +the job before browser installation. CI installs Chromium Headless Shell and WebKit. ## Customer support integration diff --git a/fern/card-effects.js b/fern/card-effects.js index 949f777f..96ef8d85 100644 --- a/fern/card-effects.js +++ b/fern/card-effects.js @@ -5,6 +5,12 @@ var languageGroups = ".sixmm-language-menu-enhanced .fern-language-selector-radio-group, .sixmm-mobile-language-dialog-options"; var groupSelector = ".fern-card-group, .sixmm-stat-grid, .fern-layout-footer .fern-footer-nav, " + languageGroups; var cardSelector = ".fern-card, .sixmm-stat-grid > div"; + var footerCardSelector = ".fern-layout-footer .fern-footer-nav > a"; + var languageOptionSelector = ".sixmm-language-menu-enhanced .fern-language-dropdown-item, .sixmm-mobile-language-dialog-option"; + // Native menus acquire their enhanced class in the language script's next + // frame, so discover their insertion before that class is present as well. + var addedTargetSelector = "article .fern-card, article .sixmm-stat-grid > div, " + footerCardSelector + ", " + languageOptionSelector + ", .fern-language-dropdown-content"; + var registeredTargetSelector = ".sixmm-content-card, .sixmm-language-option-effect"; var groups = new Map(); var hover = window.matchMedia("(hover: hover) and (pointer: fine)"); var reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)"); @@ -62,10 +68,8 @@ }); }); // Only the footer's page-switching cards opt in; feedback and edit controls do not. - document.querySelectorAll(".fern-layout-footer .fern-footer-nav > a").forEach(register); - document.querySelectorAll( - ".sixmm-language-menu-enhanced .fern-language-dropdown-item, .sixmm-mobile-language-dialog-option" - ).forEach(function (option) { register(option, "sixmm-language-option-effect"); }); + document.querySelectorAll(footerCardSelector).forEach(register); + document.querySelectorAll(languageOptionSelector).forEach(function (option) { register(option, "sixmm-language-option-effect"); }); groups.forEach(function (cards) { // Compact private group lists without allocating replacements on every scan. var count = 0; @@ -109,7 +113,7 @@ function move(event) { if (!enabled() || event.pointerType === "touch") { reset(); return; } var target = event.target instanceof Element ? event.target : null; - var card = target && target.closest(".sixmm-content-card, .sixmm-language-option-effect"); + var card = target && target.closest(registeredTargetSelector); var group = target && (target.closest(groupSelector) || card); if (!group || !groups.has(group)) { reset(); return; } if (activeGroup !== group) { reset(); activeGroup = group; } @@ -124,17 +128,23 @@ if (!frame) frame = requestAnimationFrame(render); } - function containsElement(nodes) { - return Array.prototype.some.call(nodes, function (node) { return node.nodeType === 1; }); + function containsTarget(nodes, selector) { + return Array.prototype.some.call(nodes, function (node) { + return node.nodeType === 1 && (node.matches(selector) || node.querySelector(selector)); + }); } function observeBody() { if (observedBody === document.body) return; if (bodyObserver) bodyObserver.disconnect(); else bodyObserver = new MutationObserver(function (records) { - // Text and comment changes cannot add or remove card targets. + // Search results, support messages and ordinary article markup do not + // change effect targets. Inspect only changed subtrees before scheduling + // a full scan. Removed targets retain their effect class even after losing + // the article/group ancestors needed by the discovery selectors. if (records.some(function (record) { - return containsElement(record.addedNodes) || containsElement(record.removedNodes); + return containsTarget(record.addedNodes, addedTargetSelector) || + containsTarget(record.removedNodes, registeredTargetSelector); })) { scheduleScan(); } diff --git a/fern/docs-interface.js b/fern/docs-interface.js index fefc3317..6dce107c 100644 --- a/fern/docs-interface.js +++ b/fern/docs-interface.js @@ -113,20 +113,25 @@ return NodeFilter.FILTER_SKIP; } }), node; + // Most navigation and article labels are already in the right language. + // Check React ownership only before a write, when it can affect behavior. while ((node = walker.nextNode())) { - if (!eligible(node.parentElement)) continue; var next = translate(node.nodeValue, selected); - if (next !== node.nodeValue) node.nodeValue = next; + if (next !== node.nodeValue && eligible(node.parentElement)) node.nodeValue = next; } var elements = root.querySelectorAll('[aria-label], [title], [placeholder]'); function syncAttributes(element) { - if (!eligible(element)) return; - translatedAttributes.forEach(function (name) { + var canWrite = false; + for (var index = 0; index < translatedAttributes.length; index++) { + var name = translatedAttributes[index]; var value = element.getAttribute(name); - if (value === null) return; + if (value === null) continue; var next = translate(value, selected); - if (next !== value) element.setAttribute(name, next); - }); + if (next === value) continue; + if (!canWrite && !eligible(element)) return; + canWrite = true; + element.setAttribute(name, next); + } } syncAttributes(root); elements.forEach(syncAttributes); diff --git a/fern/language-modal.js b/fern/language-modal.js index a9587345..8b013592 100644 --- a/fern/language-modal.js +++ b/fern/language-modal.js @@ -667,10 +667,29 @@ window.requestAnimationFrame(syncInterface); } + function tuneStaticSidebarPrefetch(root) { + var sidebar = root && root.getElementById && root.getElementById("fern-sidebar-static"); + if (!sidebar) return; + sidebar.querySelectorAll('a[data-astro-prefetch="viewport"], a[data-astro-prefetch="load"]').forEach(function (link) { + // Fern scans the static sidebar before the afterInteractive script runs. + // Leave React-owned links to the existing post-hydration bridge. + if (!link.closest("astro-island")) link.setAttribute("data-astro-prefetch", "hover"); + }); + } + // This script loads before interactive content. Set the pathname-derived // locale immediately so standalone navigation tabs never flash on first paint. syncLocaleTabs(currentRoute()); - document.addEventListener("DOMContentLoaded", scheduleSync); + var parsingSidebar = document.readyState === "loading"; + tuneStaticSidebarPrefetch(document); + document.addEventListener("DOMContentLoaded", function () { + parsingSidebar = false; + tuneStaticSidebarPrefetch(document); + scheduleSync(); + }); + document.addEventListener("astro:before-swap", function (event) { + tuneStaticSidebarPrefetch(event.newDocument); + }); document.addEventListener("fern:island-hydrated", scheduleSync); document.addEventListener("astro:page-load", scheduleSync); window.addEventListener("pageshow", function () { @@ -685,6 +704,7 @@ if (!isMobileViewport()) closeMobileLocaleDialog(false); }); new MutationObserver(function (records) { + if (parsingSidebar) tuneStaticSidebarPrefetch(document); var controls = '.fern-language-selector, .fern-language-dropdown-content, .sixmm-theme-trigger, .fern-header-mobile-menu-button'; if (records.some(function (record) { var target = record.target.nodeType === 1 ? record.target : record.target.parentElement; diff --git a/fern/seo-structured-data.js b/fern/seo-structured-data.js index 834dbb20..8bb74585 100644 --- a/fern/seo-structured-data.js +++ b/fern/seo-structured-data.js @@ -243,7 +243,7 @@ function upsertStructuredData(key, value) { var selector = 'script[data-sixmm-schema="' + key + '"]'; - var script = document.querySelector(selector); + var script = document.head.querySelector(selector); if (!value) { if (script) { @@ -331,9 +331,9 @@ } function syncStructuredData() { - var pathname = normalizedPathname(window.location.pathname); + lastStructuredPath = window.location.pathname; + var pathname = normalizedPathname(lastStructuredPath); var pagePath = pagePathForPathname(pathname); - lastStructuredPath = pathname; var locale = localeForPathname(pathname); var isHome = pagePath === "/"; var canonicalUrl = localizedUrl(locale.route, pagePath); @@ -378,25 +378,28 @@ } var lastStructuredPath; + var observedHead; var observer; var scheduled = false; var syncing = false; function observeChanges() { - if (!observer) return; - observer.observe(document.documentElement, { - childList: true, - subtree: true, - }); + observedHead = document.head; + // Watch the root for replacement of the head. Astro notifies us directly + // when navigation finishes, so body content need not be observed. + observer.observe(document.documentElement, { childList: true }); + if (observedHead) { + observer.observe(observedHead, { childList: true, subtree: true, characterData: true }); + } } function runSync() { if (syncing) return; syncing = true; scheduled = false; - if (observer) observer.disconnect(); + observer.disconnect(); try { - syncStructuredData(); + if (document.head) syncStructuredData(); } finally { observeChanges(); syncing = false; @@ -409,43 +412,20 @@ window.requestAnimationFrame(runSync); } - function containsManagedSeoNode(node) { - if (!node || node.nodeType !== 1) return false; - - if ( - node.hasAttribute("data-sixmm-schema") - ) { - return true; - } - - return Boolean( - node.querySelector && - node.querySelector( - 'script[data-sixmm-schema]', - ), - ); + function isTitle(node) { + return node && node.nodeName === "TITLE"; } function shouldResync(mutations) { - var pathname = normalizedPathname(window.location.pathname); - if (pathname !== lastStructuredPath) return true; + if (document.head !== observedHead || window.location.pathname !== lastStructuredPath) return true; return mutations.some(function (mutation) { - var target = mutation.target; - if (target && target.nodeName === "TITLE") return true; - - var titleAdded = Array.prototype.some.call( - mutation.addedNodes || [], - function (node) { - return node && node.nodeName === "TITLE"; - }, - ); - if (titleAdded) return true; - - return Array.prototype.some.call( - mutation.removedNodes || [], - containsManagedSeoNode, - ); + var target = mutation.type === "characterData" ? mutation.target.parentNode : mutation.target; + return isTitle(target) || + Array.prototype.some.call(mutation.addedNodes, isTitle) || + Array.prototype.some.call(mutation.removedNodes, function (node) { + return node.nodeType === 1 && node.matches("title, script[data-sixmm-schema]"); + }); }); } @@ -456,4 +436,5 @@ window.addEventListener("popstate", scheduleSync); window.addEventListener("pageshow", scheduleSync); document.addEventListener("DOMContentLoaded", scheduleSync); + document.addEventListener("astro:page-load", scheduleSync); })(); diff --git a/scripts/check-customer-support.mjs b/scripts/check-customer-support.mjs index bd76916a..6671935e 100644 --- a/scripts/check-customer-support.mjs +++ b/scripts/check-customer-support.mjs @@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; import { parse } from 'yaml'; +import { assertSourcePagesListed } from './documentation-pages.mjs'; const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); // Validation is read-only; share each file's text within this run. const contents = new Map(); @@ -15,7 +16,10 @@ const config=parse(await read('fern/docs.yml')); const nav=config.navigation.find(item=>item.tab==='customerSupport'); assert(nav, 'AI Support must have a top-level navigation entry'); const pages=nav.layout.flatMap(group=>group.contents.map(page=>page.path)); -assert.equal(new Set(pages).size,18,'Expected 18 tenant guide pages'); +const supportDirectory = 'docs/pages/customer-support'; +assert(pages.length && pages.every(page => page?.startsWith(supportDirectory + '/')), 'AI Support navigation must point to tenant guide pages'); +assert.equal(new Set(pages).size, pages.length, 'Duplicate tenant guide page in AI Support navigation'); +await assertSourcePagesListed(path.join(root, 'fern'), pages, supportDirectory); const source=await read('fern/docs/pages/customer-support/mcp-calls.mdx'); // Protocol examples are read-only and normally identical across all locales. const parsedExamples = new Map(); @@ -41,7 +45,7 @@ const sourceHeadingCounts = new Map(); for(const locale of config.translations){ const base=locale.default?'fern':`fern/translations/${locale.lang}`; const prefix=locale.default?'':`/${locale.lang}`; - // Read one locale's 18 guides together; validate in the original order below. + // Read one locale's guides together; validate in the original order below. // Settle failures here so a later missing file cannot mask an earlier assertion. await Promise.allSettled(pages.map(file=>read(`${base}/${file}`))); for(const file of pages) { @@ -70,4 +74,4 @@ for(const locale of config.translations){ assert(entry.includes(`href="${prefix}/customer-support/mcp-connect"`),`${locale.lang}: missing MCP entry`); } } -console.log(`Customer support docs verified: 18 pages, ${config.translations.length} locales, tenant entry points and valid MCP examples.`); +console.log(`Customer support docs verified: ${pages.length} pages, ${config.translations.length} locales, tenant entry points and valid MCP examples.`); diff --git a/scripts/check-docs-interface.mjs b/scripts/check-docs-interface.mjs index 0399d42b..a77ed097 100644 --- a/scripts/check-docs-interface.mjs +++ b/scripts/check-docs-interface.mjs @@ -147,4 +147,18 @@ observerCallbacks[0]([{ target: { nodeType: 1, closest: selector => selector.inc flush(); assert.ok(fullWalks > beforeLocaleWalks, 'A control mutation cannot downgrade a pending full locale update'); assert.equal(nodes[0].nodeValue, '搜索'); +let unrelatedOwnershipChecks = 0; +nodes.push({ + nodeValue: 'Untranslated navigation heading', + parentElement: { + closest(selector) { + if (selector === 'astro-island') unrelatedOwnershipChecks++; + return hydratedAncestor(selector); + }, + }, +}); +listeners['astro:page-load'](); +flush(); +assert.equal(nodes.at(-1).nodeValue, 'Untranslated navigation heading'); +assert.equal(unrelatedOwnershipChecks, 0, 'Unchanged labels must not visit React ownership'); console.log("Docs interface regression checks passed: locale edit links, reversible labels, hydration guard and scoped singleton lifecycle."); diff --git a/scripts/check-navigation-icons.test.mjs b/scripts/check-navigation-icons.test.mjs index 3bc407cc..b7528639 100644 --- a/scripts/check-navigation-icons.test.mjs +++ b/scripts/check-navigation-icons.test.mjs @@ -3,9 +3,9 @@ import test from "node:test"; import { mkdtemp, mkdir, copyFile, symlink, writeFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; import { inspectNavigationIcons, mergeNavigationOverlay } from "./check-navigation-icons.mjs"; +import { linkDirectory, linkFixtureDependencies } from "./test-fixture-paths.mjs"; const page = (name, glyph, family = "fa-duotone") => ({ page: name, icon: `${family} ${glyph}` }); const section = (name, contents) => ({ section: name, contents }); @@ -82,13 +82,19 @@ test("CLI path aliases execute validation while imports remain side-effect free" await mkdir(path.join(root, "scripts")); await mkdir(path.join(root, "fern")); await copyFile(new URL("./check-navigation-icons.mjs", import.meta.url), path.join(root, "scripts/check.mjs")); - await symlink("check.mjs", path.join(root, "scripts/linked-check.mjs")); - await symlink("scripts/check.mjs", path.join(root, "linked-check.mjs")); - await symlink(fileURLToPath(new URL("../node_modules", import.meta.url)), path.join(root, "node_modules"), "dir"); + await linkFixtureDependencies(root); + const aliases = []; + if (process.platform === "win32") { + await linkDirectory(path.join(root, "scripts"), path.join(root, "linked-scripts")); + aliases.push("linked-scripts/check.mjs"); + } else { + await symlink("check.mjs", path.join(root, "scripts/linked-check.mjs")); + await symlink("scripts/check.mjs", path.join(root, "linked-check.mjs")); + aliases.push("scripts/linked-check.mjs", "linked-check.mjs"); + } const entries = [ ["scripts/check.mjs"], [path.join(root, "scripts/check.mjs")], - ["scripts/linked-check.mjs"], ["--preserve-symlinks-main", "scripts/linked-check.mjs"], - ["linked-check.mjs"], ["--preserve-symlinks-main", "linked-check.mjs"], + ...aliases.flatMap(alias => [[alias], ["--preserve-symlinks-main", alias]]), ]; for (const valid of [true, false]) { await writeFile(path.join(root, "fern/docs.yml"), JSON.stringify({ diff --git a/scripts/check-translations.mjs b/scripts/check-translations.mjs index 946d6b93..fd740eb4 100644 --- a/scripts/check-translations.mjs +++ b/scripts/check-translations.mjs @@ -14,6 +14,7 @@ import { } from "./locale-config.mjs"; import { findTranslationQualityIssues } from "./polish-core-translations.mjs"; import { frontmatter, internalDestinations } from "./documentation-text.mjs"; +import { activeDocumentationPages, assertSourcePagesListed } from "./documentation-pages.mjs"; const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const fernRoot = path.join(projectRoot, "fern"); @@ -146,20 +147,8 @@ if (!sameArray(configuredLocales, nativeLocales)) { ); } -const activePages = [ - ...new Set( - (config.navigation ?? []).flatMap((navigationItem) => - (navigationItem.layout ?? []).flatMap((section) => - (section.contents ?? []) - .map((content) => content.path) - .filter((contentPath) => contentPath?.startsWith("docs/pages/")), - ), - ), - ), -]; -if (activePages.length !== 158) { - pushError(`Expected 158 active pages, found ${activePages.length}`); -} +const activePages = activeDocumentationPages(config); +await assertSourcePagesListed(fernRoot, activePages); if (config.title !== "6MM Docs") { pushError(`Site title must remain "6MM Docs"; found ${config.title ?? "missing"}`); diff --git a/scripts/check-workflows-translations.test.mjs b/scripts/check-workflows-translations.test.mjs index d7fd2433..8f2f5bcd 100644 --- a/scripts/check-workflows-translations.test.mjs +++ b/scripts/check-workflows-translations.test.mjs @@ -1,14 +1,17 @@ import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { mkdtemp, mkdir, readFile, readdir, writeFile, rm, copyFile, symlink } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; +import { describe, test } from 'node:test'; +import { mkdtemp, mkdir, readFile, readdir, writeFile, rm, copyFile } from 'node:fs/promises'; +import { availableParallelism, tmpdir } from 'node:os'; import path from 'node:path'; -import { spawnSync } from 'node:child_process'; +import { execFile } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { createHash } from 'node:crypto'; import { generatorVersion } from './locale-config.mjs'; +import { linkFixtureDependencies } from './test-fixture-paths.mjs'; -async function translationRequestFixture(scenario, label, manifestState, extraArgs = [], cachedPageState, sourceBody = 'Example content.\n') { +const fixturePageCount = 3; + +async function translationRequestFixture(scenario, label, manifestState, extraArgs = [], cachedPageState, sourceBody = 'Example content.\n', exercise) { const root = await mkdtemp(path.join(tmpdir(), 'sixmm-translation-request-')); const projectRoot = fileURLToPath(new URL('../', import.meta.url)); const manifestContent = manifestState?.content ?? '{'; @@ -16,15 +19,15 @@ async function translationRequestFixture(scenario, label, manifestState, extraAr await mkdir(path.join(root, 'scripts')); // Copy the generator's modules, not unrelated maintenance scripts or tests. // Real copies keep import.meta.url rooted in this disposable workspace. - for (const name of ['generate-translations.mjs', 'locale-config.mjs', 'polish-core-translations.mjs', 'translation-text.mjs', 'write-generated-file.mjs', 'ordered-batches.mjs']) { + for (const name of ['generate-translations.mjs', 'locale-config.mjs', 'polish-core-translations.mjs', 'translation-text.mjs', 'write-generated-file.mjs', 'ordered-batches.mjs', 'documentation-pages.mjs']) { await copyFile(path.join(projectRoot, 'scripts', name), path.join(root, 'scripts', name)); } - await symlink(path.join(projectRoot, 'node_modules'), path.join(root, 'node_modules'), 'dir'); + await linkFixtureDependencies(root); await mkdir(path.join(root, 'fern')); await writeFile(path.join(root, 'fern/docs.yml'), JSON.stringify({ tabs: { home: { 'display-name': label } }, navigation: [{ tab: 'home', layout: [{ section: label, contents: - Array.from({ length: 158 }, (_, i) => ({ page: label, path: `docs/pages/page-${i}.mdx` })) + Array.from({ length: fixturePageCount }, (_, i) => ({ page: label, path: `docs/pages/page-${i}.mdx` })) }] }] })); if (manifestState) { @@ -38,12 +41,13 @@ async function translationRequestFixture(scenario, label, manifestState, extraAr const pages = {}; await mkdir(path.join(root, 'fern/docs/pages'), { recursive: true }); await mkdir(path.join(root, 'fern/translations/ja/docs/pages'), { recursive: true }); - for (let i = 0; i < 158; i++) { + for (let i = 0; i < fixturePageCount; i++) { const relative = `docs/pages/page-${i}.mdx`; const source = `---\ntitle: Example\nslug: page-${i}\n---\n\n${sourceBody}`; const sourcePath = path.join(root, 'fern', relative); - if (i === 157 && cachedPageState === 'source-directory') await mkdir(sourcePath); - else if (!(i === 157 && cachedPageState === 'source-missing')) await writeFile(sourcePath, source); + const lastPage = i === fixturePageCount - 1; + if (lastPage && cachedPageState === 'source-directory') await mkdir(sourcePath); + else if (!(lastPage && cachedPageState === 'source-missing')) await writeFile(sourcePath, source); pages[relative] = createHash('sha256').update(`${generatorVersion}\0ja\0ja\0${source}`).digest('hex'); const destination = path.join(root, 'fern/translations/ja', relative); if (i === 0 && cachedPageState === 'missing') continue; @@ -54,6 +58,11 @@ async function translationRequestFixture(scenario, label, manifestState, extraAr } await writeFile(path.join(root, 'fern/translations/.translation-manifest.json'), JSON.stringify({ version: generatorVersion, locales: { ja: { pages } } })); + if (cachedPageState === 'source-unlisted') { + const extraPage = path.join(root, 'fern/docs/pages/nested/unlisted.mdx'); + await mkdir(path.dirname(extraPage)); + await writeFile(extraPage, 'Unlisted source page\n'); + } } const originalManifest = cachedPageState ? await readFile(path.join(root, 'fern/translations/.translation-manifest.json'), 'utf8') : null; @@ -142,13 +151,20 @@ globalThis.fetch = async (input, options) => { }) }; }; `); - const localeArgs = extraArgs.some(argument => argument.startsWith('--locales=')) ? [] : ['--locales=ja']; - const result = spawnSync(process.execPath, ['--require', preload, - 'scripts/generate-translations.mjs', ...(cachedPageState ? [] : ['--labels-only']), ...localeArgs, ...extraArgs], { - cwd: root, encoding: 'utf8', timeout: 10000, - env: { ...process.env, DOCS_TRANSLATION_PROVIDER: scenario.startsWith('edge-') ? 'edge' : 'google', SIXMM_TRANSLATION_CASE: scenario } + const runGenerator = args => new Promise((resolve, reject) => { + execFile(process.execPath, ['--require', preload, 'scripts/generate-translations.mjs', ...args], { + cwd: root, encoding: 'utf8', timeout: 10000, + env: { ...process.env, DOCS_TRANSLATION_PROVIDER: scenario.startsWith('edge-') ? 'edge' : 'google', SIXMM_TRANSLATION_CASE: scenario } + }, (error, stdout, stderr) => { + if (error && typeof error.code !== 'number') { + reject(error); + return; + } + resolve({ status: error?.code ?? 0, stdout, stderr }); + }); }); - assert.equal(result.signal, null, result.error?.message); + const localeArgs = extraArgs.some(argument => argument.startsWith('--locales=')) ? [] : ['--locales=ja']; + const result = await runGenerator([...(cachedPageState ? [] : ['--labels-only']), ...localeArgs, ...extraArgs]); const log = await readFile(path.join(root, 'requests.jsonl'), 'utf8').catch(error => { if (error.code !== 'ENOENT') throw error; return ''; @@ -179,230 +195,316 @@ globalThis.fetch = async (input, options) => { const temporaryWrites = cachedPageState ? (await Promise.all(['', 'ja', 'ja/docs/pages'].map(directory => readdir(path.join(root, 'fern/translations', directory))))) .flat().filter(name => name.startsWith('.translation-manifest-') || name.startsWith('.translation-write-')) : []; + if (exercise) await exercise({ root, runGenerator, result, requests }); return { ...result, requests, requestEvents, authRequests, output, recoveredPage, preservedManifest, temporaryWrites }; } finally { await rm(root, { recursive: true, force: true }); } } -for (const state of ['source-missing', 'source-directory', 'missing', 'directory']) { - test(`manifest refresh preserves the cache when input is ${state}`, async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, ['--refresh-manifest'], state); - assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, state.includes('directory') ? /EISDIR/ : /ENOENT/); - assert.equal(result.requests.length, 0); - assert.equal(result.output, null); - assert.equal(result.preservedManifest, true); - assert.deepEqual(result.temporaryWrites, []); - }); -} - -test('multiple placeholder repairs finish in order without overlapping provider requests', async () => { - const body = 'First SDK\nSecond API\n'; - const result = await translationRequestFixture('multi-missing', 'Example', undefined, [], 'missing', body); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.requests.length, 4); - assert.ok(result.recoveredPage?.endsWith(body)); - assert.deepEqual(result.requestEvents, [1, 2, 3, 4].flatMap(id => [['start', id], ['finish', id]])); -}); - -for (const [scenario, requests, authRequests] of [ - ['edge-http-400', 1, 1], ['edge-http-403', 1, 1], ['edge-http-404', 1, 1], - ['edge-http-408', 8, 1], ['edge-http-429', 20, 1], ['edge-http-503', 8, 1], ['edge-http-401', 8, 8], - ['edge-auth-forbidden', 0, 1], -]) { - test(`${scenario} stops at the appropriate retry limit without writing`, async () => { - const result = await translationRequestFixture(scenario, 'Example'); - assert.equal(result.status, 1, result.stderr); - assert.equal(result.requests.length, requests); - assert.equal(result.authRequests, authRequests); - assert.equal(result.output, null); - assert.match(result.stderr, /returned HTTP/); - }); -} -for (const [scenario, authRequests] of [['edge-http-401-once', 2], ['edge-refresh-transient', 3]]) { - test(`${scenario} recovers through the bounded token refresh flow`, async () => { - const result = await translationRequestFixture(scenario, 'SDK Example'); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.requests.length, 2); - assert.equal(result.authRequests, authRequests); - assert.ok(result.output?.includes('display-name: "SDK Example"')); - }); -} +// Each case owns a temporary workspace and a simulated provider. +describe("translation generation", { concurrency: Math.min(4, availableParallelism()) }, () => { + for (const state of ['source-missing', 'source-directory', 'missing', 'directory']) { + test(`manifest refresh preserves the cache when input is ${state}`, async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, ['--refresh-manifest'], state); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, state.includes('directory') ? /EISDIR/ : /ENOENT/); + assert.equal(result.requests.length, 0); + assert.equal(result.output, null); + assert.equal(result.preservedManifest, true); + assert.deepEqual(result.temporaryWrites, []); + }); + } -for (const scenario of ['edge-missing-text', 'edge-null-item', 'edge-number-text', 'edge-empty-text', 'edge-missing-placeholder', 'edge-extra-placeholder', 'empty-text']) { - test(`${scenario} exhausts retries without writing incomplete translations`, async () => { - const result = await translationRequestFixture(scenario, 'SDK Example'); - assert.equal(result.status, 1, result.stderr); - assert.equal(result.requests.length, scenario.startsWith('edge-') ? 8 : 4); - assert.equal(result.output, null); - assert.match(result.stderr, /Translation response|Translation service.*placeholder/); - }); -} -for (const scenario of ['edge-valid', 'edge-transient']) { - test(`${scenario} restores protected terms and preserves navigation labels`, async () => { - const result = await translationRequestFixture(scenario, 'SDK Example'); + test('multiple placeholder repairs finish in order without overlapping provider requests', async () => { + const body = 'First SDK\nSecond API\n'; + const result = await translationRequestFixture('multi-missing', 'Example', undefined, [], 'missing', body); assert.equal(result.status, 0, result.stderr); - assert.equal(result.requests.length, scenario === 'edge-transient' ? 2 : 1); - assert.ok(result.output?.includes('display-name: "SDK Example"')); - assert.doesNotMatch(result.output, /notranslate|\[\[\[ph/); - }); -} - -test('generation preserves literal dollar sequences in protected code and translated attributes', async () => { - const body = [ - "Literal `$$` and `$&` and `$'`.", - 'Use $$ literally.', - '[Guide $$ and $&](/sdk/overview)', - 'API', - 'Visit https://example.com/$$', - ].join('\n') + '\n'; - const result = await translationRequestFixture('normal', 'Example', undefined, [], 'missing', body); - assert.equal(result.status, 0, result.stderr); - assert.ok(result.recoveredPage?.endsWith(body.replaceAll('/sdk/overview', '/ja/sdk/overview')), result.recoveredPage); - assert.doesNotMatch(result.recoveredPage, /\[\[\[(?:ph|attr)\d+\]\]\]/); -}); - -for (const state of ['source-missing', 'source-directory']) { - test(`${state} stops full generation before translation requests or writes`, async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, [], state); - assert.equal(result.status, 1, result.stderr); - assert.equal(result.requests.length, 0); - assert.equal(result.output, null); - assert.equal(result.preservedManifest, true); - assert.match(result.stderr, state === 'source-missing' ? /ENOENT/ : /EISDIR/); + assert.equal(result.requests.length, 4); + assert.ok(result.recoveredPage?.endsWith(body)); + assert.deepEqual(result.requestEvents, [1, 2, 3, 4].flatMap(id => [['start', id], ['finish', id]])); }); -} -test('labels-only generation does not require article sources', async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, ['--labels-only'], 'source-missing'); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.requests.length, 1); - assert.ok(result.output?.includes('display-name: "Example"')); - assert.equal(result.preservedManifest, true); -}); -for (const target of ['page', 'navigation']) { - for (const operation of ['write', 'rename']) { - test(`${target}-${operation}-failure preserves existing output and cache`, async () => { - const result = await translationRequestFixture(`${target}-${operation}-failure`, 'Example', undefined, ['--force'], 'present'); + for (const [scenario, requests, authRequests] of [ + ['edge-http-400', 1, 1], ['edge-http-403', 1, 1], ['edge-http-404', 1, 1], + ['edge-http-408', 8, 1], ['edge-http-429', 20, 1], ['edge-http-503', 8, 1], ['edge-http-401', 8, 8], + ['edge-auth-forbidden', 0, 1], + ]) { + test(`${scenario} stops at the appropriate retry limit without writing`, async () => { + const result = await translationRequestFixture(scenario, 'Example'); assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, /Simulated (partial output write|output rename failure)/); - assert.equal(result.requests.length, target === 'page' ? 2 : 1); - assert.equal(result.preservedManifest, true); - assert.deepEqual(result.temporaryWrites, []); - if (target === 'navigation') assert.equal(result.output, 'Preserved navigation\n'); + assert.equal(result.requests.length, requests); + assert.equal(result.authRequests, authRequests); + assert.equal(result.output, null); + assert.match(result.stderr, /returned HTTP/); + }); + } + for (const [scenario, authRequests] of [['edge-http-401-once', 2], ['edge-refresh-transient', 3]]) { + test(`${scenario} recovers through the bounded token refresh flow`, async () => { + const result = await translationRequestFixture(scenario, 'SDK Example'); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.requests.length, 2); + assert.equal(result.authRequests, authRequests); + assert.ok(result.output?.includes('display-name: "SDK Example"')); }); } -} -for (const scenario of ['manifest-write-failure', 'manifest-rename-failure']) { - for (const args of [[], ['--refresh-manifest']]) { - test(`${scenario} preserves the previous manifest during ${args.length ? 'refresh' : 'generation'}`, async () => { - const result = await translationRequestFixture(scenario, 'Example', undefined, args, 'present'); + for (const scenario of ['edge-missing-text', 'edge-null-item', 'edge-number-text', 'edge-empty-text', 'edge-missing-placeholder', 'edge-extra-placeholder', 'empty-text']) { + test(`${scenario} exhausts retries without writing incomplete translations`, async () => { + const result = await translationRequestFixture(scenario, 'SDK Example'); assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, /Simulated (partial manifest write|manifest rename failure)/); - assert.equal(result.preservedManifest, true, 'A failed save must not damage the previous manifest'); - assert.deepEqual(result.temporaryWrites, [], 'Temporary files must be cleaned up after failure'); + assert.equal(result.requests.length, scenario.startsWith('edge-') ? 8 : 4); + assert.equal(result.output, null); + assert.match(result.stderr, /Translation response|Translation service.*placeholder/); + }); + } + for (const scenario of ['edge-valid', 'edge-transient']) { + test(`${scenario} restores protected terms and preserves navigation labels`, async () => { + const result = await translationRequestFixture(scenario, 'SDK Example'); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.requests.length, scenario === 'edge-transient' ? 2 : 1); + assert.ok(result.output?.includes('display-name: "SDK Example"')); + assert.doesNotMatch(result.output, /notranslate|\[\[\[ph/); }); } -} -for (const state of ['present', 'missing', 'directory']) { - test(`cached translation output ${state}: preserve existing files and recover only missing pages`, async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, [], state); - assert.equal(result.status, state === 'directory' ? 1 : 0, result.stderr); - assert.equal(result.requests.length, state === 'missing' ? 2 : 1); - if (state === 'missing') { - assert.ok(result.recoveredPage?.includes('canonical-url: https://docs.6mm.com/ja/page-0')); - assert.match(result.stdout, /1 generated, 157 unchanged/); - } else if (state === 'present') { - assert.match(result.stdout, /0 generated, 158 unchanged/); - } else { - assert.match(result.stderr, /Translation output is not a file/); - } + test('generation preserves literal dollar sequences in protected code and translated attributes', async () => { + const body = [ + "Literal `$$` and `$&` and `$'`.", + 'Use $$ literally.', + '[Guide $$ and $&](/sdk/overview)', + 'API', + 'Visit https://example.com/$$', + ].join('\n') + '\n'; + const result = await translationRequestFixture('normal', 'Example', undefined, [], 'missing', body); + assert.equal(result.status, 0, result.stderr); + assert.ok(result.recoveredPage?.endsWith(body.replaceAll('/sdk/overview', '/ja/sdk/overview')), result.recoveredPage); + assert.doesNotMatch(result.recoveredPage, /\[\[\[(?:ph|attr)\d+\]\]\]/); }); -} -for (const args of [['--locales='], ['--locales=,,'], ['--locales=ja', '--locales=fr']]) { - test(`invalid locale selection ${args.join(' ')} stops without requests or writes`, async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, args); - assert.equal(result.status, 1, result.stderr); - assert.equal(result.requests.length, 0); - assert.equal(result.output, null); - assert.match(result.stderr, /At least one locale|Specify --locales once/); - }); -} -for (const args of [['--locales=ja', '--locales=ja'], ['--locales=ja,ja,']]) { - test(`equivalent locale selection ${args.join(' ')} still generates only once`, async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, args); + for (const state of ['source-missing', 'source-directory']) { + test(`${state} stops full generation before translation requests or writes`, async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, [], state); + assert.equal(result.status, 1, result.stderr); + assert.equal(result.requests.length, 0); + assert.equal(result.output, null); + assert.equal(result.preservedManifest, true); + assert.match(result.stderr, state === 'source-missing' ? /ENOENT/ : /EISDIR/); + }); + } + test('labels-only generation does not require article sources', async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, ['--labels-only'], 'source-missing'); assert.equal(result.status, 0, result.stderr); assert.equal(result.requests.length, 1); assert.ok(result.output?.includes('display-name: "Example"')); + assert.equal(result.preservedManifest, true); }); -} -for (const argument of ['--locale=fr', '--froce', '--labels_only', '--refresh-manifset', 'fr']) { - test(`unrecognized translation argument ${argument} stops before requests or writes`, async () => { - const result = await translationRequestFixture('normal', 'Example', undefined, [argument]); - assert.equal(result.requests.length, 0, 'Invalid arguments must not invoke the provider'); - assert.equal(result.output, null, 'Invalid arguments must not overwrite navigation'); - assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, /Unknown argument/); - assert.ok(result.stderr.includes(argument)); + test('unlisted English pages stop generation and manifest refresh before requests or writes', async () => { + for (const args of [[], ['--refresh-manifest']]) { + const result = await translationRequestFixture('normal', 'Example', undefined, args, 'source-unlisted'); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /English documentation pages missing from navigation/); + assert.match(result.stderr, /docs\/pages\/nested\/unlisted\.mdx/); + assert.equal(result.requests.length, 0); + assert.equal(result.output, null); + assert.equal(result.preservedManifest, true); + } }); -} -for (const manifestState of ['malformed', 'directory']) { - test(`unreadable translation manifest (${manifestState}) stops before requesting or writing labels`, async () => { - const result = await translationRequestFixture('normal', 'Example', manifestState); - assert.equal(result.status, 1, result.stderr); - assert.equal(result.requests.length, 0); - assert.equal(result.output, null); - assert.match(result.stderr, manifestState === 'directory' ? /EISDIR/ : /SyntaxError/); - }); -} + for (const target of ['page', 'navigation']) { + for (const operation of ['write', 'rename']) { + test(`${target}-${operation}-failure preserves existing output and cache`, async () => { + const result = await translationRequestFixture(`${target}-${operation}-failure`, 'Example', undefined, ['--force'], 'present'); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /Simulated (partial output write|output rename failure)/); + assert.equal(result.requests.length, target === 'page' ? 2 : 1); + assert.equal(result.preservedManifest, true); + assert.deepEqual(result.temporaryWrites, []); + if (target === 'navigation') assert.equal(result.output, 'Preserved navigation\n'); + }); + } + } -for (const [name, manifest] of [ - ['root array', []], - ['null root', null], - ['locale map array', { locales: [] }], - ['locale record array', { locales: { ja: [] } }], - ['page map array', { locales: { ja: { pages: [] } } }], - ['missing page map', { locales: { ja: {} } }], - ['non-string page hash', { locales: { ja: { pages: { 'docs/pages/page-0.mdx': null } } } }], -]) { - test(`invalid manifest shape (${name}) stops before any translation request`, async () => { - const result = await translationRequestFixture('normal', 'Example', { content: JSON.stringify(manifest) }); - assert.equal(result.status, 1, result.stderr); - assert.equal(result.requests.length, 0); - assert.equal(result.output, null); - assert.match(result.stderr, /Invalid translation manifest/); - }); -} + for (const scenario of ['manifest-write-failure', 'manifest-rename-failure']) { + for (const args of [[], ['--refresh-manifest']]) { + test(`${scenario} preserves the previous manifest during ${args.length ? 'refresh' : 'generation'}`, async () => { + const result = await translationRequestFixture(scenario, 'Example', undefined, args, 'present'); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /Simulated (partial manifest write|manifest rename failure)/); + assert.equal(result.preservedManifest, true, 'A failed save must not damage the previous manifest'); + assert.deepEqual(result.temporaryWrites, [], 'Temporary files must be cleaned up after failure'); + }); + } + } -for (const manifest of [{}, { version: 3, locales: { ja: { pages: { 'docs/pages/page-0.mdx': 'older-source-hash' } } } }]) { - test(`valid empty or earlier-version manifest remains usable: ${JSON.stringify(manifest)}`, async () => { - const result = await translationRequestFixture('normal', 'Example', { content: JSON.stringify(manifest) }); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.requests.length, 1); - assert.ok(result.output?.includes('display-name: "Example"')); - }); -} + for (const state of ['present', 'missing', 'directory']) { + test(`cached translation output ${state}: preserve existing files and recover only missing pages`, async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, [], state); + assert.equal(result.status, state === 'directory' ? 1 : 0, result.stderr); + assert.equal(result.requests.length, state === 'missing' ? 2 : 1); + if (state === 'missing') { + assert.ok(result.recoveredPage?.includes('canonical-url: https://docs.6mm.com/ja/page-0')); + assert.ok(result.stdout.includes(`1 generated, ${fixturePageCount - 1} unchanged`)); + } else if (state === 'present') { + assert.ok(result.stdout.includes(`0 generated, ${fixturePageCount} unchanged`)); + } else { + assert.match(result.stderr, /Translation output is not a file/); + } + }); + } -for (const [scenario, label, requests] of [ - ['poison', 'Example', 4], - ['poison', 'Example SDK', 20], - ['transient', 'Example', 2], - ['missing', 'Example SDK', 2], - ['normal', 'Example SDK', 1], -]) { - test(`translation provider ${scenario} (${label}): bounded requests and preserved labels`, async () => { - const result = await translationRequestFixture(scenario, label); - assert.equal(result.requests.length, requests); - assert.equal(result.status, scenario === 'poison' ? 1 : 0, result.stderr); - if (scenario === 'poison') { - assert.equal(result.output, null, 'Rejected responses must not write navigation labels'); - assert.match(result.stderr, /Translation service introduced an unexpected placeholder/); - } else { - assert.ok(result.output?.includes(`display-name: ${JSON.stringify(label)}`)); - } + test('incremental generation preserves reviewed navigation and only requests changed or missing output', async () => { + await translationRequestFixture('normal', 'Example', undefined, [], 'present', undefined, + async ({ root, runGenerator, result, requests }) => { + assert.equal(result.status, 0, result.stderr); + assert.equal(requests.length, 1, 'Legacy manifests generate navigation once to populate the cache'); + const manifestPath = path.join(root, 'fern/translations/.translation-manifest.json'); + const sourceConfig = path.join(root, 'fern/docs.yml'); + const overlayPath = path.join(root, 'fern/translations/ja/docs.yml'); + const requestLog = path.join(root, 'requests.jsonl'); + const originalManifest = await readFile(manifestPath, 'utf8'); + const originalOverlay = await readFile(overlayPath, 'utf8'); + const reviewedOverlay = originalOverlay.replace('display-name: "Example"', 'display-name: "Reviewed navigation"'); + assert.notEqual(reviewedOverlay, originalOverlay); + await writeFile(overlayPath, reviewedOverlay); + const config = JSON.parse(await readFile(sourceConfig, 'utf8')); + config.title = 'Unrelated site title'; + await writeFile(sourceConfig, JSON.stringify(config)); + + async function run(expectedRequests, args = []) { + const next = await runGenerator(['--locales=ja', ...args]); + assert.equal(next.status, 0, next.stderr); + const calls = (await readFile(requestLog, 'utf8')).trim().split('\n').map(JSON.parse); + assert.equal(calls.length, expectedRequests); + return calls.at(-1); + } + + await run(1); + assert.equal(await readFile(overlayPath, 'utf8'), reviewedOverlay); + assert.equal(await readFile(manifestPath, 'utf8'), originalManifest); + + const page = path.join(root, 'fern/docs/pages/page-0.mdx'); + const article = await readFile(page, 'utf8'); + await writeFile(page, article.replace('Example content.', 'Updated page content.')); + assert.ok((await run(2)).includes('Updated page content.')); + assert.equal(await readFile(overlayPath, 'utf8'), reviewedOverlay); + + config.tabs.home['display-name'] = 'Updated navigation'; + await writeFile(sourceConfig, JSON.stringify(config)); + assert.ok((await run(3)).includes('Updated navigation')); + const updatedOverlay = await readFile(overlayPath, 'utf8'); + assert.match(updatedOverlay, /display-name: "Updated navigation"/); + + await rm(overlayPath); + await run(4); + assert.equal(await readFile(overlayPath, 'utf8'), updatedOverlay); + const updatedManifest = await readFile(manifestPath, 'utf8'); + await run(5, ['--labels-only']); + assert.equal(await readFile(manifestPath, 'utf8'), updatedManifest); + + const entries = config.navigation[0].layout[0].contents; + const retired = entries.pop().path; + await rm(path.join(root, 'fern', retired)); + await writeFile(sourceConfig, JSON.stringify(config)); + await run(6); + let manifest = JSON.parse(await readFile(manifestPath, 'utf8')); + assert.equal(manifest.locales.ja.pages[retired], undefined); + assert.ok((await readFile(path.join(root, 'fern/translations/ja', retired), 'utf8')).includes('Preserved manually reviewed translation')); + + const added = 'docs/pages/new.mdx'; + entries.push({ page: 'New document', path: added }); + await writeFile(sourceConfig, JSON.stringify(config)); + await writeFile(path.join(root, 'fern', added), article.replace('slug: page-0', 'slug: new')); + await run(8); + manifest = JSON.parse(await readFile(manifestPath, 'utf8')); + assert.equal(Object.keys(manifest.locales.ja.pages).length, fixturePageCount); + assert.equal(typeof manifest.locales.ja.pages[added], 'string'); + assert.match(await readFile(path.join(root, 'fern/translations/ja', added), 'utf8'), /canonical-url: https:\/\/docs\.6mm\.com\/ja\/new/); + }); }); -} + + for (const args of [['--locales='], ['--locales=,,'], ['--locales=ja', '--locales=fr']]) { + test(`invalid locale selection ${args.join(' ')} stops without requests or writes`, async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, args); + assert.equal(result.status, 1, result.stderr); + assert.equal(result.requests.length, 0); + assert.equal(result.output, null); + assert.match(result.stderr, /At least one locale|Specify --locales once/); + }); + } + for (const args of [['--locales=ja', '--locales=ja'], ['--locales=ja,ja,']]) { + test(`equivalent locale selection ${args.join(' ')} still generates only once`, async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, args); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.requests.length, 1); + assert.ok(result.output?.includes('display-name: "Example"')); + }); + } + + for (const argument of ['--locale=fr', '--froce', '--labels_only', '--refresh-manifset', 'fr']) { + test(`unrecognized translation argument ${argument} stops before requests or writes`, async () => { + const result = await translationRequestFixture('normal', 'Example', undefined, [argument]); + assert.equal(result.requests.length, 0, 'Invalid arguments must not invoke the provider'); + assert.equal(result.output, null, 'Invalid arguments must not overwrite navigation'); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /Unknown argument/); + assert.ok(result.stderr.includes(argument)); + }); + } + + for (const manifestState of ['malformed', 'directory']) { + test(`unreadable translation manifest (${manifestState}) stops before requesting or writing labels`, async () => { + const result = await translationRequestFixture('normal', 'Example', manifestState); + assert.equal(result.status, 1, result.stderr); + assert.equal(result.requests.length, 0); + assert.equal(result.output, null); + assert.match(result.stderr, manifestState === 'directory' ? /EISDIR/ : /SyntaxError/); + }); + } + + for (const [name, manifest] of [ + ['root array', []], + ['null root', null], + ['locale map array', { locales: [] }], + ['locale record array', { locales: { ja: [] } }], + ['page map array', { locales: { ja: { pages: [] } } }], + ['missing page map', { locales: { ja: {} } }], + ['non-string page hash', { locales: { ja: { pages: { 'docs/pages/page-0.mdx': null } } } }], + ]) { + test(`invalid manifest shape (${name}) stops before any translation request`, async () => { + const result = await translationRequestFixture('normal', 'Example', { content: JSON.stringify(manifest) }); + assert.equal(result.status, 1, result.stderr); + assert.equal(result.requests.length, 0); + assert.equal(result.output, null); + assert.match(result.stderr, /Invalid translation manifest/); + }); + } + + for (const manifest of [{}, { version: 3, locales: { ja: { pages: { 'docs/pages/page-0.mdx': 'older-source-hash' } } } }]) { + test(`valid empty or earlier-version manifest remains usable: ${JSON.stringify(manifest)}`, async () => { + const result = await translationRequestFixture('normal', 'Example', { content: JSON.stringify(manifest) }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.requests.length, 1); + assert.ok(result.output?.includes('display-name: "Example"')); + }); + } + + for (const [scenario, label, requests] of [ + ['poison', 'Example', 4], + ['poison', 'Example SDK', 20], + ['transient', 'Example', 2], + ['missing', 'Example SDK', 2], + ['normal', 'Example SDK', 1], + ]) { + test(`translation provider ${scenario} (${label}): bounded requests and preserved labels`, async () => { + const result = await translationRequestFixture(scenario, label); + assert.equal(result.requests.length, requests); + assert.equal(result.status, scenario === 'poison' ? 1 : 0, result.stderr); + if (scenario === 'poison') { + assert.equal(result.output, null, 'Rejected responses must not write navigation labels'); + assert.match(result.stderr, /Translation service introduced an unexpected placeholder/); + } else { + assert.ok(result.output?.includes(`display-name: ${JSON.stringify(label)}`)); + } + }); + } +}); diff --git a/scripts/check-workflows.test.mjs b/scripts/check-workflows.test.mjs index be0e5cbc..7cfb9208 100644 --- a/scripts/check-workflows.test.mjs +++ b/scripts/check-workflows.test.mjs @@ -7,6 +7,7 @@ import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { parse } from 'yaml'; import { locales, generatedLocaleSpecs } from './locale-config.mjs'; +import { linkDirectory, linkFixtureDependencies } from './test-fixture-paths.mjs'; const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')); test('ordered batches enforce their concurrency limit and preserve input order', async () => { @@ -91,8 +92,10 @@ test('support guide prefetch preserves validation order when later reads fail', const root = await mkdtemp(path.join(tmpdir(), 'sixmm-support-order-')); try { await mkdir(path.join(root, 'scripts')); - await copyFile(new URL('./check-customer-support.mjs', import.meta.url), path.join(root, 'scripts/check-customer-support.mjs')); - await symlink(fileURLToPath(new URL('../node_modules', import.meta.url)), path.join(root, 'node_modules'), 'dir'); + for (const file of ['check-customer-support.mjs', 'documentation-pages.mjs']) { + await copyFile(new URL(file, import.meta.url), path.join(root, 'scripts', file)); + } + await linkFixtureDependencies(root); const config = parse(await readFile(new URL('../fern/docs.yml', import.meta.url), 'utf8')); config.translations = config.translations.filter(locale => locale.default || locale.lang === 'ja'); const pages = config.navigation.find(item => item.tab === 'customerSupport').layout.flatMap(group => group.contents.map(page => page.path)); @@ -125,44 +128,79 @@ test('support guide prefetch preserves validation order when later reads fail', result = run(); assert.equal(result.status, 0, result.stderr); assert.match(result.stdout, /Customer support docs verified/); + + const addedGuide = 'docs/pages/customer-support/new-guide.mdx'; + await writeFile(path.join(root, 'fern', addedGuide), await readFile(path.join(root, 'fern', pages[0]), 'utf8')); + result = run(); + assert.equal(result.status, 1); + assert.ok(result.stderr.includes(addedGuide), result.stderr); + assert.match(result.stderr, /missing from navigation/); + const supportTab = config.navigation.find(item => item.tab === 'customerSupport'); + supportTab.layout[0].contents.push({ page: 'New guide', path: addedGuide }); + await writeFile(path.join(root, 'fern/docs.yml'), JSON.stringify(config)); + await writeFile(path.join(root, 'fern/translations/ja', addedGuide), firstBody); + result = run(); + assert.equal(result.status, 0, result.stderr); + assert.ok(result.stdout.includes(`verified: ${pages.length + 1} pages`)); } finally { await rm(root, { recursive: true, force: true }); } }); -for (const [file, jobName] of [['docs-check.yml', 'validate'], ['docs-publish.yml', 'publish']]) { -test(`${file} runs documentation validation before browser setup and requires both gates`, async () => { - const workflow = parse(await readFile(new URL(`../.github/workflows/${file}`, import.meta.url), 'utf8')); - const job = workflow.jobs[jobName]; - const validationIndex = job.steps.findIndex(step => step.run === 'npm run check'); - const browserInstallIndex = job.steps.findIndex(step => step.run === 'npm ci --prefix tests/browser --ignore-scripts'); - const browserSetupIndex = job.steps.findIndex(step => step.run === 'npm run install:browsers -- --with-deps'); - const browserIndex = job.steps.findIndex(step => step.run === 'npm run browser:check'); - const publishIndex = job.steps.findIndex(step => step.run === './node_modules/.bin/fern generate --docs --no-prompt'); - assert.ok(validationIndex >= 0 && browserInstallIndex > validationIndex); - assert.ok(browserSetupIndex > browserInstallIndex && browserIndex > browserSetupIndex); - assert.equal(job.steps[browserSetupIndex]['working-directory'], 'tests/browser'); - assert.equal(job.steps.filter(step => step.run === 'npm run check').length, 1); - assert.equal(job.steps[validationIndex].env.FERN_TOKEN, '${{ secrets.FERN_TOKEN }}'); - const setup = job.steps.find(step => step.uses?.startsWith('actions/setup-node@')).with; +const docsValidationAction = './.github/actions/validate-docs'; + +test('shared docs validation runs both gates and installs only the required browsers', async () => { + const action = parse(await readFile(new URL(`../${docsValidationAction}/action.yml`, import.meta.url), 'utf8')); + assert.equal(action.runs.using, 'composite'); + assert.equal(action.inputs['fern-token'].required, false); + const [node, ...steps] = action.runs.steps; + assert.match(node.uses, /^actions\/setup-node@/); + const setup = node.with; assert.equal(setup['node-version'], 22); assert.equal(setup.cache, 'npm'); assert.deepEqual(setup['cache-dependency-path'].trim().split(/\s+/), ['package-lock.json', 'tests/browser/package-lock.json']); - for (const target of [job, ...job.steps.slice(validationIndex, browserIndex + 1)]) { - assert.ok(target['continue-on-error'] === undefined || target['continue-on-error'] === false); - } - for (const step of job.steps.slice(validationIndex, browserIndex + 1)) { - assert.equal(step.if, undefined, 'Do not skip validation or run after a failed prerequisite'); - } - if (jobName === 'publish') { - assert.ok(publishIndex > browserIndex); - assert.equal(job.steps[publishIndex].if, undefined, 'Do not publish after a failed gate'); - } else { - assert.equal(publishIndex, -1); - assert.ok(Object.hasOwn(workflow.on, 'pull_request')); - assert.deepEqual(workflow.on.push.branches, ['main']); - assert.equal(job.if, undefined); - assert.deepEqual(workflow.permissions, { contents: 'read' }); + assert.deepEqual(steps.map(step => step.run), [ + 'npm ci', + 'npm run check', + 'npm ci --prefix tests/browser --ignore-scripts', + 'npm run install:browsers -- --with-deps --only-shell', + 'npm run browser:check', + ]); + assert.equal(steps[3]['working-directory'], 'tests/browser'); + assert.equal(steps[1].env.FERN_TOKEN, '${{ inputs.fern-token }}'); + for (const step of [node, ...steps]) { + assert.equal(step.if, undefined); + assert.ok(!step['continue-on-error']); + if (step.run) assert.equal(step.shell, 'bash'); + if (step.run !== 'npm run check') assert.equal(step.env?.FERN_TOKEN, undefined); } }); + +for (const [file, jobName] of [['docs-check.yml', 'validate'], ['docs-publish.yml', 'publish']]) { + test(`${file} requires the shared validation action`, async () => { + const workflow = parse(await readFile(new URL(`../.github/workflows/${file}`, import.meta.url), 'utf8')); + const job = workflow.jobs[jobName]; + const [checkout, validate, ...remaining] = job.steps; + assert.match(checkout.uses, /^actions\/checkout@/); + assert.equal(validate.uses, docsValidationAction); + assert.equal(validate.with['fern-token'], '${{ secrets.FERN_TOKEN }}'); + assert.deepEqual(workflow.permissions, { contents: 'read' }); + for (const step of [checkout, validate, ...remaining]) { + assert.equal(step.if, undefined, 'A failed prerequisite must stop the job'); + assert.ok(!step['continue-on-error']); + } + assert.ok(!job['continue-on-error']); + if (jobName === 'publish') { + assert.equal(job.if, "github.ref == 'refs/heads/main'"); + assert.deepEqual(Object.keys(workflow.on), ['workflow_dispatch']); + assert.equal(remaining.length, 1); + assert.equal(remaining[0].run, './node_modules/.bin/fern generate --docs --no-prompt'); + assert.equal(remaining[0].env.FERN_TOKEN, '${{ secrets.FERN_TOKEN }}'); + } else { + assert.equal(remaining.length, 0); + assert.ok(Object.hasOwn(workflow.on, 'pull_request')); + assert.deepEqual(workflow.on.push.branches, ['main']); + assert.equal(job.if, undefined); + } + }); } async function fixture(run) { @@ -179,9 +217,16 @@ if(process.env.FAIL_STEP===name)process.exit(7); await writeFile(path.join(root, 'scripts', name), probe); } await writeFile(path.join(root, 'node_modules/.bin/fern'), '#!/usr/bin/env node\n' + probe.replace("import fs from 'node:fs';", "const fs=require('node:fs');"), { mode: 0o755 }); + if (process.platform === 'win32') { + await writeFile(path.join(root, 'node_modules/.bin/fern.cmd'), '@node "%~dp0fern" %*\r\n'); + } await writeFile(path.join(root, 'package.json'), JSON.stringify({ type: 'module', scripts: { ...pkg.scripts, check: 'node scripts/check.mjs' } })); await run((command, args = [], fail = '') => { - const result = spawnSync('npm', ['run', command, '--', ...args], { + // npm run provides its JS entry point, so no shell is needed for npm.cmd. + const npm = process.env.npm_execpath; + const npmCommand = npm ? process.execPath : 'npm'; + const npmArgs = npm ? [npm] : []; + const result = spawnSync(npmCommand, [...npmArgs, 'run', command, '--', ...args], { cwd: root, encoding: 'utf8', env: { ...process.env, FAIL_STEP: fail, npm_config_ignore_scripts: 'false' } }); return result; @@ -247,7 +292,7 @@ test('maintenance commands reject unsupported options before rewriting documents for (const name of ['stabilize-heading-anchors.mjs', 'repair-translation-links.mjs', 'polish-core-translations.mjs', 'locale-config.mjs', 'documentation-text.mjs', 'write-generated-file.mjs', 'ordered-batches.mjs']) { await copyFile(new URL(name, import.meta.url), path.join(root, 'scripts', name)); } - await symlink(fileURLToPath(new URL('../node_modules', import.meta.url)), path.join(root, 'node_modules'), 'dir'); + await linkFixtureDependencies(root); await mkdir(path.join(root, 'fern/docs/pages'), { recursive: true }); const documentPath = path.join(root, 'fern/docs/pages/home.mdx'); const original = '## Existing heading\n'; @@ -279,7 +324,7 @@ test('anchor validation preserves error order and avoids partial writes when a l for (const name of ['stabilize-heading-anchors.mjs', 'write-generated-file.mjs']) { await copyFile(new URL(name, import.meta.url), path.join(root, 'scripts', name)); } - await symlink(fileURLToPath(new URL('../node_modules', import.meta.url)), path.join(root, 'node_modules'), 'dir'); + await linkFixtureDependencies(root); const relative = 'docs/pages/example.mdx'; const source = path.join(root, 'fern', relative); const japanese = path.join(root, 'fern/translations/ja', relative); @@ -322,7 +367,7 @@ for (const failure of ['missing-source', 'missing-later-translation', 'multiple- for (const name of ['repair-translation-links.mjs', 'stabilize-heading-anchors.mjs', 'locale-config.mjs', 'documentation-text.mjs', 'write-generated-file.mjs', 'ordered-batches.mjs']) { await copyFile(new URL(name, import.meta.url), path.join(root, 'scripts', name)); } - await symlink(fileURLToPath(new URL('../node_modules', import.meta.url)), path.join(root, 'node_modules'), 'dir'); + await linkFixtureDependencies(root); await mkdir(path.join(root, 'fern/docs/pages'), { recursive: true }); const paths = ['docs/pages/first.mdx', 'docs/pages/second.mdx']; await writeFile(path.join(root, 'fern/docs.yml'), JSON.stringify({ @@ -401,8 +446,9 @@ for (const failure of ['missing-source', 'missing-later-translation', 'multiple- }); } -for (const failure of ['missing-direct-file', 'missing-locale', 'unreadable-local-files']) { - test(`polishing ${failure} leaves earlier documents unchanged`, async () => { +for (const failure of ['missing-direct-file', 'missing-locale', 'unreadable-local-files', null]) { + const label = failure ? `${failure} leaves earlier documents unchanged` : 'applies page-specific rules to nested files'; + test(`polishing ${label}`, async () => { const root = await mkdtemp(path.join(tmpdir(), 'sixmm-polish-preflight-')); try { await mkdir(path.join(root, 'scripts')); @@ -428,12 +474,27 @@ for (const failure of ['missing-direct-file', 'missing-locale', 'unreadable-loca originals.delete(file); } else if (failure === 'missing-locale') { await rm(path.join(root, 'fern/translations/ar'), { recursive: true }); - } else { + } else if (failure === 'unreadable-local-files') { for (const name of ['000-first.mdx', '001-second.mdx']) { - await symlink(`missing-${name}`, path.join(root, 'fern/translations/ja', name)); + const destination = path.join(root, 'fern/translations/ja', name); + if (process.platform === 'win32') { + await linkDirectory(path.join(root, `missing-${name}`), destination); + } else { + await symlink(`missing-${name}`, path.join(root, 'fern/translations/ja', name), 'file'); + } } } + const orderPage = path.join(root, 'fern/translations/de/docs/pages/trading/order-types.mdx'); + if (!failure) { + await mkdir(path.dirname(orderPage), { recursive: true }); + await writeFile(orderPage, 'Ordnungstypen\n'); + } const result = spawnSync(process.execPath, ['scripts/polish-core-translations.mjs'], { cwd: root, encoding: 'utf8', timeout: 10_000 }); + if (!failure) { + assert.equal(result.status, 0, result.stderr); + assert.equal(await readFile(orderPage, 'utf8'), 'Ordertypen\n'); + return; + } assert.equal(result.status, 1, result.stderr); assert.match(result.stderr, /ENOENT/); if (failure === 'unreadable-local-files') { @@ -452,12 +513,18 @@ test('polishing recognizes path aliases while library imports stay read-only', a for (const name of ['polish-core-translations.mjs', 'locale-config.mjs', 'write-generated-file.mjs', 'ordered-batches.mjs']) { await copyFile(new URL(name, import.meta.url), path.join(root, 'scripts', name)); } - await symlink('polish-core-translations.mjs', path.join(root, 'scripts/linked-polish.mjs'), 'file'); + const script = 'scripts/polish-core-translations.mjs'; + const alias = process.platform === 'win32' ? 'linked-scripts/polish-core-translations.mjs' : 'scripts/linked-polish.mjs'; + if (process.platform === 'win32') { + await linkDirectory(path.join(root, 'scripts'), path.join(root, 'linked-scripts')); + } else { + await symlink('polish-core-translations.mjs', path.join(root, alias), 'file'); + } for (const entry of [ - ['scripts/polish-core-translations.mjs'], - [path.join(root, 'scripts/polish-core-translations.mjs')], - ['scripts/linked-polish.mjs'], - ['--preserve-symlinks-main', 'scripts/linked-polish.mjs'], + [script], + [path.join(root, script)], + [alias], + ['--preserve-symlinks-main', alias], ]) { const result = spawnSync(process.execPath, [...entry, '--check'], { cwd: root, encoding: 'utf8', timeout: 10_000 }); assert.equal(result.status, 1, `${entry.join(' ')}: ${result.stderr}`); @@ -474,19 +541,20 @@ test('polishing recognizes path aliases while library imports stay read-only', a assert.equal(result.status, 0, result.stderr); assert.equal(result.stdout.trim(), 'function'); } - assert.deepEqual((await readdir(root)).sort(), ['consumer.mjs', 'scripts']); + const expected = ['consumer.mjs', 'scripts']; + if (process.platform === 'win32') expected.splice(1, 0, 'linked-scripts'); + assert.deepEqual((await readdir(root)).sort(), expected); } finally { await rm(root, { recursive: true, force: true }); } }); async function previewFixture(run) { - const root = await mkdtemp(path.join(tmpdir(), 'sixmm-preview-options-')); + const root = await mkdtemp(path.join(tmpdir(), 'sixmm preview options-')); try { await mkdir(path.join(root, 'scripts')); - await mkdir(path.join(root, 'node_modules/.bin'), { recursive: true }); + await mkdir(path.join(root, 'node_modules/fern-api'), { recursive: true }); await copyFile(new URL('./preview-prediction.mjs', import.meta.url), path.join(root, 'scripts/preview-prediction.mjs')); - const executable = path.join(root, 'node_modules/.bin/fern'); - await writeFile(executable, `#!/usr/bin/env node -require('node:fs').writeFileSync('launch.json', JSON.stringify(process.argv.slice(2))); + const executable = path.join(root, 'node_modules/fern-api/cli.cjs'); + await writeFile(executable, `require('node:fs').writeFileSync('launch.json', JSON.stringify(process.argv.slice(2))); if (process.env.SIXMM_PREVIEW_SIGNAL) process.kill(process.pid, process.env.SIXMM_PREVIEW_SIGNAL); else process.exit(Number(process.env.SIXMM_PREVIEW_EXIT || 0)); `, { mode: 0o755 }); @@ -533,19 +601,24 @@ test('invalid preview options fail before starting Fern', async () => { } }); }); -test('preview propagates child failures and signal termination', async () => { +test('preview propagates child failures and reports a missing Fern installation', async () => { await previewFixture(async (run, executable) => { assert.equal((await run([], { SIXMM_PREVIEW_EXIT: '7' })).status, 7); - for (const [signal, status] of [['SIGINT', 130], ['SIGTERM', 143], ['SIGKILL', 137]]) { - assert.equal((await run([], { SIXMM_PREVIEW_SIGNAL: signal })).status, status); - } await rm(executable); const missing = await run(); assert.equal(missing.status, 1); - assert.match(missing.stderr, /ENOENT/); + assert.match(missing.stderr, /Cannot find module/); assert.equal(missing.launch, null); }); }); +test('preview reports POSIX signal termination', { skip: process.platform === 'win32' }, async () => { + await previewFixture(async run => { + for (const [signal, status] of [['SIGINT', 130], ['SIGTERM', 143], ['SIGKILL', 137]]) { + assert.equal((await run([], { SIXMM_PREVIEW_SIGNAL: signal })).status, status); + } + }); +}); + // Run the actual generator against a local provider stub. No network or // repository documentation is touched, including when retries fail. diff --git a/scripts/documentation-pages.mjs b/scripts/documentation-pages.mjs new file mode 100644 index 00000000..0a35a78c --- /dev/null +++ b/scripts/documentation-pages.mjs @@ -0,0 +1,34 @@ +import { readdir } from "node:fs/promises"; +import path from "node:path"; + +export function activeDocumentationPages(config) { + const pages = new Set(); + for (const navigationItem of config.navigation ?? []) { + for (const section of navigationItem.layout ?? []) { + for (const { path: page } of section.contents ?? []) { + if (page?.startsWith("docs/pages/")) pages.add(page); + } + } + } + if (pages.size === 0) throw new Error("English navigation does not list any documentation pages"); + return [...pages]; +} + +export async function assertSourcePagesListed(fernRoot, activePages, directory = "docs/pages") { + const listed = new Set(activePages); + const unlisted = []; + async function scan(directory) { + for (const entry of await readdir(path.join(fernRoot, directory), { withFileTypes: true })) { + const relative = `${directory}/${entry.name}`; + if (entry.isDirectory()) { + await scan(relative); + } else if (/\.mdx?$/.test(entry.name) && !listed.has(relative)) { + unlisted.push(relative); + } + } + } + await scan(directory); + if (unlisted.length) { + throw new Error(`English documentation pages missing from navigation:\n${unlisted.sort().join("\n")}`); + } +} diff --git a/scripts/generate-translations.mjs b/scripts/generate-translations.mjs index 731e918b..2c9735d8 100644 --- a/scripts/generate-translations.mjs +++ b/scripts/generate-translations.mjs @@ -13,6 +13,7 @@ import { polishMachineTranslation } from "./polish-core-translations.mjs"; import { protectText, extractDocumentRecords } from "./translation-text.mjs"; import { writeGeneratedFile } from "./write-generated-file.mjs"; import { orderedBatches } from "./ordered-batches.mjs"; +import { activeDocumentationPages, assertSourcePagesListed } from "./documentation-pages.mjs"; const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const fernRoot = path.join(projectRoot, "fern"); @@ -517,23 +518,23 @@ async function saveManifest(manifest) { await saveTextFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); } -const config = loadYamlAsJson(docsConfigPath); -const activePages = [ - ...new Set( - (config.navigation ?? []).flatMap((navigationItem) => - (navigationItem.layout ?? []).flatMap((section) => - (section.contents ?? []) - .map((content) => content.path) - .filter((contentPath) => contentPath?.startsWith("docs/pages/")), - ), - ), - ), -]; - -if (activePages.length !== 158) { - throw new Error(`Expected 158 active pages, found ${activePages.length}`); +async function hasTranslationOutput(outputPath) { + try { + if (!(await stat(outputPath)).isFile()) { + throw new Error(`Translation output is not a file: ${outputPath}`); + } + return true; + } catch (error) { + if (error.code !== "ENOENT") throw error; + return false; + } } +const config = loadYamlAsJson(docsConfigPath); +const navigationSource = JSON.stringify([config.tabs ?? {}, config.navigation ?? []]); +const activePages = activeDocumentationPages(config); +const activePageSet = new Set(activePages); + const manifest = await loadManifest(); if (!isRecord(manifest)) throw new Error("Invalid translation manifest: root must be an object"); if (manifest.locales !== undefined && !isRecord(manifest.locales)) { @@ -557,6 +558,7 @@ Object.keys(manifest.locales).forEach((locale) => { if (!labelsOnly && !refreshManifestOnly && selectedLocales.length) { for (const relativePagePath of activePages) await readSource(relativePagePath); } +if (!labelsOnly && selectedLocales.length) await assertSourcePagesListed(fernRoot, activePages); console.log(`Generating ${activePages.length} active pages for ${selectedLocales.length} locale(s).`); @@ -583,11 +585,19 @@ for (const locale of selectedLocales) { continue; } - const labels = await translatedLabelMap(locale); - await saveTextFile( - path.join(localeRoot, "docs.yml"), - renderNavigationOverlay(config, labels), + const navigationPath = path.join(localeRoot, "docs.yml"); + const navigationHash = sha256( + `${generatorVersion}\0${locale.code}\0${locale.sourceLanguage ?? ""}\0${locale.targetLanguage ?? "copy"}\0${navigationSource}`, ); + // Reuse the existing overlay, including edits made after generation. A + // missing output must be rebuilt even when its input hash still matches. + const reuseNavigation = !force && !labelsOnly && + localeManifest.navigationHash === navigationHash && await hasTranslationOutput(navigationPath); + if (!reuseNavigation) { + const labels = await translatedLabelMap(locale); + await saveTextFile(navigationPath, renderNavigationOverlay(config, labels)); + localeManifest.navigationHash = navigationHash; + } if (labelsOnly) { console.log(`[${locale.code}] ${locale.label}: navigation labels generated`); continue; @@ -602,17 +612,10 @@ for (const locale of selectedLocales) { const sourceHash = sha256( `${generatorVersion}\0${locale.code}\0${locale.targetLanguage ?? "copy"}\0${source}`, ); - if (!force && localeManifest.pages[relativePagePath] === sourceHash) { - try { - if (!(await stat(outputPath)).isFile()) { - throw new Error(`Translation output is not a file: ${outputPath}`); - } - skippedCount += 1; - continue; - } catch (error) { - if (error.code !== "ENOENT") throw error; - // The manifest is only a cache: a missing output still needs generation. - } + if (!force && localeManifest.pages[relativePagePath] === sourceHash && + await hasTranslationOutput(outputPath)) { + skippedCount += 1; + continue; } const translated = await translateDocument( source, @@ -629,9 +632,13 @@ for (const locale of selectedLocales) { generatedCount += 1; } - localeManifest.generatedAt = new Date().toISOString(); - localeManifest.label = locale.label; - await saveManifest(manifest); + const retiredPages = Object.keys(localeManifest.pages).filter(page => !activePageSet.has(page)); + for (const page of retiredPages) delete localeManifest.pages[page]; + if (!reuseNavigation || generatedCount > 0 || retiredPages.length > 0) { + localeManifest.generatedAt = new Date().toISOString(); + localeManifest.label = locale.label; + await saveManifest(manifest); + } console.log( `[${locale.code}] ${locale.label}: ${generatedCount} generated, ${skippedCount} unchanged`, ); diff --git a/scripts/polish-core-translations.mjs b/scripts/polish-core-translations.mjs index 5efa93cc..3728e89b 100644 --- a/scripts/polish-core-translations.mjs +++ b/scripts/polish-core-translations.mjs @@ -1314,7 +1314,7 @@ if (isMain) { const prepared = updates.get(filePath); return prepared ? prepared.output : readFile(filePath, "utf8"); })) { - const relativePath = path.relative(localeRoot, filePath); + const relativePath = path.relative(localeRoot, filePath).split(path.sep).join("/"); const prepared = updates.get(filePath); const polished = polishMachineTranslation( content, diff --git a/scripts/preview-prediction.mjs b/scripts/preview-prediction.mjs index ebe15c91..d0321df4 100755 --- a/scripts/preview-prediction.mjs +++ b/scripts/preview-prediction.mjs @@ -20,11 +20,10 @@ const backendPort = portArgument("backend-port", 3011); if (port === backendPort) throw new Error("Preview and backend ports must differ"); console.log(`Local prediction review: http://127.0.0.1:${port}/zh-CN/prediction/overview`); console.log("Uses all configured languages and Fern's normal renderer. This command does not publish."); -const executable = path.join(root, "node_modules/.bin", process.platform === "win32" ? "fern.cmd" : "fern"); -const child = spawn(executable, ["docs", "dev", "--port", String(port), "--backend-port", String(backendPort)], { +const executable = path.join(root, "node_modules/fern-api/cli.cjs"); +const child = spawn(process.execPath, [executable, "docs", "dev", "--port", String(port), "--backend-port", String(backendPort)], { cwd: root, stdio: "inherit", - shell: process.platform === "win32", }); for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal)); child.on("error", (error) => { console.error(error.message); process.exitCode = 1; }); diff --git a/scripts/test-fixture-paths.mjs b/scripts/test-fixture-paths.mjs new file mode 100644 index 00000000..5b44c89d --- /dev/null +++ b/scripts/test-fixture-paths.mjs @@ -0,0 +1,15 @@ +import { symlink } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export function linkDirectory(target, destination) { + // Windows directory junctions do not require symbolic-link privileges. + return symlink(target, destination, process.platform === "win32" ? "junction" : "dir"); +} + +export function linkFixtureDependencies(root) { + return linkDirectory( + fileURLToPath(new URL("../node_modules", import.meta.url)), + path.join(root, "node_modules"), + ); +} diff --git a/tests/browser/regression.test.mjs b/tests/browser/regression.test.mjs index e961b51f..ffad71f0 100644 --- a/tests/browser/regression.test.mjs +++ b/tests/browser/regression.test.mjs @@ -55,6 +55,109 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) { }); }); + await t.test('structured data ignores body churn and follows navigation and metadata changes', async () => { + const page = await browser.newPage(); + try { + await page.route(origin + '/**', route => route.fulfill({ + contentType: 'text/html', + body: 'Guide | 6MM Docs
', + })); + await page.goto(origin + '/guide'); + await page.evaluate(() => { + window.seoMutationCount = 0; + const NativeObserver = window.MutationObserver; + window.MutationObserver = class extends NativeObserver { + constructor(callback) { + super((records, observer) => { + seoMutationCount += records.length; + callback(records, observer); + }); + } + }; + }); + await page.addScriptTag({ content: await readFile(new URL('../../fern/seo-structured-data.js', import.meta.url), 'utf8') }); + await flush(page); + const schema = async () => JSON.parse(await page.locator('head script[data-sixmm-schema="webpage"]').textContent()); + assert.equal((await schema()).name, 'Guide'); + await page.evaluate(() => { + seoMutationCount = 0; + const main = document.querySelector('main'); + for (let i = 0; i < 300; i++) { + const result = document.createElement('div'); + result.innerHTML = 'Search result'; + main.appendChild(result); + result.remove(); + } + }); + await flush(page); + assert.equal(await page.evaluate(() => seoMutationCount), 0); + + // Astro navigation can keep both the head and title unchanged. + await page.evaluate(() => { + history.pushState({}, '', '/ar/sdk/overview'); + document.dispatchEvent(new Event('astro:page-load')); + }); + await flush(page); + assert.equal((await schema()).url, 'https://docs.6mm.com/ar/sdk/overview'); + assert.equal((await schema()).inLanguage, 'ar'); + + await page.evaluate(() => { + const nextHead = document.createElement('head'); + nextHead.innerHTML = 'Replaced | 6MM Docs'; + document.head.replaceWith(nextHead); + }); + await flush(page); + assert.equal((await schema()).name, 'Replaced'); + await page.evaluate(() => { document.querySelector('title').firstChild.data = 'Updated | 6MM Docs'; }); + await flush(page); + assert.equal((await schema()).name, 'Updated'); + await page.evaluate(() => { + document.querySelector('head script[data-sixmm-schema="webpage"]').remove(); + }); + await flush(page); + assert.equal((await schema()).name, 'Updated'); + } finally { + await page.close(); + } + }); + + await t.test('static sidebar links use intent-based prefetch before initial and swapped markup is scanned', async () => { + const source = await readFile(new URL('../../fern/language-modal.js', import.meta.url), 'utf8'); + const markup = ` +
Outside sidebar
`; + const page = await browser.newPage(); + try { + await page.route(origin + '/**', route => route.fulfill({ + contentType: 'text/html', + body: `${markup}`, + })); + await page.goto(origin + '/guide'); + assert.equal(await page.evaluate(() => initialSidebarStrategy), 'hover'); + assert.equal(await page.locator('#eager').getAttribute('data-astro-prefetch'), 'hover'); + assert.equal(await page.locator('#disabled').getAttribute('data-astro-prefetch'), 'false'); + assert.equal(await page.locator('#react').getAttribute('data-astro-prefetch'), 'viewport'); + assert.equal(await page.locator('#outside').getAttribute('data-astro-prefetch'), 'viewport'); + assert.equal(await page.locator('#visible').getAttribute('href'), '/relative'); + const swapped = await page.evaluate(markup => { + const event = new Event('astro:before-swap'); + event.newDocument = new DOMParser().parseFromString(markup, 'text/html'); + document.dispatchEvent(event); + return ['visible', 'eager', 'disabled', 'react', 'outside'].map(id => + event.newDocument.getElementById(id).dataset.astroPrefetch); + }, markup); + assert.deepEqual(swapped, ['hover', 'hover', 'false', 'viewport', 'viewport']); + } finally { await page.close(); } + }); + await t.test('all locales retain the page, query, section and support frame', async () => { await withPage(browser, {}, async page => { for (const locale of locales) { @@ -232,6 +335,63 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) { }); }); + await t.test('unrelated element updates do not rescan cards', async () => { + await withPage(browser, {}, async page => { + await flush(page); + await page.evaluate(() => { + window.cardScans = 0; + const query = document.querySelectorAll.bind(document); + document.querySelectorAll = (selector, ...args) => { + if (selector === 'article') cardScans++; + return query(selector, ...args); + }; + }); + // Separate frames model repeated search results, support messages and + // article content updates rather than a single coalesced mutation. + for (let update = 0; update < 12; update++) { + await page.evaluate(() => { + for (const root of [document.querySelector('article'), document.querySelector('#cs-widget-container'), document.body]) { + const content = document.createElement('div'); + content.innerHTML = '

Updated content with nested markup

'; + root.appendChild(content); + content.remove(); + } + }); + await flush(page); + } + assert.equal(await page.evaluate(() => cardScans), 0); + // New targets still register, including direct children whose target + // selector depends on an ancestor outside the added subtree. + for (const [container, child, effect] of [ + ['
', 'Card', 'sixmm-content-card'], + ['
', '
Statistic
', 'sixmm-content-card'], + ['
', 'Next page', 'sixmm-content-card'], + ['
', 'Language', 'sixmm-language-option-effect'], + ['
', 'English', 'sixmm-language-option-effect'], + ['
', '', 'sixmm-language-option-effect'], + ]) { + await page.evaluate(({ container, child }) => { + const wrapper = document.createElement('section'); + wrapper.id = 'dynamic-effect-fixture'; + wrapper.innerHTML = container; + document.body.appendChild(wrapper); + let parent = wrapper; + while (parent.firstElementChild) parent = parent.firstElementChild; + parent.insertAdjacentHTML('beforeend', child); + window.dynamicEffectTarget = parent.lastElementChild; + }, { container, child }); + await flush(page); + assert.equal(await page.evaluate(effect => dynamicEffectTarget.classList.contains(effect), effect), true); + const beforeRemoval = await page.evaluate(() => cardScans); + await page.evaluate(() => dynamicEffectTarget.remove()); + await flush(page); + assert.equal(await page.evaluate(() => cardScans), beforeRemoval + 1, 'Detached targets must trigger group cleanup'); + await page.locator('#dynamic-effect-fixture').evaluate(node => node.remove()); + await flush(page); + } + }); + }); + await t.test('late cards retain their existing effects after body replacements', async () => { await withPage(browser, {}, async page => { for (let swap = 0; swap < 2; swap++) {