Compare commits

..

7 Commits

Author SHA1 Message Date
taranvohra c4c4af40dd testEntryUrl 2024-10-11 15:52:59 +05:30
taranvohra 66f9526594 open.gitbook.com e2e test 2024-10-11 15:44:09 +05:30
Taran Vohra f9a075eed1 add support for sites in multi id mode (#2514) 2024-10-11 15:23:38 +05:30
Greg Bergé 32e4193557 Implement header link style (#2513) 2024-10-09 15:25:47 +02:00
Zeno Kapitein 133c3e7c0a Update Checkbox component (#2511) 2024-10-08 11:02:51 +02:00
Samy Pessé 6ce3cea682 Stop using KV cache backend for now, but also improves it for higher performances (#2510) 2024-10-03 15:46:58 +02:00
Greg Bergé 250e77d18b Fix synced blocks display (#2508) 2024-10-03 10:30:21 +02:00
25 changed files with 360 additions and 263 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Stop using KV cache backend for now, but also improves it for higher performances
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Update design of Checkbox to be more consistent and readable
+4 -3
View File
@@ -120,24 +120,25 @@ If you plan to distribute the code, you must make the source code public to comp
See `LICENSE` for more information.
## Badges
<p align="left">
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1"></a>
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=F4E28D"></a>
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=FDA599"></a>
</p>
```md
[![GitBook](https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1)](https://gitbook.com/)
```
```html
<a href="https://gitbook.com">
<img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1">
<img
src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1"
/>
</a>
```
## Acknowledgements
GitBook wouldn't be possible without these projects:
BIN
View File
Binary file not shown.
+10 -10
View File
@@ -1,8 +1,16 @@
{
"name": "gitbook",
"version": "0.1.0",
"private": true,
"devDependencies": {
"@changesets/cli": "^2.27.7",
"prettier": "^3.0.3",
"turbo": "^2.1.2"
},
"packageManager": "bun@1.1.18",
"patchedDependencies": {
"@vercel/next@4.3.6": "patches/@vercel%2Fnext@4.3.6.patch"
},
"private": true,
"scripts": {
"dev": "turbo run dev",
"build": "turbo run build",
@@ -22,13 +30,5 @@
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"@changesets/cli": "^2.27.7",
"prettier": "^3.0.3",
"turbo": "^2.1.2"
},
"patchedDependencies": {
"@vercel/next@4.3.6": "patches/@vercel%2Fnext@4.3.6.patch"
}
]
}
+3
View File
@@ -25,3 +25,6 @@
### Sentry ###
# SENTRY_DSN=xxx
### Silent logs
# SILENT=true
+57 -3
View File
@@ -3,6 +3,7 @@ import {
CustomizationHeaderPreset,
CustomizationIconsStyle,
CustomizationLocale,
PublishedSiteContentLookup,
SiteCustomizationSettings,
} from '@gitbook/api';
import { test, expect, Page } from '@playwright/test';
@@ -14,10 +15,11 @@ import { getContentTestURL } from '../tests/utils';
interface Test {
name: string;
url: string; // URL to visit for testing
url: string | (() => Promise<string>); // URL to visit for testing
run?: (page: Page) => Promise<unknown>; // The test to run
fullPage?: boolean; // Whether the test should be fullscreened during testing
screenshot?: false; // Should a screenshot be stored
only?: boolean; // Only run this test
}
interface TestsCase {
@@ -452,6 +454,29 @@ const testCases: TestsCase[] = [
}),
run: waitForCookiesDialog,
},
{
name: 'With header buttons',
url: getCustomizationURL({
header: {
preset: CustomizationHeaderPreset.Default,
links: [
{
title: 'Secondary button',
to: { kind: 'url', url: 'https://www.gitbook.com' },
// @ts-ignore Remove once we upgrade to the latest version of the API
style: 'button-secondary',
},
{
title: 'Primary button',
to: { kind: 'url', url: 'https://www.gitbook.com' },
// @ts-ignore Remove once we upgrade to the latest version of the API
style: 'button-primary',
},
],
},
}),
run: waitForCookiesDialog,
},
],
},
{
@@ -739,13 +764,42 @@ const testCases: TestsCase[] = [
},
],
},
{
name: 'open.gitbook.com',
baseUrl: 'https://open.gitbook.com/',
tests: [
{
name: 'GitBook Docs',
url: async () => {
const res = await fetch(
`https://api.gitbook.com/v1/urls/published?url=https://docs.gitbook.com`,
);
if (!res.ok) {
throw new Error('Failed to get published URL');
}
const published = await res.json<PublishedSiteContentLookup>();
if (!('site' in published)) {
throw new Error('Expected site for published URL');
}
return `~site/${published.site}?token=${published.apiToken}`;
},
run: waitForCookiesDialog,
},
],
},
];
for (const testCase of testCases) {
test.describe(testCase.name, () => {
for (const testEntry of testCase.tests) {
test(testEntry.name, async ({ page, baseURL }) => {
const contentUrl = new URL(testEntry.url, testCase.baseUrl);
const testFn = testEntry.only ? test.only : test;
testFn(testEntry.name, async ({ page, baseURL }) => {
const testEntryUrl =
typeof testEntry.url === 'string' ? testEntry.url : await testEntry.url();
const contentUrl = new URL(testEntryUrl, testCase.baseUrl);
const url = getContentTestURL(contentUrl.toString(), baseURL);
await page.goto(url);
if (testEntry.run) {
+4 -3
View File
@@ -17,12 +17,12 @@
},
"dependencies": {
"@gitbook/api": "0.60.0",
"@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*",
"@gitbook/react-contentkit": "workspace:*",
"@gitbook/react-math": "workspace:*",
"@gitbook/react-openapi": "workspace:*",
"@gitbook/react-contentkit": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/cache-do": "workspace:*",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-popover": "^1.0.7",
"@sentry/nextjs": "^7.94.1",
@@ -48,6 +48,7 @@
"openapi-types": "^12.1.3",
"p-map": "^7.0.0",
"parse-cache-control": "^1.0.1",
"postcss-color-contrast": "^1.1.0",
"react": "^18",
"react-dom": "^18",
"react-hotkeys-hook": "^4.4.1",
@@ -8,6 +8,7 @@ import {
} from '@gitbook/api';
import { IconsProvider, IconStyle } from '@gitbook/icons';
import assertNever from 'assert-never';
import colorContrast from 'postcss-color-contrast/js';
import colors from 'tailwindcss/colors';
import { emojiFontClassName } from '@/components/primitives';
@@ -73,6 +74,21 @@ export default async function SpaceRootLayout(props: { children: React.ReactNode
'primary-color',
customization.styling.primaryColor.light,
)}
${
// Generate the right contrast color for each shade of primary-color
generateColorVariable(
'contrast-primary',
Object.fromEntries(
Object.entries(
shadesOfColor(customization.styling.primaryColor.light),
).map(([index, color]) => [
index,
colorContrast(color, ['#000', '#fff']),
]),
),
)
}
${generateColorVariable(
'primary-base',
customization.styling.primaryColor.light,
@@ -82,6 +98,7 @@ export default async function SpaceRootLayout(props: { children: React.ReactNode
headerTheme.backgroundColor.light,
)}
${generateColorVariable('header-link', headerTheme.linkColor.light)}
${generateColorVariable('header-button-text', colorContrast(headerTheme.linkColor.light as string, ['#000', '#fff']))}
}
.dark {
${generateColorVariable(
@@ -92,11 +109,26 @@ export default async function SpaceRootLayout(props: { children: React.ReactNode
'primary-base',
customization.styling.primaryColor.dark,
)}
${
// Generate the right contrast color for each shade of primary-color
generateColorVariable(
'contrast-primary',
Object.fromEntries(
Object.entries(
shadesOfColor(customization.styling.primaryColor.dark),
).map(([index, color]) => [
index,
colorContrast(color, ['#000', '#fff']),
]),
),
)
}
${generateColorVariable(
'header-background',
headerTheme.backgroundColor.dark,
)}
${generateColorVariable('header-link', headerTheme.linkColor.dark)}
${generateColorVariable('header-button-text', colorContrast(headerTheme.linkColor.dark as string, ['#000', '#fff']))}
}
`}</style>
</head>
@@ -4,7 +4,7 @@ import { getSyncedBlockContent } from '@/lib/api';
import { resolveContentRefWithFiles } from '@/lib/references';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
import { Blocks, UnwrappedBlocks } from './Blocks';
export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBlock>) {
const { block, ancestorBlocks, context, style } = props;
@@ -30,7 +30,7 @@ export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBloc
}
return (
<Blocks
<UnwrappedBlocks
nodes={syncedBlock.document.nodes}
document={syncedBlock.document}
ancestorBlocks={[...ancestorBlocks, block]}
@@ -47,7 +47,6 @@ export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBloc
return context.resolveContentRef(ref, options);
},
}}
style={style}
/>
);
}
@@ -5,50 +5,66 @@ import { tcls, ClassValue } from '@/lib/tailwind';
import { Block } from './Block';
import { DocumentContextProps } from './DocumentView';
export function Blocks<T extends DocumentBlock, Tag extends React.ElementType = 'div'>(
props: DocumentContextProps & {
/** Blocks to render */
nodes: T[];
/** Document being rendered */
document: JSONDocument;
/** Ancestors of the blocks */
ancestorBlocks: DocumentBlock[];
/**
* Renders a list of blocks with a wrapper element.
*/
export function Blocks<TBlock extends DocumentBlock, Tag extends React.ElementType = 'div'>(
props: UnwrappedBlocksProps<TBlock> & {
/** HTML tag to use for the wrapper */
tag?: Tag;
/** Style passed to the wrapper */
style?: ClassValue;
/** Style passed to all blocks */
blockStyle?: ClassValue;
/** Props to pass to the wrapper element */
wrapperProps?: React.ComponentProps<Tag>;
},
) {
const { nodes, tag: Tag = 'div', style, blockStyle, wrapperProps, ...contextProps } = props;
const { tag: Tag = 'div', style, wrapperProps, ...blocksProps } = props;
return (
<Tag {...wrapperProps} className={tcls(style)}>
{nodes.map((node, index) => (
<UnwrappedBlocks {...blocksProps} />
</Tag>
);
}
type UnwrappedBlocksProps<TBlock extends DocumentBlock> = DocumentContextProps & {
/** Blocks to render */
nodes: TBlock[];
/** Document being rendered */
document: JSONDocument;
/** Ancestors of the blocks */
ancestorBlocks: DocumentBlock[];
/** Style passed to all blocks */
blockStyle?: ClassValue;
};
/**
* Renders a list of blocks without a wrapper element.
*/
export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) {
const { nodes, blockStyle, ...contextProps } = props;
return (
<>
{nodes.map((node) => (
<Block
key={node.key}
block={node}
style={[
'w-full mx-auto decoration-primary/6',
node.data && 'fullWidth' in node.data && node.data.fullWidth
? 'max-w-screen-xl'
: 'max-w-3xl',
'w-full',
'mx-auto',
'decoration-primary/6',
blockStyle,
]}
{...contextProps}
/>
))}
</Tag>
</>
);
}
@@ -25,7 +25,7 @@ export function Dropdown<E extends HTMLElement>(props: {
const dropdownId = useId();
return (
<div className={tcls('group/dropdown', 'relative')}>
<div className={tcls('group/dropdown', 'relative flex')}>
{button({
id: dropdownId,
tabIndex: 0,
@@ -5,6 +5,7 @@ import {
CustomizationHeaderPreset,
SiteCustomizationSettings,
} from '@gitbook/api';
import assertNever from 'assert-never';
import { ContentRefContext, resolveContentRef } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
@@ -16,56 +17,95 @@ import {
DropdownMenu,
DropdownMenuItem,
} from './Dropdown';
import { Link } from '../primitives';
import { Button, Link } from '../primitives';
// @TODO Remove it once we have the proper types in API
type CustomizationHeaderLinkWithStyle = CustomizationHeaderLink & {
style?: 'link' | 'button-primary' | 'button-secondary';
};
export async function HeaderLink(props: {
context: ContentRefContext;
link: CustomizationHeaderLink;
link: CustomizationHeaderLinkWithStyle;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { context, link, customization } = props;
const isCustomizationCustom = customization.header.preset === CustomizationHeaderPreset.Custom;
const isCustomizationDefault =
customization.header.preset === CustomizationHeaderPreset.Default;
const target = await resolveContentRef(link.to, context);
if (!target) {
return null;
}
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => (
<Link
{...linkProps}
href={target.href}
className={tcls(
'overflow-hidden',
'text-sm',
'flex',
'flex-row',
'items-center',
'whitespace-nowrap',
'lg:text-base',
const headerPreset = customization.header.preset;
!isCustomizationDefault
? ['text-header-link-500']
: ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
target.active
? [
isCustomizationCustom
? ['shadow-header-link-500/7']
: ['shadow-dark/6', 'dark:shadow-light/7'],
]
: ['hover:text-header-link-400'],
)}
>
<span className={tcls('truncate')}> {link.title}</span>
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => {
const linkStyle = link.style ?? 'link';
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
</Link>
);
switch (linkStyle) {
case 'button-secondary':
case 'button-primary': {
const variant = (() => {
switch (linkStyle) {
case 'button-secondary':
return 'secondary';
case 'button-primary':
return 'primary';
default:
assertNever(linkStyle);
}
})();
return (
<Button
href={target.href}
variant={variant}
className={tcls(
{
'button-primary':
headerPreset === CustomizationHeaderPreset.Custom ||
headerPreset === CustomizationHeaderPreset.Bold
? tcls(
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
)
: null,
'button-secondary': tcls(
'dark:bg-transparent dark:hover:bg-transparent',
'ring-header-link-500 hover:ring-header-link-300 dark:ring-header-link-500 dark:hover:ring-header-link-300 text-header-link-500 dark:text-header-link-500',
),
}[linkStyle],
)}
>
{link.title}
</Button>
);
}
case 'link': {
return (
<Link
{...linkProps}
href={target.href}
className={tcls(
'overflow-hidden',
'text-sm lg:text-base',
'flex flex-row items-center',
'whitespace-nowrap',
'hover:text-header-link-400 dark:hover:text-light',
headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8']
: ['text-header-link-500 hover:text-header-link-400'],
)}
>
<span className={tcls('truncate')}>{link.title}</span>
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
</Link>
);
}
default:
assertNever(linkStyle);
}
};
if (link.links && link.links.length > 0) {
return (
@@ -10,21 +10,13 @@ interface HeaderLinksProps {
export async function HeaderLinks({ children }: HeaderLinksProps) {
return (
<div className={tcls('w-full', 'h-full', 'inline-flex', 'tracking-[-0.02em]')}>
<div
className={`${styles.containerHeaderlinks} ${tcls(
'flex',
'w-full',
'h-full',
'justify-end',
'gap-x-2.5',
'mr-2.5',
'lg:gap-x-5',
'*:max-w-56',
)}`}
>
{children}
</div>
<div
className={tcls(
styles.containerHeaderlinks,
'flex justify-end items-center gap-x-2.5 mr-2.5 lg:gap-x-5 lg:mr-2.5 *:max-w-56',
)}
>
{children}
</div>
);
}
@@ -3,9 +3,6 @@
container-name: headerlinks;
}
.containerHeaderlinks > * {
display: flex;
}
.linkEllipsis {
display: none;
& div > a {
@@ -79,8 +76,3 @@
}
}
}
@container headerlinks ( width > 900px ) {
.containerHeaderlinks > *:not(.linkEllipsis) {
display: flex;
}
}
@@ -51,6 +51,7 @@ export function Button({
['text-xs', 'px-3 py-2'];
const domClassName = tcls(
'inline-block',
'rounded-md',
'straight-corners:rounded-none',
'place-self-start',
@@ -58,6 +59,7 @@ export function Button({
'ring-inset',
'grow-0',
'shrink-0',
'truncate',
variantClasses,
sizeClasses,
className,
@@ -1,6 +1,6 @@
'use client';
import { Icon } from '@gitbook/icons';
import { Icon, IconStyle } from '@gitbook/icons';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import React from 'react';
@@ -14,54 +14,33 @@ export const Checkbox = React.forwardRef<
ref={ref}
className={tcls(
'peer',
'h-4',
'w-4',
'h-5',
'w-5',
'shrink-0',
'rounded-sm',
'straight-corners:rounded-none',
'ring-1',
'bg-primary-300/1',
'ring-dark/3',
'ring-inset',
'grid',
'place-items-center',
'data-[state=checked]:bg-primary-300/6',
'[&>*:has(svg)]:absolute',
'dark:bg-primary-100/[0.02]',
'flex',
'items-center',
'justify-center',
'data-[state=checked]:bg-primary-500',
'data-[state=checked]:text-contrast-primary-500',
'contrast-more:data-[state=checked]:bg-primary-600',
'contrast-more:ring-dark',
'dark:ring-light/3',
'dark:data-[state=checked]:bg-primary-300/4',
'dark:contrast-more:ring-light/6',
'dark:data-[state=checked]:bg-primary-500',
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={tcls(
'flex',
'items-center',
'justify-center',
'text-opacity-[1]',
'text-primary-800',
'grid-area-1-1',
'z-[1]',
'relative',
'dark:text-primary-200',
)}
>
{props.checked ? <Icon icon="check" className={'size-3'} /> : null}
<CheckboxPrimitive.Indicator className={tcls('relative', 'text-current')}>
{props.checked ? (
<Icon icon="check" iconStyle={IconStyle.Solid} className={'size-3'} />
) : null}
</CheckboxPrimitive.Indicator>
<div
className={tcls(
'flex',
'items-center',
'justify-center',
'text-dark/4',
'grid-area-1-1',
'z-[0]',
'relative',
'dark:text-light/2',
)}
>
{props.checked ? <Icon icon="check" className={'size-3'} /> : null}
</div>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
+1 -3
View File
@@ -1,6 +1,5 @@
import { cloudflareCache } from './cloudflare-cache';
import { cloudflareDOCache } from './cloudflare-do';
import { cloudflareKVCache } from './cloudflare-kv';
import { memoryCache } from './memory';
export const cacheBackends = [
@@ -10,7 +9,6 @@ export const cacheBackends = [
// Cache local to the datacenter
// It can't be purged globally but it's faster
cloudflareCache,
// Cache global, but with slow replication
cloudflareKVCache,
// Global cache with slower performances
cloudflareDOCache,
];
+9 -7
View File
@@ -197,13 +197,15 @@ export function cache<Args extends any[], Result>(
const totalDuration = now() - timeStart;
// Log
console.log(
`cache: ${key} ${cacheStatus}${
cacheStatus === 'hit' ? ` on ${backendName}` : ''
} in total ${totalDuration.toFixed(0)}ms, fetch in ${fetchDuration.toFixed(
0,
)}ms, read in ${readCacheDuration.toFixed(0)}ms`,
);
if (process.env.SILENT !== 'true') {
console.log(
`cache: ${key} ${cacheStatus}${
cacheStatus === 'hit' ? ` on ${backendName}` : ''
} in total ${totalDuration.toFixed(0)}ms, fetch in ${fetchDuration.toFixed(
0,
)}ms, read in ${readCacheDuration.toFixed(0)}ms`,
);
}
if (savedEntry.meta.revalidatesAt && savedEntry.meta.revalidatesAt < Date.now()) {
// Revalidate in the background
+14 -69
View File
@@ -1,44 +1,15 @@
import type { KVNamespace } from '@cloudflare/workers-types';
import { CacheBackend, CacheEntry, CacheEntryMeta } from './types';
import { CacheBackend, CacheEntry, CacheEntryLookup, CacheEntryMeta } from './types';
import { getCacheMaxAge } from './utils';
import { trace } from '../tracing';
const cacheVersion = 1;
const cacheVersion = 2;
interface KVTagMetadata {
meta: CacheEntryMeta;
}
/**
* As we migrate off KV, we start disabling it for some tests content.
*/
const noKVTags = new Set([
// docs.gitbook.com
'url:docs.gitbook.com',
'site:site_p4Xo4',
'space:NkEGS7hzeqa35sMXQZ4X',
]);
function shouldUseKVForTag(tag: string): boolean {
if (noKVTags.has(tag)) {
return false;
}
if (tag.startsWith('change-request:')) {
return false;
}
// Hash the tag and return true for 95% of the tags
const hash = tag.split('').reduce((acc, char) => {
return acc + char.charCodeAt(0);
}, 0);
if (hash % 100 <= 30) {
return true;
}
return false;
}
/**
* Cache implementation using the Cloudflare KV API.
* https://developers.cloudflare.com/kv/
@@ -46,11 +17,7 @@ function shouldUseKVForTag(tag: string): boolean {
export const cloudflareKVCache: CacheBackend = {
name: 'cloudflare-kv',
replication: 'global',
async get({ key, tag }, options) {
if (tag && !shouldUseKVForTag(tag)) {
return null;
}
async get(entry, options) {
const kv = await getKVNamespace();
if (!kv) {
return null;
@@ -59,19 +26,19 @@ export const cloudflareKVCache: CacheBackend = {
return trace(
{
operation: `cloudflareKV.get`,
name: key,
name: entry.key,
},
async (span) => {
const kvKey = getValueKey(key);
const kvKey = getKey(entry);
const entry = await kv.get<CacheEntry>(kvKey, {
const kvEntry = await kv.get<CacheEntry>(kvKey, {
type: 'json',
cacheTtl: 60,
});
span.setAttribute('hit', !!entry);
span.setAttribute('hit', !!kvEntry);
return entry;
return kvEntry;
},
);
},
@@ -94,23 +61,10 @@ export const cloudflareKVCache: CacheBackend = {
return;
}
const kvKey = getValueKey(entry.meta.key);
const kvKey = getKey(entry.meta);
await kv.put(kvKey, JSON.stringify(entry), {
expirationTtl: secondsFromNow,
});
if (entry.meta.tag) {
const metadata: KVTagMetadata = {
meta: entry.meta,
};
const jsonMetadata = JSON.stringify(metadata);
const tagKey = getTagKey(entry.meta.tag, entry.meta.key);
await kv.put(tagKey, jsonMetadata, {
metadata,
expirationTtl: secondsFromNow,
});
}
},
);
},
@@ -121,8 +75,8 @@ export const cloudflareKVCache: CacheBackend = {
}
await Promise.all(
entries.map(async ({ key }) => {
const kvKey = getValueKey(key);
entries.map(async (entry) => {
const kvKey = getKey(entry);
await kv.delete(kvKey);
}),
);
@@ -147,12 +101,7 @@ export const cloudflareKVCache: CacheBackend = {
for (const entry of entries.keys) {
if (entry.metadata) {
const metadata = entry.metadata;
const key = metadata.meta.key;
result.push(metadata.meta);
// Delete the tag key and the value key
pendingDeletions.push(kv.delete(getValueKey(key)));
pendingDeletions.push(kv.delete(entry.name));
}
}
@@ -174,16 +123,12 @@ export const cloudflareKVCache: CacheBackend = {
},
};
function getValueKey(key: string): string {
return `${cacheVersion}.v.${key}`;
function getKey(entry: CacheEntryLookup) {
return `${getTagPrefix(entry.tag || 'default')}.${entry.key}`;
}
function getTagPrefix(tag: string) {
return `${cacheVersion}.tag.${tag}.`;
}
function getTagKey(tag: string, key: string) {
return `${getTagPrefix(tag)}${key}`;
return `${cacheVersion}.${tag}.`;
}
async function getKVNamespace(): Promise<KVNamespace | null> {
-4
View File
@@ -19,10 +19,6 @@ export function resolvePagePath(
}
if (page.path !== pagePath) {
if (page.path.split('/').slice(1).join('/') === pagePath) {
return resolvePageDocument(page, ancestors);
}
// TODO: can be optimized to count the number of slashes and skip the entire subtree
const result = iteratePages(page.pages, [...ancestors, page]);
if (result) {
+1 -1
View File
@@ -213,7 +213,7 @@ export async function resolveContentRef(
return {
href: targetSpace.urls.published ?? targetSpace.urls.app,
text: targetSpace.title,
active: true,
active: contentRef.space === space.id,
};
}
+4 -2
View File
@@ -43,8 +43,10 @@ export async function trace<T>(
span.setAttribute('error', true);
throw error;
} finally {
let end = now();
console.log(`trace ${completeName} ${end - start}ms`, attributes);
if (process.env.SILENT !== 'true') {
let end = now();
console.log(`trace ${completeName} ${end - start}ms`, attributes);
}
}
},
);
+69 -38
View File
@@ -16,6 +16,7 @@ import {
getSpaceLayoutData,
DEFAULT_API_ENDPOINT,
getCurrentSiteLayoutData,
getSite,
} from '@/lib/api';
import { race } from '@/lib/async';
import { buildVersion } from '@/lib/build';
@@ -54,7 +55,7 @@ type URLLookupMode =
*/
| 'multi-path'
/**
* Spaces are located using an ID stored in the first segments of the URL (open.gitbook.com/~space/:id/).
* Sites or Spaces are located using an ID stored in the first segments of the URL (open.gitbook.com/~site|~space/:id/)
* This mode is automatically detected and doesn't need to be configured.
* When this mode is used, an authentication token should be passed as a query parameter (`token`).
*/
@@ -75,14 +76,32 @@ export type LookupResult = PublishedContentWithCache & {
cookies?: LookupCookies;
};
interface ContentAPITokenPayload {
// FIXME: This is a temporary type for now. Use @gitbook/api types when available.
interface ContentAPIBaseToken {
organization: string;
spaces: string[];
collection?: string;
site?: string;
siteSpace?: string;
rateLimitMultiplier?: number;
}
type SpaceAPIToken = ContentAPIBaseToken & {
kind: 'space';
space: string;
};
type CollectionAPIToken = ContentAPIBaseToken & {
kind: 'collection';
collection: string;
};
type SiteAPIToken = ContentAPIBaseToken & {
kind: 'site';
site: string;
siteSpace: string;
space: string;
};
type ContentAPITokenPayload = SpaceAPIToken | CollectionAPIToken | SiteAPIToken;
/**
* Middleware to lookup the space to render.
* It takes as input a request with an URL, and a set of headers:
@@ -328,8 +347,8 @@ function getInputURL(request: NextRequest): { url: URL; mode: URLLookupMode } {
url.host = xGitbookHost;
}
// When request started with ~space/:id, we force the mode as 'multi-id'.
if (url.pathname.startsWith('/~space/')) {
// When request started with ~space/:id or ~site/:id, we force the mode as 'multi-id'.
if (url.pathname.startsWith('/~space/') || url.pathname.startsWith('/~site/')) {
mode = 'multi-id';
}
@@ -352,7 +371,7 @@ async function lookupSpaceForURL(
return await lookupSpaceInMultiPathMode(request, url);
}
case 'multi-id': {
return await lookupSpaceInMultiIdMode(request, url);
return await lookupSiteOrSpaceInMultiIdMode(request, url);
}
default:
assertNever(mode);
@@ -406,11 +425,14 @@ async function lookupSpaceInMultiMode(request: NextRequest, url: URL): Promise<L
* When serving multi spaces with the ID passed in the path.
*
* The format of the path is:
* - /~space/:id/:path
* - /~space/:id/~changes/:changeId/:path
* - /~space/:id/~revisions/:revisionId/:path
* - /~space|~site/:id/:path
* - /~space|~site/:id/~changes/:changeId/:path
* - /~space|~site/:id/~revisions/:revisionId/:path
*/
async function lookupSpaceInMultiIdMode(request: NextRequest, url: URL): Promise<LookupResult> {
async function lookupSiteOrSpaceInMultiIdMode(
request: NextRequest,
url: URL,
): Promise<LookupResult> {
const basePathParts: string[] = [];
const pathSegments = url.pathname.slice(1).split('/');
@@ -429,11 +451,18 @@ async function lookupSpaceInMultiIdMode(request: NextRequest, url: URL): Promise
};
const spaceId = eatPathId('~space');
if (!spaceId) {
const siteId = eatPathId('~site');
const source: { kind: 'space' | 'site'; id: string } | undefined = spaceId
? { kind: 'space', id: spaceId }
: siteId
? { kind: 'site', id: siteId }
: undefined;
if (!source) {
return {
error: {
code: 400,
message: `Missing space ID in the path`,
message: `Missing site or space ID in the path`,
},
};
}
@@ -445,14 +474,14 @@ async function lookupSpaceInMultiIdMode(request: NextRequest, url: URL): Promise
// Get the auth token from the URL query
const AUTH_TOKEN_QUERY = 'token';
const API_ENDPOINT_QUERY = 'api';
const cookieName = `gitbook-token-${spaceId}`;
const cookieName = `gitbook-token-${source.id}`;
const { apiToken, apiEndpoint } = url.searchParams.has(AUTH_TOKEN_QUERY)
? {
apiToken: url.searchParams.get(AUTH_TOKEN_QUERY) ?? '',
apiEndpoint: url.searchParams.get(API_ENDPOINT_QUERY) ?? undefined,
}
: (decodeGitBookTokenCookie(spaceId, request.cookies.get(cookieName)?.value) ?? {
: (decodeGitBookTokenCookie(source.id, request.cookies.get(cookieName)?.value) ?? {
apiToken: undefined,
apiEndpoint: undefined,
});
@@ -466,20 +495,32 @@ async function lookupSpaceInMultiIdMode(request: NextRequest, url: URL): Promise
};
}
const decoded = jwt.decode(apiToken) as ContentAPITokenPayload;
if (decoded.kind === 'collection') {
throw new Error('Collection is not supported in multi-id mode');
}
const gitbookAPI = new GitBookAPI({
endpoint: apiEndpoint ?? api().endpoint,
authToken: apiToken,
userAgent: userAgent(),
});
// Verify access to the space to avoid leaking cached data in this mode
// (the cache is not dependend on the auth token, so it could leak data)
await withAPI(
new GitBookAPI({
endpoint: apiEndpoint ?? api().endpoint,
authToken: apiToken,
userAgent: userAgent(),
}),
() => getSpace.revalidate(spaceId, undefined),
);
if (source.kind === 'space') {
await withAPI(gitbookAPI, () => getSpace.revalidate(source.id, undefined));
}
// Verify access to the site to avoid leaking cached data in this mode
// (the cache is not dependend on the auth token, so it could leak data)
if (source.kind === 'site') {
await withAPI(gitbookAPI, () => getSite.revalidate(decoded.organization, source.id));
}
const cookies: LookupCookies = {
[cookieName]: {
value: encodeGitBookTokenCookie(spaceId, apiToken, apiEndpoint),
value: encodeGitBookTokenCookie(source.id, apiToken, apiEndpoint),
options: {
httpOnly: true,
maxAge: 60 * 30,
@@ -502,20 +543,10 @@ async function lookupSpaceInMultiIdMode(request: NextRequest, url: URL): Promise
};
}
const { organization, site, siteSpace } = jwt.decode(apiToken) as ContentAPITokenPayload;
const siteLookupResult =
typeof organization === 'string' && organization && typeof site === 'string' && site
? {
organization,
site,
...(typeof siteSpace === 'string' && siteSpace ? { siteSpace } : {}),
}
: {};
return {
space: spaceId,
...decoded,
changeRequest: changeRequestId,
revision: revisionId,
...siteLookupResult,
basePath: normalizePathname(basePathParts.join('/')),
pathname: normalizePathname(pathSegments.join('/')),
apiToken,
@@ -816,7 +847,7 @@ function encodePathname(pathname: string): string {
}
function decodeGitBookTokenCookie(
spaceId: string,
sourceId: string,
cookie: string | undefined,
): { apiToken: string; apiEndpoint: string | undefined } | undefined {
if (!cookie) {
@@ -825,7 +856,7 @@ function decodeGitBookTokenCookie(
try {
const parsed = JSON.parse(cookie);
if (typeof parsed.t === 'string' && parsed.s === spaceId) {
if (typeof parsed.t === 'string' && parsed.s === sourceId) {
return {
apiToken: parsed.t,
apiEndpoint: typeof parsed.e === 'string' ? parsed.e : undefined,
+2
View File
@@ -70,12 +70,14 @@ const config: Config = {
/** primary-color used to accent elements, these colors remain unchanged when toggling between the CustomizationBackground options**/
primary: generateVarShades('primary-color'),
'contrast-primary': generateVarShades('contrast-primary'),
/** primary-base is an internal color that generates the same colors as primary-color. But it's shades will change into a grayscale if CustomizationBackground.Plain is selected. (globals.css) **/
primarybase: generateVarShades('primary-base'),
'header-background': generateVarShades('header-background'),
'header-link': generateVarShades('header-link'),
'header-button-text': generateVarShades('header-button-text'),
light: {
1: `color-mix(in srgb, var(--light-1), transparent calc(100% - 100% * <alpha-value>))`, //1 99%