Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/frontend-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -480,10 +480,16 @@ jobs:
name: frontend-site
path: ${{ runner.temp }}

# StaticHost treats the locale manifest as the sign that the web root is
# complete and stops re-indexing it, so the manifest lands last.
- name: Unpack site archive
run: |
set -euo pipefail
zstd -d -T0 -q -c "$RUNNER_TEMP/site.tar.zst" | tar -C ../statichost/StaticHost/wwwroot -xf -
wwwroot=../statichost/StaticHost/wwwroot
manifest="$wwwroot/locale-fallback/locales.json"
zstd -d -T0 -q -c "$RUNNER_TEMP/site.tar.zst" \
| tar -C "$wwwroot" -xf - --transform='s,^\./locale-fallback/locales\.json$,./locale-fallback/locales.json.pending,'
mv "$manifest.pending" "$manifest"
rm -f "$RUNNER_TEMP/site.tar.zst"

- name: Wait for StaticHost
Expand Down
13 changes: 8 additions & 5 deletions src/frontend/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { unified } from '@astrojs/markdown-remark';
import { sidebarTopics } from './config/sidebar/sidebar.topics.ts';
import { redirects } from './config/redirects.mjs';
import { locales } from './config/locales.ts';
import { getTranslatedPaths } from './config/translated-paths.mjs';
import { localeFallbackDevIntegration } from './config/locale-fallback-dev-integration.mjs';
import { isExcludedFromLinkValidation } from './config/links-validator-exclude.mjs';
import { headAttrs } from './config/head.attrs.ts';
import { socialConfig } from './config/socials.config.ts';
import { aspireProject } from './src/data/aspire-project.ts';
Expand Down Expand Up @@ -79,6 +82,9 @@ export default defineConfig({
define: {
// Resolve filesystem-backed redirects before prerender modules are bundled.
__ASPIRE_REDIRECT_PATHS__: JSON.stringify(Object.keys(redirects)),
// Untranslated locale routes aren't built (see the Starlight patch), so
// hreflang alternates only list localized routes that really exist.
__ASPIRE_TRANSLATED_PATHS__: JSON.stringify(getTranslatedPaths()),
},
...(staticHostUrl
? {
Expand Down Expand Up @@ -173,11 +179,7 @@ export default defineConfig({
starlightLinksValidator({
errorOnRelativeLinks: false,
errorOnFallbackPages: false,
exclude: [
'/i18n/', '/reference/api', '/reference/api/**',
// Custom Astro destinations checked by the Dev Hub browser tests.
'/hub/', '/hub/glossary/ats/', '/get-started/glossary/#polyglot',
],
exclude: ({ link }) => isExcludedFromLinkValidation(link),
}),
starlightGitHubAlerts(),
starlightLlmsTxt({
Expand Down Expand Up @@ -256,6 +258,7 @@ export default defineConfig({
}),
...(isBuildTimingEnabled ? [buildTiming()] : []),
aspireVersionPlaceholdersIntegration(),
localeFallbackDevIntegration(),
],
build: {
concurrency: buildConcurrency,
Expand Down
66 changes: 66 additions & 0 deletions src/frontend/config/links-validator-exclude.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// @ts-check
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { locales } from './locales.ts';

const defaultDocsDir = fileURLToPath(new URL('../src/content/docs/', import.meta.url));

/** Custom Astro destinations the validator can't see; checked by browser tests instead. */
const customPaths = new Set([
'/i18n/',
'/hub/',
'/hub/glossary/ats/',
'/get-started/glossary/#polyglot',
]);

const localePrefixes = Object.keys(locales).filter((locale) => locale !== 'root');

/**
* @param {string} link
*/
function isCustomPath(link) {
const path = link.split('?')[0];
return (
customPaths.has(path) ||
path === '/reference/api' ||
path.startsWith('/reference/api/')
);
}

/**
* Whether a docs page for a route exists as content.
*
* @param {string} path Route path without hash or query.
* @param {string} docsDir
*/
function hasDocsPage(path, docsDir) {
const slug = path.replace(/^\/+|\/+$/g, '');
const base = slug === '' ? 'index' : slug;
return ['.md', '.mdx', '/index.md', '/index.mdx'].some((suffix) =>
existsSync(join(docsDir, `${base}${suffix}`))
);
}

/**
* Links to untranslated locale routes (e.g. `/de/docs/`) point at pages that
* aren't built: StaticHost serves the English page in place. Skip those only
* when the page isn't translated and the English target exists, so broken
* links and translated anchors are still reported.
*
* @param {string} link
* @param {string} [docsDir]
*/
export function isExcludedFromLinkValidation(link, docsDir = defaultDocsDir) {
if (isCustomPath(link)) return true;

const match = /^\/([^/?#]+)(\/[^?#]*)?/.exec(link);
if (!match || !localePrefixes.includes(match[1])) return false;

const unlocalized = match[2] ?? '/';
const unlocalizedLink = `${unlocalized}${link.slice(match[0].length)}`;
if (isCustomPath(unlocalizedLink)) return true;

if (hasDocsPage(`/${match[1]}${unlocalized}`, docsDir)) return false;
return hasDocsPage(unlocalized, docsDir);
}
80 changes: 80 additions & 0 deletions src/frontend/config/locale-fallback-dev-integration.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// @ts-check
import { locales } from './locales.ts';
import { redirects } from './redirects.mjs';
import { getTranslatedPaths } from './translated-paths.mjs';

const localeSegments = Object.keys(locales)
.filter((key) => key !== 'root')
.map((key) => key.toLowerCase());

/**
* Path the dev server should render for `pathname`, mirroring StaticHost's
* `LocaleFallbackMiddleware`: untranslated locale routes (which the build no
* longer emits) render the English page in place. Returns `undefined` when the
* request needs no rewrite.
*
* @param {string} pathname
* @param {ReadonlySet<string>} translatedPaths
* @param {ReadonlySet<string>} [redirectSources] Lowercased configured redirect
* sources; Astro handles those itself, as StaticHost leaves existing paths alone.
* @returns {string | undefined}
*/
export function getLocaleFallbackDevPath(pathname, translatedPaths, redirectSources = new Set()) {
const match = pathname.match(/^\/([^/]+)(\/.*)$/);
if (!match) return undefined;

const [, segment, unlocalizedPath] = match;
if (!localeSegments.includes(segment.toLowerCase()) || unlocalizedPath === '/') {
return undefined;
}
// `/de/ja/x/` must not serve the Japanese page as an English fallback for `de`.
if (localeSegments.includes(unlocalizedPath.split('/')[1]?.toLowerCase())) return undefined;

const lastSegment = unlocalizedPath.slice(unlocalizedPath.lastIndexOf('/') + 1);
const isMarkdown = lastSegment.endsWith('.md');
// Only pages and their Markdown copies fall back; directory routes without a
// trailing slash are left for the dev server to redirect.
if (!unlocalizedPath.endsWith('/') && !isMarkdown) return undefined;
const pagePath = isMarkdown ? `${pathname.slice(0, -'.md'.length)}/` : pathname;
const normalizedPagePath = pagePath.toLowerCase();
if (translatedPaths.has(normalizedPagePath) || redirectSources.has(normalizedPagePath)) {
return undefined;
}

return unlocalizedPath;
}

/**
* Serves the English page in place of untranslated locale routes during
* `astro dev`, so local development and E2E runs match production.
*
* @returns {import('astro').AstroIntegration}
*/
export function localeFallbackDevIntegration() {
const redirectSources = new Set(
Object.keys(redirects).map((source) =>
(source.endsWith('/') ? source : `${source}/`).toLowerCase()
)
);
return {
name: 'aspire-locale-fallback-dev',
hooks: {
'astro:server:setup': ({ server }) => {
server.middlewares.use((req, res, next) => {
const url = new URL(req.url ?? '/', 'http://localhost');
// Re-read on each locale request so new translations are picked up without a restart.
const rewrittenPath = localeSegments.some((locale) =>
url.pathname.toLowerCase().startsWith(`/${locale}/`)
)
? getLocaleFallbackDevPath(url.pathname, new Set(getTranslatedPaths()), redirectSources)
: undefined;
if (rewrittenPath) {
Comment thread
IEvangelist marked this conversation as resolved.
Resolved
req.url = `${rewrittenPath}${url.search}`;
res.setHeader('Content-Language', 'en');
}
next();
});
},
},
};
}
33 changes: 33 additions & 0 deletions src/frontend/config/translated-paths.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// @ts-check
import { existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { locales } from './locales.ts';

const defaultDocsDir = fileURLToPath(new URL('../src/content/docs/', import.meta.url));

/**
* Route paths (for example `/ja/get-started/install-cli/`) of every page that
* has a real translation in a non-default locale. Untranslated locale routes
* are not built; the static host serves the English page in place.
*
* @param {string} [docsDir]
* @returns {string[]}
*/
export function getTranslatedPaths(docsDir = defaultDocsDir) {
const paths = new Set();
for (const locale of Object.keys(locales)) {
if (locale === 'root') continue;
const localeDir = join(docsDir, locale);
if (!existsSync(localeDir)) continue;

for (const file of readdirSync(localeDir, { recursive: true, encoding: 'utf8' })) {
if (!/\.mdx?$/i.test(file)) continue;
const slug = `${locale}/${file.replace(/\\/g, '/').replace(/\.mdx?$/i, '')}`
.toLowerCase()
.replace(/\/index$/, '');
paths.add(`/${slug}/`);
}
}
return [...paths].sort();
}
57 changes: 49 additions & 8 deletions src/frontend/patches/@astrojs__starlight@0.41.3.patch
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
diff --git a/components/Search.astro b/components/Search.astro
index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..0a35ace9530404d2469ae11ed87688766d75e8bd 100644
index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..a1ccda6bf9c7beddc4090f1f9069eb7dc5b5b41c 100644
--- a/components/Search.astro
+++ b/components/Search.astro
@@ -59,7 +59,7 @@ if (project.trailingSlash === 'never') dataAttributes['data-strip-trailing-slash
Expand Down Expand Up @@ -51,13 +51,17 @@ index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..0a35ace9530404d2469ae11ed8768876

// Listen for `ctrl + k` and `cmd + k` keyboard shortcuts.
window.addEventListener('keydown', (e) => {
@@ -121,7 +126,16 @@ if (project.trailingSlash === 'never') dataAttributes['data-strip-trailing-slash
@@ -121,30 +126,56 @@ if (project.trailingSlash === 'never') dataAttributes['data-strip-trailing-slash
dialog.open ? closeModal() : openModal();
e.preventDefault();
}
- });
+ }, { signal });
+

- let translations = {};
- try {
- translations = JSON.parse(this.dataset.translations || '{}');
- } catch {}
+ this.cleanup = () => {
+ controller.abort();
+ if (dialog.open) {
Expand All @@ -66,10 +70,26 @@ index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..0a35ace9530404d2469ae11ed8768876
+ }
+ pagefindUI?.destroy();
+ };
+
+ // Read when Pagefind initializes: the page can localize `data-translations` first.
+ const readTranslations = () => {
+ try {
+ return JSON.parse(this.dataset.translations || '{}');
+ } catch {
+ return {};
+ }
+ };
+ // The page sets `data-translations-pending` while it localizes them, then
+ // removes it and dispatches `translationsready`.
+ const translationsReady = () =>
+ this.hasAttribute('data-translations-pending')
+ ? new Promise<void>((resolve) => {
+ this.addEventListener('translationsready', () => resolve(), { once: true, signal });
+ signal.addEventListener('abort', () => resolve(), { once: true });
+ })
+ : Promise.resolve();

let translations = {};
try {
@@ -132,15 +146,18 @@ if (project.trailingSlash === 'never') dataAttributes['data-strip-trailing-slash
const shouldStrip = this.dataset.stripTrailingSlash !== undefined;
const stripTrailingSlash = (path: string) => path.replace(/(.)\/(#.*)?$/, '$1$2');
const formatURL = shouldStrip ? stripTrailingSlash : (path: string) => path;

Expand All @@ -82,6 +102,7 @@ index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..0a35ace9530404d2469ae11ed8768876
// @ts-expect-error — Missing types for @pagefind/default-ui package.
const { PagefindUI } = await import('@pagefind/default-ui');
- new PagefindUI({
+ await translationsReady();
+ // Navigation can detach this instance while the module is loading.
+ if (signal.aborted) return;
+ pagefindUI = new PagefindUI({
Expand All @@ -91,7 +112,12 @@ index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..0a35ace9530404d2469ae11ed8768876
baseUrl: import.meta.env.BASE_URL,
bundlePath: import.meta.env.BASE_URL.replace(/\/$/, '') + '/pagefind/',
showImages: false,
@@ -154,8 +171,19 @@ if (project.trailingSlash === 'never') dataAttributes['data-strip-trailing-slash
- translations,
+ translations: readTranslations(),
showSubResults: true,
processResult: (result: { url: string; sub_results: Array<{ url: string }> }) => {
result.url = formatURL(result.url);
@@ -154,8 +185,19 @@ if (project.trailingSlash === 'never') dataAttributes['data-strip-trailing-slash
});
},
});
Expand All @@ -113,7 +139,7 @@ index d8c80d826995d6c8ce598aa618ddf7ea575ecadc..0a35ace9530404d2469ae11ed8768876
}
customElements.define('site-search', SiteSearch);
diff --git a/components/SidebarSublist.astro b/components/SidebarSublist.astro
index 457ab20fd3583f521bd756cd2acb5cc57643d60b..b6c81a9520418c03b14e3053c46edc9541556e03 100644
index 457ab20fd3583f521bd756cd2acb5cc57643d60b..f384d361dcc9d7b252a605b9a8c7dbf185fda32c 100644
--- a/components/SidebarSublist.astro
+++ b/components/SidebarSublist.astro
@@ -1,7 +1,6 @@
Expand Down Expand Up @@ -161,3 +187,18 @@ index 457ab20fd3583f521bd756cd2acb5cc57643d60b..b6c81a9520418c03b14e3053c46edc95

a {
display: block;
diff --git a/utils/routing/index.ts b/utils/routing/index.ts
index c4af65f6c1c711399b58a984a3301ff56e39e2d5..a56582378a8514b88d5c188484d87a565b5e46c0 100644
--- a/utils/routing/index.ts
+++ b/utils/routing/index.ts
@@ -96,7 +96,9 @@ export function getRouteBySlugParam(slugParam: string | undefined): Route | unde
}

function getPaths(): Path[] {
- return routes.map((route) => ({
+ // Fallback pages aren't emitted: the host serves the default-locale page in place.
+ const pageRoutes = routes.filter((route) => !route.isFallback);
+ return pageRoutes.map((route) => ({
params: { slug: slugToParam(route.id) },
props: route,
}));
2 changes: 1 addition & 1 deletion src/frontend/patches/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ regenerated (`bun patch <package>`, edit, then `bun patch --commit <directory>`)

| Patch | Why |
| --- | --- |
| `@astrojs__starlight@0.41.3.patch` | Starlight search must initialize and dispose per element across `ClientRouter` swaps, not only on `DOMContentLoaded` ([#1673](https://github.com/microsoft/aspire.dev/issues/1673)). The sidebar group caret is drawn with a CSS mask from the shared stylesheet instead of an inline SVG repeated for every group (hundreds per API reference page). |
| `@astrojs__starlight@0.41.3.patch` | Starlight search must initialize and dispose per element across `ClientRouter` swaps, not only on `DOMContentLoaded` ([#1673](https://github.com/microsoft/aspire.dev/issues/1673)). The sidebar group caret is drawn with a CSS mask from the shared stylesheet instead of an inline SVG repeated for every group (hundreds per API reference page). Also skips untranslated locale fallback routes: StaticHost serves the English page in place (`LocaleFallbackMiddleware`) and `src/scripts/locale-fallback.ts` localizes the chrome, instead of emitting a full English copy per locale. On those pages search waits for `data-translations-pending` to clear, then reads the localized `data-translations` (including Pagefind's own strings for the locale) while it keeps searching the English index. |
| `astro@7.4.1.patch` | Imported SVGs are callable components that can't be structured-cloned, so the parallel prerender worker keeps only their image metadata before posting results. |
| `starlight-page-actions@0.7.0.patch` | Keeps accessible actions across page swaps, allows readable heading markup, and points Markdown actions on untranslated locale pages to the default-locale Markdown. The dropdown's external-link icon is a CSS mask instead of an inline SVG per item. |
| `starlight-plugin-icons@1.1.6.patch` | Temporary network-resilience fix for `getMaterialIconsData`: falls back to the vendored `.starlight-icons` cache when the icon-data fetch fails. Remove once [Rettend/starlight-plugin-icons#9](https://github.com/Rettend/starlight-plugin-icons/pull/9) is merged and released. |
Loading
Loading