mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-26 10:13:46 +00:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 338c5ab040 | |||
| ab7d6292e7 | |||
| 82b85ddbaa | |||
| 9cf7ab6265 | |||
| 0052c19b48 | |||
| 8512a29ac1 | |||
| 0db6c62be8 | |||
| 2e45304130 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Run the Cloudflare server worker next to the GitBook API.
|
||||
@@ -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.
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
+4
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,12 @@ 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');
|
||||
|
||||
@@ -205,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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { permanentRedirect, redirect } from 'next/navigation';
|
||||
import { after } from 'next/server';
|
||||
|
||||
import {
|
||||
type RevisionPageDocument,
|
||||
@@ -6,10 +7,12 @@ import {
|
||||
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 { getRequestPlanStats, logPlanStats, markPlanStart, planScope } from '@/lib/plan-stats';
|
||||
import { findSiteSpaceByUrl, resolveSiteSpacePagePath } from '@/lib/sites';
|
||||
|
||||
const MAX_PAGE_URL_REDIRECTS = 5;
|
||||
@@ -40,6 +43,25 @@ 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) {
|
||||
// TEMP: the scope marks the plan's calls, and the stats are logged once the response is sent.
|
||||
const stats = getRequestPlanStats();
|
||||
markPlanStart(stats);
|
||||
planScope.run(true, () => void runSitePagePlan(context, resolved.page));
|
||||
try {
|
||||
after(() => logPlanStats(stats));
|
||||
} catch {
|
||||
// Outside a request (tests, build), there is nothing to log.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a page from the params.
|
||||
* If the path can't be found, we try to resolve it from the API to handle redirects.
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
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: {
|
||||
customization?: Record<string, unknown>;
|
||||
embed?: unknown;
|
||||
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: options.embed ?? {} })),
|
||||
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' },
|
||||
header: {},
|
||||
footer: {},
|
||||
favicon: {},
|
||||
...options.customization,
|
||||
},
|
||||
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,
|
||||
contentType: 'image/png',
|
||||
downloadURL: 'https://files/download.png',
|
||||
},
|
||||
}
|
||||
: { href: '/x' };
|
||||
}
|
||||
);
|
||||
const loadIcons = mock(async () => ({}));
|
||||
const loadGitMetadata = mock(async () => undefined);
|
||||
return { context, dataFetcher, imageResizer, resolveRef, loadIcons, loadGitMetadata };
|
||||
}
|
||||
|
||||
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 the Git metadata of the page for the Edit on Git action', async () => {
|
||||
const s = setup({});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.loadGitMetadata).toHaveBeenCalledWith(s.context, page);
|
||||
});
|
||||
|
||||
it('resolves cross-space links of the layout and the table of contents', async () => {
|
||||
const ref = (space: string, page: string) => ({ kind: 'page', space, page });
|
||||
const s = setup({
|
||||
customization: {
|
||||
header: {
|
||||
primaryLink: ref('space-2', 'primary'),
|
||||
links: [
|
||||
{
|
||||
title: 'Docs',
|
||||
to: ref('space-2', 'top'),
|
||||
links: [{ title: 'API', to: ref('space-2', 'nested') }],
|
||||
},
|
||||
{ title: 'Here', to: { kind: 'page', page: 'same-space' } },
|
||||
],
|
||||
},
|
||||
footer: { groups: [{ title: 'More', links: [{ to: ref('space-2', 'footer') }] }] },
|
||||
announcement: {
|
||||
enabled: true,
|
||||
message: 'Hi',
|
||||
link: { to: ref('space-2', 'announce') },
|
||||
},
|
||||
},
|
||||
});
|
||||
(s.context as unknown as { revision: unknown }).revision = {
|
||||
pages: [
|
||||
{
|
||||
type: 'group',
|
||||
pages: [{ type: 'link', target: ref('space-2', 'toc') }],
|
||||
},
|
||||
],
|
||||
};
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const resolved = s.resolveRef.mock.calls.map(([d, r]) => [
|
||||
d,
|
||||
(r as { page?: string }).page,
|
||||
]);
|
||||
for (const name of ['primary', 'top', 'nested', 'footer', 'announce', 'toc']) {
|
||||
expect(resolved).toContainEqual([null, name]);
|
||||
}
|
||||
expect(resolved).not.toContainEqual([null, 'same-space']);
|
||||
});
|
||||
|
||||
it('skips hidden table of contents links and a disabled announcement', async () => {
|
||||
const ref = (page: string) => ({ kind: 'page', space: 'space-2', page });
|
||||
const s = setup({
|
||||
customization: {
|
||||
announcement: { enabled: false, message: 'Hi', link: { to: ref('announce') } },
|
||||
},
|
||||
});
|
||||
(s.context as unknown as { revision: unknown }).revision = {
|
||||
pages: [
|
||||
{ type: 'link', hidden: true, target: ref('hidden-link') },
|
||||
{ type: 'group', hidden: true, pages: [{ type: 'link', target: ref('inside') }] },
|
||||
],
|
||||
};
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.resolveRef).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
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('measures the site logos, and the custom icon only without a header logo', async () => {
|
||||
const withLogo = setup({
|
||||
customization: {
|
||||
header: { logo: { light: 'https://l/h.png', dark: 'https://l/hd.png' } },
|
||||
footer: { logo: { light: 'https://l/f.png' } },
|
||||
favicon: { icon: { light: 'https://l/i.png', dark: 'https://l/id.png' } },
|
||||
},
|
||||
});
|
||||
await runSitePagePlan(withLogo.context, page, withLogo);
|
||||
const measured = withLogo.imageResizer.getImageSize.mock.calls as unknown[][];
|
||||
expect(measured).toContainEqual(['https://l/h.png', { dpr: 2 }]);
|
||||
expect(measured).toContainEqual(['https://l/hd.png', { dpr: 2 }]);
|
||||
expect(measured).toContainEqual(['https://l/f.png', { dpr: 2 }]);
|
||||
expect(measured).not.toContainEqual(['https://l/i.png', { dpr: 2 }]);
|
||||
|
||||
const iconOnly = setup({
|
||||
customization: {
|
||||
favicon: { icon: { light: 'https://l/i.png', dark: 'https://l/id.png' } },
|
||||
},
|
||||
});
|
||||
await runSitePagePlan(iconOnly.context, page, iconOnly);
|
||||
const iconCalls = iconOnly.imageResizer.getImageSize.mock.calls as unknown[][];
|
||||
expect(iconCalls).toContainEqual(['https://l/i.png', { dpr: 2 }]);
|
||||
expect(iconCalls).toContainEqual(['https://l/id.png', { dpr: 2 }]);
|
||||
});
|
||||
|
||||
it('measures the page cover like PageCover, only when the layout shows it', async () => {
|
||||
const cover = { ref: { kind: 'file', file: 'c1' }, refDark: { kind: 'file', file: 'c2' } };
|
||||
const s = setup({});
|
||||
await runSitePagePlan(
|
||||
s.context,
|
||||
{
|
||||
...page,
|
||||
cover,
|
||||
layout: { cover: true, coverSize: 'hero' },
|
||||
} as unknown as RevisionPageDocument,
|
||||
s
|
||||
);
|
||||
const refs = s.resolveRef.mock.calls.map(([d, ref]) => [d, ref]);
|
||||
expect(refs).toContainEqual([null, cover.ref]);
|
||||
expect(refs).toContainEqual([null, cover.refDark]);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://files/image.png', {});
|
||||
|
||||
const hidden = setup({});
|
||||
await runSitePagePlan(
|
||||
hidden.context,
|
||||
{
|
||||
...page,
|
||||
cover,
|
||||
layout: { cover: false, coverSize: 'hero' },
|
||||
} as unknown as RevisionPageDocument,
|
||||
hidden
|
||||
);
|
||||
expect(hidden.imageResizer.getImageSize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('measures inline images, drawings and image files like their blocks', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'inline',
|
||||
type: 'inline-image',
|
||||
data: { ref: { kind: 'file', file: 'i1' }, size: 'line' },
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
object: 'block',
|
||||
type: 'drawing',
|
||||
data: { ref: { kind: 'file', file: 'd1' } },
|
||||
nodes: [],
|
||||
},
|
||||
{ object: 'block', type: 'file', data: { ref: { kind: 'file', file: 'f1' } } },
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const measured = s.imageResizer.getImageSize.mock.calls as unknown[][];
|
||||
expect(measured).toContainEqual(['https://files/image.png', { dpr: 2 }]);
|
||||
expect(measured).toContainEqual(['https://files/image.png', { dpr: 3 }]);
|
||||
expect(measured).toContainEqual(['https://files/download.png', { dpr: 2 }]);
|
||||
});
|
||||
|
||||
it('measures the icon of link embeds once the embed arrives', async () => {
|
||||
const s = setup({
|
||||
embed: { type: 'link', icon: 'https://site/icon.png' },
|
||||
document: doc([{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] }]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://site/icon.png', {
|
||||
dpr: 2,
|
||||
});
|
||||
|
||||
const rich = setup({
|
||||
embed: { type: 'rich', icon: 'https://site/icon.png' },
|
||||
document: doc([{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] }]),
|
||||
});
|
||||
await runSitePagePlan(rich.context, page, rich);
|
||||
expect(rich.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,393 @@
|
||||
import type {
|
||||
ContentRef,
|
||||
DocumentBlockTable,
|
||||
JSONDocument,
|
||||
RevisionPageDocument,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import {
|
||||
getRecordCardCovers,
|
||||
isDocumentTableImageRecord,
|
||||
isStringArray,
|
||||
} from '@/components/DocumentView/Table/utils';
|
||||
import { getPageGitMetadata } from '@/components/PageActions/pageActionsData';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getDataOrNull, getPageDocument } from '@/lib/data';
|
||||
import { getSimplifiedContentType } from '@/lib/files';
|
||||
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>;
|
||||
loadGitMetadata: (context: GitBookSiteContext, page: RevisionPageDocument) => 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,
|
||||
})
|
||||
),
|
||||
loadGitMetadata: getPageGitMetadata,
|
||||
};
|
||||
|
||||
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 measure = (src: string | undefined, options: { dpr?: number }) => {
|
||||
const resizer = context.imageResizer;
|
||||
if (src && resizer) {
|
||||
start(() => resizer.getImageSize(src, options));
|
||||
}
|
||||
};
|
||||
|
||||
const resolveFile = (document: JSONDocument | null, ref: ContentRef) =>
|
||||
deps.resolveRef(document, ref, context, {}) as Promise<{
|
||||
href: string;
|
||||
file?: { dimensions?: unknown; contentType?: string; downloadURL?: string };
|
||||
} | null>;
|
||||
|
||||
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 };
|
||||
|
||||
// The Edit on Git action reloads the page with its Git metadata, which the revision tree omits.
|
||||
start(() => deps.loadGitMetadata(context, page));
|
||||
|
||||
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(async () => {
|
||||
const embed = await getDataOrNull(
|
||||
context.dataFetcher.getEmbedByUrl({
|
||||
url: data.url as string,
|
||||
spaceId: context.space.id,
|
||||
})
|
||||
);
|
||||
// Only link cards render the icon, without a size.
|
||||
if (embed && embed.type !== 'rich' && embed.type !== 'integration') {
|
||||
measure(embed.icon, { dpr: 2 });
|
||||
}
|
||||
});
|
||||
}
|
||||
if (node.type === 'image') {
|
||||
for (const ref of [data.ref, data.refDark]) {
|
||||
if (ref) {
|
||||
planImage(document, ref as ContentRef);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'inline-image') {
|
||||
// Line-sized inline images also measure the light image for their width.
|
||||
const lineSize = data.size === 'line' ? [{ dpr: 2 }, { dpr: 3 }] : [{ dpr: 2 }];
|
||||
if (data.ref) {
|
||||
planImage(document, data.ref as ContentRef, lineSize);
|
||||
}
|
||||
if (data.refDark) {
|
||||
planImage(document, data.refDark as ContentRef);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'drawing') {
|
||||
if (data.ref) {
|
||||
planImage(document, data.ref as ContentRef);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'file' && data.ref) {
|
||||
planFilePreview(document, data.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 | null, ref: ContentRef, anchorText: boolean) => {
|
||||
if (needsRequest(ref, anchorText, context)) {
|
||||
resolveRef(document, ref, anchorText);
|
||||
}
|
||||
};
|
||||
|
||||
const planImage = (
|
||||
document: JSONDocument | null,
|
||||
ref: ContentRef,
|
||||
sizes: { dpr?: number }[] = [{ dpr: 2 }]
|
||||
) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(async () => {
|
||||
const resolved = await resolveFile(document, ref);
|
||||
// Like `Image`, a file with known dimensions is never measured.
|
||||
if (resolved && !resolved.file?.dimensions) {
|
||||
for (const options of sizes) {
|
||||
measure(resolved.href, options);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// The file block previews images from their download URL.
|
||||
const planFilePreview = (document: JSONDocument, ref: ContentRef) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(async () => {
|
||||
const file = (await resolveFile(document, ref))?.file;
|
||||
if (
|
||||
file &&
|
||||
!file.dimensions &&
|
||||
getSimplifiedContentType(file.contentType ?? '') === 'image'
|
||||
) {
|
||||
measure(file.downloadURL, { dpr: 2 });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const planSite = () => {
|
||||
// Links the layout resolves: header, announcement, footer, and link pages of the table of contents.
|
||||
const { header: headerLinks, footer: footerLinks, announcement } = context.customization;
|
||||
const layoutRefs: (ContentRef | null | undefined)[] = [
|
||||
headerLinks.primaryLink,
|
||||
// Same condition as `Announcement`, which renders nothing otherwise.
|
||||
announcement?.enabled && announcement.message ? announcement.link?.to : undefined,
|
||||
...(headerLinks.links ?? []).flatMap((link) => [
|
||||
link.to,
|
||||
...(link.links ?? []).map((sub) => sub.to),
|
||||
]),
|
||||
...(footerLinks.groups ?? []).flatMap((group) =>
|
||||
(group.links ?? []).map((link) => link.to)
|
||||
),
|
||||
];
|
||||
visitPages(context.revision?.pages, (target) => layoutRefs.push(target));
|
||||
for (const ref of layoutRefs) {
|
||||
if (ref) {
|
||||
planRef(null, ref, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Logos and the custom icon carry no size, so the layout measures them on every page.
|
||||
const { header, footer, favicon } = context.customization;
|
||||
if (header.logo) {
|
||||
measure(header.logo.light, { dpr: 2 });
|
||||
measure(header.logo.dark, { dpr: 2 });
|
||||
} else if ('icon' in favicon && favicon.icon) {
|
||||
measure(favicon.icon.light, { dpr: 2 });
|
||||
measure(favicon.icon.dark, { dpr: 2 });
|
||||
}
|
||||
if (footer.logo) {
|
||||
measure(footer.logo.light, { dpr: 2 });
|
||||
measure(footer.logo.dark, { dpr: 2 });
|
||||
}
|
||||
|
||||
// Same conditions as SitePage (full/background) and PageBody (hero).
|
||||
const coverSize = page.layout?.coverSize;
|
||||
if (
|
||||
page.cover &&
|
||||
page.layout?.cover &&
|
||||
(coverSize === 'hero' || coverSize === 'full' || coverSize === 'background')
|
||||
) {
|
||||
for (const ref of [page.cover.ref, page.cover.refDark]) {
|
||||
if (ref) {
|
||||
planImage(null, ref, [{}]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// After every helper above is defined, and inside `start` so nothing throws out of the plan.
|
||||
start(async () => planSite());
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Calls `fn` with the target of every link page, as the table of contents resolves them. */
|
||||
function visitPages(pages: unknown, fn: (target: ContentRef) => void) {
|
||||
if (!Array.isArray(pages)) {
|
||||
return;
|
||||
}
|
||||
for (const page of pages as {
|
||||
type?: string;
|
||||
hidden?: boolean;
|
||||
target?: ContentRef;
|
||||
pages?: unknown;
|
||||
}[]) {
|
||||
// The table of contents skips hidden pages and everything under them.
|
||||
if (!page || page.hidden) {
|
||||
continue;
|
||||
}
|
||||
if (page.type === 'link' && page.target) {
|
||||
fn(page.target);
|
||||
}
|
||||
visitPages(page.pages, fn);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
throwIfDataError,
|
||||
} from '@/lib/data';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { measureDataFetcher, measureImageResizer } from '@/lib/plan-stats';
|
||||
import type { DirectSearchProps } from '@/lib/search-results';
|
||||
import {
|
||||
findSiteSpaceBy,
|
||||
@@ -248,9 +249,12 @@ export function getBaseContext(input: {
|
||||
const { urlMode, siteURLData } = input;
|
||||
const siteURL = typeof input.siteURL === 'string' ? new URL(input.siteURL) : input.siteURL;
|
||||
|
||||
const dataFetcher = createDataFetcher({
|
||||
apiToken: siteURLData.apiToken ?? null,
|
||||
});
|
||||
// TEMP: measured to log what the site page plan saves (lib/plan-stats.ts).
|
||||
const dataFetcher = measureDataFetcher(
|
||||
createDataFetcher({
|
||||
apiToken: siteURLData.apiToken ?? null,
|
||||
})
|
||||
);
|
||||
|
||||
const linkerInput: SiteLinkerInput = {
|
||||
urlMode,
|
||||
@@ -261,12 +265,14 @@ export function getBaseContext(input: {
|
||||
};
|
||||
const linker = createSiteLinker(linkerInput);
|
||||
|
||||
const imageResizer = createImageResizer({
|
||||
imagesContextId: siteURLData.imagesContextId,
|
||||
// To ensure image resizing work for proxied sites,
|
||||
// we serve images from the root of the site.
|
||||
linker: linker,
|
||||
});
|
||||
const imageResizer = measureImageResizer(
|
||||
createImageResizer({
|
||||
imagesContextId: siteURLData.imagesContextId,
|
||||
// To ensure image resizing work for proxied sites,
|
||||
// we serve images from the root of the site.
|
||||
linker: linker,
|
||||
})
|
||||
);
|
||||
|
||||
const directSearch: GitBookBaseContext['directSearch'] =
|
||||
!siteURLData.revision && !siteURLData.changeRequest && !siteURLData.preview
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { createPlanStats, markPlanStart, recordCall, summarizePlanStats } from './plan-stats';
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function clock() {
|
||||
let now = 0;
|
||||
return {
|
||||
now: () => now,
|
||||
set: (value: number) => {
|
||||
now = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
describe('plan stats', () => {
|
||||
it('counts the head start when the render asks before the plan call settles', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
const call = deferred();
|
||||
recordCall(stats, 'getRevisionPageDocument', { pageId: 'p' }, call.promise, true);
|
||||
c.set(60);
|
||||
recordCall(stats, 'getRevisionPageDocument', { pageId: 'p' }, call.promise, false);
|
||||
c.set(100);
|
||||
call.resolve();
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.used).toBe(1);
|
||||
expect(summary.savedMsMax).toBe(60);
|
||||
expect(summary.savedMsTotal).toBe(60);
|
||||
});
|
||||
|
||||
it('counts the whole duration when the plan call settled before the render asked', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
const call = deferred();
|
||||
recordCall(stats, 'getEmbedByUrl', { url: 'u' }, call.promise, true);
|
||||
c.set(50);
|
||||
call.resolve();
|
||||
await flush();
|
||||
c.set(200);
|
||||
recordCall(stats, 'getEmbedByUrl', { url: 'u' }, call.promise, false);
|
||||
|
||||
expect(summarizePlanStats(stats).savedMsMax).toBe(50);
|
||||
});
|
||||
|
||||
it('matches calls by method and argument shape', async () => {
|
||||
const stats = createPlanStats(() => 0);
|
||||
const call = Promise.resolve();
|
||||
recordCall(stats, 'getSpace', { spaceId: 's', shareKey: undefined }, call, true);
|
||||
recordCall(stats, 'getSpace', { shareKey: undefined, spaceId: 's' }, call, false);
|
||||
recordCall(stats, 'getRevision', { spaceId: 's' }, call, false);
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.used).toBe(1);
|
||||
expect(summary.notPlanned).toEqual({
|
||||
getRevision: { count: 1, maxMs: 0, example: { spaceId: 's' } },
|
||||
});
|
||||
});
|
||||
|
||||
it('reports plan calls the render never made as wasted', async () => {
|
||||
const stats = createPlanStats(() => 0);
|
||||
recordCall(stats, 'getImageSize', ['https://x', { dpr: 2 }], Promise.resolve(), true);
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.wasted).toEqual({ getImageSize: 1 });
|
||||
expect(summary.used).toBe(0);
|
||||
});
|
||||
|
||||
it('measures rejected calls too', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
const call = Promise.reject(new Error('boom'));
|
||||
recordCall(stats, 'getRevision', { spaceId: 's' }, call, false);
|
||||
call.catch(() => {});
|
||||
c.set(30);
|
||||
await flush();
|
||||
|
||||
expect(summarizePlanStats(stats).notPlanned).toEqual({
|
||||
getRevision: { count: 1, maxMs: 30, example: { spaceId: 's' } },
|
||||
});
|
||||
});
|
||||
|
||||
it('only reports render calls made after the plan began as not planned', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
recordCall(stats, 'getPublishedContentSite', { siteId: 's' }, Promise.resolve(), false);
|
||||
c.set(10);
|
||||
markPlanStart(stats);
|
||||
c.set(20);
|
||||
recordCall(stats, 'getRevisionPageByPath', { path: 'p' }, Promise.resolve(), false);
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.beforePlan).toBe(1);
|
||||
expect(Object.keys(summary.notPlanned)).toEqual(['getRevisionPageByPath']);
|
||||
});
|
||||
|
||||
it('keeps only ids in the example of a not planned call', async () => {
|
||||
const stats = createPlanStats(() => 0);
|
||||
recordCall(
|
||||
stats,
|
||||
'getSpace',
|
||||
{ spaceId: 's', shareKey: 'secret', extra: { deep: true } },
|
||||
Promise.resolve(),
|
||||
false
|
||||
);
|
||||
await flush();
|
||||
|
||||
expect(summarizePlanStats(stats).notPlanned.getSpace?.example).toEqual({ spaceId: 's' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
// TEMP: measures what the site page plan saves; remove once the plan is validated in production.
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { identify } from 'object-identity';
|
||||
import * as React from 'react';
|
||||
|
||||
import type { GitBookDataFetcher } from '@/lib/data';
|
||||
import type { ImageResizer } from '@/lib/images';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
|
||||
/** Set while the plan runs, so its calls can be told apart from the render's. */
|
||||
export const planScope = new AsyncLocalStorage<true>();
|
||||
|
||||
type Entry = {
|
||||
label: string;
|
||||
example?: Record<string, string>;
|
||||
planStart?: number;
|
||||
planEnd?: number;
|
||||
renderAsk?: number;
|
||||
renderEnd?: number;
|
||||
};
|
||||
|
||||
export type PlanStats = {
|
||||
now: () => number;
|
||||
t0: number;
|
||||
planStart?: number;
|
||||
entries: Map<string, Entry>;
|
||||
};
|
||||
|
||||
export function createPlanStats(now: () => number = Date.now): PlanStats {
|
||||
return { now, t0: now(), entries: new Map() };
|
||||
}
|
||||
|
||||
/** Render calls made before this are the site context fetch, not gaps in the plan. */
|
||||
export function markPlanStart(stats: PlanStats) {
|
||||
stats.planStart ??= stats.now();
|
||||
}
|
||||
|
||||
/** One per request; outside a render scope this just returns a fresh, unused object. */
|
||||
export const getRequestPlanStats = React.cache(() => createPlanStats());
|
||||
|
||||
/** Record the first plan call and the first render call of a request, keyed by method and args. */
|
||||
export function recordCall(
|
||||
stats: PlanStats,
|
||||
label: string,
|
||||
args: unknown,
|
||||
promise: Promise<unknown>,
|
||||
inPlan: boolean
|
||||
) {
|
||||
const key = `${label}:${identify(args)}`;
|
||||
let entry = stats.entries.get(key);
|
||||
if (!entry) {
|
||||
entry = { label };
|
||||
stats.entries.set(key, entry);
|
||||
}
|
||||
const current = entry;
|
||||
const settled = () => stats.now();
|
||||
if (inPlan && current.planStart === undefined) {
|
||||
current.planStart = stats.now();
|
||||
promise.then(
|
||||
() => {
|
||||
current.planEnd = settled();
|
||||
},
|
||||
() => {
|
||||
current.planEnd = settled();
|
||||
}
|
||||
);
|
||||
} else if (!inPlan && current.renderAsk === undefined) {
|
||||
current.renderAsk = stats.now();
|
||||
current.example = pickIds(args);
|
||||
promise.then(
|
||||
() => {
|
||||
current.renderEnd = settled();
|
||||
},
|
||||
() => {
|
||||
current.renderEnd = settled();
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Only id-like string fields, so logs never carry share keys, tokens or content. */
|
||||
function pickIds(args: unknown): Record<string, string> | undefined {
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) {
|
||||
return undefined;
|
||||
}
|
||||
const ids: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(args)) {
|
||||
if (key.endsWith('Id') && typeof value === 'string') {
|
||||
ids[key] = value;
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function summarizePlanStats(stats: PlanStats) {
|
||||
let used = 0;
|
||||
let beforePlan = 0;
|
||||
let savedMsTotal = 0;
|
||||
let savedMsMax = 0;
|
||||
const wasted: Record<string, number> = {};
|
||||
const notPlanned: Record<
|
||||
string,
|
||||
{ count: number; maxMs: number; example?: Record<string, string> }
|
||||
> = {};
|
||||
const saved: { label: string; ms: number }[] = [];
|
||||
|
||||
for (const entry of stats.entries.values()) {
|
||||
const { planStart, planEnd, renderAsk, renderEnd } = entry;
|
||||
if (planStart !== undefined && renderAsk !== undefined) {
|
||||
used++;
|
||||
if (planEnd !== undefined) {
|
||||
// Without the plan the render would have started this call itself when it asked.
|
||||
const withoutPlan = renderAsk + (planEnd - planStart);
|
||||
const withPlan = Math.max(renderAsk, planEnd);
|
||||
const ms = Math.max(0, withoutPlan - withPlan);
|
||||
savedMsTotal += ms;
|
||||
savedMsMax = Math.max(savedMsMax, ms);
|
||||
saved.push({ label: entry.label, ms });
|
||||
}
|
||||
} else if (planStart !== undefined) {
|
||||
wasted[entry.label] = (wasted[entry.label] ?? 0) + 1;
|
||||
} else if (
|
||||
renderAsk !== undefined &&
|
||||
stats.planStart !== undefined &&
|
||||
renderAsk < stats.planStart
|
||||
) {
|
||||
beforePlan++;
|
||||
} else if (renderAsk !== undefined) {
|
||||
const item = (notPlanned[entry.label] ??= {
|
||||
count: 0,
|
||||
maxMs: 0,
|
||||
example: entry.example,
|
||||
});
|
||||
item.count++;
|
||||
if (renderEnd !== undefined) {
|
||||
item.maxMs = Math.max(item.maxMs, renderEnd - renderAsk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
used,
|
||||
savedMsTotal,
|
||||
savedMsMax,
|
||||
topSaved: saved.sort((a, b) => b.ms - a.ms).slice(0, 5),
|
||||
wasted,
|
||||
beforePlan,
|
||||
notPlanned,
|
||||
};
|
||||
}
|
||||
|
||||
export function logPlanStats(stats: PlanStats) {
|
||||
const summary = summarizePlanStats(stats);
|
||||
// One JSON string so log tooling keeps nested fields (console truncates objects at depth 2).
|
||||
getLogger()
|
||||
.subLogger('data-plan')
|
||||
.info(
|
||||
'site-page-plan.stats',
|
||||
JSON.stringify({ elapsedMs: stats.now() - stats.t0, ...summary })
|
||||
);
|
||||
}
|
||||
|
||||
function record<T>(label: string, args: unknown, promise: Promise<T>): Promise<T> {
|
||||
try {
|
||||
recordCall(getRequestPlanStats(), label, args, promise, planScope.getStore() === true);
|
||||
} catch {
|
||||
// Measuring must never break a fetch.
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** Wrap a request's data fetcher so each call is timed; `withToken` fetchers aren't measured. */
|
||||
export function measureDataFetcher(fetcher: GitBookDataFetcher): GitBookDataFetcher {
|
||||
return new Proxy(fetcher, {
|
||||
get(target, prop, receiver) {
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
if (typeof prop !== 'string' || prop === 'api' || prop === 'withToken') {
|
||||
return value;
|
||||
}
|
||||
if (typeof value !== 'function') {
|
||||
return value;
|
||||
}
|
||||
return (...args: unknown[]) =>
|
||||
record(prop, args[0], (value as (...a: unknown[]) => Promise<unknown>)(...args));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function measureImageResizer(resizer: ImageResizer): ImageResizer {
|
||||
return {
|
||||
...resizer,
|
||||
getImageSize: (input, options) =>
|
||||
record('getImageSize', [input, options], resizer.getImageSize(input, options)),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user