Compare commits

..

3 Commits

Author SHA1 Message Date
Peter White af08c4ac08 Prefetch search results on hover or keyboard selection 2026-11-22 18:03:00 +00:00
Peter White e9890dfa4c changeset 2026-11-22 17:40:20 +00:00
Peter White 5c2986e1c5 Prefetch search results on hover or keyboard selection 2026-11-22 17:40:08 +00:00
45 changed files with 189 additions and 449 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Serve the published-docs MCP endpoint independently of the Connect with MCP page action.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published site search results visible while visitors refine a query.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published revision URLs out of search results.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Track the displayed position and search request ID when a visitor opens a search result.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Reduce background downloads during search by prefetching the result visitors hover or select.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Update the GitBook API SDK for site revision responses.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix wide content in Updates blocks overflowing into the page outline.
+2 -2
View File
@@ -357,7 +357,7 @@
},
"catalog": {
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.213.0",
"@gitbook/api": "0.211.0",
"@scalar/api-client-react": "^1.3.46",
"@tsconfig/node20": "^20.1.6",
"@tsconfig/strictest": "^2.0.6",
@@ -725,7 +725,7 @@
"@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="],
"@gitbook/api": ["@gitbook/api@0.213.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-c61/FejKsDJFjLuZVgKplQZm21VyVnC4ahX9NBleRVnYbiN8UJ9lijHCch2sEZ2lR9KM42pi5DVvaMKymli8eg=="],
"@gitbook/api": ["@gitbook/api@0.211.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-G+rY2m7ZvyR1RA4oilarzrNDABDkYhARoIyfNCE5mYqZQgpgsLShn3rGgzTudO2iqwt/5iK6RcJc2enfj+37Jg=="],
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
+1 -1
View File
@@ -48,7 +48,7 @@
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.213.0",
"@gitbook/api": "0.211.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
-42
View File
@@ -442,48 +442,6 @@ const searchTestCases: Test[] = [
expect(new URL(page.url()).pathname).toBe(new URL(topResult.href, page.url()).pathname);
},
},
{
name: 'Search - Enter opens the visible result while a new query loads',
url: `blocks/lists${getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
})}`,
screenshot: false,
run: async (page) => {
await waitForHydration(page);
const heldSearch = await holdSearchRequests(page);
const searchInput = page.getByTestId('search-input');
const searchPopup = page.getByTestId('search-popover');
await searchInput.focus();
await page.waitForURL(/[?&]q=/);
await searchInput.pressSequentially('gitbook');
const initialSearch = await heldSearch('gitbook');
const { siteSpaceId } = initialSearch.request().postDataJSON().scope;
const topResult = searchPageResult(
initialSearch,
siteSpaceId,
'Headings',
'blocks/headings'
);
await initialSearch.fulfill({ json: [topResult] });
const firstResult = searchPopup.getByTestId('search-page-result').first();
await expect(firstResult).toHaveAttribute('href', topResult.href);
await searchInput.pressSequentially(' docs');
const pendingSearch = await heldSearch('gitbook docs');
await expect(searchPopup.locator('output[aria-busy="true"]')).toBeVisible();
await expect(firstResult).toHaveAttribute('href', topResult.href);
await expect(searchPopup.locator('[data-search-placeholder-row]')).toHaveCount(0);
await searchInput.press('Enter');
await expect(searchPopup).toBeHidden();
await expect
.poll(() => new URL(page.url()).pathname)
.toBe(new URL(topResult.href, page.url()).pathname);
await pendingSearch.abort().catch(() => {});
},
},
{
name: 'Search - Enter opens the result under the mouse',
url: `blocks/lists${getCustomizationURL({
@@ -14,8 +14,7 @@ const SEARCH_FALLBACK_REASON =
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
export async function POST(request: NextRequest) {
const { asEmbeddable, query, scope, searchId } =
(await request.json()) as SearchSiteContentRequest;
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
const [context, siteURLData] = await Promise.all([
getServerActionBaseContext({ isEmbeddable: asEmbeddable }),
getSiteURLDataFromMiddleware(),
@@ -41,7 +40,6 @@ export async function POST(request: NextRequest) {
siteId: siteURLData.site,
query,
scope,
searchId,
})
),
throwIfDataError(
@@ -75,7 +75,7 @@ export function Update(props: BlockProps<DocumentBlockUpdate>) {
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style="flex min-w-0 flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
style="flex flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
/>
</FilteredUpdate>
);
@@ -2,8 +2,6 @@
import React from 'react';
import { SiteInsightsDisplayContext } from '@gitbook/api';
import { useTrackEvent } from '../Insights';
import { LinkContext } from '../primitives';
import { useIsVisible } from '../VisibilityContext';
@@ -39,10 +37,9 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
return;
}
trackEvent(
{ type: 'search_open' },
{ pageId: null, displayContext: SiteInsightsDisplayContext.Embed }
);
trackEvent({
type: 'search_open',
});
}, [trackEvent, isVisible]);
const tabsRef = React.useRef<HTMLDivElement>(null);
@@ -59,7 +56,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
query,
results,
resultsId,
resultsQuery,
resultsRef,
searchValue,
setQuery,
@@ -83,7 +79,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
query={query}
results={results}
resultsId={resultsId}
resultsQuery={resultsQuery}
resultsRef={resultsRef}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
@@ -1,7 +1,6 @@
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
import { isSiteMcpEnabled } from '@/lib/mcp/endpoints';
const CONFIGURABLE_PAGE_ACTIONS = [
CustomizationPageActionType.Assistant,
@@ -30,14 +29,8 @@ export function isPageActionEnabled(
* Whether any of the configured page actions is enabled. The RSS feed is not part of them: it is
* only offered on pages with an updates block.
*/
export function hasConfiguredPageActions(context: Pick<GitBookSiteContext, 'customization'>) {
const { customization } = context;
return CONFIGURABLE_PAGE_ACTIONS.some((type) => {
if (type === CustomizationPageActionType.Mcp && !isSiteMcpEnabled(context)) {
return false;
}
return isPageActionEnabled(customization, type);
});
export function hasConfiguredPageActions(customization: GitBookSiteContext['customization']) {
return CONFIGURABLE_PAGE_ACTIONS.some((type) => isPageActionEnabled(customization, type));
}
/**
@@ -8,7 +8,7 @@ import type { PageActionsDropdownURLs } from './PageActionsDropdown';
import type { GitBookSiteContext } from '@/lib/context';
import { getPageDocument } from '@/lib/data';
import { hasTopLevelBlock } from '@/lib/document';
import { hasAdaptiveMcpEndpoint, isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
import { getPageRSSURL } from '@/routes/rss';
/**
@@ -51,7 +51,7 @@ export async function getPageActionsURLs(
}).toString()}`
)
: undefined,
mcp: isMcpPageActionEnabled(context) ? getPageActionsMCPURL(context) : undefined,
mcp: getPageActionsMCPURL(context),
};
}
@@ -139,7 +139,8 @@ export async function PageHeader(props: {
// Show page actions if *any* of the configured actions are enabled, or if the RSS feed is
// available. RSS is contextual (only on update/blog index pages) and is not part of the
// configured `items` list, so it is checked separately.
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions(context) || withRSSFeed);
const hasPageActions =
pageActionsEnabled && (hasConfiguredPageActions(context.customization) || withRSSFeed);
if (!page.layout.title && !page.layout.description && !hasPageActions) {
return null;
@@ -63,7 +63,6 @@ export function SearchContainer({
query,
results,
resultsId,
resultsQuery,
resultsRef,
searchValue,
setQuery,
@@ -179,7 +178,6 @@ export function SearchContainer({
query={query}
results={results}
resultsId={resultsId}
resultsQuery={resultsQuery}
resultsRef={resultsRef}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
@@ -27,7 +27,6 @@ export function SearchFrame(props: {
query: string;
results: ResultType[];
resultsId: string;
resultsQuery: string;
resultsRef: React.Ref<SearchResultsRef>;
onResultSelect?: () => void;
/** Select the result under the mouse, so hover and keyboard share one highlight. */
@@ -51,7 +50,6 @@ export function SearchFrame(props: {
query,
results,
resultsId,
resultsQuery,
resultsRef,
onResultSelect,
onResultHover,
@@ -80,7 +78,7 @@ export function SearchFrame(props: {
fetching ? 'block animate-fade-in' : 'hidden animate-fade-out-slow'
)}
style={{
animationDelay: fetching && results.length === 0 ? '2s' : undefined,
animationDelay: fetching ? '2s' : undefined,
}}
>
<div
@@ -120,7 +118,7 @@ export function SearchFrame(props: {
) : (
<SearchResults
ref={resultsRef}
query={resultsQuery}
query={query}
id={resultsId}
fetching={fetching}
results={results}
@@ -135,7 +135,7 @@ export const SearchInput = React.forwardRef<HTMLDivElement, SearchInputProps>(
}
}
trailing={
!showAsk && !fetching && value && resultsCount > 0 ? (
!showAsk && value && resultsCount > 0 ? (
<div className="animate-blur-in mr-2 text-sm text-tint-subtle">
{t(language, 'search_results_count', resultsCount.toString())}
</div>
@@ -6,35 +6,33 @@ import { useResizeObserver } from '../hooks';
import { Tooltip } from '../primitives';
import { getPageResultPresentation } from './getPageResultHref';
import { HighlightQuery } from './HighlightQuery';
import type { ComputedPageResult, SearchResultSource } from './search-types';
import type { ComputedPageResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import { usePrefetchWhenActive } from './usePrefetchWhenActive';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem(
props: {
query: string;
item: ComputedPageResult & SearchResultSource;
position: number;
resultsCount: number;
item: ComputedPageResult;
active: boolean;
style?: React.CSSProperties;
},
ref: React.Ref<HTMLAnchorElement>
) {
const { query, item, active, position, resultsCount, style, ...rest } = props;
const { query, item, active, style, ...rest } = props;
const language = useLanguage();
const { preview: bestSection, description, href } = getPageResultPresentation(item);
usePrefetchWhenActive(href, active);
const preview = bestSection
? [bestSection.title, bestSection.body].filter(Boolean).join(' · ')
: undefined;
const insights = {
type: 'search_open_result' as const,
...item.search,
position,
resultsCount,
query,
result: {
pageId: item.pageId,
spaceId: item.spaceId,
@@ -54,6 +52,7 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
...style,
}}
{...rest}
prefetch={false}
>
<Breadcrumbs breadcrumbs={item.breadcrumbs} />
<p className="line-clamp-1 font-heading text-base font-semibold leading-snug text-tint-strong">
@@ -4,36 +4,26 @@ import { Icon } from '@gitbook/icons';
import { Favicon } from '../utils';
import { HighlightQuery } from './HighlightQuery';
import type { ComputedRecordResult, SearchResultSource } from './search-types';
import type { ComputedRecordResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import { usePrefetchWhenActive } from './usePrefetchWhenActive';
import { tString, useLanguage } from '@/intl/client';
export const SearchRecordResultItem = React.forwardRef(function SearchRecordResultItem(
props: {
query: string;
item: ComputedRecordResult & SearchResultSource;
position: number;
resultsCount: number;
item: ComputedRecordResult;
active: boolean;
style?: React.CSSProperties;
},
ref: React.Ref<HTMLAnchorElement>
) {
const { query, item, active, position, resultsCount, style, ...rest } = props;
const { query, item, active, style, ...rest } = props;
const language = useLanguage();
usePrefetchWhenActive(item.href, active);
const domain = getDomain(item.href);
const insights = {
type: 'search_open_result' as const,
...item.search,
position,
resultsCount,
result: {
recordId: item.id,
},
};
return (
<SearchResultItem
ref={ref}
@@ -48,10 +38,17 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
fallback={<Icon icon="memo" className="size-4" />}
/>
}
insights={insights}
insights={{
type: 'search_open_result',
query,
result: {
recordId: item.id,
},
}}
aria-label={tString(language, 'search_page_result_title', item.title)}
style={{ ...style }}
{...rest}
prefetch={false}
>
<p className="line-clamp-2 text-base font-semibold leading-snug text-tint-strong">
<HighlightQuery query={query} text={item.title} />
@@ -72,7 +72,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
const language = useLanguage();
const { siteSpaceId } = useCurrentContent();
const shouldAnimateResults = !query;
const shouldAnimateResults = !query || fetching;
const previousCursor = React.useRef<number | null>(cursor);
const seenResultKeys = React.useRef(new Set<string>());
const lastQuery = React.useRef(query);
@@ -228,8 +228,9 @@ export const SearchResults = React.forwardRef(function SearchResults(
// users should keep their place in it.
if (navigatesCurrentWindow(event)) {
event.currentTarget.blur();
onResultSelect?.();
}
onResultSelect?.();
};
const resultItemProps = {
'aria-posinset': index + 1,
@@ -271,8 +272,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
}}
query={query}
item={item}
position={index + 1}
resultsCount={results.length}
active={index === cursor}
style={{
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
@@ -342,8 +341,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
key={itemKey}
query={query}
item={item}
position={index + 1}
resultsCount={results.length}
active={index === cursor}
style={{
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
@@ -362,11 +359,15 @@ export const SearchResults = React.forwardRef(function SearchResults(
{!fetching && results.length === 0 ? noResults : null}
</>
)}
{fetching && results.length === 0 ? (
{fetching ? (
<div
role="status"
aria-busy="true"
className="flex animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] flex-col gap-1 motion-reduce:animate-none"
className={tcls(
results.length > 0 ? 'mt-1' : '',
'flex flex-col gap-1',
'animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] motion-reduce:animate-none'
)}
>
<SearchResultsPlaceholder />
</div>
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'bun:test';
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
import type { OrderedComputedResult } from './search-types';
describe('computeFilterSiteSpaceIds', () => {
@@ -36,7 +36,7 @@ describe('computeFilterSiteSpaceIds', () => {
});
});
describe('getDisplayedSearchResults', () => {
describe('filterResultsBySiteSpaces', () => {
const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({
type: 'page',
id,
@@ -52,7 +52,7 @@ describe('getDisplayedSearchResults', () => {
it('keeps the server order and drops pages outside the scope', () => {
const results = [page('a', 'current'), page('b', 'other'), page('c', 'current'), page('d')];
expect(getDisplayedSearchResults(results, ['current']).map((result) => result.id)).toEqual([
expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([
'a',
'c',
]);
@@ -60,24 +60,6 @@ describe('getDisplayedSearchResults', () => {
it('returns every result when the scope is unrestricted', () => {
const results = [page('b', 'other'), page('a', 'current')];
expect(getDisplayedSearchResults(results, undefined)).toBe(results);
});
it('caps the displayed list after applying the site space filter', () => {
const pages = Array.from({ length: 10 }, (_, index) => page(`page-${index}`, 'current'));
const records = Array.from({ length: 11 }, (_, index): OrderedComputedResult => ({
type: 'record',
id: `record-${index}`,
title: `Record ${index}`,
description: undefined,
href: `/record-${index}`,
score: 1,
}));
const results = [page('hidden', 'other'), ...pages, ...records];
expect(getDisplayedSearchResults(results, ['current'])).toEqual([
...pages,
...records.slice(0, 10),
]);
expect(filterResultsBySiteSpaces(results, undefined)).toBe(results);
});
});
@@ -1,9 +1,6 @@
import type { OrderedComputedResult } from './search-types';
import type { SearchScope } from './useSearch';
// Keep aligned with SiteInsightsSearchResultNumber in the GitBook API schema.
const MAX_DISPLAYED_SEARCH_RESULTS = 20;
/**
* Site spaces whose pages may be shown for a UI search scope, or `undefined` for no restriction.
*
@@ -32,20 +29,20 @@ export function computeFilterSiteSpaceIds(
}
}
/** Keep the first results in server order within the selected site spaces. */
export function getDisplayedSearchResults<Result extends OrderedComputedResult>(
results: Result[],
/** Keep the server's order, dropping pages owned by a site space outside the scope. */
export function filterResultsBySiteSpaces(
results: OrderedComputedResult[],
allowedSiteSpaceIds: string[] | undefined
): Result[] {
const allowed = allowedSiteSpaceIds && new Set(allowedSiteSpaceIds);
const matching = allowed
? results.filter(
(result) =>
result.type === 'record' ||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
)
: results;
return matching.length > MAX_DISPLAYED_SEARCH_RESULTS
? matching.slice(0, MAX_DISPLAYED_SEARCH_RESULTS)
: matching;
): OrderedComputedResult[] {
if (!allowedSiteSpaceIds) {
return results;
}
const allowed = new Set(allowedSiteSpaceIds);
return results.filter(
(result) =>
result.type === 'record' ||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
);
}
@@ -124,12 +124,11 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
const search = async (input: {
query: string;
searchId?: string;
scope: SearchSiteContentScope;
signal: AbortSignal;
asEmbeddable: boolean;
}): Promise<DirectSearchOutcome> => {
const { query, searchId, scope, signal, asEmbeddable } = input;
const { query, scope, signal, asEmbeddable } = input;
if (!directSearch) {
return { type: 'route' };
}
@@ -164,7 +163,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)),
body: JSON.stringify(toSearchSiteContentBody(query, scope)),
credentials: 'omit',
signal: request.signal,
});
@@ -2,10 +2,6 @@ import type { IconName } from '@gitbook/icons';
export type OrderedComputedResult = ComputedPageResult | ComputedRecordResult;
export type SearchResultSource = {
search: { query: string; searchId: string | undefined };
};
export type BaseComputedResult = {
id: string;
title: string;
@@ -59,7 +55,6 @@ export type SearchSiteContentScope =
export interface SearchSiteContentRequest {
asEmbeddable?: boolean;
searchId?: string;
query: string;
scope: SearchSiteContentScope;
}
@@ -0,0 +1,32 @@
import { PrefetchKind } from 'next/dist/client/components/router-reducer/router-reducer-types';
import { useRouter } from 'next/navigation';
import React from 'react';
import { defaultIsExternalClient, hasSideEffectQueryParams, LinkContext } from '../primitives';
import { isExternalLink, isSiteAuthLink } from '../utils/link';
const RESULT_PREFETCH_DELAY_MS = 200;
export function usePrefetchWhenActive(href: string, active: boolean) {
const router = useRouter();
const { isExternalServer = isExternalLink, isExternalClient = defaultIsExternalClient } =
React.useContext(LinkContext);
React.useEffect(() => {
if (
!active ||
isExternalServer(href) ||
isSiteAuthLink(href) ||
hasSideEffectQueryParams(href) ||
(window.self !== window.top && isExternalClient(href))
) {
return;
}
const timeout = setTimeout(
() => router.prefetch(href, { kind: PrefetchKind.FULL }),
RESULT_PREFETCH_DELAY_MS
);
return () => clearTimeout(timeout);
}, [active, href, isExternalClient, isExternalServer, router]);
}
@@ -141,6 +141,7 @@ function useSearchKeyboardNavigation(props: {
requestKey: string;
flush: () => void;
resultsRef: React.RefObject<SearchResultsRef | null>;
abort: () => void;
askCount: number;
onAskSelect: (index: number) => void;
}) {
@@ -153,6 +154,7 @@ function useSearchKeyboardNavigation(props: {
requestKey,
flush,
resultsRef,
abort,
askCount,
onAskSelect,
} = props;
@@ -188,6 +190,8 @@ function useSearchKeyboardNavigation(props: {
}
if (resultsRef.current?.select()) {
// Stop any in-flight search request only when activating a result.
abort();
return;
}
@@ -203,6 +207,7 @@ function useSearchKeyboardNavigation(props: {
results.length,
onAskSelect,
resultsRef,
abort,
query,
fetching,
requestKey,
@@ -224,11 +229,13 @@ function useSearchKeyboardNavigation(props: {
}
pendingOpenRef.current = null;
if (results.length > 0) {
resultsRef.current?.selectFirst();
if (resultsRef.current?.selectFirst()) {
abort();
}
} else if (!error && askCount > 0) {
onAskSelect(0);
}
}, [isOpen, requestKey, fetching, error, results, resultsRef, askCount, onAskSelect]);
}, [isOpen, requestKey, fetching, error, results, resultsRef, abort, askCount, onAskSelect]);
return {
cursor,
@@ -372,10 +379,9 @@ export function useSearchController(
const selectedSection = state?.section ? findSearchSection(sections, state.section) : undefined;
const { consumeImmediate, flushRef, inputHandlers } = useSearchInputIntent();
const { results, resultsQuery, fetching, error, requestKey, flush, abort } = useSearchResults({
const { results, fetching, error, requestKey, flush, abort } = useSearchResults({
asEmbeddable,
disabled: options.requestsEnabled === false || showAsk || !(normalizedQuery || withAI),
retainPreviousResults: Boolean(state?.open),
disabled: options.requestsEnabled === false || !(normalizedQuery || withAI),
query: normalizedQuery,
siteSpaceId: siteSpace.id,
siteSpaceIds,
@@ -436,6 +442,7 @@ export function useSearchController(
requestKey,
flush,
resultsRef,
abort,
askCount,
onAskSelect: askInAssistant,
});
@@ -456,7 +463,6 @@ export function useSearchController(
query: normalizedQuery,
results,
resultsId: searchResultsId,
resultsQuery,
resultsRef,
searchValue,
setQuery,
@@ -8,36 +8,22 @@ import {
createRecommendedQuestionResult,
getEmptySearchResults,
} from './empty-search-results';
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
import { useRecentSearchQueries } from './recent-queries';
import { computeRemoteSearchScope } from './remote-scope';
import { SEARCH_FALLBACK_HEADER, type SearchPassStore } from './search-pass-store';
import type {
OrderedComputedResult,
SearchResultSource,
SearchSiteContentScope,
} from './search-types';
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
import { streamRecommendedQuestions } from './server-actions';
import { type SearchScope, useSearchPass } from './useSearch';
import { useAI } from '@/components/AI';
export type ResultType = RemoteSearchResult | RecommendedQuestionResult;
const SEARCH_ID_BYTES = 16;
type RemoteSearchResult = OrderedComputedResult & SearchResultSource;
type SearchAnswer = {
scopeKey: string;
query: string;
results: RemoteSearchResult[];
};
export type ResultType = OrderedComputedResult | RecommendedQuestionResult;
type RemoteSearchState =
| { status: 'idle' }
| { status: 'loading'; requestKey: string; answer?: SearchAnswer }
| { status: 'ready'; requestKey: string; answer: SearchAnswer }
| { status: 'error'; requestKey: string };
| { status: 'loading' }
| { status: 'ready'; requestKey: string; results: OrderedComputedResult[] }
| { status: 'error' };
/**
* We cache the recommended questions globally to avoid calling the API multiple times
@@ -51,7 +37,6 @@ export function useSearchResults(props: {
asEmbeddable?: boolean;
disabled: boolean;
query: string;
retainPreviousResults: boolean;
siteSpaceId: string;
siteSpaceIds: string[];
selectedSectionSiteSpaceIds?: string[];
@@ -68,7 +53,6 @@ export function useSearchResults(props: {
asEmbeddable,
disabled,
query,
retainPreviousResults,
siteSpaceId,
siteSpaceIds,
selectedSectionSiteSpaceIds,
@@ -99,15 +83,8 @@ export function useSearchResults(props: {
computeRemoteSearchScope(scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds),
[scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds]
);
const scopeKey = JSON.stringify([
searchURL,
asEmbeddable,
siteSpaceId,
scope,
remoteScope,
filterSiteSpaceIds,
]);
const requestKey = JSON.stringify([scopeKey, query]);
// Identifies the answer the UI needs now; an answer for any other key is never shown as current.
const requestKey = JSON.stringify([query, remoteScope]);
const [remoteState, setRemoteState] = React.useState<RemoteSearchState>({ status: 'idle' });
@@ -123,7 +100,6 @@ export function useSearchResults(props: {
React.useEffect(() => {
if (disabled) {
setRemoteState({ status: 'idle' });
return;
}
if (!query) {
@@ -150,7 +126,7 @@ export function useSearchResults(props: {
// We currently have a bug where the same question can be returned multiple times.
// This is a workaround to avoid that.
const questions = new Set<string>();
let recommendedQuestions: RecommendedQuestionResult[] = [];
const recommendedQuestions: RecommendedQuestionResult[] = [];
if (suggestions && suggestions.length > 0) {
suggestions.forEach((question) => {
@@ -177,10 +153,7 @@ export function useSearchResults(props: {
}
questions.add(question);
recommendedQuestions = [
...recommendedQuestions,
createRecommendedQuestionResult(question, question),
];
recommendedQuestions.push(createRecommendedQuestionResult(question, question));
cachedRecommendedQuestions.set(siteSpaceId, recommendedQuestions);
if (!cancelled) {
@@ -195,19 +168,14 @@ export function useSearchResults(props: {
clearTimeout(timeout);
};
}
setRemoteState((state) => {
const answer = 'answer' in state ? state.answer : undefined;
return answer?.scopeKey === scopeKey
? { status: 'loading', requestKey, answer }
: { status: 'loading', requestKey };
});
setRemoteState({ status: 'loading' });
let cancelled = false;
const abortController = new AbortController();
const send = async () => {
flushRef.current = null;
const fetchSearch = (
scope: Parameters<typeof fetchSearchResults>[1]
): Promise<RemoteSearchResult[]> =>
): Promise<OrderedComputedResult[]> =>
fetchSearchResults(
searchURL,
scope,
@@ -220,29 +188,25 @@ export function useSearchResults(props: {
try {
const resultsPromise = fetchSearch(remoteScope);
const onResults = (results: RemoteSearchResult[]) => {
const onResults = (results: OrderedComputedResult[]) => {
if (cancelled) {
return;
}
if (!results) {
// Can happen when the route cannot be found and returns the page's html.
setRemoteState({ status: 'error', requestKey });
setRemoteState({ status: 'error' });
return;
}
setRemoteState({
status: 'ready',
requestKey,
answer: { scopeKey, query, results },
});
setRemoteState({ status: 'ready', requestKey, results });
trackEvent({ type: 'search_type_query', query });
};
const onError = () => {
if (cancelled) {
return;
}
setRemoteState({ status: 'error', requestKey });
setRemoteState({ status: 'error' });
};
await resultsPromise.then(onResults, onError);
@@ -251,7 +215,7 @@ export function useSearchResults(props: {
if (cancelled) {
return;
}
setRemoteState({ status: 'error', requestKey });
setRemoteState({ status: 'error' });
}
};
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 100);
@@ -277,7 +241,6 @@ export function useSearchResults(props: {
query,
remoteScope,
requestKey,
scopeKey,
trackEvent,
withAI,
siteSpaceId,
@@ -289,16 +252,6 @@ export function useSearchResults(props: {
searchPass,
]);
React.useEffect(() => {
if (!retainPreviousResults) {
setRemoteState((state) =>
state.status === 'loading' && state.answer
? { status: 'loading', requestKey: state.requestKey }
: state
);
}
}, [retainPreviousResults, requestKey]);
const flush = React.useCallback(() => {
flushRef.current?.();
}, []);
@@ -309,20 +262,10 @@ export function useSearchResults(props: {
setRemoteState((prev) => (prev.status === 'loading' ? { status: 'idle' } : prev));
}, []);
const answer = 'answer' in remoteState ? remoteState.answer : undefined;
const visibleAnswer =
query &&
!disabled &&
answer?.scopeKey === scopeKey &&
(answer.query === query || retainPreviousResults)
? answer
: undefined;
const streamedQuestions = cachedRecommendedQuestions.get(siteSpaceId);
const results = React.useMemo<ResultType[]>(() => {
if (!query) {
const recommendedQuestions =
streamedQuestions ??
cachedRecommendedQuestions.get(siteSpaceId) ??
suggestions?.map((question, index) =>
createRecommendedQuestionResult(`recommended-question-${index}`, question)
) ??
@@ -335,32 +278,27 @@ export function useSearchResults(props: {
});
}
return visibleAnswer
? getDisplayedSearchResults(visibleAnswer.results, filterSiteSpaceIds)
return remoteState.status === 'ready' && remoteState.requestKey === requestKey
? filterResultsBySiteSpaces(remoteState.results, filterSiteSpaceIds)
: [];
}, [
visibleAnswer,
remoteState,
requestKey,
query,
filterSiteSpaceIds,
withAI,
streamedQuestions,
siteSpaceId,
suggestions,
recentQueries,
]);
// Between a query change and its loading state, the previous answer must still read as loading.
const isOutdated = remoteState.status === 'ready' && remoteState.requestKey !== requestKey;
return {
results,
resultsQuery: visibleAnswer?.query ?? query,
fetching:
Boolean(query) &&
!disabled &&
(remoteState.status === 'loading' ||
(remoteState.status !== 'idle' && remoteState.requestKey !== requestKey)),
error:
Boolean(query) &&
!disabled &&
remoteState.status === 'error' &&
remoteState.requestKey === requestKey,
fetching: remoteState.status === 'loading' || (Boolean(query) && isOutdated),
error: remoteState.status === 'error',
requestKey,
flush,
abort,
@@ -377,21 +315,17 @@ async function fetchSearchResults(
signal: AbortSignal,
asEmbeddable: boolean | undefined,
searchPass: SearchPassStore | null
): Promise<RemoteSearchResult[]> {
const directSearchId = generateSearchId();
): Promise<OrderedComputedResult[]> {
const direct = await searchPass?.search({
query,
searchId: directSearchId,
scope,
signal,
asEmbeddable: Boolean(asEmbeddable),
});
if (direct?.type === 'results') {
const search = { query, searchId: directSearchId };
return direct.results.map((result) => ({ ...result, search }));
return direct.results;
}
const searchId = direct ? generateSearchId() : directSearchId;
const response = await fetch(searchURL, {
method: 'POST',
headers: {
@@ -401,7 +335,6 @@ async function fetchSearchResults(
body: JSON.stringify({
asEmbeddable,
query,
searchId,
scope,
}),
signal,
@@ -411,12 +344,5 @@ async function fetchSearchResults(
throw new Error(`Search request failed: ${response.status}`);
}
const results: OrderedComputedResult[] = await response.json();
const search = { query, searchId };
return results.map((result) => ({ ...result, search }));
}
function generateSearchId() {
const bytes = globalThis.crypto?.getRandomValues(new Uint8Array(SEARCH_ID_BYTES));
return bytes && Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
return response.json() as Promise<OrderedComputedResult[]>;
}
@@ -17,11 +17,9 @@ export function useSearchResultsCursor(props: {
}, [query]);
React.useEffect(() => {
if (fetching) {
if (resultCount === 0) {
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
setCursor(null);
}
if (fetching && resultCount === 0) {
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
setCursor(null);
return;
}
@@ -3,7 +3,7 @@ import Script from 'next/script';
import React from 'react';
import * as ReactDOM from 'react-dom';
import { CustomizationDefaultThemeMode } from '@gitbook/api';
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
import { AIContextProvider } from '../AI';
import { LLMsTxtDirective } from './LLMsTxtDirective';
@@ -20,7 +20,6 @@ import { buildVersion } from '@/lib/build';
import type { GitBookSiteContext } from '@/lib/context';
import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@/lib/env';
import { getResizedImageURL } from '@/lib/images';
import { isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
import { removeTrailingSlash } from '@/lib/paths';
import { isSiteIndexable } from '@/lib/seo';
import { getOpenSearchURL } from '@/routes/opensearch';
@@ -128,7 +127,7 @@ export async function SiteLayout(props: {
</AIContextProvider>
<LoadIntegrations />
{isMcpPageActionEnabled(context) ? (
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
) : null}
{scripts.map(({ script }) =>
@@ -74,7 +74,7 @@ function getTargetProps(
/**
* Check if the link is external with the origin.
*/
function defaultIsExternalClient(href: string) {
export function defaultIsExternalClient(href: string) {
return isExternalLink(href, window.location.origin);
}
@@ -183,7 +183,7 @@ export function Link(props: LinkProps) {
* NextLink automatically prefetches links (RSC requests) on hover/viewport, which would fire those
* side effects without any user intent, so such links should not be prefetched.
*/
function hasSideEffectQueryParams(href: string): boolean {
export function hasSideEffectQueryParams(href: string): boolean {
const baseURL = typeof window !== 'undefined' ? window.location.origin : 'http://localhost';
const linkURL = URL.canParse(href) ? new URL(href) : new URL(href, baseURL);
@@ -24,7 +24,6 @@ function makeContext(
siteId?: string;
visibility?: SiteVisibility;
pageActions?: CustomizationPageActionType[];
mcpEnabled?: boolean;
} = {}
): GitBookSiteContext {
const {
@@ -33,16 +32,11 @@ function makeContext(
siteId = 'site_123',
visibility = SiteVisibility.Public,
pageActions = [CustomizationPageActionType.Mcp],
mcpEnabled,
} = options;
return {
site: { id: siteId, title: 'Acme', visibility },
customization: {
pageActions: { items: pageActions },
// DO NOT MERGE - mocking type for development
...(mcpEnabled === undefined ? {} : { mcp: { enabled: mcpEnabled } }),
},
customization: { pageActions: { items: pageActions } },
linker: createLinker({ host, siteBasePath, spaceBasePath: siteBasePath }),
} as unknown as GitBookSiteContext;
}
@@ -166,14 +160,6 @@ describe('serveSiteAiCatalog', () => {
}
);
it('does not advertise the MCP server when the page action is off', () => {
expect(buildSiteAiCatalog(makeContext({ mcpEnabled: true, pageActions: [] }))).toBeNull();
});
it('does not advertise the MCP server when the endpoint is off', () => {
expect(buildSiteAiCatalog(makeContext({ mcpEnabled: false }))).toBeNull();
});
it('does not serve a catalog when there is nothing to advertise', async () => {
const res = await serveSiteAiCatalog(makeContext({ pageActions: [] }), catalogRequest());
+2 -2
View File
@@ -1,6 +1,6 @@
import type { GitBookSiteContext } from '@/lib/context';
import { serveDiscoveryDocument } from '@/lib/discoveryDocument';
import { isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
import { isSiteMcpEnabled } from '@/lib/mcp/endpoints';
import { MCP_SERVER_CARD_PATH } from '@/lib/mcp/paths';
import { SERVER_CARD_MEDIA_TYPE } from '@/lib/mcp/serverCard';
@@ -45,7 +45,7 @@ export function buildSiteAiCatalog(context: GitBookSiteContext): AiCatalog | nul
const entries: AiCatalogEntry[] = [];
if (isMcpPageActionEnabled(context)) {
if (isSiteMcpEnabled(context)) {
entries.push({
identifier: buildCatalogIdentifier(context, 'mcp', site.id),
type: SERVER_CARD_MEDIA_TYPE,
+1 -1
View File
@@ -5,6 +5,7 @@ import { assert } from 'ts-essentials';
import type {
ChangeRequest,
CustomizationDefaultThemeMode,
PublishedSiteContent,
Revision,
RevisionPageDocument,
Site,
@@ -31,7 +32,6 @@ import { isPublishedPreviewAllowed } from './preview';
import type { AskVisitorAgent } from '@/lib/ask-visitor';
import {
type GitBookDataFetcher,
type PublishedSiteContent,
createDataFetcher,
getDataOrNull,
throwIfDataError,
+16 -3
View File
@@ -6,6 +6,7 @@ import {
GitBookAPI,
type HttpResponse,
type RenderIntegrationUI,
type SiteSearchScope,
} from '@gitbook/api';
import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags';
@@ -13,7 +14,6 @@ import { cache } from '../cache';
import { DataFetcherError, wrapDataFetcherError } from './errors';
import type { GitBookDataFetcher } from './types';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env';
import { toSearchSiteContentBody } from '@/lib/search-results';
import { trace } from '@/lib/tracing';
interface DataFetcherInput {
@@ -793,12 +793,25 @@ async function searchSiteContent(
return trace(
`searchSiteContent(${params.organizationId}, ${params.siteId}, ${params.query})`,
async () => {
const { organizationId, siteId, query, scope, searchId } = params;
const { organizationId, siteId, query, scope } = params;
const api = apiClient(input);
const res = await api.orgs.searchSiteContent(
organizationId,
siteId,
toSearchSiteContentBody(query, scope, searchId),
{
query,
...(scope.mode === 'current' && scope.restrictTo
? {
// `restrictTo` only exists in the newer `scope` request shape,
// and the published @gitbook/api types don't include it yet.
scope: {
mode: 'default',
currentSiteSpace: scope.siteSpaceId,
restrictTo: scope.restrictTo,
} as SiteSearchScope,
}
: scope),
},
{},
{
...noCacheFetchOptions,
+5 -12
View File
@@ -1,4 +1,4 @@
import type * as API from '@gitbook/api';
import type { GitBookAPI, PublishedSiteContentLookup, SiteVisitorPayload } from '@gitbook/api';
import { apiClient } from './api';
import { getExposableError } from './errors';
@@ -8,16 +8,13 @@ import { tryCatch } from '@/lib/async';
import { isPreviewRequest } from '@/lib/preview';
import { trace } from '@/lib/tracing';
type ResolveBody = Parameters<API.GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
export type PublishedSiteContent = API.PublishedSiteContent &
Partial<API.PublishedSiteContentAtRevision & API.PublishedSiteContentInChangeRequest>;
type ResolveBody = Parameters<GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
interface LookupPublishedContentByUrlInput {
url: string;
redirectOnError: boolean;
apiToken: string | null;
visitorPayload: API.SiteVisitorPayload;
visitorPayload: SiteVisitorPayload;
}
/**
@@ -25,7 +22,7 @@ interface LookupPublishedContentByUrlInput {
*/
export async function lookupPublishedContentByUrl(
input: LookupPublishedContentByUrlInput
): Promise<DataFetcherResponse<PublishedSiteContent | API.PublishedContentRedirect>> {
): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
const lookupURL = new URL(input.url);
const lookup = getURLLookup(stripURLSearch(lookupURL));
@@ -64,11 +61,7 @@ export async function lookupPublishedContentByUrl(
data: { data },
} = callResult;
if (!('redirect' in data)) {
return { data };
}
if (data.target === 'application' && isPreviewRequest(lookupURL)) {
if ('redirect' in data && data.target === 'application' && isPreviewRequest(lookupURL)) {
// The cached lookup omits the query params needed after login.
const redirect = new URL(data.redirect);
redirect.searchParams.set('redirect', lookupURL.toString());
-1
View File
@@ -180,7 +180,6 @@ export interface GitBookDataFetcher {
organizationId: string;
siteId: string;
query: string;
searchId?: string;
scope:
| { mode: 'all' }
| {
+2 -21
View File
@@ -3,31 +3,12 @@ import { CustomizationPageActionType, SiteVisibility } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
/**
* Whether the site serves its MCP endpoint. Falls back to the `mcp` page action for cached
* customizations that predate the setting.
* Whether the site publishes an MCP server at all. Gates the endpoint and everything describing it.
*/
export function isSiteMcpEnabled(context: Pick<GitBookSiteContext, 'customization'>): boolean {
// DO NOT MERGE - mocking type for development
const mcp = (context.customization as { mcp?: { enabled: boolean } }).mcp;
if (mcp) {
return mcp.enabled;
}
export function isSiteMcpEnabled(context: GitBookSiteContext): boolean {
return context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp);
}
/**
* Whether the site advertises its MCP server to visitors: the endpoint is served and the
* "Connect with MCP server" page action is enabled for this visitor.
*/
export function isMcpPageActionEnabled(
context: Pick<GitBookSiteContext, 'customization'>
): boolean {
return (
isSiteMcpEnabled(context) &&
context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp)
);
}
/**
* Whether `~gitbook/mcp` endpoint requires auth for the site (i.e VA site).
*/
@@ -31,7 +31,6 @@ function makeContext(
adaptiveContent?: boolean;
aiMode?: CustomizationAIMode;
pageActions?: CustomizationPageActionType[];
mcpEnabled?: boolean;
} = {}
): GitBookSiteContext {
const {
@@ -44,7 +43,6 @@ function makeContext(
adaptiveContent = true,
aiMode = CustomizationAIMode.Search,
pageActions = [CustomizationPageActionType.Mcp],
mcpEnabled,
} = options;
return {
@@ -61,8 +59,6 @@ function makeContext(
customization: {
ai: { mode: aiMode },
pageActions: { items: pageActions },
// DO NOT MERGE - mocking type for development
...(mcpEnabled === undefined ? {} : { mcp: { enabled: mcpEnabled } }),
},
linker: createLinker({ host, siteBasePath, spaceBasePath }),
} as unknown as GitBookSiteContext;
@@ -388,29 +384,6 @@ describe('serveSiteMcpServerCard', () => {
expect(card.$schema).toBe(SERVER_CARD_SCHEMA_URL);
});
it.each([
{
scenario: 'the endpoint is on and the page action is off',
options: { mcpEnabled: true, pageActions: [] },
status: 200,
},
{
scenario: 'the endpoint is off and the page action is on',
options: { mcpEnabled: false },
status: 404,
},
{ scenario: 'the setting is missing and the page action is on', options: {}, status: 200 },
{
scenario: 'the setting is missing and the page action is off',
options: { pageActions: [] },
status: 404,
},
])('answers $status when $scenario', async ({ options, status }) => {
const res = await serveSiteMcpServerCard(makeContext(options), cardRequest());
expect(res.status).toBe(status);
});
it('answers a preflight with a 204', async () => {
const res = await serveSiteMcpServerCard(makeContext(), cardRequest({ method: 'OPTIONS' }));
-4
View File
@@ -76,7 +76,3 @@ export function getExtension(path: string): string {
export function isGitBookInternalPath(path: string): boolean {
return /(^|\/)~gitbook(\/|$)/.test(path);
}
export function hasRevisionSelector(path: string): boolean {
return /(?:^|\/)~\/revisions\/[^/]+/.test(path);
}
+2 -4
View File
@@ -52,12 +52,10 @@ export type DirectSearchProps = {
*/
export function toSearchSiteContentBody(
query: string,
scope: SearchSiteContentScope,
searchId?: string
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] & { searchId?: string } {
scope: SearchSiteContentScope
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] {
return {
query,
searchId,
...(scope.mode === 'current' && scope.restrictTo
? {
// `restrictTo` only exists in the newer `scope` request shape,
+2 -6
View File
@@ -1,7 +1,6 @@
import { type RevisionPageDocument, type RevisionPageGroup, SiteVisibility } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
import { hasRevisionSelector } from '@/lib/paths';
/**
* Return true if a page is indexable in search.
@@ -30,11 +29,8 @@ export function isSiteIndexable(context: GitBookSiteContext) {
return false;
}
if (
context.changeRequest ||
context.revisionId !== context.space.revision ||
hasRevisionSelector(context.linker.spaceBasePath)
) {
// Prevent indexation of preview of revisions / change-requests
if (context.changeRequest || context.revisionId !== context.space.revision) {
return false;
}
+2 -27
View File
@@ -10,6 +10,7 @@ import {
ContentType,
CustomizationDefaultThemeMode,
CustomizationThemeMode,
type PublishedSiteContent,
SiteInsightsDisplayContext,
type SiteInsightsEventLocation,
SiteInsightsLLMSVariant,
@@ -30,7 +31,6 @@ import { getContentSecurityPolicy } from '@/lib/csp';
import { validateSerializedCustomization } from '@/lib/customization';
import {
DataFetcherError,
type PublishedSiteContent,
apiClient,
getVisitorAuthBasePath,
lookupPublishedContentByUrl,
@@ -51,7 +51,7 @@ import {
isOAuthProtectedResourceMetadataRequestForAuthEndpoint,
isOAuthProtectedResourceRequest,
} from '@/lib/oauth-protected';
import { hasRevisionSelector, removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import {
getPreviewCookieResponse,
getPreviewRequestIdentifier,
@@ -85,8 +85,6 @@ export const config = {
type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
const REVISION_ROBOTS_TAG = 'noindex, nofollow';
export async function middleware(request: NextRequest) {
try {
const requestURL = new URL(request.url);
@@ -170,20 +168,6 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
return null;
}
const response = await serveSiteRequest(requestURL, request, match);
if (
response &&
hasRevisionSelector(match.url.pathname) &&
!response.headers.has('x-robots-tag')
) {
const revisionResponse = new Response(response.body, response);
revisionResponse.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
return revisionResponse;
}
return response;
}
async function serveSiteRequest(requestURL: URL, request: NextRequest, match: URLWithMode) {
const { url: siteRequestURL, mode } = match;
if (isAITrainingOrIndexingRequest(request)) {
@@ -196,13 +180,6 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
// Normalize URL after extracting the URL from the request to make sure the client is redirected to the proper one
const normalization = normalizeRequestURL(siteRequestURL, mode);
if (normalization instanceof Response) {
const location = normalization.headers.get('location');
if (location && hasRevisionSelector(new URL(location).pathname)) {
return NextResponse.redirect(location, {
status: normalization.status,
headers: { 'x-robots-tag': REVISION_ROBOTS_TAG },
});
}
return normalization;
}
const isNormalizedURL = normalization.isNormalized;
@@ -645,8 +622,6 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
// noindex search/assistant deep links, kept crawlable so Google sees the directive.
if (rewrittenURL.searchParams.has('ask') || rewrittenURL.searchParams.has('q')) {
response.headers.set('x-robots-tag', 'none');
} else if (hasRevisionSelector(siteURLData.basePath)) {
response.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
}
// Allow cross-origin requests from the same parent domain as the site.
@@ -1,6 +1,6 @@
import { describe, expect, it, mock } from 'bun:test';
import { type RevisionPageDocument, SiteVisibility } from '@gitbook/api';
import type { RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
import { createLinker } from '@/lib/links';
@@ -26,7 +26,7 @@ function createContext(options: {
return {
displayAgentInstructions: false,
organizationId: 'org-1',
site: { id: 'site-1', visibility: SiteVisibility.Public },
site: { id: 'site-1' },
siteSpace: { id: 'site-space-1' },
space: { id: 'space-1', revision: 'revision-1' },
revisionId: 'revision-1',
@@ -66,23 +66,6 @@ describe('servePageMarkdown', () => {
);
});
it('serves the current revision by selector with a noindex header for AI agents', async () => {
const context = createContext({});
const response = await servePageMarkdown(
{
...context,
isAiAgent: true,
linker: context.linker.fork({
spaceBasePath: `/docs/~/revisions/${context.revisionId}/`,
}),
},
'new-page'
);
expect(response.status).toBe(200);
expect(response.headers.get('X-Robots-Tag')).toBe('noindex, nofollow');
});
it('redirects to the markdown version of a site redirect target', async () => {
const context = createContext({
siteRedirect: { target: 'https://docs.example.com/docs/new-page', permanent: true },