Compare commits

..

3 Commits

Author SHA1 Message Date
Steven H 7f08fb14d1 Read site revision previews through the site revision endpoints (#4818)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:46:02 +00:00
Nolann B. 867da7b94c Resolve GitBook links in OpenAPI schema descriptions to the site's URLs (#4838) 2026-11-24 19:32:47 +01:00
Peter White 76e1abd7e1 Use the default scope for legacy search links (#4837) 2026-11-24 11:54:25 +01:00
27 changed files with 684 additions and 118 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render Heading 4 blocks.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Apply the default language-aware search scope to legacy search links.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
-1
View File
@@ -342,7 +342,6 @@
},
"patchedDependencies": {
"decode-named-character-reference@1.0.2": "patches/decode-named-character-reference@1.0.2.patch",
"@gitbook/api@0.214.0": "patches/@gitbook%2Fapi@0.214.0.patch",
"@shikijs/langs@3.21.0": "patches/@shikijs%2Flangs@3.21.0.patch",
"mermaid@11.16.1": "patches/mermaid@11.16.1.patch",
"next@16.4.6": "patches/next@16.4.6.patch",
+1 -2
View File
@@ -69,7 +69,6 @@
"@vercel/next@4.4.2": "patches/@vercel%2Fnext@4.4.2.patch",
"mermaid@11.16.1": "patches/mermaid@11.16.1.patch",
"next@16.4.6": "patches/next@16.4.6.patch",
"@shikijs/langs@3.21.0": "patches/@shikijs%2Flangs@3.21.0.patch",
"@gitbook/api@0.214.0": "patches/@gitbook%2Fapi@0.214.0.patch"
"@shikijs/langs@3.21.0": "patches/@shikijs%2Flangs@3.21.0.patch"
}
}
@@ -14,6 +14,11 @@ export async function hasContentBeenUpdated(props: { revisionId: string }) {
const context = await getServerActionBaseContext();
const siteURLData = await getSiteURLDataFromMiddleware();
// A site revision never changes what it shows.
if (siteURLData.siteRevision) {
return false;
}
if (siteURLData.changeRequest) {
const changeRequest = await getDataOrNull(
context.dataFetcher.getChangeRequest({
@@ -57,7 +57,6 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
case 'heading-1':
case 'heading-2':
case 'heading-3':
case 'heading-4':
return <Heading {...props} block={block} />;
case 'list-ordered':
case 'list-unordered':
@@ -141,7 +140,6 @@ export function BlockSkeleton(props: { block: DocumentBlock; style: ClassValue }
case 'heading-1':
case 'heading-2':
case 'heading-3':
case 'heading-4':
case 'file':
return <SkeletonHeading id={id} style={style} />;
case 'paragraph':
@@ -92,5 +92,4 @@ const TAGS: { [type in DocumentBlockHeading['type']]: React.ElementType } = {
'heading-1': 'h2',
'heading-2': 'h3',
'heading-3': 'h4',
'heading-4': 'h5',
};
@@ -27,7 +27,6 @@ export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
case 'heading-2':
return '-mt-[calc(1.25rem+1px)]';
case 'heading-3':
case 'heading-4':
return '-mt-[calc(0.50rem+1px)]';
default:
return '';
@@ -35,12 +35,6 @@ export function getBlockTextStyle(block: DocumentBlock): {
lineHeight: 'leading-snug',
marginTop: 'column-first-of-type:pt-0 pt-[0.5em]',
};
case 'heading-4':
return {
textSize: 'text-base @xs:text-lg font-semibold',
lineHeight: 'leading-snug',
marginTop: 'column-first-of-type:pt-0 pt-[0.5em]',
};
case 'divider':
return {
textSize: '',
@@ -83,7 +83,6 @@ const getBlockHeight = memoize((block: DocumentBlock | undefined): number => {
case 'heading-2':
return 50;
case 'heading-3':
case 'heading-4':
return 40;
case 'paragraph':
return 30;
@@ -15,8 +15,6 @@ export function computeRemoteSearchScope(
}
switch (scope) {
case 'all':
return { mode: 'all' };
case 'default':
return { mode: 'current', siteSpaceId };
case 'extended':
@@ -1,6 +1,13 @@
import { describe, expect, it } from 'bun:test';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { createElement } from 'react';
import { renderToString } from 'react-dom/server';
import { shouldKeepSearchState } from './useSearch';
import { SearchContextProvider, shouldKeepSearchState, useSearchState } from './useSearch';
function SearchScopeValue() {
return useSearchState()?.scope ?? null;
}
describe('shouldKeepSearchState', () => {
it('discards an empty default search state', () => {
@@ -23,3 +30,25 @@ describe('shouldKeepSearchState', () => {
).toBe(true);
});
});
it.each([
['scope=all', 'default'],
['global=true', 'default'],
['scope=current&global=true', 'current'],
['scope=extended&global=true', 'extended'],
])('resolves %s to %s for a linked search', (params, scope) => {
const search = createElement(
SearchContextProvider,
{ prewarmURL: '/~gitbook/search' },
createElement(SearchScopeValue)
);
expect(
renderToString(
createElement(NuqsTestingAdapter, {
searchParams: `q=setup&${params}`,
children: search,
})
)
).toBe(scope);
});
@@ -1,12 +1,6 @@
'use client';
import {
type Values,
parseAsBoolean,
parseAsString,
parseAsStringLiteral,
useQueryStates,
} from 'nuqs';
import { type Values, parseAsString, parseAsStringLiteral, useQueryStates } from 'nuqs';
import React from 'react';
import type { LinkProps } from '../primitives';
@@ -16,8 +10,6 @@ import { useSearchPrewarm } from './useSearchPrewarm';
import type { DirectSearchProps } from '@/lib/search-results';
export type SearchScope =
/** Search all content on the site */
| 'all'
/** Search the current section's variant + matched/default variant for other sections */
| 'default'
/** Search all variants of the current section */
@@ -41,9 +33,8 @@ export interface SearchState {
const keyMap = {
q: parseAsString,
ask: parseAsString,
scope: parseAsStringLiteral(['all', 'default', 'extended', 'current']).withDefault('default'),
scope: parseAsStringLiteral(['default', 'extended', 'current']).withDefault('default'),
section: parseAsString,
global: parseAsBoolean, // Legacy support for global=true
};
export type UpdateSearchState = (
@@ -62,11 +53,6 @@ function normalizeRawState(values: Values<typeof keyMap>) {
if (values.ask === 'true' && values.q) {
return { ...values, q: null, ask: values.q };
}
// Handle legacy global=true
if (values.global === true) {
return { ...values, scope: 'all' as const, global: null };
}
return values;
}
+28 -2
View File
@@ -44,6 +44,7 @@ import {
getLinkerForSiteSpace,
getLocalizedTitle,
getSiteStructureSections,
listAllSiteSpaces,
} from '@/lib/sites';
/**
@@ -57,8 +58,6 @@ export type SiteURLData = Pick<
| 'site'
| 'siteSpace'
| 'space'
| 'revision'
| 'changeRequest'
| 'shareKey'
| 'siteSection'
| 'siteBasePath'
@@ -71,6 +70,14 @@ export type SiteURLData = Pick<
*/
imagesContextId: string;
/**
* Space revision, change request or site revision the URL previews: at most one is set. The
* middleware reads them from the resolved content, which types them as exclusive.
*/
revision?: string;
changeRequest?: string;
siteRevision?: string;
/**
* Whether this request is a fallback rendering.
* We use this when switching variant as we don't know if the page exists in the other variant.
@@ -217,6 +224,9 @@ export type GitBookSiteContext = GitBookSpaceContext & {
/** Whether search indexation is blocked for this deployment. */
noIndexSearch: boolean;
/** Site revision the URL previews. Content is read as it pins it. */
siteRevision?: string;
/** Whether the request included a visitor token. */
isLoggedInVisitor: boolean;
@@ -250,6 +260,13 @@ export function getBaseContext(input: {
const dataFetcher = createDataFetcher({
apiToken: siteURLData.apiToken ?? null,
siteRevision: siteURLData.siteRevision
? {
organizationId: siteURLData.organization,
siteId: siteURLData.site,
siteRevisionId: siteURLData.siteRevision,
}
: undefined,
});
const linkerInput: SiteLinkerInput = {
@@ -305,6 +322,7 @@ export async function fetchSiteContextByURLLookup(
contextId: data.contextId,
isFallback: data.isFallback ?? false,
noIndexSearch: data.noIndexSearch ?? false,
siteRevision: data.siteRevision,
isLoggedInVisitor: data.isLoggedInVisitor ?? false,
preview: data.preview ?? false,
displayAgentInstructions: data.displayAgentInstructions,
@@ -329,6 +347,7 @@ export async function fetchSiteContextByIds(
contextId?: string;
isFallback: boolean;
noIndexSearch: boolean;
siteRevision?: string;
isLoggedInVisitor: boolean;
preview: boolean;
displayAgentInstructions?: boolean;
@@ -462,6 +481,12 @@ export async function fetchSiteContextByIds(
return {
...spaceContext,
// Only the site's own spaces are read at the site revision it previews.
dataFetcher: ids.siteRevision
? spaceContext.dataFetcher.withSiteRevisionSpaces(
listAllSiteSpaces(siteStructure).map((entry) => entry.space.id)
)
: spaceContext.dataFetcher,
locale: siteSpace.space.language ?? spaceContext.locale,
linker: getLinkerForSiteSpace(siteLinker, siteSpace, spaceContext.revision.pages),
organizationId: ids.organization,
@@ -477,6 +502,7 @@ export async function fetchSiteContextByIds(
contextId: ids.contextId,
isFallback: ids.isFallback,
noIndexSearch: ids.noIndexSearch,
siteRevision: ids.siteRevision,
isLoggedInVisitor: ids.isLoggedInVisitor,
preview: ids.preview,
displayAgentInstructions: ids.displayAgentInstructions,
+351 -47
View File
@@ -11,7 +11,7 @@ import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-t
import { cache } from '../cache';
import { DataFetcherError, wrapDataFetcherError } from './errors';
import type { GitBookDataFetcher } from './types';
import type { DataFetcherResponse, 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';
@@ -21,6 +21,25 @@ interface DataFetcherInput {
* API token.
*/
apiToken: string | null;
/**
* Site revision being previewed. The site's spaces and OpenAPI specs are read at it.
*/
siteRevision?: DataFetcherSiteRevision;
}
/**
* A site revision, as a preview URL resolves it.
*/
export interface DataFetcherSiteRevision {
organizationId: string;
siteId: string;
siteRevisionId: string;
/**
* Spaces of the site, read at the site revision. Other spaces are read live. Until the site
* structure is known, every space is read at the site revision.
*/
spaceIds?: string[];
}
/**
@@ -46,10 +65,18 @@ export function createDataFetcher(
withToken({ apiToken }) {
return createDataFetcher({
...input,
apiToken,
});
},
withSiteRevisionSpaces(spaceIds) {
return createDataFetcher({
...input,
siteRevision: input.siteRevision ? { ...input.siteRevision, spaceIds } : undefined,
});
},
//
// API that are tied to the token
//
@@ -77,61 +104,120 @@ export function createDataFetcher(
});
},
getRevision(params) {
return getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getRevisionAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
metadata: params.metadata ?? false,
}),
() =>
getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
})
);
},
getRevisionPageByPath(params) {
return getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getPageByPathAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
path: params.path,
metadata: params.metadata ?? false,
cachedMetadata: params.cachedMetadata ?? false,
}),
() =>
getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
})
);
},
getRevisionPageMarkdown(params) {
return getRevisionPageMarkdown(
return readAtSiteRevision(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageMarkdown'
params.spaceId,
(siteRevisionInput) =>
getPageMarkdownAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
pageId: params.pageId,
}),
() =>
getRevisionPageMarkdown(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageMarkdown'
)
);
},
getRevisionPageDocument(params) {
return getRevisionPageDocument(
return readAtSiteRevision(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageDocument'
params.spaceId,
(siteRevisionInput) =>
getPageDocumentAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
pageId: params.pageId,
}),
() =>
getRevisionPageDocument(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageDocument'
)
);
},
getRevisionReusableContentDocument(params) {
return getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getReusableContentDocumentAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
reusableContentId: params.reusableContentId,
}),
() =>
getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
})
);
},
getLatestOpenAPISpecVersionContent(params) {
return getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
});
return readAtSiteRevision(
input,
null,
(siteRevisionInput) =>
getOpenAPISpecContentAtSiteRevision(siteRevisionInput, { slug: params.slug }),
() =>
getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
})
);
},
getSpace(params) {
return getSpace(input, {
@@ -195,15 +281,233 @@ export function createDataFetcher(
},
listRevisionPageMetaLinks(params) {
return listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
listPageMetaLinksAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
pageId: params.pageId,
}),
() =>
listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
})
);
},
};
}
/**
* Data fetcher input to read at a site revision. It leaves out the site's space IDs, which only
* choose what to read at the site revision, so they stay out of cache keys.
*/
type SiteRevisionDataFetcherInput = DataFetcherInput & {
siteRevision: Omit<DataFetcherSiteRevision, 'spaceIds'>;
};
/**
* Read content at the site revision of the input, or `live` when there is no site revision or
* for a space outside the site. An OpenAPI spec (no space) is always read at the site revision.
*/
async function readAtSiteRevision<T>(
input: DataFetcherInput,
spaceId: string | null,
atSiteRevision: (input: SiteRevisionDataFetcherInput) => Promise<DataFetcherResponse<T>>,
live: () => Promise<DataFetcherResponse<T>>
): Promise<DataFetcherResponse<T>> {
const { siteRevision } = input;
if (!siteRevision || (spaceId && siteRevision.spaceIds?.includes(spaceId) === false)) {
return live();
}
const { spaceIds: _spaceIds, ...cacheableSiteRevision } = siteRevision;
return atSiteRevision({ ...input, siteRevision: cacheableSiteRevision });
}
// Each read at a site revision sends the same query as its live counterpart.
const getRevisionAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; metadata: boolean }) => {
'use cache';
return fetchAtSiteRevision(
input,
`getRevisionAtSiteRevision(${params.spaceId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getRevisionInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
{ metadata: params.metadata },
{ ...noCacheFetchOptions }
)
);
}
);
const getPageByPathAtSiteRevision = cache(
async (
input: SiteRevisionDataFetcherInput,
params: { spaceId: string; path: string; metadata: boolean; cachedMetadata: boolean }
) => {
'use cache';
return fetchAtSiteRevision(
input,
`getPageByPathAtSiteRevision(${params.spaceId}, ${params.path})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getPageByPathInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
encodeURIComponent(params.path),
{ metadata: params.metadata, cachedMetadata: params.cachedMetadata },
{ ...noCacheFetchOptions }
)
);
}
);
const getPageMarkdownAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
'use cache';
return wrapDataFetcherError(async () => {
return trace(
`getPageMarkdownAtSiteRevision(${params.spaceId}, ${params.pageId})`,
async () => {
const { organizationId, siteId, siteRevisionId } = input.siteRevision;
const res = await apiClient(input).orgs.getPageInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.pageId,
{
format: 'markdown',
'format.markdown.refs': 'stable',
evaluated: 'deterministic-only',
metadata: false,
},
{ ...noCacheFetchOptions }
);
cacheTag(...getCacheTagsFromResponse(res));
cacheLife('max');
if (!('markdown' in res.data)) {
throw new DataFetcherError('Page is not a document', 404);
}
return res.data.markdown;
}
);
});
}
);
const getPageDocumentAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
'use cache';
return fetchAtSiteRevision(
input,
`getPageDocumentAtSiteRevision(${params.spaceId}, ${params.pageId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getPageDocumentInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.pageId,
{ evaluated: 'deterministic-only', dereferenced: 'reusable-contents' },
{ ...noCacheFetchOptions }
)
);
}
);
const getReusableContentDocumentAtSiteRevision = cache(
async (
input: SiteRevisionDataFetcherInput,
params: { spaceId: string; reusableContentId: string }
) => {
'use cache';
return fetchAtSiteRevision(
input,
`getReusableContentDocumentAtSiteRevision(${params.spaceId}, ${params.reusableContentId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getReusableContentDocumentInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.reusableContentId,
{ evaluated: 'deterministic-only' },
{ ...noCacheFetchOptions }
)
);
}
);
const listPageMetaLinksAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
'use cache';
return fetchAtSiteRevision(
input,
`listPageMetaLinksAtSiteRevision(${params.spaceId}, ${params.pageId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.listPageMetaLinksInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.pageId,
{ ...noCacheFetchOptions }
)
);
}
);
const getOpenAPISpecContentAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { slug: string }) => {
'use cache';
return fetchAtSiteRevision(
input,
`getOpenAPISpecContentAtSiteRevision(${params.slug})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getOpenApiSpecContentInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.slug,
{ ...noCacheFetchOptions }
)
);
}
);
/**
* Fetch from an endpoint at a site revision. What a site revision pins never changes, so the
* response is cached forever.
*/
function fetchAtSiteRevision<T>(
input: SiteRevisionDataFetcherInput,
name: string,
request: (
api: ReturnType<typeof apiClient>,
siteRevision: SiteRevisionDataFetcherInput['siteRevision']
) => Promise<HttpResponse<T, unknown>>
): Promise<DataFetcherResponse<T>> {
return wrapDataFetcherError(async () => {
return trace(name, async () => {
const res = await request(apiClient(input), input.siteRevision);
cacheTag(...getCacheTagsFromResponse(res));
cacheLife('max');
return res.data;
});
});
}
/**
* Infer the cache life from the api response headers.
* @param response The response from the API call.
+6
View File
@@ -51,6 +51,12 @@ export interface GitBookDataFetcher {
*/
withToken(input: { apiToken: string }): GitBookDataFetcher;
/**
* Create a data fetcher that reads only these spaces at the site revision it previews, and
* other spaces live.
*/
withSiteRevisionSpaces(spaceIds: string[]): GitBookDataFetcher;
/**
* Get a user by its ID.
*/
@@ -237,11 +237,8 @@ describe('getDocumentSections', () => {
]);
});
it('nests heading-3 under the heading before it and leaves heading-4 out', async () => {
const heading = (
type: 'heading-1' | 'heading-2' | 'heading-3' | 'heading-4',
id: string
) => ({
it('nests heading-3 under the heading before it', async () => {
const heading = (type: 'heading-1' | 'heading-2' | 'heading-3', id: string) => ({
object: 'block' as const,
type,
data: {},
@@ -264,7 +261,6 @@ describe('getDocumentSections', () => {
heading('heading-3', 'h3-under-h1'),
heading('heading-2', 'h2'),
heading('heading-3', 'h3-under-h1-h2'),
heading('heading-4', 'h4-not-in-outline'),
{
object: 'block',
type: 'stepper',
@@ -276,10 +272,7 @@ describe('getDocumentSections', () => {
type: 'stepper-step',
data: {},
isVoid: false,
nodes: [
heading('heading-3', 'h3-in-stepper'),
heading('heading-4', 'h4-in-stepper'),
],
nodes: [heading('heading-3', 'h3-in-stepper')],
},
],
},
+1 -2
View File
@@ -183,7 +183,6 @@ const TEXT_ONLY_BLOCKS = new Set<DocumentBlock['type']>([
'heading-1',
'heading-2',
'heading-3',
'heading-4',
]);
/**
@@ -271,7 +270,7 @@ export function getBlocksByType<Type extends DocumentBlock['type']>(
* Check if a block is a heading block.
*/
export function isHeadingBlock(block: DocumentBlock): block is DocumentBlockHeading {
return ['heading-1', 'heading-2', 'heading-3', 'heading-4'].includes(block.type);
return ['heading-1', 'heading-2', 'heading-3'].includes(block.type);
}
/**
+4 -1
View File
@@ -10,6 +10,7 @@ import {
} from '@gitbook/openapi-parser';
import { enrichFilesystem } from './enrich';
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
import type {
AnyOpenAPIOperationsBlock,
OpenAPISchemasBlock,
@@ -41,7 +42,9 @@ export async function fetchOpenAPIFilesystem(
// If the reference is a new OpenAPI reference, we return it.
if (ref.kind === 'openapi') {
assert(resolved.openapi?.filesystem);
return resolved.openapi.filesystem;
return resolveOpenAPIDescriptionLinks(resolved.openapi.filesystem, (contentRef) =>
resolveContentRef(contentRef, context)
);
}
// For legacy blocks ("swagger"), we need to fetch the file system.
return fetchFilesystem(resolved.href, context.space.id);
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'bun:test';
import { parseOpenAPI } from '@gitbook/openapi-parser';
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
const APP_URL = 'https://app.gitbook.com/s/space-1/tables';
describe('resolveOpenAPIDescriptionLinks', () => {
it('points tagged links at their resolved URL without mutating the input', async () => {
const original =
`<p><a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>` +
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
' <a href="https://example.com">Docs</a></p>';
const { filesystem } = await parseOpenAPI({
value: JSON.stringify({
openapi: '3.0.0',
info: { title: 'Test', version: '1.0.0' },
paths: {},
components: {
schemas: {
Condition: { type: 'object', 'x-gitbook-description-html': original },
},
},
}),
rootURL: null,
});
const resolved = await resolveOpenAPIDescriptionLinks(filesystem, async (ref) =>
ref.kind === 'page' && ref.page === 'page-1' ? { href: '/docs/tables' } : null
);
expect(resolved[0]?.specification.components?.schemas?.Condition).toMatchObject({
'x-gitbook-description-html':
'<p><a href="/docs/tables" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>' +
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
' <a href="https://example.com">Docs</a></p>',
});
// The spec content comes from the data cache, shared across sites.
expect(filesystem[0]?.specification.components?.schemas?.Condition).toMatchObject({
'x-gitbook-description-html': original,
});
});
});
@@ -0,0 +1,173 @@
import { type DefaultTreeAdapterMap, parseFragment } from 'parse5';
import * as React from 'react';
import type { ContentRef } from '@gitbook/api';
import type { Filesystem, OpenAPIV3xDocument } from '@gitbook/openapi-parser';
import { escapeHTML } from '@/lib/html';
import { resolveStringContentRef } from '@/lib/references';
const DESCRIPTION_HTML_KEY = 'x-gitbook-description-html';
// Slate JSON, which never holds description HTML: skipped to keep the walk short.
const DESCRIPTION_DOCUMENT_KEY = 'x-gitbook-description-document';
// Set by spec processing on links to GitBook content, e.g. `/spaces/{space}/pages/{page}`.
const CONTENT_REF_ATTRIBUTE = 'data-gitbook-ref';
type OpenAPIFilesystem = Filesystem<OpenAPIV3xDocument>;
type ResolveContentRef = (ref: ContentRef) => Promise<{ href: string } | null>;
// Per request: resolved hrefs depend on the site being rendered.
const getResolvedFilesystems = React.cache(
() => new WeakMap<OpenAPIFilesystem, Promise<OpenAPIFilesystem>>()
);
/**
* Point description links that spec processing tagged with a content ref at their URL in the
* current site. Links whose ref doesn't resolve keep the href written in the spec.
* Returns a copy when something changed: the input may be shared through the data cache.
*/
export function resolveOpenAPIDescriptionLinks(
filesystem: OpenAPIFilesystem,
resolveContentRef: ResolveContentRef
): Promise<OpenAPIFilesystem> {
const resolvedFilesystems = getResolvedFilesystems();
let promise = resolvedFilesystems.get(filesystem);
if (!promise) {
promise = baseResolveOpenAPIDescriptionLinks(filesystem, resolveContentRef);
resolvedFilesystems.set(filesystem, promise);
}
return promise;
}
async function baseResolveOpenAPIDescriptionLinks(
filesystem: OpenAPIFilesystem,
resolveContentRef: ResolveContentRef
): Promise<OpenAPIFilesystem> {
// Tagged HTML → its rewritten version, filled in once the refs resolve.
const rewritten = new Map<string, string>();
mapDescriptionHTML(filesystem, (html) => {
if (html.includes(CONTENT_REF_ATTRIBUTE)) {
rewritten.set(html, html);
}
return html;
});
if (rewritten.size === 0) {
return filesystem;
}
const hrefs = new Map<string, Promise<string | null>>();
const resolveHref = (source: string) => {
let href = hrefs.get(source);
if (!href) {
const ref = resolveStringContentRef(source);
href = ref
? resolveContentRef(ref).then((resolved) => resolved?.href ?? null)
: Promise.resolve(null);
hrefs.set(source, href);
}
return href;
};
await Promise.all(
Array.from(rewritten.keys(), async (html) => {
rewritten.set(html, await rewriteLinks(html, resolveHref));
})
);
return mapDescriptionHTML(filesystem, (html) => rewritten.get(html) ?? html);
}
/**
* Replace the href of each tagged link with its resolved URL.
*/
async function rewriteLinks(
html: string,
resolveHref: (source: string) => Promise<string | null>
): Promise<string> {
const fragment = parseFragment(html, { sourceCodeLocationInfo: true });
const replacements: { start: number; end: number; value: string }[] = [];
await Promise.all(
collectLinks(fragment).map(async (link) => {
const source = link.attrs.find((attr) => attr.name === CONTENT_REF_ATTRIBUTE)?.value;
const location = link.sourceCodeLocation?.attrs?.href;
if (!source || !location) {
return;
}
const href = await resolveHref(source);
if (href) {
replacements.push({
start: location.startOffset,
end: location.endOffset,
value: `href="${escapeHTML(href)}"`,
});
}
})
);
// Apply from the end so earlier offsets stay valid.
replacements.sort((a, b) => b.start - a.start);
let result = html;
for (const { start, end, value } of replacements) {
result = result.slice(0, start) + value + result.slice(end);
}
return result;
}
function collectLinks(
node: DefaultTreeAdapterMap['node'],
links: DefaultTreeAdapterMap['element'][] = []
): DefaultTreeAdapterMap['element'][] {
if ('tagName' in node && node.tagName === 'a') {
links.push(node);
}
if ('childNodes' in node) {
for (const child of node.childNodes) {
collectLinks(child, links);
}
}
return links;
}
/**
* Map every description HTML in a JSON value, copying only the objects on a changed path.
*/
function mapDescriptionHTML<T>(value: T, transform: (html: string) => string): T {
if (typeof value !== 'object' || value === null) {
return value;
}
if (Array.isArray(value)) {
let result: unknown[] | null = null;
for (let index = 0; index < value.length; index++) {
const item = value[index];
const next = mapDescriptionHTML(item, transform);
if (next !== item) {
result ??= [...value];
result[index] = next;
}
}
return (result ?? value) as T;
}
const record = value as Record<string, unknown>;
let result: Record<string, unknown> | null = null;
// `for...in` over plain JSON objects: several times faster than `Object.entries` on large specs.
for (const key in record) {
if (key === DESCRIPTION_DOCUMENT_KEY) {
continue;
}
const child = record[key];
const next =
key === DESCRIPTION_HTML_KEY && typeof child === 'string'
? transform(child)
: mapDescriptionHTML(child, transform);
if (next !== child) {
result ??= { ...record };
result[key] = next;
}
}
return (result ?? record) as T;
}
+1
View File
@@ -32,6 +32,7 @@ export function isSiteIndexable(context: GitBookSiteContext) {
if (
context.changeRequest ||
context.siteRevision ||
context.revisionId !== context.space.revision ||
hasRevisionSelector(context.linker.spaceBasePath)
) {
+20 -3
View File
@@ -449,8 +449,7 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
basePath: siteURLData.basePath,
space: siteURLData.space,
organization: siteURLData.organization,
changeRequest: siteURLData.changeRequest,
revision: siteURLData.revision,
...getPreviewedContent(siteURLData),
shareKey: siteURLData.shareKey,
preview: siteURLData.preview,
apiToken: siteURLData.apiToken,
@@ -965,7 +964,7 @@ function encodePathInSiteContent(
siteSpace: siteURLData.siteSpace,
siteShareKey: siteURLData.shareKey,
space: siteURLData.space,
revision: siteURLData.revision,
revision: getPreviewedContent(siteURLData).revision,
displayContext: SiteInsightsDisplayContext.Server,
};
@@ -1229,3 +1228,21 @@ function acceptsMarkdown(request: Request): boolean {
const htmlIndex = mediaTypes.findIndex((type) => type === 'text/html' || type === '*/*');
return htmlIndex === -1 || markdownIndex < htmlIndex;
}
/**
* The revision, change request or site revision a URL previews: at most one of them.
*/
function getPreviewedContent(
content: PublishedSiteContent
): Pick<SiteURLData, 'revision' | 'changeRequest' | 'siteRevision'> {
if ('revision' in content) {
return { revision: content.revision };
}
if ('changeRequest' in content) {
return { changeRequest: content.changeRequest };
}
if ('siteRevision' in content) {
return { siteRevision: content.siteRevision };
}
return {};
}
-2
View File
@@ -133,8 +133,6 @@ function getNodeHTML(node: DocumentBlock | DocumentInline | DocumentText): strin
return `<h3>${children}</h3>`;
case 'heading-3':
return `<h4>${children}</h4>`;
case 'heading-4':
return `<h5>${children}</h5>`;
case 'list-unordered':
case 'list-tasks':
return `<ul>${children}</ul>`;
-13
View File
@@ -1,13 +0,0 @@
diff --git a/dist/client.d.ts b/dist/client.d.ts
index a55c2aa43b1fe90f2050ef14607a42d4082cccf4..60e8a5fe17844652a1cf7cd368dbeb0c96708a23 100644
--- a/dist/client.d.ts
+++ b/dist/client.d.ts
@@ -2496,7 +2496,7 @@ export interface DocumentBlockParagraph {
export type DocumentInline = DocumentInlineLink | DocumentInlineEmoji | DocumentInlineIcon | DocumentInlineExpression | DocumentInlineMath | DocumentInlineImage | DocumentInlineAnnotation | DocumentInlineMention | DocumentInlineButton;
export interface DocumentBlockHeading {
object: "block";
- type: "heading-1" | "heading-2" | "heading-3";
+ type: "heading-1" | "heading-2" | "heading-3" | "heading-4";
key?: string;
nodes: (DocumentInline | DocumentText)[];
data: {