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
27 changes: 23 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -95,24 +95,30 @@ jobs:
);
NODE

- name: Checkout pinned Thally runtime
# Begin with protected source. Prove the manifest's exact commit is on
# that history before checking out or executing any of its files.
- name: Checkout protected Thally runtime
if: needs.plan.outputs.full == 'true'
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
with:
repository: thallylabs/thally
ref: ${{ steps.runtime.outputs.sha }}
ref: main
path: runtime-source
fetch-depth: 0
persist-credentials: false

- name: Prove runtime revision is on protected main
if: needs.plan.outputs.full == 'true'
shell: bash
env:
RUNTIME_SHA: ${{ steps.runtime.outputs.sha }}
run: |
[[ "$RUNTIME_SHA" =~ ^[0-9a-f]{40}$ ]]
git -C runtime-source fetch --no-tags origin main
test "$(git -C runtime-source rev-parse HEAD)" = "$RUNTIME_SHA"
git -C runtime-source cat-file -e "$RUNTIME_SHA^{commit}"
git -C runtime-source merge-base --is-ancestor "$RUNTIME_SHA" origin/main
git -C runtime-source checkout --detach "$RUNTIME_SHA"
test "$(git -C runtime-source rev-parse HEAD)" = "$RUNTIME_SHA"

- name: Verify generated runtime snapshot
if: needs.plan.outputs.full == 'true'
Expand All @@ -134,7 +140,9 @@ jobs:
with:
# Wrangler 4.111+ requires Node 22 for the exact dry-run package gate.
node-version: 22
cache: npm
# Repository scripts are untrusted, including on manual runs. Never
# persist their npm cache into a shared default-branch cache.
package-manager-cache: false

- name: Install pinned content tooling
run: npm ci --ignore-scripts --prefix .github/thally-tooling
Expand All @@ -155,10 +163,21 @@ jobs:
if: needs.plan.outputs.full == 'true'
run: npm ci --ignore-scripts

# Lifecycle scripts are intentionally skipped during install. Type checking
# still needs the generated modules normally created by postinstall.
- name: Generate runtime sources
if: needs.plan.outputs.full == 'true'
run: npm run runtime-sources:build

- name: Test
if: needs.plan.outputs.full == 'true'
run: npm test

# Cloudflare is an explicit CI profile, not a portable site dependency.
- name: Install optional Cloudflare tooling
if: needs.plan.outputs.full == 'true'
run: npm run setup:cloudflare

- name: Build managed runtime and content assets
if: needs.plan.outputs.full == 'true'
run: npm run build:cloudflare
Expand Down
29 changes: 25 additions & 4 deletions src/app/(docs)/changelog/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
/** Changelog content and its complete, canonical social metadata. */
import type { Metadata } from 'next'
import { DocLayout } from '@/components/docs/doc-layout'
import { getBreadcrumbs, getSeoConfig } from '@/data/docs'
import { getBreadcrumbs, getSeoConfig, canReaderViewPage } from '@/data/docs'
import { getEffectiveI18nConfig } from '@/lib/i18n/request'
import { getContentI18nConfig } from '@/lib/i18n/content'
import { buildLocaleAlternates } from '@/lib/i18n/metadata'
import { getReaderContext } from '@/lib/reader-auth/context'
import { canReaderViewResolvedDoc, denyDocumentAccess } from '@/lib/reader-auth/page-gate'
import { getDocFromParams } from '@/data/get-doc'
Expand All @@ -9,10 +14,17 @@ import { resolveBuildSiteConfig } from '@/lib/site-config'
import { getSiteUrl } from '@/lib/site-url'
import { buildOgImageUrl, formatOgBreadcrumb, formatOgDisplayUrl } from '@/lib/og'

