Compare commits

..

5 Commits

Author SHA1 Message Date
Nicolas Dorseuil 9cf7ab6265 perf(gitbook): plan table and cards requests in the site page plan
Start what table blocks render as soon as the document arrives: card cover sizes, card
targets, and the users, content-ref and image columns of the view. Values are checked with
the render's own guards, and each table is planned in isolation so a malformed one can't
stop the rest of the walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:12:08 +01:00
Nicolas Dorseuil 0052c19b48 changeset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:12:08 +01:00
Nicolas Dorseuil 8512a29ac1 perf(gitbook): place the Cloudflare server worker next to the GitBook API
Pin the OpenNext server worker to gcp:us-central1 with placement.region, in every environment;
the middleware worker stays at the edge. Wrangler 4.43.0 rejects placement.region, so the CI
pins move to 4.80.0, the version the repo already uses locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:12:08 +01:00
Nicolas Dorseuil 0db6c62be8 changeset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:12:08 +01:00
Nicolas Dorseuil 2e45304130 perf(gitbook): start site page requests as soon as their inputs are known
A site page render fetched in a waterfall: the page document only after the meta links and
their alternate spaces, embeds and image sizes only once React reached their block. Add a
per-request site page plan, started from generateViewport, that starts each of these requests
the moment its input arrives (page document and meta links, alternate and cross-space
spaces with their revision, embeds, icons, image sizes, user/OpenAPI/anchor refs). The render
reuses them through the per-request memo; getImageSize is now memoized for that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:12:08 +01:00
26 changed files with 750 additions and 1025 deletions
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
@@ -1,5 +0,0 @@
---
"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
---
Run the Cloudflare server worker next to the GitBook API.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Start the requests a site page needs as soon as their inputs are known, instead of when each component renders.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
@@ -30,7 +30,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: deployments status --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
@@ -49,7 +49,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: versions deploy ${{ steps.extract_current_version.outputs.version_id }}@100% ${{ inputs.serverVersionId }}@0% -y --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
@@ -61,7 +61,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: versions deploy ${{ inputs.middlewareVersionId }}@100% -y --config ./packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc
@@ -71,7 +71,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: versions deploy ${{ inputs.serverVersionId }}@100% -y --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
@@ -78,7 +78,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: deploy --config ./packages/gitbook/openNext/customWorkers/doWrangler.jsonc
@@ -89,7 +89,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
@@ -112,7 +112,7 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.43.0'
wranglerVersion: '4.80.0'
environment: ${{ inputs.environment }}
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc
@@ -12,6 +12,8 @@
"observability": {
"enabled": false,
},
// Run the server next to the GitBook API so its request waterfall stays short; the middleware stays at the edge.
"placement": { "region": "gcp:us-central1" },
"vars": {
"NEXT_CACHE_DO_QUEUE_DISABLE_SQLITE": "true",
},
@@ -5,6 +5,7 @@ import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
startSitePagePlan,
} from '@/components/SitePage';
type PageProps = {
@@ -21,7 +22,9 @@ export default async function Page(props: PageProps) {
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
const { context } = await getDynamicSiteContext(await props.params);
const params = await props.params;
const { context } = await getDynamicSiteContext(params);
startSitePagePlan(context, { pathname: getPagePathFromParams(params) });
return generateSitePageViewport(context);
}
@@ -5,6 +5,7 @@ import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
startSitePagePlan,
} from '@/components/SitePage';
export const dynamic = 'force-static';
@@ -22,7 +23,9 @@ export default async function Page(props: PageProps) {
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
const { context } = await getStaticSiteContext(await props.params);
const params = await props.params;
const { context } = await getStaticSiteContext(params);
startSitePagePlan(context, { pathname: getPagePathFromParams(params) });
return generateSitePageViewport(context);
}
@@ -14,11 +14,6 @@ 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({
@@ -1,13 +1,17 @@
import { describe, expect, it, mock } from 'bun:test';
import type { RevisionPageDocument, SiteRedirectDestination } from '@gitbook/api';
import type { RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
await import('./fetch');
const {
getLowercasePathnameRedirect,
startSitePagePlan,
resolveMissingPagePath,
resolveSitePageFromURL,
} = await import('./fetch');
const { normalizeURL } = await import('@/lib/data/urls');
const { createLinker } = await import('@/lib/links');
@@ -23,28 +27,15 @@ const page = {
describe('resolveMissingPagePath', () => {
function createRedirectContext(options: {
siteRedirect?: {
source?: string;
target: string;
permanent?: boolean;
destination?: SiteRedirectDestination;
};
siteRedirect?: { source?: string; target: string; permanent?: boolean };
spaceRedirectPageId?: string;
contextId?: string;
structure?: GitBookSiteContext['structure'];
revisionsBySpace?: Record<string, RevisionPageDocument[]>;
}) {
const getSiteRedirectBySource = mock(async ({ source }: { source: string }) =>
options.siteRedirect && source === (options.siteRedirect.source ?? '/old')
? {
data: {
target: options.siteRedirect.target,
redirect: {
permanent: options.siteRedirect.permanent ?? false,
...(options.siteRedirect.destination
? { destination: options.siteRedirect.destination }
: {}),
},
redirect: { permanent: options.siteRedirect.permanent ?? false },
},
}
: { error: { code: 404, message: 'Not found' } }
@@ -54,35 +45,19 @@ describe('resolveMissingPagePath', () => {
? { data: { id: options.spaceRedirectPageId } }
: { error: { code: 404, message: 'Not found' } }
);
const getRevision = mock(async ({ spaceId }: { spaceId: string }) =>
options.revisionsBySpace?.[spaceId]
? { data: { pages: options.revisionsBySpace[spaceId] } }
: { error: { code: 404, message: 'Not found' } }
);
const defaultSiteSpace = {
id: 'site-space-1',
space: { id: 'space-1', revision: 'revision-1' },
};
return {
organizationId: 'org-1',
site: { id: 'site-1' },
siteSpace: defaultSiteSpace,
structure: options.structure ?? {
type: 'siteSpaces',
structure: [defaultSiteSpace],
},
space: { id: 'space-1', revision: 'revision-1' },
revisionId: 'revision-1',
revision: { pages: [page] },
contextId: options.contextId,
linker: {
toPathInSpace: (path: string) => path,
toRelativePathInSite: (path: string) => path,
toLinkForContent: (url: string) => new URL(url).pathname,
},
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath, getRevision },
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath },
} as unknown as GitBookSiteContext;
}
@@ -116,224 +91,6 @@ describe('resolveMissingPagePath', () => {
});
});
it('ignores a site redirect that targets the current path', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/release-notes/restricted',
target: 'https://docs.example.com/release-notes/restricted',
},
});
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
});
it('ignores a site redirect that targets the current path with trailing slash, case, or query differences', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/release-notes/restricted',
target: 'https://docs.example.com/Release-Notes/Restricted/?tab=1#top',
},
});
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
});
it('ignores a space-relative redirect that resolves back to the current section path', async () => {
const context = {
...createRedirectContext({
siteRedirect: {
source: '/v3/getting-started',
target: 'https://docs.example.com/docs/v3/getting-started',
},
}),
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/docs/',
}),
} as unknown as GitBookSiteContext;
expect(await resolveMissingPagePath(context, 'v3/getting-started')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden site space on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/getting-started',
target: 'https://docs.example.com/docs/v3/getting-started',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-hidden',
pageId: 'page-v3',
},
},
});
expect(await resolveMissingPagePath(context, 'getting-started')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden section on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
structure: {
type: 'sections',
structure: [
{
object: 'site-section',
id: 'section-visible',
siteSpaces: [
{
id: 'site-space-1',
space: { id: 'space-1', revision: 'revision-1' },
},
],
},
],
} as unknown as GitBookSiteContext['structure'],
siteRedirect: {
source: '/old-section',
target: 'https://docs.example.com/hidden-section',
destination: {
kind: 'site-section',
siteSectionId: 'section-hidden',
},
},
});
expect(await resolveMissingPagePath(context, 'old-section')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden page in the current space on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/release-notes/restricted.html',
target: 'https://docs.example.com/release-notes/restricted',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-1',
pageId: 'hidden-page',
},
},
});
expect(
await resolveMissingPagePath(context, 'release-notes/restricted.html')
).toBeUndefined();
});
it('checks target page visibility in another accessible space on an adaptive site', async () => {
const otherSpace = {
id: 'site-space-2',
space: { id: 'space-2', revision: 'revision-2' },
};
const structure = {
type: 'siteSpaces',
structure: [
{ id: 'site-space-1', space: { id: 'space-1', revision: 'revision-1' } },
otherSpace,
],
} as unknown as GitBookSiteContext['structure'];
const hiddenContext = createRedirectContext({
contextId: 'adaptive-ctx',
structure,
revisionsBySpace: { 'space-2': [] },
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/other/secret',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-2',
pageId: 'page-secret',
},
},
});
expect(await resolveMissingPagePath(hiddenContext, 'old')).toBeUndefined();
const visibleContext = createRedirectContext({
contextId: 'adaptive-ctx',
structure,
revisionsBySpace: { 'space-2': [{ ...page, id: 'page-secret', path: 'secret' }] },
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/other/secret',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-2',
pageId: 'page-secret',
},
},
});
expect(await resolveMissingPagePath(visibleContext, 'old')).toEqual({
type: 'redirect',
destination: '/other/secret',
permanent: false,
});
});
it('ignores a site redirect targeting the reassigned default variant path of the current space', async () => {
const context = {
...createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/guide/missing',
target: 'https://docs.example.com/guide/v3/missing',
destination: {
kind: 'site-space',
siteSpaceId: 'site-space-v3',
},
},
structure: {
type: 'sections',
structure: [
{
object: 'site-section',
id: 'section-guide',
siteSpaces: [
{
id: 'site-space-v3',
path: 'v3',
default: true,
space: { id: 'space-v3', revision: 'revision-1' },
},
],
},
],
} as unknown as GitBookSiteContext['structure'],
}),
siteSpace: {
id: 'site-space-v3',
path: 'v3',
default: true,
space: { id: 'space-v3', revision: 'revision-1' },
},
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/guide/',
}),
} as unknown as GitBookSiteContext;
expect(await resolveMissingPagePath(context, 'missing')).toBeUndefined();
});
it('keeps a redirect whose current path contains a literal question mark', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/foo/bar%3Fbaz',
target: 'https://docs.example.com/foo/bar',
},
});
expect(await resolveMissingPagePath(context, 'foo/bar?baz')).toEqual({
type: 'redirect',
destination: '/foo/bar',
permanent: false,
});
});
it('resolves a space redirect to a page', async () => {
const context = createRedirectContext({ spaceRedirectPageId: page.id });
@@ -452,3 +209,45 @@ describe('getLowercasePathnameRedirect', () => {
}
});
});
describe('startSitePagePlan', () => {
function createContext(getRevisionPageDocument: (params: unknown) => Promise<unknown>) {
return {
space: { id: 'space-1' },
revisionId: 'revision-1',
revision: { pages: [page] },
siteSpace: { id: 'site-space-1', pageId: null },
dataFetcher: { getRevisionPageDocument: mock(getRevisionPageDocument) },
} as unknown as GitBookSiteContext;
}
it('requests the document of the page at the lowercased path', () => {
const context = createContext(async () => ({ data: {} }));
startSitePagePlan(context, { pathname: 'ReadMe' });
expect(context.dataFetcher.getRevisionPageDocument).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
pageId: 'page-1',
});
});
it('does nothing when the path does not resolve to a page', () => {
const context = createContext(async () => ({ data: {} }));
startSitePagePlan(context, { pathname: 'missing' });
expect(context.dataFetcher.getRevisionPageDocument).not.toHaveBeenCalled();
});
it('does not leak a rejection when the request fails', async () => {
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown) => unhandled.push(reason);
process.on('unhandledRejection', onUnhandled);
try {
const context = createContext(async () => ({ error: { code: 500, message: 'boom' } }));
startSitePagePlan(context, { pathname: 'readme' });
await new Promise((resolve) => setTimeout(resolve, 10));
expect(unhandled).toEqual([]);
} finally {
process.off('unhandledRejection', onUnhandled);
}
});
});
@@ -2,21 +2,16 @@ import { permanentRedirect, redirect } from 'next/navigation';
import {
type RevisionPageDocument,
type SiteRedirect,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
} from '@gitbook/api';
import { runSitePagePlan } from './plan';
import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/context';
import { getDataOrNull } from '@/lib/data';
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
import { withLeadingSlash } from '@/lib/paths';
import {
findSiteSpaceBy,
findSiteSpaceByUrl,
getSiteStructureSections,
resolveSiteSpacePagePath,
} from '@/lib/sites';
import { findSiteSpaceByUrl, resolveSiteSpacePagePath } from '@/lib/sites';
const MAX_PAGE_URL_REDIRECTS = 5;
@@ -46,6 +41,17 @@ export async function fetchPageData(context: GitBookSiteContext, params: PagePar
};
}
/**
* Start the site page plan from `generateViewport`, which Next runs before the page itself.
*/
export function startSitePagePlan(context: GitBookSiteContext, params: PagePathParams) {
const pathname = getPathnameParam(params).toLowerCase();
const resolved = resolveSiteSpacePagePath(context.siteSpace, context.revision.pages, pathname);
if (resolved) {
void runSitePagePlan(context, resolved.page);
}
}
/**
* Resolve a page from the params.
* If the path can't be found, we try to resolve it from the API to handle redirects.
@@ -119,14 +125,6 @@ export async function resolveMissingPagePath(
.filter((source) => SITE_REDIRECT_SOURCE_PATH_REGEX.test(source))
);
const currentPath = linker.toPathInSpace(redirectPathname);
let currentPathWithDefaultVariant: string | null = null;
if (context.siteSpace.default && context.siteSpace.path) {
currentPathWithDefaultVariant = linker.toPathInSpace(
`/${context.siteSpace.path}${redirectPathname}`
);
}
for (const source of redirectSources) {
// We try to resolve the site redirect
const resolvedSiteRedirect =
@@ -140,18 +138,6 @@ export async function resolveMissingPagePath(
})
));
if (resolvedSiteRedirect) {
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
// Skip self-redirects (including default-variant canonical aliases) and hidden adaptive targets.
const targetsCurrentPath =
isSameRedirectPath(currentPath, destination) ||
(currentPathWithDefaultVariant !== null &&
isSameRedirectPath(currentPathWithDefaultVariant, destination));
if (
targetsCurrentPath ||
!(await isRedirectDestinationAccessible(context, resolvedSiteRedirect.redirect))
) {
break;
}
const isPublicLiveContext =
!shareKey &&
!context.changeRequest &&
@@ -160,7 +146,7 @@ export async function resolveMissingPagePath(
!context.isLoggedInVisitor;
return {
type: 'redirect',
destination,
destination: linker.toLinkForContent(resolvedSiteRedirect.target),
permanent: Boolean(
resolvedSiteRedirect.redirect?.permanent &&
!resolvedSiteRedirect.redirect.draft &&
@@ -228,17 +214,6 @@ export async function resolveSitePageFromURL(
return null;
}
export function isSameRedirectPath(currentPath: string, destination: string): boolean {
if (!destination.startsWith('/') || destination.startsWith('//')) {
return false;
}
const destinationPathname = new URL(destination, 'https://gitbook.invalid').pathname;
return (
normalizeRedirectPathname(currentPath) === normalizeRedirectPathname(destinationPathname)
);
}
/**
* Transform a pathname into a candidate source for site redirect matching.
* The pathname is already percent-encoded, so each segment is decoded before being encoded
@@ -263,60 +238,6 @@ function safeDecodeURIComponent(segment: string): string {
}
}
async function isRedirectDestinationAccessible(
context: GitBookSiteContext,
siteRedirect: SiteRedirect | null
): Promise<boolean> {
if (!context.contextId || !siteRedirect?.destination) {
return true;
}
const { destination } = siteRedirect;
switch (destination.kind) {
case 'external':
return true;
case 'site-section':
return getSiteStructureSections(context.structure, { ignoreGroups: true }).some(
(section) => section.id === destination.siteSectionId
);
case 'site-space':
return Boolean(
findSiteSpaceBy(context.structure, (entry) => entry.id === destination.siteSpaceId)
);
case 'site-page': {
const target = findSiteSpaceBy(
context.structure,
(entry) => entry.id === destination.siteSpaceId
);
if (!target) {
return false;
}
if (destination.siteSpaceId === context.siteSpace.id) {
return Boolean(resolvePageId(context.revision.pages, destination.pageId));
}
const targetRevision = await getDataOrNull(
context.dataFetcher.getRevision({
spaceId: target.siteSpace.space.id,
revisionId: target.siteSpace.space.revision,
})
);
if (!targetRevision) {
return false;
}
return Boolean(resolvePageId(targetRevision.pages, destination.pageId));
}
}
}
function normalizeRedirectPathname(pathname: string): string {
const normalized = pathname
.split('/')
.filter(Boolean)
.map((segment) => safeDecodeURIComponent(segment).toLowerCase())
.join('/');
return `/${normalized}`;
}
/**
* Get the page path from the params.
*/
@@ -0,0 +1,341 @@
import { describe, expect, it, mock } from 'bun:test';
import type { JSONDocument, RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { runSitePagePlan } = await import('./plan');
const page = { id: 'page-1', type: 'document' } as RevisionPageDocument;
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => {
resolve = r;
});
return { promise, resolve };
}
function setup(options: {
document?: unknown;
metaLinks?: unknown;
documentPromise?: Promise<unknown>;
resolveRefError?: boolean;
}) {
const dataFetcher = {
getRevisionPageDocument: mock(
() => options.documentPromise ?? Promise.resolve({ data: options.document ?? null })
),
listRevisionPageMetaLinks: mock(async () => ({ data: options.metaLinks ?? null })),
getEmbedByUrl: mock(async () => ({ data: {} })),
getRevision: mock(async () => ({ data: {} })),
};
const imageResizer = { getImageSize: mock(async () => ({ width: 1, height: 1 })) };
const context = {
space: { id: 'space-1' },
revisionId: 'revision-1',
customization: { styling: { icons: 'regular' } },
structure: {
type: 'siteSpaces',
structure: [
{ id: 'ss-1', space: { id: 'space-1', revision: 'revision-1' } },
{ id: 'ss-2', space: { id: 'space-2', revision: 'revision-2' } },
],
},
dataFetcher,
imageResizer,
} as unknown as GitBookSiteContext;
const resolveRef = mock(
async (_doc: unknown, ref: { kind: string }, _ctx?: unknown, _opts?: unknown) => {
if (options.resolveRefError) {
throw new Error('boom');
}
return ref.kind === 'file'
? { href: 'https://files/image.png', file: { dimensions: undefined } }
: { href: '/x' };
}
);
const loadIcons = mock(async () => ({}));
return { context, dataFetcher, imageResizer, resolveRef, loadIcons };
}
const doc = (nodes: unknown[]) => ({ object: 'document', nodes }) as unknown as JSONDocument;
describe('runSitePagePlan', () => {
it('requests the document and the meta links in parallel', async () => {
const pending = deferred<unknown>();
const s = setup({ documentPromise: pending.promise });
const done = runSitePagePlan(s.context, page, s);
expect(s.dataFetcher.getRevisionPageDocument).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
pageId: 'page-1',
});
expect(s.dataFetcher.listRevisionPageMetaLinks).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
pageId: 'page-1',
});
pending.resolve({ data: null });
await done;
});
it('starts embeds from the document with the page space', async () => {
const s = setup({
document: doc([
{ object: 'block', type: 'embed', data: { url: 'https://a.example' }, nodes: [] },
]),
});
await runSitePagePlan(s.context, page, s);
expect(s.dataFetcher.getEmbedByUrl).toHaveBeenCalledWith({
url: 'https://a.example',
spaceId: 'space-1',
});
});
it('resolves network refs of nested blocks and inlines, with anchor text for mentions', async () => {
const link = { kind: 'page', space: 'space-2', page: 'p2' };
const mention = { kind: 'anchor', page: 'p3', anchor: 'a' };
const s = setup({
document: doc([
{
object: 'block',
type: 'paragraph',
nodes: [
{ object: 'inline', type: 'link', data: { ref: link }, nodes: [] },
{ object: 'inline', type: 'mention', data: { ref: mention }, nodes: [] },
],
},
]),
});
await runSitePagePlan(s.context, page, s);
const calls = s.resolveRef.mock.calls.map(([, ref, , opts]) => [ref, opts]);
expect(calls).toContainEqual([link, {}]);
expect(calls).toContainEqual([mention, { resolveAnchorText: true }]);
});
it('skips refs that resolve without a request', async () => {
const s = setup({
document: doc([
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'inline',
type: 'link',
data: { ref: { kind: 'page', page: 'p2' } },
nodes: [],
},
],
},
]),
});
await runSitePagePlan(s.context, page, s);
expect(s.resolveRef).not.toHaveBeenCalled();
});
it('measures images without known dimensions like the image block does', async () => {
const s = setup({
document: doc([
{
object: 'block',
type: 'images',
nodes: [
{
object: 'block',
type: 'image',
data: { ref: { kind: 'file', file: 'f1' } },
nodes: [],
},
],
},
]),
});
await runSitePagePlan(s.context, page, s);
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://files/image.png', {
dpr: 2,
});
});
it('starts the revision of cross-space image files in the site', async () => {
const s = setup({
document: doc([
{
object: 'block',
type: 'image',
data: { ref: { kind: 'file', space: 'space-2', file: 'f1' } },
nodes: [],
},
]),
});
await runSitePagePlan(s.context, page, s);
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
spaceId: 'space-2',
revisionId: 'revision-2',
});
});
it('measures card covers and resolves cross-space card targets', async () => {
const target = { kind: 'page', space: 'space-2', page: 'p2' };
const s = setup({
document: doc([
{
object: 'block',
type: 'table',
data: {
view: {
type: 'cards',
columns: [],
coverDefinition: 'cover',
coverDefinitionDark: 'coverDark',
targetDefinition: 'target',
},
definition: {},
records: {
r1: {
orderIndex: 'a',
values: {
cover: { kind: 'file', file: 'f1' },
coverDark: { kind: 'file', file: 'f2' },
target,
},
},
},
},
nodes: [],
},
]),
});
await runSitePagePlan(s.context, page, s);
const refs = s.resolveRef.mock.calls.map(([, ref]) => ref);
expect(refs).toContainEqual({ kind: 'file', file: 'f1' });
expect(refs).toContainEqual({ kind: 'file', file: 'f2' });
expect(refs).toContainEqual(target);
expect(s.imageResizer.getImageSize).toHaveBeenCalledTimes(2);
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
spaceId: 'space-2',
revisionId: 'revision-2',
});
});
it('starts the requests of visible table columns only', async () => {
const anchor = { kind: 'anchor', page: 'p3', anchor: 'a' };
const s = setup({
document: doc([
{
object: 'block',
type: 'table',
data: {
view: { type: 'grid', columns: ['people', 'link', 'picture'] },
definition: {
people: { type: 'users' },
link: { type: 'content-ref' },
picture: { type: 'image' },
hidden: { type: 'users' },
},
records: {
r1: {
orderIndex: 'a',
values: {
people: ['u1'],
link: anchor,
picture: { ref: { kind: 'file', file: 'f1' } },
hidden: ['u2'],
},
},
},
},
nodes: [],
},
]),
});
await runSitePagePlan(s.context, page, s);
const calls = s.resolveRef.mock.calls.map(([, ref, , opts]) => [ref, opts]);
expect(calls).toContainEqual([{ kind: 'user', user: 'u1' }, {}]);
expect(calls).toContainEqual([anchor, { resolveAnchorText: true }]);
expect(calls).toContainEqual([{ kind: 'file', file: 'f1' }, {}]);
expect(calls).not.toContainEqual([{ kind: 'user', user: 'u2' }, {}]);
expect(s.imageResizer.getImageSize).toHaveBeenCalledTimes(1);
});
it('keeps planning after a malformed table and skips values the render skips', async () => {
const table = (data: unknown) => ({ object: 'block', type: 'table', data, nodes: [] });
const s = setup({
document: doc([
table({ view: { type: 'grid', columns: ['a'] }, records: { r1: {} } }),
table({
view: {
type: 'cards',
columns: ['img', 'people'],
coverDefinitionDark: 'dark',
},
definition: { img: { type: 'image' }, people: { type: 'users' } },
records: {
r1: {
orderIndex: 'a',
values: {
img: { ref: undefined },
people: ['u1', 2],
dark: { kind: 'file', file: 'f2' },
},
},
},
}),
{ object: 'block', type: 'embed', data: { url: 'https://after' }, nodes: [] },
]),
});
await runSitePagePlan(s.context, page, s);
expect(s.dataFetcher.getEmbedByUrl).toHaveBeenCalledWith({
url: 'https://after',
spaceId: 'space-1',
});
expect(s.resolveRef).not.toHaveBeenCalled();
expect(s.imageResizer.getImageSize).not.toHaveBeenCalled();
});
it('starts the revision of meta-link alternates in the site alongside their space', async () => {
const alternate = { kind: 'page', space: 'space-2', page: 'p9' };
const s = setup({ metaLinks: { canonical: null, alternates: [alternate] } });
await runSitePagePlan(s.context, page, s);
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
spaceId: 'space-2',
revisionId: 'revision-2',
});
expect(s.resolveRef.mock.calls.map(([, ref]) => ref)).toContainEqual(alternate);
});
it('settles without unhandled rejections when every branch fails', async () => {
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown) => unhandled.push(reason);
process.on('unhandledRejection', onUnhandled);
try {
const s = setup({
resolveRefError: true,
metaLinks: { alternates: [{ kind: 'page', space: 'space-2', page: 'p' }] },
document: doc([
{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] },
{
object: 'block',
type: 'paragraph',
nodes: [{ object: 'inline', type: 'link', data: { ref: { kind: 'url' } } }],
},
]),
});
s.dataFetcher.getEmbedByUrl.mockImplementation(async () => {
throw new Error('embed');
});
s.loadIcons.mockImplementation(async () => {
throw new Error('icons');
});
await runSitePagePlan(s.context, page, s);
await new Promise((r) => setTimeout(r, 10));
expect(unhandled).toEqual([]);
} finally {
process.off('unhandledRejection', onUnhandled);
}
});
});
@@ -0,0 +1,254 @@
import type {
ContentRef,
DocumentBlockTable,
JSONDocument,
RevisionPageDocument,
} from '@gitbook/api';
import {
getRecordCardCovers,
isDocumentTableImageRecord,
isStringArray,
} from '@/components/DocumentView/Table/utils';
import type { GitBookSiteContext } from '@/lib/context';
import { getDataOrNull, getPageDocument } from '@/lib/data';
import {
getContentInlineIconSourceRequests,
getCustomizationIconStyle,
getInlineIconSources,
} from '@/lib/icons/inline';
import {
type ResolveContentRefOptions,
resolveContentRef,
resolveContentRefInDocument,
} from '@/lib/references';
import { findSiteSpaceBy } from '@/lib/sites';
type Deps = {
/** `document` is null for refs that don't come from the page document (meta links). */
resolveRef: (
document: JSONDocument | null,
ref: ContentRef,
context: GitBookSiteContext,
options: ResolveContentRefOptions
) => Promise<unknown>;
loadIcons: (context: GitBookSiteContext, document: JSONDocument) => Promise<unknown>;
};
const defaultDeps: Deps = {
resolveRef: (document, ref, context, options) =>
document
? resolveContentRefInDocument(document, ref, context, options)
: resolveContentRef(ref, context, options),
loadIcons: (context, document) =>
getInlineIconSources(
getContentInlineIconSourceRequests({
iconStyle: getCustomizationIconStyle(context.customization),
document,
})
),
};
type Node = { object?: string; type?: string; data?: Record<string, unknown>; nodes?: unknown };
/** Node types the render resolves with `resolveAnchorText: true` (an extra page document). */
const ANCHOR_TEXT_TYPES = new Set(['mention', 'content-ref']);
/**
* Start every request a site page render will make, as soon as its input is known, instead of
* when React reaches the component that needs it. Each call is the one the render makes, with
* the same arguments, so the render reuses it through the per-request memo of the data fetcher
* (and of the image size and icon helpers). Failures are left for the render to surface.
*/
export function runSitePagePlan(
context: GitBookSiteContext,
page: RevisionPageDocument,
deps: Deps = defaultDeps
): Promise<void> {
const pending: Promise<unknown>[] = [];
const start = (fn: () => Promise<unknown>) => {
let promise: Promise<unknown>;
try {
promise = fn();
} catch (error) {
promise = Promise.reject(error);
}
pending.push(promise.catch(() => {}));
};
const resolveRef = (document: JSONDocument | null, ref: ContentRef, anchorText: boolean) => {
startSpaceRevisionFor(ref);
start(() =>
deps.resolveRef(document, ref, context, anchorText ? { resolveAnchorText: true } : {})
);
};
// Cross-space refs fetch the space, then its revision; the site structure already knows the
// revision, so start both. A stale structure only costs one unused (usually cached) call.
const startSpaceRevisionFor = (ref: ContentRef) => {
const spaceId = 'space' in ref ? ref.space : undefined;
if (!spaceId || spaceId === context.space.id) {
return;
}
const found = findSiteSpaceBy(context.structure, (s) => s.space.id === spaceId);
if (found) {
start(() =>
context.dataFetcher.getRevision({
spaceId,
revisionId: found.siteSpace.space.revision,
})
);
}
};
const ids = { spaceId: context.space.id, revisionId: context.revisionId, pageId: page.id };
start(async () => {
const links = await getDataOrNull(context.dataFetcher.listRevisionPageMetaLinks(ids));
for (const ref of [links?.canonical, ...(links?.alternates ?? [])]) {
if (ref) {
resolveRef(null, ref, false);
}
}
});
start(async () => {
const document = await getPageDocument(context, page);
if (!document) {
return;
}
start(() => deps.loadIcons(context, document));
visit(document.nodes, (node) => {
const data = node.data ?? {};
if (node.type === 'embed' && typeof data.url === 'string') {
start(() =>
context.dataFetcher.getEmbedByUrl({
url: data.url as string,
spaceId: context.space.id,
})
);
}
if (node.type === 'image') {
for (const ref of [data.ref, data.refDark]) {
if (ref) {
planImage(document, ref as ContentRef);
}
}
return;
}
if (node.type === 'table') {
// Through `start` so a malformed table can't stop the rest of the walk.
start(async () =>
planTable(document, node.data as unknown as DocumentBlockTable['data'])
);
}
const ref = data.ref as ContentRef | undefined;
if (ref) {
planRef(document, ref, ANCHOR_TEXT_TYPES.has(node.type ?? ''));
}
});
});
const planRef = (document: JSONDocument, ref: ContentRef, anchorText: boolean) => {
if (needsRequest(ref, anchorText, context)) {
resolveRef(document, ref, anchorText);
}
};
const planImage = (document: JSONDocument, ref: ContentRef) => {
startSpaceRevisionFor(ref);
start(() => measureImage(document, ref));
};
// Only what the table view renders: its columns, plus covers and target for cards.
const planTable = (document: JSONDocument, table: DocumentBlockTable['data']) => {
const { view, definition } = table;
for (const record of Object.values(table.records ?? {})) {
for (const column of view.columns ?? []) {
const value = record.values[column];
switch (definition[column]?.type) {
case 'content-ref':
if (value && typeof value === 'object' && 'kind' in value) {
planRef(document, value as ContentRef, true);
}
break;
case 'users':
if (isStringArray(value)) {
for (const user of value) {
resolveRef(document, { kind: 'user', user }, false);
}
}
break;
case 'image':
if (isDocumentTableImageRecord(value)) {
planImage(document, 'ref' in value ? value.ref : value);
}
break;
}
}
if (view.type === 'cards') {
const { light, dark } = getRecordCardCovers(record, view);
// The dark cover only renders alongside a light one.
if (light.contentRef) {
planImage(document, light.contentRef);
if (dark.contentRef) {
planImage(document, dark.contentRef);
}
}
const target = view.targetDefinition
? (record.values[view.targetDefinition] as ContentRef | undefined)
: undefined;
if (target) {
planRef(document, target, false);
}
}
}
};
// Same as the images block: a file without known dimensions is measured by the resizer.
const measureImage = async (document: JSONDocument, ref: ContentRef) => {
const resolved = (await deps.resolveRef(document, ref, context, {})) as {
href: string;
file?: { dimensions?: unknown };
} | null;
if (resolved && !resolved.file?.dimensions) {
await context.imageResizer?.getImageSize(resolved.href, { dpr: 2 });
}
};
return settle(pending);
}
/** Whether resolving `ref` makes a request; same-space page and file refs resolve in memory. */
function needsRequest(ref: ContentRef, anchorText: boolean, context: GitBookSiteContext) {
if ('space' in ref && ref.space && ref.space !== context.space.id) {
return true;
}
if (ref.kind === 'user' || ref.kind === 'openapi') {
return true;
}
return ref.kind === 'anchor' && anchorText;
}
function visit(nodes: unknown, fn: (node: Node) => void) {
if (!Array.isArray(nodes)) {
return;
}
for (const node of nodes as Node[]) {
if (node && (node.object === 'block' || node.object === 'inline')) {
fn(node);
visit(node.nodes, fn);
visit((node as { fragments?: unknown }).fragments, fn);
}
}
}
/** Waits for every started call, including ones started while waiting. */
async function settle(pending: Promise<unknown>[]) {
let settled = 0;
while (settled < pending.length) {
const batch = pending.slice(settled);
settled = pending.length;
await Promise.all(batch);
}
}
+2 -28
View File
@@ -44,7 +44,6 @@ import {
getLinkerForSiteSpace,
getLocalizedTitle,
getSiteStructureSections,
listAllSiteSpaces,
} from '@/lib/sites';
/**
@@ -58,6 +57,8 @@ export type SiteURLData = Pick<
| 'site'
| 'siteSpace'
| 'space'
| 'revision'
| 'changeRequest'
| 'shareKey'
| 'siteSection'
| 'siteBasePath'
@@ -70,14 +71,6 @@ 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.
@@ -224,9 +217,6 @@ 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;
@@ -260,13 +250,6 @@ 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 = {
@@ -322,7 +305,6 @@ 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,
@@ -347,7 +329,6 @@ export async function fetchSiteContextByIds(
contextId?: string;
isFallback: boolean;
noIndexSearch: boolean;
siteRevision?: string;
isLoggedInVisitor: boolean;
preview: boolean;
displayAgentInstructions?: boolean;
@@ -481,12 +462,6 @@ 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,
@@ -502,7 +477,6 @@ 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,
+47 -351
View File
@@ -11,7 +11,7 @@ import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-t
import { cache } from '../cache';
import { DataFetcherError, wrapDataFetcherError } from './errors';
import type { DataFetcherResponse, GitBookDataFetcher } from './types';
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';
@@ -21,25 +21,6 @@ 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[];
}
/**
@@ -65,18 +46,10 @@ 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
//
@@ -104,120 +77,61 @@ export function createDataFetcher(
});
},
getRevision(params) {
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,
})
);
return getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
});
},
getRevisionPageByPath(params) {
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,
})
);
return getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
});
},
getRevisionPageMarkdown(params) {
return readAtSiteRevision(
return getRevisionPageMarkdown(
input,
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'
)
{
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 readAtSiteRevision(
return getRevisionPageDocument(
input,
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'
)
{
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 readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getReusableContentDocumentAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
reusableContentId: params.reusableContentId,
}),
() =>
getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
})
);
return getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
});
},
getLatestOpenAPISpecVersionContent(params) {
return readAtSiteRevision(
input,
null,
(siteRevisionInput) =>
getOpenAPISpecContentAtSiteRevision(siteRevisionInput, { slug: params.slug }),
() =>
getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
})
);
return getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
});
},
getSpace(params) {
return getSpace(input, {
@@ -281,233 +195,15 @@ export function createDataFetcher(
},
listRevisionPageMetaLinks(params) {
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,
})
);
return 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,12 +51,6 @@ 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.
*/
@@ -9,12 +9,14 @@ import type {
CloudflareImageOptions,
CloudflareResizeImageOptions,
} from './types';
import { cache } from '@/lib/cache';
import { getLogger } from '@/lib/logger';
/**
* Get the size of an image.
* Memoized per request so the site page plan's early call is reused by the render.
*/
export async function getImageSize(
export const getImageSize = cache(async function getImageSize(
input: string,
defaultSize: Partial<CloudflareImageOptions> = {}
): Promise<{ width: number; height: number } | null> {
@@ -43,7 +45,7 @@ export async function getImageSize(
logger.warn(`Error getting image size for ${input}:`, error);
return null;
}
}
});
/**
* Execute a Cloudflare Image Resize operation on an image.
+1 -4
View File
@@ -10,7 +10,6 @@ import {
} from '@gitbook/openapi-parser';
import { enrichFilesystem } from './enrich';
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
import type {
AnyOpenAPIOperationsBlock,
OpenAPISchemasBlock,
@@ -42,9 +41,7 @@ export async function fetchOpenAPIFilesystem(
// If the reference is a new OpenAPI reference, we return it.
if (ref.kind === 'openapi') {
assert(resolved.openapi?.filesystem);
return resolveOpenAPIDescriptionLinks(resolved.openapi.filesystem, (contentRef) =>
resolveContentRef(contentRef, context)
);
return resolved.openapi.filesystem;
}
// For legacy blocks ("swagger"), we need to fetch the file system.
return fetchFilesystem(resolved.href, context.space.id);
@@ -1,44 +0,0 @@
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,
});
});
});
@@ -1,173 +0,0 @@
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,7 +32,6 @@ export function isSiteIndexable(context: GitBookSiteContext) {
if (
context.changeRequest ||
context.siteRevision ||
context.revisionId !== context.space.revision ||
hasRevisionSelector(context.linker.spaceBasePath)
) {
+3 -20
View File
@@ -449,7 +449,8 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
basePath: siteURLData.basePath,
space: siteURLData.space,
organization: siteURLData.organization,
...getPreviewedContent(siteURLData),
changeRequest: siteURLData.changeRequest,
revision: siteURLData.revision,
shareKey: siteURLData.shareKey,
preview: siteURLData.preview,
apiToken: siteURLData.apiToken,
@@ -964,7 +965,7 @@ function encodePathInSiteContent(
siteSpace: siteURLData.siteSpace,
siteShareKey: siteURLData.shareKey,
space: siteURLData.space,
revision: getPreviewedContent(siteURLData).revision,
revision: siteURLData.revision,
displayContext: SiteInsightsDisplayContext.Server,
};
@@ -1228,21 +1229,3 @@ 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 {};
}
@@ -94,17 +94,6 @@ describe('servePageMarkdown', () => {
expect(response.headers.get('Location')).toBe('/docs/new-page.md');
});
it('returns not-found markdown instead of looping when a site redirect targets the same markdown path', async () => {
const context = createContext({
siteRedirect: { target: 'https://docs.example.com/docs/old-page.md', permanent: false },
});
const response = await servePageMarkdown(context, 'old-page');
expect(response.status).toBe(200);
expect(await response.text()).toContain('# Page Not Found');
});
it('redirects to the markdown version of a space redirect target', async () => {
const context = createContext({ spaceRedirectPageId: page.id });
+5 -10
View File
@@ -1,6 +1,6 @@
import type { RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import { isSameRedirectPath, resolveMissingPagePath } from '@/components/SitePage/fetch';
import { resolveMissingPagePath } from '@/components/SitePage/fetch';
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
import { renderPageAgentInstructions, renderQueryingDocumentation } from '@/lib/ask-prompt';
import type { GitBookSiteContext } from '@/lib/context';
@@ -38,15 +38,10 @@ export async function servePageMarkdown(baseContext: GitBookSiteContext, pagePat
if (!pageLookup) {
const fallback = await resolveMissingPagePath(baseContext, pagePath);
if (fallback?.type === 'redirect') {
const destination = toMarkdownDestination(fallback.destination);
if (
!isSameRedirectPath(
context.linker.toPathForPagePath({ path: pagePath }),
destination
)
) {
return markdownRedirect(destination, fallback.permanent);
}
return markdownRedirect(
toMarkdownDestination(fallback.destination),
fallback.permanent
);
}
if (fallback?.type === 'page') {
return markdownRedirect(