Compare commits

..

1 Commits

Author SHA1 Message Date
Peter White 1ecd2ca65a Keep integration dependency errors inside their blocks (#4820) 2026-11-21 10:11:45 +01:00
12 changed files with 81 additions and 301 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Keep published pages available when an integration block needs its connection or settings checked.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
@@ -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,4 +1,5 @@
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { ContentKitOutput } from '@gitbook/react-contentkit';
import type { BlockProps } from '../Block';
@@ -53,6 +54,7 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
{
integrationName: block.data.integration,
request: initialInput,
allowFailedDependency: true,
}
);
@@ -66,12 +68,29 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
// Integration output can render blocks with generated keys.
{...getCommentAnchorProps(context, block.key)}
{...getCommentMarkerProps(context, 'data-comment-block')}
className={tcls(style)}
role="note"
className={tcls(
'flex items-start gap-3 p-4 text-sm',
'rounded-corners:rounded-md circular-corners:rounded-xl',
'bg-warning border-warning text-neutral-strong',
style
)}
>
<pre>
Unexpected error with integration {block.data.integration}:{' '}
{initialResponse.error.message}
</pre>
<Icon
icon="circle-exclamation"
className="mt-0.5 size-4 shrink-0 text-warning-subtle contrast-more:text-warning"
aria-hidden="true"
/>
<div className="wrap-anywhere min-w-0">
<p className="font-medium">
Could not load the {block.data.integration} integration
</p>
<p>
{initialResponse.error.code === 424
? 'Ask an administrator to check its connection and settings.'
: initialResponse.error.message}
</p>
</div>
</div>
);
}
@@ -11,9 +11,11 @@ export async function fetchSafeIntegrationUI(
{
integrationName,
request,
allowFailedDependency = false,
}: {
integrationName: string;
request: RenderIntegrationUI;
allowFailedDependency?: boolean;
}
) {
const output = await ignoreDataFetcherErrors(
@@ -27,6 +29,7 @@ export async function fetchSafeIntegrationUI(
404, // Integration has been uninstalled
400, // Integration is rejecting its own request
422, // Integration is triggering an invalid request, failing at the validation step
...(allowFailedDependency ? [424] : []),
502, // Integration is failing in an unexpected way
]
);
-25
View File
@@ -44,7 +44,6 @@ import {
getLinkerForSiteSpace,
getLocalizedTitle,
getSiteStructureSections,
listAllSiteSpaces,
} from '@/lib/sites';
/**
@@ -72,11 +71,6 @@ export type SiteURLData = Pick<
*/
imagesContextId: string;
/**
* Site revision being previewed, when the URL previews one. Content is read as it pins it.
*/
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.
@@ -223,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;
@@ -259,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 = {
@@ -321,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,
@@ -346,7 +329,6 @@ export async function fetchSiteContextByIds(
contextId?: string;
isFallback: boolean;
noIndexSearch: boolean;
siteRevision?: string;
isLoggedInVisitor: boolean;
preview: boolean;
displayAgentInstructions?: boolean;
@@ -480,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,
@@ -501,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,
+45 -184
View File
@@ -12,7 +12,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 { 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,106 +77,61 @@ export function createDataFetcher(
});
},
getRevision(params) {
return readAtSiteRevision(
input,
params.spaceId,
`content/${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,
`content/${params.spaceId}/path/${encodeURIComponent(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,
`content/${params.spaceId}/page/${params.pageId}`,
{
format: 'markdown',
'format.markdown.refs': 'stable',
evaluated: 'deterministic-only',
metadata: false,
spaceId: params.spaceId,
revisionId: params.revisionId,
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'
)
// 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,
`content/${params.spaceId}/page/${params.pageId}/document`,
{ evaluated: 'deterministic-only', dereferenced: 'reusable-contents' },
() =>
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,
`content/${params.spaceId}/reusable-contents/${params.reusableContentId}/document`,
{ evaluated: 'deterministic-only' },
() =>
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, `openapi/${params.slug}/content`, {}, () =>
getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
})
);
return getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
});
},
getSpace(params) {
return getSpace(input, {
@@ -267,82 +195,15 @@ export function createDataFetcher(
},
listRevisionPageMetaLinks(params) {
return readAtSiteRevision(
input,
params.spaceId,
`content/${params.spaceId}/page/${params.pageId}/meta-links`,
{},
() =>
listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
})
);
return listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
});
},
};
}
/**
* Read content at the site revision of the input, with the same query as `live` reads it. Reads
* 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,
path: string,
query: Record<string, string | boolean>,
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;
// Typed like the space endpoint it mirrors: the API client doesn't publish these endpoints yet.
return (await getAtSiteRevision(
{ ...input, siteRevision: cacheableSiteRevision },
{ path, query }
)) as DataFetcherResponse<T>;
}
/**
* Get content at a site revision. It never changes, so it is cached forever.
*/
const getAtSiteRevision = cache(
async (
input: DataFetcherInput,
params: { path: string; query: Record<string, string | boolean> }
) => {
'use cache';
return wrapDataFetcherError(async () => {
const { siteRevision } = input;
if (!siteRevision) {
throw new Error('A site revision is required to read content at it');
}
const { organizationId, siteId, siteRevisionId } = siteRevision;
const path = `/orgs/${organizationId}/sites/${siteId}/revisions/${siteRevisionId}/${params.path}`;
return trace(`getAtSiteRevision(${path})`, async () => {
const api = apiClient(input);
const res = await api.request<unknown>({
path,
method: 'GET',
query: params.query,
secure: true,
format: 'json',
...noCacheFetchOptions,
});
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.
-1
View File
@@ -6,4 +6,3 @@ export * from './lookup';
export * from './visitor';
export * from './pages';
export * from './revisions';
export * from './siteRevisionTypes';
@@ -1,43 +0,0 @@
// TEMPORARY: mirrors the `PublishedSiteContent` variants of GitbookIO/gitbook-x#27870 until a
// published `@gitbook/api` includes them. Delete this file and import the official types then.
import type * as api from '@gitbook/api';
/** Site content at the live revision of its spaces. */
export type PublishedSiteContentLive = object;
/** Site content previewed at a revision of its space. */
export interface PublishedSiteContentAtRevision {
revision: string;
}
/** Site content previewed in a change request of its space. */
export interface PublishedSiteContentInChangeRequest {
changeRequest: string;
}
/** Site content previewed at a site revision. */
export interface PublishedSiteContentAtSiteRevision {
siteRevision: string;
}
/** Site content a URL resolves to: at most one of `revision`, `changeRequest` and `siteRevision`. */
export type PublishedSiteContentWithSiteRevision = Omit<
api.PublishedSiteContent,
'revision' | 'changeRequest'
> &
(
| PublishedSiteContentLive
| PublishedSiteContentAtRevision
| PublishedSiteContentInChangeRequest
| PublishedSiteContentAtSiteRevision
);
/**
* Read a resolution with the variants of the next `@gitbook/api`: the published type has neither
* `siteRevision` nor the variants, though the API already returns them.
*/
export function asPublishedSiteContentWithSiteRevision(
content: api.PublishedSiteContent
): PublishedSiteContentWithSiteRevision {
return content as PublishedSiteContentWithSiteRevision;
}
-6
View File
@@ -34,12 +34,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.
*/
+2 -6
View File
@@ -29,12 +29,8 @@ export function isSiteIndexable(context: GitBookSiteContext) {
return false;
}
// Prevent indexation of preview of revisions / change-requests / site revisions
if (
context.changeRequest ||
context.siteRevision ||
context.revisionId !== context.space.revision
) {
// Prevent indexation of preview of revisions / change-requests
if (context.changeRequest || context.revisionId !== context.space.revision) {
return false;
}
+2 -21
View File
@@ -32,7 +32,6 @@ import { validateSerializedCustomization } from '@/lib/customization';
import {
DataFetcherError,
apiClient,
asPublishedSiteContentWithSiteRevision,
getVisitorAuthBasePath,
lookupPublishedContentByUrl,
normalizeRequestURL,
@@ -427,7 +426,8 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
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,
@@ -1204,22 +1204,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(
lookup: PublishedSiteContent
): Pick<SiteURLData, 'revision' | 'changeRequest' | 'siteRevision'> {
const content = asPublishedSiteContentWithSiteRevision(lookup);
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 {};
}