export async function generateMetadata() {
/** Project the same published locale cluster as ordinary documentation pages. */
export async function generateMetadata(): Promise<Metadata> {
const doc = await getDocFromParams(['changelog'])
if (!doc) return {}
if (!(await canReaderViewResolvedDoc(doc, await getReaderContext()))) return {}
const reader = await getReaderContext()
if (!(await canReaderViewResolvedDoc(doc, reader))) return {}
const i18n = await getEffectiveI18nConfig()
const contentI18n = await getContentI18nConfig(['changelog'], i18n)
const allowed = await Promise.all(contentI18n.locales.map(locale =>
canReaderViewPage(doc.id, reader, locale.code === i18n.defaultLocale ? undefined : locale.code)))
const availableI18n = { ...contentI18n, locales: contentI18n.locales.filter((_, index) => allowed[index]) }
const siteUrl = getSiteUrl()
const description = plainInlineText(doc.description)
const ogImageUrl = buildOgImageUrl({
Expand All @@ -32,8 +44,17 @@ export async function generateMetadata() {
return {
title: fullTitle ? { absolute: fullTitle } : doc.title,
description,
alternates: { canonical: `${siteUrl}${doc.href}` },
...(doc.noindex || doc.hidden ? { robots: { index: false, follow: false } } : {}),
alternates: {
canonical: `${siteUrl}${doc.href}`,
...(!doc.noindex && !doc.hidden
? { languages: buildLocaleAlternates(siteUrl, doc.href, availableI18n) }
: {}),
},
openGraph: {
type: 'article',
url: `${siteUrl}${doc.href}`,
siteName: resolveBuildSiteConfig().name,
title: doc.title,
description,
images: [{ url: ogImageUrl, width: 1200, height: 630 }],
Expand Down
19 changes: 16 additions & 3 deletions src/app/api/site-config/route.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
/** Public identity and optional artwork availability, never private settings. */
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getEffectiveSiteConfig } from '@/lib/admin/site-config'
import { getAdminSettings } from '@/lib/admin/settings'
import { resolveBrandAsset } from '@/lib/brand-assets'

export const runtime = 'nodejs'

/** Public: the effective site name/description/repo (build config + admin overrides).
* Lets client components (the header) reflect dashboard edits without a rebuild. */
export async function GET(request: NextRequest) {
const [identity, settings] = await Promise.all([
const [identity, settings, lightLogo, darkLogo] = await Promise.all([
getEffectiveSiteConfig(request.nextUrl.origin),
getAdminSettings(),
resolveBrandAsset('logo', 'light', request.nextUrl.origin),
resolveBrandAsset('logo', 'dark', request.nextUrl.origin),
])
// Only this public capability flag crosses the boundary; never serialize settings.
return NextResponse.json({ ...identity, mcpEnabled: settings.mcpEnabled !== false }, {
// Project only public capabilities; never serialize the settings record.
return NextResponse.json({
...identity,
mcpEnabled: settings.mcpEnabled !== false,
// Presence is enough to select the existing byte route. Upload data and
// private configuration never cross this public identity projection.
logos: {
light: Boolean(lightLogo?.path || lightLogo?.dataUri),
dark: Boolean(darkLogo?.path || darkLogo?.dataUri),
},
}, {
headers: { 'cache-control': 'public, max-age=30' },
})
}
7 changes: 4 additions & 3 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { SiteBanner } from '@/components/layout/site-banner'
import { WebMcpTools } from '@/components/agent/web-mcp-tools'
import { CloudHandshake } from '@/components/cloud/cloud-handshake'
import { localeDirection } from '@/lib/i18n/config'
import { getEffectiveI18nConfig } from '@/lib/i18n/request'
import { getEffectiveI18nConfig, getDocumentLocale } from '@/lib/i18n/request'
import { resolveBuildSiteConfig } from '@/lib/site-config'
import { validMetatags } from '@/lib/metatags'
import { getBuildSiteAppearance } from '@/lib/cloud-link/appearance'
Expand Down Expand Up @@ -277,6 +277,7 @@ export default async function RootLayout({ children }: Readonly<{ children: Reac
const effectiveSite = resolveBuildSiteConfig()
const siteUrl = getSiteUrl()
const defaultLang = i18n.defaultLocale
const documentLang = await getDocumentLocale(i18n)
const siteJsonLd = buildSiteJsonLd({
siteUrl,
siteName: effectiveSite.name,
Expand All @@ -290,8 +291,8 @@ export default async function RootLayout({ children }: Readonly<{ children: Reac
// globals.css --font-heading default and docs.json font overrides — can
// reference and override them.
<html
lang={defaultLang}
dir={localeDirection(defaultLang)}
lang={documentLang}
dir={localeDirection(documentLang)}
suppressHydrationWarning
data-theme={structuralTheme}
data-content-icons={contentIconTone}
Expand Down
5 changes: 4 additions & 1 deletion src/app/sitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,8 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
},
]

return [...docPages, ...apiPages, ...staticPages]
// Special routes can also be navigable documents. Keep their first entry,
// which contains document locale alternates and authored modification dates.
return [...docPages, ...apiPages, ...staticPages].filter((entry, index, pages) =>
pages.findIndex(candidate => candidate.url === entry.url) === index)
}
39 changes: 21 additions & 18 deletions src/components/layout/logo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { useReaderTheme } from '@/components/theme/reader-theme'
import { cn } from '@/lib/utils'
import { displaySiteName, useSiteName } from './use-site-name'
import { displaySiteName, useSiteName, useSiteLogo } from './use-site-name'

// Stable no-op subscribe for the hydration gate below.
const emptySubscribe = () => () => {}
Expand All @@ -19,7 +19,7 @@ interface LogoProps {
export function Logo({ className, showText = true }: LogoProps) {
const siteName = useSiteName()
// Show an admin-uploaded logo when one exists; otherwise the default mark +
// site name. The <img> probes /api/brand/logo and swaps in on load.
// site name. Only emit the image after the public identity confirms artwork.
const [customOk, setCustomOk] = useState(false)
const imgRef = useRef<HTMLImageElement>(null)

Expand All @@ -31,10 +31,11 @@ export function Logo({ className, showText = true }: LogoProps) {
const mounted = useSyncExternalStore(emptySubscribe, () => true, () => false)
const { resolvedTheme } = useReaderTheme()
const isDark = mounted && resolvedTheme === 'dark'
const hasCustomLogo = useSiteLogo(isDark ? 'dark' : 'light')
const src = isDark ? '/api/brand/logo?mode=dark' : '/api/brand/logo'

// The <img> is server-rendered, so it can finish loading BEFORE React attaches
// onLoad (the event never fires). Check completeness on mount to catch that.
// Artwork may already be cached when a live identity update adds it. Check
// completeness as well as onLoad so the fallback does not remain visible.
// The default mark can be missing too (a site that pruned public/brand):
// drop it rather than show a broken-image icon; the site name stays.
const defaultRef = useRef<HTMLImageElement>(null)
Expand All @@ -45,23 +46,25 @@ export function Logo({ className, showText = true }: LogoProps) {
if (img?.complete) setCustomOk(img.naturalWidth > 0)
const fallback = defaultRef.current
if (fallback?.complete && fallback.naturalWidth === 0) setDefaultOk(false)
}, [])
}, [hasCustomLogo, src])

return (
<div className={cn('inline-flex min-w-0 max-w-full items-center gap-2', className)}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
ref={imgRef}
src={src}
alt={siteName}
data-custom-logo=""
onLoad={() => setCustomOk(true)}
onError={() => setCustomOk(false)}
// A fixed height gives icons and wordmarks equal visual weight. The
// width cap contains unusually wide assets; object-fit avoids distortion.
style={{ height: 28, width: 'auto', maxWidth: 'min(160px, 100%)', objectFit: 'contain', objectPosition: 'left', display: customOk ? 'block' : 'none' }}
/>
{!customOk ? (
{hasCustomLogo ? (
/* eslint-disable-next-line @next/next/no-img-element */
<img
ref={imgRef}
src={src}
alt={siteName}
data-custom-logo=""
onLoad={() => setCustomOk(true)}
onError={() => setCustomOk(false)}
// A fixed height gives icons and wordmarks equal visual weight. The
// width cap contains unusually wide assets; object-fit avoids distortion.
style={{ height: 28, width: 'auto', maxWidth: 'min(160px, 100%)', objectFit: 'contain', objectPosition: 'left', display: customOk ? 'block' : 'none' }}
/>
) : null}
{!hasCustomLogo || !customOk ? (
<>
{/* The default Thally leaf keeps its exact olive in both modes. A
site owner's uploaded logo still replaces it above. */}
Expand Down
19 changes: 18 additions & 1 deletion src/components/layout/use-site-name.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use client'

/** Shared public identity refresh; absent artwork never creates an image probe. */

import {
createContext,
createElement,
Expand All @@ -12,6 +14,13 @@ import { siteConfig } from '@/data/site'

const SiteNameContext = createContext<string | null>(null)

interface SiteLogos {
light: boolean
dark: boolean
}

const SiteLogoContext = createContext<SiteLogos>({ light: false, dark: false })

interface SiteNameProviderProps {
children: ReactNode
initialName: string
Expand All @@ -25,15 +34,23 @@ interface SiteNameProviderProps {
*/
export function SiteNameProvider({ children, initialName }: SiteNameProviderProps) {
const [name, setName] = useState(initialName)
const [logos, setLogos] = useState<SiteLogos>({ light: false, dark: false })
useEffect(() => {
fetch('/api/site-config')
.then((r) => (r.ok ? r.json() : null))
.then((c) => {
if (c?.name && typeof c.name === 'string') setName(c.name)
if (c?.logos) setLogos({ light: c.logos.light === true, dark: c.logos.dark === true })
})
.catch(() => {})
}, [])
return createElement(SiteNameContext.Provider, { value: name }, children)
return createElement(SiteNameContext.Provider, { value: name },
createElement(SiteLogoContext.Provider, { value: logos }, children))
}

/** Whether the current public identity has actual artwork for the requested mode. */
export function useSiteLogo(mode: 'light' | 'dark'): boolean {
return useContext(SiteLogoContext)[mode]
}

/** The effective site name — request snapshot, refreshed live by the dashboard. */
Expand Down
11 changes: 11 additions & 0 deletions src/lib/i18n/document-locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/** Middleware-owned path context for server-rendered managed document language. */

import type { I18nConfig } from './config'

export const DOCUMENT_PATH_HEADER = 'x-thally-document-path'

/** Resolve only enabled, exact route prefixes; arbitrary headers cannot invent a locale. */
export function documentLocaleFromPath(pathname: string | null, i18n: I18nConfig): string {
const prefix = pathname?.startsWith('/') ? pathname.split('/')[1] : null
return i18n.locales.find(locale => locale.code === prefix)?.code ?? i18n.defaultLocale
}
9 changes: 9 additions & 0 deletions src/lib/i18n/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
import 'server-only'

import { cache } from 'react'
import { headers } from 'next/headers'
import { isRemoteContentSource } from '@/lib/content-source'
import { DOCUMENT_PATH_HEADER, documentLocaleFromPath } from './document-locale'
import { getI18nConfig } from '@/data/docs'
import { getAdminSettings } from '@/lib/admin/settings'
import { getRequestCloudSiteConfig } from '@/lib/cloud-link/request'
Expand Down Expand Up @@ -59,3 +62,9 @@ export const getEffectiveI18nConfig = cache(async (): Promise<I18nConfig> => {
const admin = await getAdminSettings()
return resolveI18nSelection(admin.localization, repository)
})

/** Read request context only for managed content, preserving unlinked static builds. */
export async function getDocumentLocale(i18n: I18nConfig): Promise<string> {
if (!isRemoteContentSource()) return i18n.defaultLocale
return documentLocaleFromPath((await headers()).get(DOCUMENT_PATH_HEADER), i18n)
}
8 changes: 7 additions & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { getCloudAccessConfigEdge, getManagedSiteIdEdge } from '@/lib/cloud-link
import { isMarkdownPagesEnabled } from '@/lib/markdown-pages'
import { createDailyVisitorKey, externalReferrerDomain } from '@/lib/analytics/identity'
import { problemResponse } from '@/lib/http/problem'
import { DOCUMENT_PATH_HEADER } from '@/lib/i18n/document-locale'
import { isReaderAuthActive } from '@/lib/reader-auth/config'

// Static API paths are known without importing the Node-only content graph.
Expand Down Expand Up @@ -501,7 +502,12 @@ export async function middleware(request: NextRequest, event: NextFetchEvent) {
// custom header agents read directly, so it carries an absolute URL. Only
// potential content pages get the headers, including API-reference pages;
// known service APIs, admin routes, and Next internals do not.
const response = NextResponse.next()
// Root layouts cannot receive a nested catch-all locale. Replace any caller
// supplied context with the real path so managed HTML can declare its language
// before JavaScript runs, without rewriting docs or negotiating RSC payloads.
const requestHeaders = new Headers(request.headers)
requestHeaders.set(DOCUMENT_PATH_HEADER, pathname)
const response = NextResponse.next({ request: { headers: requestHeaders } })
if (isPotentialDocsPagePath(pathname)) {
response.headers.append('Link', '</llms.txt>; rel="llms-txt"')
// Standard relation types agents actually dereference (RFC 8288): the
Expand Down
4 changes: 2 additions & 2 deletions starter-release.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"defaultBranch": "main",
"runtime": {
"repository": "thallylabs/thally",
"commitSha": "d8345dda03189ba1d75810b5310117c5cd9c3f6d",
"treeSha": "0a0831d9802d3614e4f4d11704e637ed04284ca3"
"commitSha": "79ab77f08b832fc8ee37c6103c64a9c52d48de39",
"treeSha": "b0c574508bace2fad15b8f327aedfb2e1a169520"
},
"packages": {
"@thallylabs/core": "^0.2.18"
Expand Down
Loading