Compare commits

..

2 Commits

Author SHA1 Message Date
Samy Pessé 0f7ac7ca08 Merge branch 'main' into fix-iframely-csp 2024-04-18 08:39:09 -07:00
Samy Pessé 119c22af11 Pass a nonce to the script for cdn.iframe.ly/embed.js 2024-04-18 08:25:11 -07:00
41 changed files with 213 additions and 623 deletions
+1 -5
View File
@@ -1,9 +1,5 @@
on: [push]
name: CI
on:
pull_request:
push:
branches:
- main
jobs:
deploy:
+2 -8
View File
@@ -75,7 +75,7 @@ GitBook's rendering engine is fully open-source and built on top of [Next.js](ht
### Types of contributions
We encourage you to contribute to GitBook to help us build the best tool for documenting technical knowledge. If you're looking for some quick ways to contribute, continue reading to learn more about popular contributions.
We encourage you to contribute to GitBook to help us build the best tool for doucmenting techincal knowledge. If you're looking for some quick ways to contribute, continue reading to learn more about popular contributions.
#### Translations
@@ -92,7 +92,7 @@ Encounter a bug or find an issue you'd like to fix? Helping us fix issues relate
>
> _Looking to add a specific feature in GitBook? Head to our [contributing guide](/.github/CONTRIBUTING.md) to get started._
>
> Self-hosting this project puts the responsibility of maintaining and merging future updates on **you**. We cannot guarantee support, maintenance, or updates to forked and self-hosted instances of this project.
> Self-hosting this project puts the responsibility of maintaining and merging future updates on **you**. We cannot guarantee support, maintainance, or updates to forked and self-hosted instances of this project.
>
> We want to make it as easy as possible for our community to collaborate and push the future of GitBook, which is why we encourage you to contribute to our product directly instead of creating your own version.
@@ -119,12 +119,6 @@ GitBook wouldn't be possible without these projects:
- [Tailwind CSS](https://tailwindcss.com/)
- [Framer Motion](https://www.npmjs.com/package/framer-motion)
## Contributors
<a href="https://github.com/gitbookIO/gitbook/graphs/contributors">
<img src="https://contrib.rocks/image?repo=gitbookIO/gitbook" />
</a>
## Legacy GitBook (Deprecated)
Our previous version of GitBook and it's CLI tool are now deprecated. You can still view the old repository and it's commits on this [branch](https://github.com/GitbookIO/gitbook/tree/legacy).
BIN
View File
Binary file not shown.
-9
View File
@@ -39,15 +39,6 @@ module.exports = withSentryConfig(
assetPrefix: process.env.GITBOOK_ASSETS_PREFIX,
poweredByHeader: false,
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '*.gitbook.io',
}
]
}
},
{
silent: true,
+2 -2
View File
@@ -20,7 +20,7 @@
],
"dependencies": {
"@geist-ui/icons": "^1.0.2",
"@gitbook/api": "^0.51.0",
"@gitbook/api": "^0.43.0",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-popover": "^1.0.7",
"@sentry/nextjs": "^7.94.1",
@@ -64,7 +64,7 @@
},
"devDependencies": {
"@argos-ci/playwright": "^2.0.0",
"@cloudflare/next-on-pages": "^1.11.3",
"@cloudflare/next-on-pages": "^1.9.0",
"@cloudflare/workers-types": "^4.20231218.0",
"@playwright/test": "^1.42.1",
"@types/js-cookie": "^3.0.6",
+1 -1
View File
@@ -3,7 +3,7 @@
"exports": "./src/index.ts",
"dependencies": {
"classnames": "^2.5.1",
"@gitbook/api": "^0.51.0",
"@gitbook/api": "^0.41.0",
"assert-never": "^1.2.1"
},
"peerDependencies": {
+2 -2
View File
@@ -2,8 +2,8 @@
"name": "@gitbook/react-openapi",
"exports": "./src/index.ts",
"dependencies": {
"@scalar/api-client-react": "^0.3.7",
"@scalar/oas-utils": "0.1.6",
"@scalar/api-client-react": "^0.2.9",
"@scalar/oas-utils": "0.1.1",
"classnames": "^2.5.1",
"flatted": "^3.2.9",
"openapi-types": "^12.1.3",
+1 -10
View File
@@ -7,7 +7,6 @@ import {
getRequestFromOperation,
Query,
Header,
RequestBody,
} from '@scalar/oas-utils';
import React from 'react';
@@ -99,15 +98,7 @@ export function ScalarApiClient(props: { children: React.ReactNode }) {
{
url: operationData.path,
},
getRequestFromOperation(
{
...operation,
information: {
requestBody: operationData.operation.requestBody as RequestBody,
},
},
{ requiredOnly: false },
),
getRequestFromOperation(operation, { requiredOnly: false }),
);
return {
+2 -5
View File
@@ -1,7 +1,6 @@
import { NextRequest } from 'next/server';
import { verifyImageSignature, resizeImage, CloudflareImageOptions } from '@/lib/images';
import { parseImageAPIURL } from '@/lib/urls';
export const runtime = 'edge';
@@ -11,14 +10,12 @@ export const runtime = 'edge';
* Fetch and resize an image.
*/
export async function GET(request: NextRequest) {
let urlParam = request.nextUrl.searchParams.get('url');
const url = request.nextUrl.searchParams.get('url');
const signature = request.nextUrl.searchParams.get('sign');
if (!urlParam || !signature) {
if (!url || !signature) {
return new Response('Missing url/sign parameters', { status: 400 });
}
const url = parseImageAPIURL(urlParam);
// Prevent infinite loops
if (url.includes('/~gitbook/image')) {
return new Response('Invalid url parameter', { status: 400 });
@@ -9,7 +9,6 @@ import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
import { getContentTitle } from '@/lib/utils';
import { PageClientLayout } from './PageClientLayout';
import { PagePathParams, fetchPageData, getPathnameParam, normalizePathname } from '../../fetch';
@@ -111,7 +110,7 @@ export async function generateMetadata({ params }: { params: PagePathParams }):
}
return {
title: [page.title, getContentTitle(space, customization, parent)]
title: [page.title, customization.title ?? space.title, parent?.title]
.filter(Boolean)
.join(' | '),
description: page.description ?? '',
+1 -2
View File
@@ -12,7 +12,6 @@ import { buildVersion } from '@/lib/build';
import { getContentSecurityPolicyNonce } from '@/lib/csp';
import { absoluteHref, baseUrl } from '@/lib/links';
import { shouldIndexSpace } from '@/lib/seo';
import { getContentTitle } from '@/lib/utils';
import { ClientContexts } from './ClientContexts';
import { RocketLoaderDetector } from './RocketLoaderDetector';
@@ -105,7 +104,7 @@ export async function generateMetadata(): Promise<Metadata> {
const customIcon = 'icon' in customization.favicon ? customization.favicon.icon : null;
return {
title: getContentTitle(space, customization, parent),
title: `${parent ? parent.title : customization.title ?? space.title}`,
generator: `GitBook (${buildVersion()})`,
metadataBase: new URL(baseUrl()),
icons: {
@@ -14,7 +14,6 @@ import {
} from '@/lib/api';
import { getEmojiForCode } from '@/lib/emojis';
import { tcls } from '@/lib/tailwind';
import { getContentTitle } from '@/lib/utils';
export const runtime = 'edge';
@@ -55,7 +54,7 @@ export async function GET(req: NextRequest) {
: space.visibility === ContentVisibility.InCollection && space.parent
? await getCollection(space.parent)
: null;
const contentTitle = getContentTitle(space, customization, parent);
const contentTitle = parent?.title ?? customization.title ?? space.title;
return new ImageResponse(
(
@@ -3,8 +3,6 @@ import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import { getContentTitle } from '@/lib/utils';
import { PageIdParams, fetchPageData } from '../../../../fetch';
export const runtime = 'edge';
@@ -33,7 +31,7 @@ export async function GET(req: NextRequest, { params }: { params: PageIdParams }
}}
>
<h2 tw="text-7xl font-bold tracking-tight text-left">
{getContentTitle(space, customization, parent)}
{parent?.title ?? customization.title ?? space.title}
</h2>
<div tw="flex flex-1">
<p tw="text-4xl">{page ? page.title : 'Not found'}</p>
+4 -22
View File
@@ -40,7 +40,6 @@ export function getContentPointer(): ContentPointer | SiteContentPointer {
if (siteId) {
const organizationId = headerSet.get('x-gitbook-content-organization');
const siteSpaceId = headerSet.get('x-gitbook-content-site-space');
const siteShareKey = headerSet.get('x-gitbook-content-site-share-key');
if (!organizationId) {
throw new Error('Missing site content headers');
}
@@ -49,7 +48,6 @@ export function getContentPointer(): ContentPointer | SiteContentPointer {
siteId,
spaceId,
siteSpaceId: siteSpaceId ?? undefined,
siteShareKey: siteShareKey ?? undefined,
organizationId,
revisionId: headerSet.get('x-gitbook-content-revision') ?? undefined,
changeRequestId: headerSet.get('x-gitbook-content-changerequest') ?? undefined,
@@ -73,14 +71,7 @@ export async function fetchSpaceData() {
const [{ space, contentTarget, pages, customization, scripts }, parentSite] = await Promise.all(
'siteId' in content
? [
getCurrentSiteData(content),
fetchParentSite({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
}),
]
? [getCurrentSiteData(content), fetchParentSite(content.organizationId, content.siteId)]
: [getSpaceData(content)],
);
@@ -111,11 +102,7 @@ export async function fetchPageData(params: PagePathParams | PageIdParams) {
const page = await resolvePage(contentTarget, pages, params);
const [parent, document] = await Promise.all([
'siteId' in content
? fetchParentSite({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
})
? fetchParentSite(content.organizationId, content.siteId)
: fetchParentCollection(space),
page?.page.documentId ? getDocument(space.id, page.page.documentId) : null,
]);
@@ -186,15 +173,10 @@ async function fetchParentCollection(space: Space) {
return { parent: collection, spaces };
}
async function fetchParentSite(args: {
organizationId: string;
siteId: string;
siteShareKey: string | undefined;
}) {
const { organizationId, siteId, siteShareKey } = args;
async function fetchParentSite(organizationId: string, siteId: string) {
const [site, siteSpaces] = await Promise.all([
getSite(organizationId, siteId),
getSiteSpaces({ organizationId, siteId, siteShareKey }),
getSiteSpaces(organizationId, siteId),
]);
const spaces: Record<string, Space> = {};
@@ -15,7 +15,7 @@ import './theme.css';
*/
export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
const { block, document, style, context } = props;
const withHighlighting = context.shouldHighlightCode(context.content?.spaceId);
const withHighlighting = context.shouldHighlightCode();
const lines = withHighlighting ? await highlight(block) : plainHighlighting(block);
const id = block.key!;
@@ -1,15 +1,5 @@
const CODE_HIGHLIGHT_BLOCK_LIMIT = 50;
/**
* Spaces where we'll always use plain highlighting.
*/
const PLAIN_HIGHLIGHTING_SPACES: string[] = [
'V9geAO9ITPi8WOYK5o0r',
'puRmcwVxGFtHph8IjXaf',
'e3jwbMOrr4RhKtZ9C0XL',
'ryjzVNizLfd6pYogN3dm',
];
/**
* Protect against memory issues when highlighting a large number of code blocks.
* This context only allows 50 code blocks per render to be highlighted.
@@ -19,11 +9,7 @@ const PLAIN_HIGHLIGHTING_SPACES: string[] = [
*/
export function createHighlightingContext() {
let count = 0;
return (spaceId?: string | undefined) => {
if (!spaceId || PLAIN_HIGHLIGHTING_SPACES.includes(spaceId)) {
return false;
}
return () => {
count += 1;
return count < CODE_HIGHLIGHT_BLOCK_LIMIT;
};
+1 -1
View File
@@ -45,7 +45,7 @@ export interface DocumentContext {
*
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
*/
shouldHighlightCode: (spaceId: string | undefined) => boolean;
shouldHighlightCode: () => boolean;
}
export interface DocumentContextProps {
+11 -39
View File
@@ -1,20 +1,18 @@
import * as gitbookAPI from '@gitbook/api';
import { DocumentBlockEmbed } from '@gitbook/api';
import Script from 'next/script';
import { Card } from '@/components/primitives';
import { api } from '@/lib/api';
import { getContentSecurityPolicyNonce } from '@/lib/csp';
import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block';
import { Caption } from './Caption';
import { IntegrationBlock } from './Integration';
export async function Embed(props: BlockProps<gitbookAPI.DocumentBlockEmbed>) {
const { block, context, ...otherProps } = props;
export async function Embed(props: BlockProps<DocumentBlockEmbed>) {
const { block } = props;
const { data: embed } = await (context.content
? api().spaces.getEmbedByUrlInSpace(context.content.spaceId, { url: block.data.url })
: api().urls.getEmbedByUrl({ url: block.data.url }));
const { data: embed } = await api().urls.getEmbedByUrl({ url: block.data.url });
return (
<Caption {...props}>
@@ -26,14 +24,13 @@ export async function Embed(props: BlockProps<gitbookAPI.DocumentBlockEmbed>) {
}}
/>
{/* We load the iframely script to resize the embed iframes dynamically */}
<Script src="https://cdn.iframe.ly/embed.js" defer async />
<Script
src="https://cdn.iframe.ly/embed.js"
defer
async
nonce={getContentSecurityPolicyNonce()}
/>
</>
) : embed.type === 'integration' ? (
<IntegrationBlock
{...otherProps}
context={context}
block={createIntegrationBlock(block.data.url, embed.integration, embed.block)}
/>
) : (
<Card
leadingIcon={
@@ -49,28 +46,3 @@ export async function Embed(props: BlockProps<gitbookAPI.DocumentBlockEmbed>) {
</Caption>
);
}
/**
* Create an integration block with an unfurl action from the GitBook Embed response.
*/
function createIntegrationBlock(
url: string,
integration: string,
block: gitbookAPI.IntegrationBlock,
): gitbookAPI.DocumentBlockIntegration {
return {
object: 'block',
type: 'integration',
isVoid: true,
data: {
integration,
block: block.id,
props: {},
action: {
action: '@link.unfurl',
url,
},
url,
},
};
}
+41 -6
View File
@@ -1,10 +1,12 @@
import IconDownload from '@geist-ui/icons/download';
import IconFileText from '@geist-ui/icons/fileText';
import IconImage from '@geist-ui/icons/image';
import IconPaperClip from '@geist-ui/icons/paperclip';
import { DocumentBlockFile } from '@gitbook/api';
import { getSimplifiedContentType } from '@/lib/files';
import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block';
import { FileIcon } from './FileIcon';
export async function File(props: BlockProps<DocumentBlockFile>) {
const { block, context, style } = props;
@@ -16,7 +18,42 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
return null;
}
const contentType = getSimplifiedContentType(file.contentType);
const contentType = (() => {
switch (file.contentType) {
case 'application/pdf':
case 'application/x-pdf':
return 'pdf';
case 'image/png':
case 'image/jpeg':
case 'image/gif':
case 'image/webp':
case 'image/tiff':
case 'image/svg+xml':
return 'image';
case 'application/zip':
case 'application/x-7z-compressed':
case 'application/x-zip-compressed':
case 'application/x-tar':
case 'application/x-rar-compressed':
case 'application/vnd.rar':
return 'archive';
default:
return null;
}
})();
const icon = (() => {
switch (contentType) {
case 'pdf':
return <IconFileText />;
case 'image':
return <IconImage />;
case 'archive':
return <IconPaperClip />;
default:
return <IconDownload />;
}
})();
return (
<a
@@ -66,9 +103,7 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
'dark:border-light/2',
)}
>
<div className={tcls('*:w-5', '*:h-5', '*:stroke-primary')}>
<FileIcon contentType={contentType} />
</div>
<div className={tcls('*:w-5', '*:h-5', '*:stroke-primary')}>{icon}</div>
<div
className={tcls(
'text-xs',
-24
View File
@@ -1,24 +0,0 @@
import IconDownload from '@geist-ui/icons/download';
import IconFileText from '@geist-ui/icons/fileText';
import IconImage from '@geist-ui/icons/image';
import IconPaperClip from '@geist-ui/icons/paperclip';
import { SimplifiedFileType } from '@/lib/files';
/**
* Render an appropriate icon for a file.
*/
export function FileIcon(props: { contentType: SimplifiedFileType | null }) {
const { contentType } = props;
switch (contentType) {
case 'pdf':
return <IconFileText />;
case 'image':
return <IconImage />;
case 'archive':
return <IconPaperClip />;
default:
return <IconDownload />;
}
}
@@ -70,7 +70,6 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
const initialInput = {
componentId: block.data.block,
props: block.data.props,
action: block.data.action,
context: contentKitContext,
};
+74 -82
View File
@@ -1,123 +1,115 @@
.light .scalar-modal-layout,
.light .scalar {
--scalar-color-1: color-mix(
--theme-color-1: color-mix(
in srgb,
rgb(var(--primary-base-300, 180 180 180)),
rgb(var(--dark-base, 23 23 23)) 96%
);
--scalar-color-2: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.72));
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
--scalar-color-accent: #007d9c;
--theme-color-2: color-mix(in srgb, var(--theme-color-1), transparent calc(100% - 100% * 0.72));
--theme-color-3: color-mix(in srgb, var(--theme-color-1), transparent calc(100% - 100% * 0.4));
--theme-color-accent: #007d9c;
--scalar-background-1: rgb(var(--light-base, 255 255 255));
--scalar-background-2: color-mix(
--theme-background-1: rgb(var(--light-base, 255 255 255));
--theme-background-2: color-mix(
in srgb,
rgb(var(--primary-base-800, 30 30 30)),
var(--scalar-background-1) 96%
var(--theme-background-1) 96%
);
--scalar-background-3: color-mix(
--theme-background-3: color-mix(
in srgb,
rgb(var(--primary-base-800, 30 30 30)),
var(--scalar-background-1) 90%
var(--theme-background-1) 90%
);
--scalar-background-accent: #007d9c1f;
--scalar-code-language-color-supersede: var(--scalar-color-1);
--scalar-code-languages-background-supersede: var(--scalar-background-1);
--scalar-border-color: color-mix(
--theme-background-accent: #007d9c1f;
--theme-code-language-color-supersede: var(--theme-color-1);
--theme-code-languages-background-supersede: var(--theme-background-1);
--theme-border-color: color-mix(
in srgb,
var(--scalar-color-1),
var(--theme-color-1),
transparent calc(100% - 100% * 0.08)
);
--scalar-color-green: #0a6355;
--scalar-color-red: #dc1b19;
--scalar-color-yellow: #ffc90d;
--scalar-color-blue: rgb(var(--primary-color-500, 52 109 219));
--scalar-color-orange: #ff8d4d;
--scalar-color-purple: #8250df;
--theme-color-green: #0a6355;
--theme-color-red: #dc1b19;
--theme-color-yellow: #ffc90d;
--theme-color-blue: rgb(var(--primary-color-500, 52 109 219));
--theme-color-orange: #ff8d4d;
--theme-color-purple: #8250df;
--scalar-scrollbar-color: rgba(255, 255, 255, 0.24);
--scalar-scrollbar-color-active: rgba(255, 255, 255, 0.48);
--scalar-button-1: rgb(49 53 56);
--scalar-button-1-color: #fff;
--scalar-button-1-hover: rgb(28 31 33);
--theme-scrollbar-color: rgba(255, 255, 255, 0.24);
--theme-scrollbar-color-active: rgba(255, 255, 255, 0.48);
}
.dark .scalar-modal-layout,
.dark .scalar {
--scalar-color-1: color-mix(
--theme-color-1: color-mix(
in srgb,
rgb(var(--primary-base-700, 70 70 70)),
rgb(var(--light-base, 255 255 255)) 100%
);
--scalar-color-2: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.64));
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
--scalar-color-accent: #50b7e0;
--theme-color-2: color-mix(in srgb, var(--theme-color-1), transparent calc(100% - 100% * 0.64));
--theme-color-3: color-mix(in srgb, var(--theme-color-1), transparent calc(100% - 100% * 0.4));
--theme-color-accent: #50b7e0;
--scalar-background-1: rgb(var(--dark-base, 22 22 22));
--scalar-background-2: color-mix(
--theme-background-1: rgb(var(--dark-base, 22 22 22));
--theme-background-2: color-mix(
in srgb,
rgb(var(--primary-base-200, 200 200 200)),
var(--scalar-background-1) 92%
var(--theme-background-1) 92%
);
--scalar-background-3: color-mix(
--theme-background-3: color-mix(
in srgb,
rgb(var(--primary-base-200, 200 200 200)),
var(--scalar-background-1) 88%
var(--theme-background-1) 88%
);
--scalar-background-accent: #8ab4f81f;
--scalar-code-languages-background-supersede: var(--scalar-background-1);
--scalar-border-color: color-mix(
--theme-background-accent: #8ab4f81f;
--theme-code-languages-background-supersede: var(--theme-background-1);
--theme-border-color: color-mix(
in srgb,
var(--scalar-color-1),
var(--theme-color-1),
transparent calc(100% - 100% * 0.08)
);
--scalar-color-green: #56b6c2;
--scalar-color-red: rgb(245 124 97);
--scalar-color-yellow: #edbe20;
--scalar-color-blue: rgb(var(--primary-color-400, 93 138 226));
--scalar-color-orange: #d19a66;
--scalar-color-purple: #5203d1;
--theme-color-green: #56b6c2;
--theme-color-red: rgb(245 124 97);
--theme-color-yellow: #edbe20;
--theme-color-blue: rgb(var(--primary-color-400, 93 138 226));
--theme-color-orange: #d19a66;
--theme-color-purple: #5203d1;
--scalar-scrollbar-color: rgba(0, 0, 0, 0.18);
--scalar-scrollbar-color-active: rgba(0, 0, 0, 0.36);
--scalar-button-1: #f6f6f6;
--scalar-button-1-color: #000;
--scalar-button-1-hover: #e7e7e7;
--theme-scrollbar-color: rgba(0, 0, 0, 0.18);
--theme-scrollbar-color-active: rgba(0, 0, 0, 0.36);
}
.scalar-modal-layout,
.scalar {
--scalar-font: initial;
--scalar-font-code: var(--font-mono);
--theme-font: initial;
--theme-font-code: var(--font-mono);
--scalar-paragraph: 16px;
--scalar-small: 14px;
--scalar-mini: 13px;
--scalar-micro: 12px;
--theme-paragraph: 16px;
--theme-small: 14px;
--theme-mini: 13px;
--theme-micro: 12px;
--scalar-bold: 600;
--scalar-semibold: 500;
--scalar-regular: 400;
--theme-bold: 600;
--theme-semibold: 500;
--theme-regular: 400;
/* Font sizes for interactive applications (not rendered text content) */
--scalar-font-size-1: 24px;
--scalar-font-size-2: 16px;
--scalar-font-size-3: 14px;
--scalar-font-size-4: 13px;
--scalar-font-size-5: 12px;
--theme-font-size-1: 24px;
--theme-font-size-2: 16px;
--theme-font-size-3: 14px;
--theme-font-size-4: 13px;
--theme-font-size-5: 12px;
--scalar-line-height-1: 32px;
--scalar-line-height-2: 24px;
--scalar-line-height-3: 20px;
--scalar-line-height-4: 18px;
--scalar-line-height-5: 16px;
--theme-line-height-1: 32px;
--theme-line-height-2: 24px;
--theme-line-height-3: 20px;
--theme-line-height-4: 18px;
--theme-line-height-5: 16px;
--scalar-app-header-height: 35px;
}
.scalar input::placeholder {
color: var(--scalar-color-3);
color: var(--theme-color-3);
}
.scalar .scalar-app-header {
width: 100%;
@@ -142,15 +134,15 @@
display: flex;
align-items: center;
background: transparent;
color: var(--scalar-color-1);
font-size: var(--scalar-small);
font-weight: var(--scalar-semibold);
color: var(--theme-color-1);
font-size: var(--theme-small);
font-weight: var(--theme-semibold);
}
.scalar-api-client__close:hover {
cursor: pointer;
}
.scalar .scalar-app {
background: var(--scalar-background-3);
background: var(--theme-background-3);
height: calc(100dvh - 100px);
max-width: 1280px;
width: 100%;
@@ -235,10 +227,10 @@
line-height: normal;
}
.scalar .scalar-app-header span {
color: var(--scalar-color-3);
color: var(--theme-color-3);
}
.scalar .scalar-app-header a {
color: var(--scalar-color-1);
color: var(--theme-color-1);
}
.scalar .scalar-app-header a:hover {
text-decoration: underline;
@@ -259,7 +251,7 @@
display: flex;
gap: 6px;
align-items: center;
color: var(--scalar-color-blue);
color: var(--theme-color-blue);
appearance: none;
outline: none;
border: none;
@@ -269,7 +261,7 @@
padding: 0 0.5rem;
}
.scalar-activate:hover .scalar-activate-button {
background: var(--scalar-background-3);
background: var(--theme-background-3);
border-radius: 3px;
}
@@ -301,12 +293,12 @@
scrollbar-color: rgba(255, 255, 255, 0.24) transparent;
}
.scalar .custom-scroll:hover::-webkit-scrollbar-thumb {
background: var(--scalar-scrollbar-color, var(--default-theme-scrollbar-color));
background: var(--theme-scrollbar-color, var(--default-theme-scrollbar-color));
background-clip: content-box;
border: 3px solid transparent;
}
.scalar .custom-scroll::-webkit-scrollbar-thumb:active {
background: var(--scalar-scrollbar-color-active, var(--default-theme-scrollbar-color-active));
background: var(--theme-scrollbar-color-active, var(--default-theme-scrollbar-color-active));
background-clip: content-box;
border: 3px solid transparent;
}
@@ -330,4 +322,4 @@
.scalar .custom-scroll {
padding-right: 12px;
}
}
}
@@ -4,9 +4,7 @@ import assertNever from 'assert-never';
import { Checkbox, Emoji } from '@/components/primitives';
import { StyledLink } from '@/components/primitives';
import { Image } from '@/components/utils';
import { getNodeFragmentByName } from '@/lib/document';
import { getSimplifiedContentType } from '@/lib/files';
import { tcls } from '@/lib/tailwind';
import { filterOutNullable } from '@/lib/typescript';
@@ -14,7 +12,6 @@ import { TableRecordKV } from './Table';
import { getColumnAlignment } from './utils';
import { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
import { FileIcon } from '../FileIcon';
/**
* Render the value for a column in a record.
@@ -128,41 +125,11 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
return (
<Tag className={tcls('text-base')}>
{files.filter(filterOutNullable).map((ref, index) => {
const contentType = ref.file
? getSimplifiedContentType(ref.file.contentType)
: null;
return (
<StyledLink
key={index}
href={ref.href}
target="_blank"
style={['flex', 'flex-row', 'items-center', 'gap-2']}
>
{contentType === 'image' ? (
<Image
style={['max-h-[1lh]', 'h-[1lh]']}
alt={ref.text}
sizes={[{ width: 24 }]}
sources={{
light: {
src: ref.href,
size: {
width: 24,
height: 24,
},
},
}}
priority="lazy"
/>
) : (
<FileIcon contentType={contentType} />
)}
{ref.text}
</StyledLink>
);
})}
{files.filter(filterOutNullable).map((file, index) => (
<StyledLink key={index} href={file.href}>
{file.text}
</StyledLink>
))}
</Tag>
);
case 'content-ref': {
+1 -2
View File
@@ -11,7 +11,6 @@ import { HeaderMobileMenu } from '@/components/Header/HeaderMobileMenu';
import { Image } from '@/components/utils';
import { absoluteHref } from '@/lib/links';
import { tcls } from '@/lib/tailwind';
import { getContentTitle } from '@/lib/utils';
import { Link } from '../primitives';
@@ -146,7 +145,7 @@ function LogoFallback(props: HeaderLogoProps) {
: 'text-header-link',
)}
>
{getContentTitle(space, customization, parent)}
{parent ? parent.title : customization.title ?? space.title}
</h1>
</>
);
+1 -5
View File
@@ -76,11 +76,7 @@ export async function searchParentContent(
api.searchParentContent(parent.id, query),
parent.object === 'collection' ? api.getCollectionSpaces(parent.id) : null,
parent.object === 'site' && 'organizationId' in pointer
? api.getSiteSpaces({
organizationId: pointer.organizationId,
siteId: parent.id,
siteShareKey: pointer.siteShareKey,
})
? api.getSiteSpaces(pointer.organizationId, parent.id)
: null,
]);
@@ -75,7 +75,7 @@ export function TableOfContents(props: {
'dark:group-hover:[&::-webkit-scrollbar-thumb]:bg-light/3',
'navigation-open:flex', // can be auto height animated as such https://stackoverflow.com/a/76944290
'lg:-ml-5',
customization.trademark.enabled ? 'lg:pb-20' : 'lg:pb-4',
customization.trademark.enabled ? 'lg:pb-16' : 'lg:pb-4',
)}
>
<PagesList
+3 -7
View File
@@ -84,20 +84,16 @@ export function TrademarkLink(props: {
'flex-row',
'items-center',
'hover:bg-dark/1',
'bg-light',
'dark:bg-dark',
'px-4',
'py-4',
'rounded-lg',
'py-2',
'rounded-md',
'straight-corners:rounded-none',
'hover:backdrop-blur-sm',
'lg:ring-0',
'tracking-[-0.016em]',
'dark:hover:bg-light/1',
'dark:ring-light/1',
'border',
'border-dark/2',
'dark:border-light/2',
'dark:font-normal',
)}
>
<IconLogo className={tcls('w-5', 'h-5', 'mr-3')} />
+3 -6
View File
@@ -1,16 +1,14 @@
import { ClassValue, tcls } from '@/lib/tailwind';
import { tcls } from '@/lib/tailwind';
import { Link, LinkProps } from '../primitives/Link';
/**
* Styled version of Link component.
*/
export function StyledLink(props: Omit<LinkProps, 'style'> & { style?: ClassValue }) {
const { style, ...rest } = props;
export function StyledLink(props: LinkProps) {
return (
<Link
{...rest}
{...props}
className={tcls(
'underline',
'underline-offset-2',
@@ -18,7 +16,6 @@ export function StyledLink(props: Omit<LinkProps, 'style'> & { style?: ClassValu
'text-primary',
'hover:text-primary-700',
'transition-colors',
style,
)}
>
{props.children}
-52
View File
@@ -1,52 +0,0 @@
export const de = {
locale: 'de',
powered_by_gitbook: 'Bereitgestellt von GitBook',
switch_to_dark_theme: 'Zum dunklen Modus wechseln',
switch_to_light_theme: 'Zum hellen Modus wechseln',
switch_to_system_theme: 'Zum Systemmodus wechseln',
search: 'Suche',
search_or_ask: 'Fragen oder Suchen',
search_input_placeholder: 'Inhalt durchsuchen',
search_ask_input_placeholder: 'Inhalt durchsuchen oder eine Frage stellen',
search_no_results: 'Keine Ergebnisse für "${1}".',
search_scope_space: 'Nur in ${1}',
search_scope_all: 'Alle Inhalte',
search_ask: 'Fragen "${1}"',
search_ask_sources: 'Quellen',
search_ask_no_answer: 'Es konnte keine Antwort auf Ihre Frage gefunden werden, versuchen Sie es mit einer anderen Frage.',
search_ask_error: 'Etwas ist schief gelaufen. Bitte versuchen Sie es später noch einmal.',
on_this_page: 'Auf dieser Seite',
next_page: 'Nächste',
previous_page: 'Vorherige',
page_last_modified: 'Zuletzt aktualisiert ${1}',
was_this_helpful: 'War das hilfreich?',
was_this_helpful_positive: 'Ja, das war es!',
was_this_helpful_neutral: 'Nicht sicher',
was_this_helpful_negative: 'Nein',
was_this_helpful_thank_you: 'Danke!',
annotation_button_label: 'Kommentar öffnen',
code_copied: 'Kopiert!',
code_copy: 'Kopieren',
table_of_contents_button_label: 'Inhaltsverzeichnis öffnen',
cookies_title: 'Cookies',
cookies_prompt:
'Diese Website verwendet Cookies, um ihre Dienste bereitzustellen und den Datenverkehr zu analysieren. Durch die Nutzung dieser Website akzeptieren Sie die ${1}.',
cookies_prompt_privacy: 'Datenschutzrichtlinie',
cookies_accept: 'Akzeptieren',
cookies_reject: 'Ablehnen',
cookies_close: 'Schließen',
edit_on_git: 'Bearbeiten auf ${1}',
notfound_title: 'Seite nicht gefunden',
notfound: 'Die gesuchte Seite existiert nicht.',
unexpected_error_title: 'Ein Fehler ist aufgetreten',
unexpected_error: 'Entschuldigung, ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.',
unexpected_error_retry: 'Erneut versuchen',
pdf_download: 'Als PDF exportieren',
pdf_goback: 'Zurück zum Inhalt',
pdf_print: 'Drucken oder als PDF speichern',
pdf_page_of: '${1} von ${2}',
pdf_mode_only_page: 'Nur diese Seite',
pdf_mode_all: 'Alle Seiten',
pdf_limit_reached: 'Das PDF konnte für ${1} Seiten nicht generiert werden, Generierung wurde bei ${2} gestoppt.',
pdf_limit_reached_continue: 'Mit ${1} weiteren Seiten erweitern.',
};
-4
View File
@@ -1,11 +1,9 @@
import { CustomizationLocale } from '@gitbook/api';
import { de } from './de';
import { en } from './en';
import { es } from './es';
import { fr } from './fr';
import { ja } from './ja';
import { pt_br } from './pt-br';
import { TranslationLanguage } from './types';
import { zh } from './zh';
@@ -14,11 +12,9 @@ export * from './types';
export const languages: {
[locale in CustomizationLocale]: TranslationLanguage;
} = {
de,
en,
fr,
es,
zh,
ja,
'pt-br': pt_br,
};
-55
View File
@@ -1,55 +0,0 @@
export const pt_br = {
locale: 'pt-br',
powered_by_gitbook: 'Powered by GitBook',
switch_to_dark_theme: 'Mudar para modo escuro',
switch_to_light_theme: 'Mudar para modo claro',
switch_to_system_theme: 'Mudar para configuração do sistema',
search: 'Busca',
search_or_ask: 'Perguntar ou buscar',
search_input_placeholder: 'Buscar conteúdo',
search_ask_input_placeholder: 'Buscar conteúdo ou fazer uma pergunta',
search_no_results: 'Sem resultados para "${1}".',
search_scope_space: 'Somente em ${1}',
search_scope_all: 'Todo o conteúdo',
search_ask: 'Perguntar "${1}"',
search_ask_sources: 'Fontes',
search_ask_no_answer:
'Nenhuma resposta foi encontrada para sua pergunta, tente outra pergunta.',
search_ask_error: 'Algo deu errado. Por favor tente novamente mais tarde.',
on_this_page: 'Nesta página',
next_page: 'Próximo',
previous_page: 'Anterior',
page_last_modified: 'Atualizado ${1}',
was_this_helpful: 'Isto foi útil?',
was_this_helpful_positive: 'Sim, foi!',
was_this_helpful_neutral: 'Não sei',
was_this_helpful_negative: 'Não',
was_this_helpful_thank_you: 'Obrigado!',
annotation_button_label: 'Abrir anotação',
code_copied: 'Copiado!',
code_copy: 'Copiar',
table_of_contents_button_label: 'Abrir o índice',
cookies_title: 'Cookies',
cookies_prompt:
'Este site usa cookies para entregar suas funcionalidades e analizar o tráfego. Ao navegar neste site, você aceita a ${1}.',
cookies_prompt_privacy: 'política de privacidade',
cookies_accept: 'Aceitar',
cookies_reject: 'Rejeitar',
cookies_close: 'Fechar',
edit_on_git: 'Editar no ${1}',
notfound_title: 'Página não encontrada',
notfound: 'A página que você está procurando não existe.',
unexpected_error_title: 'Aconteceu um erro',
unexpected_error:
'Desculpe, aconteceu um erro inesperado. Por favor tente novamente mais tarde.',
unexpected_error_retry: ' Tentar novamente',
pdf_download: 'Exportar como PDF',
pdf_goback: 'Voltar ao conteúdo',
pdf_print: 'Imprimir ou salvar como PDF',
pdf_page_of: '${1} de ${2}',
pdf_mode_only_page: 'Somente esta página',
pdf_mode_all: 'Todas as páginas',
pdf_limit_reached:
'Não foi possível gerar o PDF para ${1} páginas, generation stopped at ${2}.',
pdf_limit_reached_continue: 'Extender com mais ${1} páginas.',
};
+10 -38
View File
@@ -47,11 +47,6 @@ export interface SiteContentPointer extends ContentPointer {
* ID of the siteSpace can be undefined when rendering in multi-id mode (for site previews)
*/
siteSpaceId: string | undefined;
/**
* Share key of the site that was used in lookup. Only set for `multi` and `multi-path` modes
* where an URL with the share-link key is involved in the lookup/resolution.
*/
siteShareKey: string | undefined;
}
/**
@@ -243,7 +238,6 @@ export const getPublishedContentByUrl = cache(
};
return {
tags: [
...parsed.tags,
getAPICacheTag({
tag: 'url',
hostname: parsedURL.hostname,
@@ -616,7 +610,6 @@ const getSiteSpaceCustomizationFromAPI = cache(
organizationId,
siteId,
siteSpaceId,
{},
{
signal: options.signal,
...noCacheFetchOptions,
@@ -640,15 +633,10 @@ const getSiteSpaceCustomizationFromAPI = cache(
const getSiteCustomizationFromAPI = cache(
'api.getSiteCustomizationById',
async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await api().orgs.getSiteCustomizationById(
organizationId,
siteId,
{},
{
signal: options.signal,
...noCacheFetchOptions,
},
);
const response = await api().orgs.getSiteCustomizationById(organizationId, siteId, {
signal: options.signal,
...noCacheFetchOptions,
});
return cacheResponse(response, {
revalidateBefore: 60 * 60,
tags: [
@@ -742,34 +730,18 @@ export const getSite = cache(
*/
export const getSiteSpaces = cache(
'api.getSiteSpaces',
async (
args: {
organizationId: string;
siteId: string;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined;
},
options: CacheFunctionOptions,
) => {
async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await getAll((params) =>
api().orgs.listSiteSpaces(
args.organizationId,
args.siteId,
{
...params,
...(args.siteShareKey ? { shareKey: args.siteShareKey } : {}),
},
{
...noCacheFetchOptions,
signal: options.signal,
},
),
api().orgs.listSiteSpaces(organizationId, siteId, params, {
...noCacheFetchOptions,
signal: options.signal,
}),
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
data: response.data.items.map((siteSpace) => siteSpace),
tags: [getAPICacheTag({ tag: 'site', site: args.siteId })],
tags: [getAPICacheTag({ tag: 'site', site: siteId })],
});
},
);
+1 -1
View File
@@ -202,7 +202,7 @@ export function cache<Args extends any[], Result>(
if (savedEntry.meta.revalidatesAt && savedEntry.meta.revalidatesAt < Date.now()) {
// Revalidate in the background
await waitUntil(revalidate(key, undefined, ...args));
waitUntil(revalidate(key, undefined, ...args));
}
return savedEntry.data;
+1 -5
View File
@@ -26,12 +26,9 @@ export function parseCacheResponse(response: Response): {
const cacheControlHeader = response.headers.get('cache-control');
const cacheControl = cacheControlHeader ? parseCacheControl(cacheControlHeader) : null;
const cacheTagHeader = response.headers.get('x-gitbook-cache-tag');
const tags = !cacheTagHeader ? [] : cacheTagHeader.split(',');
const entry = {
ttl: 60 * 60 * 24,
tags,
tags: [],
};
if (cacheControl && cacheControl['max-age']) {
@@ -53,7 +50,6 @@ export function cacheResponse<Result, DefaultData = Result>(
return {
ttl: defaultEntry.ttl ?? parsed.ttl,
tags: [...(defaultEntry.tags ?? []), ...parsed.tags],
revalidateBefore: defaultEntry.revalidateBefore,
// @ts-ignore
data: defaultEntry.data ?? response.data,
};
-25
View File
@@ -1,25 +0,0 @@
export type SimplifiedFileType = 'image' | 'pdf' | 'archive';
/**
* Get a simplified content type for the given mime type.
*/
export function getSimplifiedContentType(mimeType: string): SimplifiedFileType | null {
if (mimeType.startsWith('image')) {
return 'image';
}
switch (mimeType) {
case 'application/pdf':
case 'application/x-pdf':
return 'pdf';
case 'application/zip':
case 'application/x-7z-compressed':
case 'application/x-zip-compressed':
case 'application/x-tar':
case 'application/x-rar-compressed':
case 'application/vnd.rar':
return 'archive';
default:
return null;
}
}
+1 -2
View File
@@ -3,7 +3,6 @@ import 'server-only';
import { noCacheFetchOptions } from '@/lib/cache/http';
import { rootUrl } from './links';
import { getImageAPIUrl } from './urls';
export interface CloudflareImageJsonFormat {
width: number;
@@ -77,7 +76,7 @@ export async function getResizedImageURL(
return (options) => {
const url = new URL('/~gitbook/image', rootUrl());
url.searchParams.set('url', getImageAPIUrl(input));
url.searchParams.set('url', input);
if (options.width) {
url.searchParams.set('width', options.width.toString());
-18
View File
@@ -65,21 +65,3 @@ export function getPDFUrlSearchParams(
return searchParams;
}
/**
* Because of a bug in Cloudflare, 127.0.0.1 is replaced by localhost.
* We protect against it by converting to a special token, and then parsing
* the token in the image API.
*/
const GITBOOK_LOCALHOST_TOKEN = '$GITBOOK_LOCALHOST$';
/**
* Prepare a URL for the GitBook Open Image API.
*/
export function getImageAPIUrl(url: string): string {
return url.replaceAll('127.0.0.1', GITBOOK_LOCALHOST_TOKEN);
}
export function parseImageAPIURL(url: string): string {
return url.replaceAll(GITBOOK_LOCALHOST_TOKEN, '127.0.0.1');
}
-25
View File
@@ -1,25 +0,0 @@
import {
Collection,
CustomizationSettings,
Site,
SiteCustomizationSettings,
Space,
} from '@gitbook/api';
/**
* Get the title to display for a content.
*/
export function getContentTitle(
space: Space,
customization: CustomizationSettings | SiteCustomizationSettings,
parent: Site | Collection | null,
) {
// When we are rendering a site, always give priority to the customization title first
// and then fallback to the site title
if (parent?.object === 'site') {
return customization.title ?? parent.title ?? space.title;
}
// Otherwise the legacy behavior is not changed to avoid regressions
return parent ? parent.title : customization.title ?? space.title;
}
+4 -21
View File
@@ -2,7 +2,6 @@ import { it, describe, expect } from 'bun:test';
import { NextRequest } from 'next/server';
import {
VisitorAuthCookieValue,
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
getVisitorAuthToken,
@@ -18,18 +17,14 @@ describe('getVisitorAuthToken', () => {
const request = nextRequest('https://example.com', {
[getVisitorAuthCookieName('/')]: { value: getVisitorAuthCookieValue('/', '123') },
});
const visitorAuth = getVisitorAuthToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123');
expect(getVisitorAuthToken(request, request.nextUrl)).toEqual('123');
});
it('should return the token from the cookie root basepath for a sub-path', () => {
const request = nextRequest('https://example.com/hello/world', {
[getVisitorAuthCookieName('/')]: { value: getVisitorAuthCookieValue('/', '123') },
});
const visitorAuth = getVisitorAuthToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123');
expect(getVisitorAuthToken(request, request.nextUrl)).toEqual('123');
});
it('should return the closest token from the path', () => {
@@ -39,9 +34,7 @@ describe('getVisitorAuthToken', () => {
value: getVisitorAuthCookieValue('/hello/', '123'),
},
});
const visitorAuth = getVisitorAuthToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123');
expect(getVisitorAuthToken(request, request.nextUrl)).toEqual('123');
});
it('should return the token from the cookie in a collection type url', () => {
@@ -50,9 +43,7 @@ describe('getVisitorAuthToken', () => {
value: getVisitorAuthCookieValue('/hello/v/space1/', '123'),
},
});
const visitorAuth = getVisitorAuthToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123');
expect(getVisitorAuthToken(request, request.nextUrl)).toEqual('123');
});
it('should return undefined if no cookie and no query param', () => {
@@ -61,14 +52,6 @@ describe('getVisitorAuthToken', () => {
});
});
function assertVisitorAuthCookieValue(value: unknown): asserts value is VisitorAuthCookieValue {
if (value && typeof value === 'object' && 'token' in value) {
return;
}
throw new Error('Expected a VisitorAuthCookieValue');
}
function nextRequest(url: string, cookies: Record<string, { value: string }> = {}) {
const nextUrl = new URL(url);
// @ts-ignore
+11 -20
View File
@@ -16,10 +16,7 @@ export type VisitorAuthCookieValue = {
* Get the visitor authentication token for the request. This token can either be in the
* query parameters or stored as a cookie.
*/
export function getVisitorAuthToken(
request: NextRequest,
url: URL,
): string | VisitorAuthCookieValue | undefined {
export function getVisitorAuthToken(request: NextRequest, url: URL): string | undefined {
return url.searchParams.get(VISITOR_AUTH_PARAM) ?? getVisitorAuthTokenFromCookies(request, url);
}
@@ -71,10 +68,7 @@ function getUrlBasePathCombinations(url: URL): string[] {
* checking all cookies for a matching "visitor authentication cookie" and returning the
* best possible match for the current URL.
*/
function getVisitorAuthTokenFromCookies(
request: NextRequest,
url: URL,
): VisitorAuthCookieValue | undefined {
function getVisitorAuthTokenFromCookies(request: NextRequest, url: URL): string | undefined {
const urlBasePaths = getUrlBasePathCombinations(url);
// Try to find a visitor authentication token for the current URL. The request
// for the content could be hosted on a base path like `/foo/v/bar` or `/foo` or just `/`
@@ -96,17 +90,14 @@ function getVisitorAuthTokenFromCookies(
function findVisitorAuthCookieForBasePath(
request: NextRequest,
basePath: string,
): VisitorAuthCookieValue | undefined {
return Array.from(request.cookies).reduce<VisitorAuthCookieValue | undefined>(
(acc, [name, cookie]) => {
if (name === getVisitorAuthCookieName(basePath)) {
const value = JSON.parse(cookie.value) as VisitorAuthCookieValue;
if (value.basePath === basePath) {
acc = value;
}
): string | undefined {
return Array.from(request.cookies).reduce<string | undefined>((acc, [name, cookie]) => {
if (name === getVisitorAuthCookieName(basePath)) {
const value = JSON.parse(cookie.value) as VisitorAuthCookieValue;
if (value.basePath === basePath) {
acc = value.token;
}
return acc;
},
undefined,
);
}
return acc;
}, undefined);
}
+23 -56
View File
@@ -22,7 +22,6 @@ import { buildVersion } from '@/lib/build';
import { createContentSecurityPolicyNonce, getContentSecurityPolicy } from '@/lib/csp';
import { getURLLookupAlternatives, normalizeURL } from '@/lib/middleware';
import {
VisitorAuthCookieValue,
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
getVisitorAuthToken,
@@ -80,7 +79,6 @@ interface ContentAPITokenPayload {
spaces: string[];
collection?: string;
site?: string;
siteSpace?: string;
}
/**
@@ -208,11 +206,7 @@ export async function middleware(request: NextRequest) {
if (resolved.siteSpace) {
headers.set('x-gitbook-content-site-space', resolved.siteSpace);
}
if (resolved.shareKey) {
headers.set('x-gitbook-content-site-share-key', resolved.shareKey);
}
}
if (resolved.revision) {
headers.set('x-gitbook-content-revision', resolved.revision);
}
@@ -265,7 +259,7 @@ export async function middleware(request: NextRequest) {
);
} else {
if (resolved.cacheMaxAge) {
const cacheControl = `public, max-age=0, s-maxage=${resolved.cacheMaxAge}, stale-if-error=0`;
const cacheControl = `public, max-age=60, s-maxage=${resolved.cacheMaxAge}, stale-while-revalidate=60, stale-if-error=0`;
if (
process.env.GITBOOK_OUTPUT_CACHE === 'true' &&
@@ -490,15 +484,15 @@ async function lookupSpaceInMultiIdMode(request: NextRequest, url: URL): Promise
};
}
const { organization, site, siteSpace } = jwt.decode(apiToken) as ContentAPITokenPayload;
const decoded = jwt.decode(apiToken) as ContentAPITokenPayload;
const siteLookupResult =
typeof organization === 'string' && organization && typeof site === 'string' && site
? {
organization,
site,
...(typeof siteSpace === 'string' && siteSpace ? { siteSpace } : {}),
}
typeof decoded.site === 'string' &&
decoded.site &&
typeof decoded.organization === 'string' &&
decoded.organization
? { site: decoded.site, organization: decoded.organization }
: {};
return {
space: spaceId,
changeRequest: changeRequestId,
@@ -593,7 +587,7 @@ async function lookupSpaceInMultiPathMode(request: NextRequest, url: URL): Promi
*/
async function lookupSpaceByAPI(
lookupURL: URL,
visitorAuthToken: ReturnType<typeof getVisitorAuthToken>,
visitorAuthToken: string | undefined,
): Promise<LookupResult> {
const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url);
@@ -603,17 +597,9 @@ async function lookupSpaceByAPI(
);
const result = await race(lookup.urls, async (alternative, { signal }) => {
const data = await getPublishedContentByUrl(
alternative.url,
typeof visitorAuthToken === 'undefined'
? undefined
: typeof visitorAuthToken === 'string'
? visitorAuthToken
: visitorAuthToken.token,
{
signal,
},
);
const data = await getPublishedContentByUrl(alternative.url, visitorAuthToken, {
signal,
});
if ('error' in data) {
if (alternative.primary) {
@@ -664,12 +650,7 @@ async function lookupSpaceByAPI(
cacheMaxAge: data.cacheMaxAge,
cacheTags: data.cacheTags,
...('site' in data
? {
site: data.site,
siteSpace: data.siteSpace,
organization: data.organization,
shareKey: data.shareKey,
}
? { site: data.site, siteSpace: data.siteSpace, organization: data.organization }
: {}),
} as PublishedContentWithCache;
});
@@ -690,36 +671,22 @@ async function lookupSpaceByAPI(
*/
function getLookupResultForVisitorAuth(
basePath: string,
visitorAuthToken: string | VisitorAuthCookieValue,
visitorAuthToken: string,
): Partial<LookupResult> {
return {
// No caching for content served with visitor auth
cacheMaxAge: undefined,
cacheTags: [],
cookies: {
/**
* If the visitorAuthToken has been retrieved from a cookie, we set it back only
* if the basePath matches the current one. This is to avoid setting cookie for
* different base paths.
*/
...(typeof visitorAuthToken === 'string' || visitorAuthToken.basePath === basePath
? {
[getVisitorAuthCookieName(basePath)]: {
value: getVisitorAuthCookieValue(
basePath,
typeof visitorAuthToken === 'string'
? visitorAuthToken
: visitorAuthToken.token,
),
options: {
httpOnly: true,
sameSite: 'none',
secure: process.env.NODE_ENV === 'production',
maxAge: 7 * 24 * 60 * 60,
},
},
}
: {}),
[getVisitorAuthCookieName(basePath)]: {
value: getVisitorAuthCookieValue(basePath, visitorAuthToken),
options: {
httpOnly: true,
sameSite: 'none',
secure: process.env.NODE_ENV === 'production',
maxAge: 7 * 24 * 60 * 60,
},
},
},
};
}