Compare commits

..

40 Commits

Author SHA1 Message Date
Samy Pessé 13514bf6fa Version Packages (#2907)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-03-04 13:42:32 +01:00
Samy Pessé 05ffd0e321 Proper data cache tagging for computed content (#2915) 2025-03-04 12:26:09 +01:00
Samy Pessé 701eaad92a Fix use of server actions with proxied domains by using middleware (#2913) 2025-03-04 10:00:08 +01:00
Greg Bergé c66ef5dd10 Fix OpenAPI tabs selection (#2914) 2025-03-03 21:10:24 +00:00
Greg Bergé f774f9b3a0 Fix all tabs behaviour in OpenAPI blocks (#2912) 2025-03-03 17:11:54 +00:00
Samy Pessé 29dc7ccb1a Fix next.js configuration for serverActions 2025-03-03 17:05:46 +01:00
Samy Pessé 80237c34f9 Allow all origins (including sub-domains) for server actions 2025-03-03 16:54:16 +01:00
Samy Pessé 979233c5c0 Allow all origins for serverActions in v2 2025-03-03 16:21:05 +01:00
Samy Pessé 2f03e6acee Define GITBOOK_URL as serverActions.allowedOrigins (#2911) 2025-03-03 15:24:31 +01:00
Greg Bergé c492f09a19 Fix outline not visible on OpenAPI blocks (#2910) 2025-03-03 14:56:19 +01:00
Greg Bergé 2c3af5e73c Improve scrolling with lot of highlighted blocks (#2909) 2025-03-03 13:47:30 +00:00
Samy Pessé 6597f8508d V2: search and ask AI (#2889) 2025-03-03 11:53:32 +01:00
Nolann B. 8beb5d6bcf Add input elements to ContentKit (#2882) 2025-02-28 17:50:20 +00:00
Greg Bergé 53f5dbea26 Fix typing of shouldIgnoreEntity (#2906) 2025-02-28 17:38:58 +00:00
Samy Pessé 725952a106 Version Packages (#2881)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-02-28 17:22:32 +00:00
Greg Bergé 3319375e9a Support OpenAPI operation block (#2902) 2025-02-28 18:12:08 +01:00
spastorelli c5a4619020 Fix multi-id/preview mode not using context id for api cache calls (#2905) 2025-02-28 18:04:16 +01:00
Greg Bergé 989fc69abe Format package.json after running changeset (#2904) 2025-02-28 15:56:44 +00:00
Greg Bergé 0924259217 Expose OpenAPI helper shouldIgnoreEntity (#2903) 2025-02-28 16:22:20 +01:00
Taran Vohra 05affac34f Add support for proxy sites using x-gitbook-url in v2 (#2901) 2025-02-28 20:03:05 +05:30
Samy Pessé 453a459566 Fix content ref resolution for pages of other spaces (#2900) 2025-02-28 13:00:54 +01:00
Nolann B. 722f02ea09 Fix recursion in OpenAPISchemaAlternative (#2892) 2025-02-28 10:07:56 +00:00
Samy Pessé 5bcea2fe3b Fix signature verification with image resizing on v1 (#2899) 2025-02-28 10:36:10 +01:00
Samy Pessé 73afd1f5d0 Improve error message for image resizing (#2898) 2025-02-28 10:23:17 +01:00
Greg Bergé 9b8a0d3e54 Fix CI tests (#2897) 2025-02-28 10:14:09 +01:00
Samy Pessé 75bd98d66c V2: robots.txt, sitemap.xml, image resizing, etc (#2895) 2025-02-28 09:52:56 +01:00
Taran Vohra 9b914d10bd Fix getProxyModeBasePath (#2896) 2025-02-28 12:27:25 +05:30
Brett Jephson 3e11678d8d fix: section groups went missing (#2891) 2025-02-28 00:00:39 +01:00
Samy Pessé 6e03638130 Remove loading.tsx for static rendering in v2 (#2894) 2025-02-27 18:23:06 +01:00
Greg Bergé 23f884efb7 Fix the fonts display on the site (#2893) 2025-02-27 17:27:17 +01:00
Taran Vohra 2ae76f999b Change how a site in proxy mode is resolved (#2890) 2025-02-27 21:43:29 +05:30
Samy Pessé 685325cdc7 Deploy v2 to staging from main using a composite action (#2888) 2025-02-27 11:12:02 +01:00
Samy Pessé ab132eadb7 Cache OpenAPI using next "use cache" for v2 (#2887) 2025-02-27 09:39:08 +01:00
Samy Pessé 14504e43b5 V2: embeds and CSP (#2885) 2025-02-27 08:44:32 +01:00
Taran Vohra 4ed79574e8 change proxy mode site lookup url (#2886) 2025-02-27 12:38:55 +05:30
Samy Pessé 31bcd1a386 Improve detection of code path not supported in v2, add visual tests (#2884) 2025-02-26 20:18:38 +01:00
Samy Pessé 270e5ef7ad Improve linking to other sections/variants in development (#2883) 2025-02-26 19:14:27 +01:00
Samy Pessé 1f4733355e Remove eslint/prettier and switch to biome (#2880) 2025-02-26 17:59:34 +01:00
Zeno Kapitein 027a859ef4 Add link styles (#2861) 2025-02-26 13:03:14 +00:00
Samy Pessé 59f50eaee7 Fix production deployments to Vercel (#2879) 2025-02-26 13:47:24 +01:00
402 changed files with 5733 additions and 4907 deletions
-1
View File
@@ -1 +0,0 @@
1.2.1
@@ -0,0 +1,58 @@
name: 'Deploy vercel'
description: 'Deploy GitBook to Vercel'
inputs:
vercel-org:
description: 'Vercel organization'
required: true
vercel-project:
description: 'Vercel project'
required: true
vercel-token:
description: 'Vercel token'
required: true
environment:
description: 'Environment to deploy to'
required: true
outputs:
deployment-url:
description: "Deployment URL"
value: ${{ steps.deploy.outputs.deployment-url }}
runs:
using: 'composite'
steps:
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
shell: bash
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Sets env vars for environment
shell: bash
run: |
echo "VERCEL_ENVIRONMENT=${{ inputs.environment }}" >> $GITHUB_ENV
- name: Pull Vercel Environment Information
run: bun run vercel pull --yes --environment=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }}
shell: bash
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
- name: Build Project Artifacts
run: bun run vercel build --target=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }}
shell: bash
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
- name: Deploy Project Artifacts to Vercel
id: deploy
shell: bash
run: |
DEPLOYMENT_URL=$(bun run vercel deploy --prebuilt --target=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }})
echo "deployment-url=$DEPLOYMENT_URL" >> "$GITHUB_OUTPUT"
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
- name: Outputs
shell: bash
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
+1 -1
View File
@@ -15,4 +15,4 @@ runs:
- name: Setup bun - name: Setup bun
uses: oven-sh/setup-bun@v2 uses: oven-sh/setup-bun@v2
with: with:
bun-version-file: '.bun-version' bun-version-file: 'package.json'
+79 -69
View File
@@ -87,49 +87,41 @@ jobs:
statuses: write statuses: write
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup Bun - name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Sets env vars for production
run: |
echo "VERCEL_ENVIRONMENT=production" >> $GITHUB_ENV
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
echo "GITBOOK_URL=https://open-2v.gitbook.com" >> $GITHUB_ENV
echo "GITBOOK_ASSETS_PREFIX=https://static-2v.gitbook.com" >> $GITHUB_ENV
if: startsWith(github.ref, 'refs/heads/main')
- name: Sets env vars for preview
run: |
echo "VERCEL_ENVIRONMENT=preview" >> $GITHUB_ENV
echo "SENTRY_ENVIRONMENT=preview" >> $GITHUB_ENV
if: 1 && !startsWith(github.ref, 'refs/heads/main')
- name: Pull Vercel Environment Information
run: bun run vercel pull --yes --environment=$VERCEL_ENVIRONMENT --token=${{ secrets.VERCEL_TOKEN }}
- name: Build Project Artifacts
run: bun run vercel build --token=${{ secrets.VERCEL_TOKEN }}
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
SENTRY_RELEASE: ${{ github.sha }}
- name: Deploy Project Artifacts to Vercel
id: deploy id: deploy
run: | uses: ./.github/composite/deploy-vercel
DEPLOYMENT_URL=$(bun run vercel deploy --prebuilt --target=$VERCEL_ENVIRONMENT $([ "$VERCEL_ENVIRONMENT" = "production" ] && echo "--prod") --token=${{ secrets.VERCEL_TOKEN }}) with:
echo "deployment-url=$DEPLOYMENT_URL" >> "$GITHUB_OUTPUT" environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
- name: Outputs vercel-org: ${{ secrets.VERCEL_ORG_ID }}
run: | vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
echo "URL: ${{ steps.deploy.outputs.deployment-url }}" vercel-token: ${{ secrets.VERCEL_TOKEN }}
deploy-v2-vercel-staging:
name: Deploy v2 to Vercel (staging)
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
issues: write
pull-requests: write
checks: write
statuses: write
if: startsWith(github.ref, 'refs/heads/main')
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Deploy staging
id: deploy
uses: ./.github/composite/deploy-vercel
with:
environment: staging
vercel-org: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }}
deploy-v2-cloudflare: deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker name: Deploy v2 to Cloudflare Worker
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -142,9 +134,6 @@ jobs:
statuses: write statuses: write
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -235,6 +224,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Visual Testing name: Visual Testing
needs: deploy needs: deploy
timeout-minutes: 6
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -247,18 +237,33 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: bun e2e run: bun e2e
env: env:
BASE_URL: ${{needs.deploy.outputs.deployment-url}} BASE_URL: ${{ needs.deploy.outputs.deployment-url }}
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }} ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
- uses: actions/upload-artifact@v4 visual-testing-v2:
if: ${{ !cancelled() }} runs-on: ubuntu-latest
with: name: Visual Testing v2
name: playwright-test-results needs: deploy-v2-vercel
path: packages/gitbook/test-results/ timeout-minutes: 6
retention-days: 3 steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Setup Playwright
uses: ./.github/actions/setup-playwright
- name: Run Playwright tests
run: bun e2e
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'v2'
visual-testing-customers: visual-testing-customers:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Visual Testing Customers name: Visual Testing Customers
needs: deploy needs: deploy
timeout-minutes: 6
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -271,15 +276,29 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: bun e2e-customers run: bun e2e-customers
env: env:
BASE_URL: ${{needs.deploy.outputs.deployment-url}} BASE_URL: ${{ needs.deploy.outputs.deployment-url }}
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }} ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers' ARGOS_BUILD_NAME: 'customers'
- uses: actions/upload-artifact@v4 visual-testing-customers-v2:
if: ${{ !cancelled() }} runs-on: ubuntu-latest
with: name: Visual Testing Customers v2
name: playwright-test-results-customers needs: deploy-v2-vercel
path: packages/gitbook/test-results/ timeout-minutes: 6
retention-days: 3 steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Setup Playwright
uses: ./.github/actions/setup-playwright
- name: Run Playwright tests
run: bun e2e-customers
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers-v2'
pagespeed-testing: pagespeed-testing:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: PageSpeed Testing name: PageSpeed Testing
@@ -301,6 +320,7 @@ jobs:
format: format:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Format name: Format
timeout-minutes: 6
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -311,22 +331,10 @@ jobs:
env: env:
PUPPETEER_SKIP_DOWNLOAD: 1 PUPPETEER_SKIP_DOWNLOAD: 1
- run: bun format:check - run: bun format:check
lint:
runs-on: ubuntu-latest
name: Lint
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- run: bun lint --no-cache
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Test name: Test
timeout-minutes: 6
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -341,6 +349,7 @@ jobs:
# CI to check that the repository builds correctly on a machine without the credentials # CI to check that the repository builds correctly on a machine without the credentials
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Build (Open Source) name: Build (Open Source)
timeout-minutes: 6
env: env:
NPM_TOKEN_READONLY: '' NPM_TOKEN_READONLY: ''
steps: steps:
@@ -356,6 +365,7 @@ jobs:
typecheck: typecheck:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Typecheck name: Typecheck
timeout-minutes: 6
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
+1
View File
@@ -28,6 +28,7 @@ jobs:
uses: changesets/action@v1 uses: changesets/action@v1
with: with:
publish: npm run release publish: npm run release
version: npm run changeset-version
env: env:
# Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created # Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761 # https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["biomejs.biome"]
}
+6 -1
View File
@@ -7,5 +7,10 @@
["style \\=([^;]*);", "\"([^\"]*)\""], ["style \\=([^;]*);", "\"([^\"]*)\""],
["style \\=([^;]*);", "\\`([^\\`]*)\\`"] ["style \\=([^;]*);", "\\`([^\\`]*)\\`"]
], ],
"tailwindCSS.classAttributes": ["class", "className", "style", ".*Style"] "tailwindCSS.classAttributes": ["class", "className", "style", ".*Style"],
"prettier.enable": false,
"editor.defaultFormatter": "biomejs.biome",
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
} }
+168
View File
@@ -0,0 +1,168 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
"vcs": {
"enabled": false,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false,
"ignore": [
"**/node_modules/**/*",
"**/dist/**/*",
"**/build/**/*",
"**/public/**/*",
"**/.next/**/*",
"**/.open-next/**/*",
"**/.turbo/**/*",
"**/.vercel/**/*",
"**/.cache/**/*",
"**/.wrangler/**/*",
"packages/openapi-parser/src/fixtures/**/*"
]
},
"formatter": {
"enabled": true,
"useEditorconfig": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentWidth": 4,
"lineEnding": "lf",
"lineWidth": 100,
"attributePosition": "auto",
"bracketSpacing": true
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"performance": {
"noDelete": "warn"
},
"security": {
"noDangerouslySetInnerHtml": "off"
},
"complexity": {
"noForEach": "off",
"noUselessFragments": "warn",
"noBannedTypes": "warn"
},
"correctness": {
"noUndeclaredVariables": "error",
"noUnusedVariables": "error",
"useArrayLiterals": "error",
"useHookAtTopLevel": "error",
"noUnusedImports": "error",
"noVoidElementsWithChildren": "warn",
"useJsxKeyInIterable": "warn",
"useExhaustiveDependencies": "warn",
"noUnknownFunction": "warn"
},
"style": {
"noNonNullAssertion": "warn",
"noParameterAssign": "off",
"useThrowOnlyError": "error"
},
"suspicious": {
"noConsole": "warn",
"noExplicitAny": "warn",
"noImplicitAnyLet": "warn",
"noConfusingVoidType": "warn",
"noControlCharactersInRegex": "warn",
"noPrototypeBuiltins": "warn",
"noAssignInExpressions": "warn",
"noArrayIndexKey": "warn"
},
"a11y": {
"useSemanticElements": "warn",
"useKeyWithClickEvents": "warn",
"noSvgWithoutTitle": "warn",
"useButtonType": "warn",
"useIframeTitle": "warn",
"useAltText": "warn",
"noPositiveTabindex": "warn",
"useFocusableInteractive": "warn",
"useAriaPropsForRole": "warn",
"useValidAnchor": "warn",
"noLabelWithoutControl": "warn",
"noNoninteractiveTabindex": "warn"
},
"nursery": {
"useSortedClasses": {
"level": "error",
"fix": "safe",
"options": {
"attributes": ["class", "className", "style"],
"functions": ["clsx", "tw"]
}
}
}
}
},
"javascript": {
"formatter": {
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "es5",
"semicolons": "always",
"arrowParentheses": "always",
"bracketSameLine": false,
"quoteStyle": "single",
"attributePosition": "auto",
"bracketSpacing": true
}
},
"overrides": [
{
"include": [
"packages/gitbook/**/*",
"packages/gitbook-v2/**/*",
"packages/react-openapi/**/*",
"packages/react-math/**/*",
"packages/react-contentkit/**/*",
"packages/icons/**/*"
],
"javascript": {
"globals": ["React"]
}
},
{
"include": ["packages/gitbook/**/*"],
"javascript": {
"globals": ["React", "GitBookIntegrationEvent"]
}
},
{
"include": ["*.css"],
"javascript": {
"globals": ["theme"]
}
},
{
"include": ["*.test.ts", "packages/gitbook/tests/**/*"],
"javascript": {
"globals": ["Bun"]
}
},
{
"include": [
"packages/cache-do/**/*",
"packages/gitbook/cf-env.d.ts",
"packages/gitbook/src/cloudflare-entrypoint.ts"
],
"javascript": {
"globals": [
"DurableObjectLocationHint",
"DurableObjectNamespace",
"DurableObjectStub",
"ContinentCode",
"Fetcher",
"ExportedHandler"
]
}
}
]
}
+128 -515
View File
File diff suppressed because it is too large Load Diff
-22
View File
@@ -1,22 +0,0 @@
# Caching
## Revalidating the cache
Invalidate cache can be done at two levels using tags:
- Data fetching cache
- Rendering cache
To invalidate and refetch the data cache, you can execute a POST request to `/~/gitbook/revalidate`:
```bash
curl --location --request POST 'https://gitbook/mycompany.com/~gitbook/revalidate' \
--header 'Content-Type: application/json' \
--data-raw '{"tags": ["space.id"]}'
```
To invalidate the rendering cache, the implementation mainly depends on the infrastructure serving the content, GitBook outputs a `Cache-Tag` header on every requests. The value of the header is a comma separated list of tags.
## Purging the cache
Purging the cache, without revalidating, is done by passing `"purge": true` in the request body.
+7 -10
View File
@@ -2,12 +2,12 @@
"name": "gitbook", "name": "gitbook",
"version": "0.1.0", "version": "0.1.0",
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^1.9.4",
"@changesets/cli": "^2.27.12", "@changesets/cli": "^2.27.12",
"prettier": "^3.0.3", "turbo": "^2.4.4",
"turbo": "^2.4.1-canary.2",
"vercel": "^39.3.0" "vercel": "^39.3.0"
}, },
"packageManager": "bun@1.1.18", "packageManager": "bun@1.2.4",
"overrides": { "overrides": {
"@codemirror/state": "6.4.1", "@codemirror/state": "6.4.1",
"react": "18.3.1", "react": "18.3.1",
@@ -20,23 +20,20 @@
"build": "turbo run build", "build": "turbo run build",
"build:v2": "turbo run build:v2", "build:v2": "turbo run build:v2",
"clean-deps": "rm -rf node_modules && rm -rf packages/*/node_modules", "clean-deps": "rm -rf node_modules && rm -rf packages/*/node_modules",
"lint": "turbo run lint",
"lint:fix": "turbo run lint -- --fix",
"typecheck": "turbo run typecheck", "typecheck": "turbo run typecheck",
"format": "prettier ./ --ignore-unknown --write", "format": "biome check --write ./",
"format:check": "prettier ./ --ignore-unknown --list-different", "format:check": "biome check --diagnostic-level=error ./",
"unit": "turbo run unit", "unit": "turbo run unit",
"e2e": "turbo run e2e", "e2e": "turbo run e2e",
"e2e-customers": "turbo run e2e-customers", "e2e-customers": "turbo run e2e-customers",
"changeset": "changeset", "changeset": "changeset",
"changeset-version": "changeset version && bun run format",
"release": "turbo run release && changeset publish", "release": "turbo run release && changeset publish",
"release:preview": "turbo run release:preview", "release:preview": "turbo run release:preview",
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local", "download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
"clean": "turbo run clean" "clean": "turbo run clean"
}, },
"workspaces": [ "workspaces": ["packages/*"],
"packages/*"
],
"patchedDependencies": { "patchedDependencies": {
"decode-named-character-reference@1.0.2": "patches/decode-named-character-reference@1.0.2.patch", "decode-named-character-reference@1.0.2": "patches/decode-named-character-reference@1.0.2.patch",
"@vercel/next@4.4.2": "patches/@vercel%2Fnext@4.4.2.patch" "@vercel/next@4.4.2": "patches/@vercel%2Fnext@4.4.2.patch"
+1 -8
View File
@@ -31,12 +31,5 @@
"release": "wrangler deploy", "release": "wrangler deploy",
"release:preview": "wrangler deploy && wrangler deploy --env preview" "release:preview": "wrangler deploy && wrangler deploy --env preview"
}, },
"files": [ "files": ["dist", "src", "bin", "data", "README.md", "CHANGELOG.md"]
"dist",
"src",
"bin",
"data",
"README.md",
"CHANGELOG.md"
]
} }
+8 -15
View File
@@ -1,5 +1,5 @@
import { encode, decode } from '@msgpack/msgpack';
import { DurableObject } from 'cloudflare:workers'; import { DurableObject } from 'cloudflare:workers';
import { decode, encode } from '@msgpack/msgpack';
import { LRUMap } from 'lru_map'; import { LRUMap } from 'lru_map';
export interface CacheObjectDescriptor { export interface CacheObjectDescriptor {
@@ -137,7 +137,7 @@ export class CacheObject extends DurableObject {
*/ */
public async purge() { public async purge() {
return this.logOperation({ operation: 'purge' }, async (setLog) => { return this.logOperation({ operation: 'purge' }, async (setLog) => {
let result = new Set<string>(); const result = new Set<string>();
try { try {
// List all the keys in the cache object. // List all the keys in the cache object.
@@ -149,11 +149,7 @@ export class CacheObject extends DurableObject {
entries.forEach((exp) => { entries.forEach((exp) => {
result.add(exp.k); result.add(exp.k);
}); });
} catch (error) { } catch (_error) {}
// If an error occurs, reset the cache object.
// This is a safety mechanism to prevent the cache object from being stuck in a bad state.
console.error('Error during purge, resetting the cache object', error);
}
await this.reset(); await this.reset();
return Array.from(result); return Array.from(result);
@@ -174,7 +170,7 @@ export class CacheObject extends DurableObject {
const toDeleteSet = new Set<string>(); const toDeleteSet = new Set<string>();
for (const [key, exp] of entries) { for (const [key, exp] of entries) {
const timestamp = parseInt(key.split('.')[1]); const timestamp = Number.parseInt(key.split('.')[1]);
if (timestamp < Date.now()) { if (timestamp < Date.now()) {
toDeleteSet.add(key); toDeleteSet.add(key);
for (let i = 0; i < exp.c; i++) { for (let i = 0; i < exp.c; i++) {
@@ -194,10 +190,7 @@ export class CacheObject extends DurableObject {
if (toDelete.length) { if (toDelete.length) {
await this.ctx.storage.setAlarm(Date.now() + 12 * 60 * 60 * 1000); await this.ctx.storage.setAlarm(Date.now() + 12 * 60 * 60 * 1000);
} }
} catch (error) { } catch (_error) {
// If an error occurs, reset the cache object.
// This is a safety mechanism to prevent the cache object from being stuck in a bad state.
console.error('Error during alarm, reset the cache object', error);
await this.reset(); await this.reset();
} }
}); });
@@ -218,10 +211,10 @@ export class CacheObject extends DurableObject {
*/ */
async logOperation<T>( async logOperation<T>(
log: Record<string, unknown>, log: Record<string, unknown>,
fn: (update: (log: Record<string, unknown>) => void) => Promise<T>, fn: (update: (log: Record<string, unknown>) => void) => Promise<T>
): Promise<T> { ): Promise<T> {
const objectId = this.ctx.id.name ?? this.ctx.id.toString(); const objectId = this.ctx.id.name ?? this.ctx.id.toString();
let update: Record<string, unknown> = {}; const update: Record<string, unknown> = {};
const start = performance.now(); const start = performance.now();
try { try {
return await fn((arg) => { return await fn((arg) => {
@@ -265,7 +258,7 @@ function encodeChunks<T>(key: string, value: T): Record<string, Uint8Array> {
function decodeChunks<T>(entries: Map<string, Uint8Array>): { value: T; size: number } | undefined { function decodeChunks<T>(entries: Map<string, Uint8Array>): { value: T; size: number } | undefined {
const chunks = Array.from(entries.entries()) const chunks = Array.from(entries.entries())
.map(([key, value]) => { .map(([key, value]) => {
const index = parseInt(key.split('.').pop()!); const index = Number.parseInt(key.split('.').pop()!);
return [index, value] as const; return [index, value] as const;
}) })
.sort(([a], [b]) => a - b) .sort(([a], [b]) => a - b)
+3 -3
View File
@@ -1,4 +1,4 @@
import type { CacheObject, CacheObjectDescriptor } from './CacheObject'; import type { CacheObject } from './CacheObject';
export type CacheLocationId = ContinentCode; export type CacheLocationId = ContinentCode;
const allLocations: CacheLocationId[] = ['AF', 'AS', 'NA', 'SA', 'AN', 'EU', 'OC']; const allLocations: CacheLocationId[] = ['AF', 'AS', 'NA', 'SA', 'AN', 'EU', 'OC'];
@@ -30,7 +30,7 @@ export class CacheObjectStub {
/** ID of the location to target */ /** ID of the location to target */
private locationId: CacheLocationId, private locationId: CacheLocationId,
/** Name of the tag */ /** Name of the tag */
private tag: string, private tag: string
) { ) {
const groupId = getCacheObjectIdName(this.locationId, this.tag); const groupId = getCacheObjectIdName(this.locationId, this.tag);
this.stub = this.doNamespace.get(this.doNamespace.idFromName(groupId), { this.stub = this.doNamespace.get(this.doNamespace.idFromName(groupId), {
@@ -85,7 +85,7 @@ export class CacheObjectStub {
}); });
const locationkeys = await cacheGroup.purge(); const locationkeys = await cacheGroup.purge();
locationkeys.forEach((key) => keys.add(key)); locationkeys.forEach((key) => keys.add(key));
}), })
); );
return keys; return keys;
+1
View File
@@ -0,0 +1 @@
dist/
+7
View File
@@ -0,0 +1,7 @@
# @gitbook/cache-tags
## 0.1.0
### Minor Changes
- 05ffd0e: Initial version of the package
+3
View File
@@ -0,0 +1,3 @@
# `@gitbook/cache-tags`
Utility to generate cache tags for GitBook Open.
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@gitbook/cache-tags",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"development": "./src/index.ts",
"default": "./dist/index.js"
}
},
"version": "0.1.0",
"dependencies": {
"@gitbook/api": "0.96.1",
"assert-never": "^1.2.1"
},
"devDependencies": {
"typescript": "^5.5.3"
},
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"dev": "tsc -w"
},
"files": ["dist", "src", "README.md", "CHANGELOG.md"]
}
+175
View File
@@ -0,0 +1,175 @@
import type { ComputedContentSource } from '@gitbook/api';
import assertNever from 'assert-never';
/**
* Get a stringified cache tag for a given object.
*/
export function getCacheTag(
spec: /**
* All data related to a user
* @deprecated - in v2, no tag as this is an immutable data
*/
| {
tag: 'user';
user: string;
}
/**
* All data related to a space
*/
| {
tag: 'space';
space: string;
}
/**
* All data related to an integration.
*/
| {
tag: 'integration';
integration: string;
}
/**
* All data related to a change request
*/
| {
tag: 'change-request';
space: string;
changeRequest: string;
}
/**
* Immutable data related to a revision
* @deprecated - in v2, no tag as this is an immutable data
*/
| {
tag: 'revision';
space: string;
revision: string;
}
/**
* Immutable data related to a document
* @deprecated - in v2, no tag as this is an immutable data
*/
| {
tag: 'document';
space: string;
document: string;
}
/**
* Immutable data related to a computed document
* @deprecated - in v2, no tag as this is an immutable data
*/
| {
tag: 'computed-document';
space: string;
integration: string;
}
/**
* All data related to the URL of a content
*/
| {
tag: 'url';
hostname: string;
}
/**
* All data related to a site
*/
| {
tag: 'site';
site: string;
}
/**
* All data related to an OpenAPI spec
*/
| {
tag: 'openapi';
organization: string;
openAPISpec: string;
}
): string {
switch (spec.tag) {
case 'user':
return `user:${spec.user}`;
case 'url':
return `url:${spec.hostname}`;
case 'space':
return `space:${spec.space}`;
case 'change-request':
return `space:${spec.space}:change-request:${spec.changeRequest}`;
case 'revision':
return `space:${spec.space}:revision:${spec.revision}`;
case 'document':
return `space:${spec.space}:document:${spec.document}`;
case 'computed-document':
return `space:${spec.space}:computed-document:${spec.integration}`;
case 'site':
return `site:${spec.site}`;
case 'integration':
return `integration:${spec.integration}`;
case 'openapi':
return `organization:${spec.organization}:openapi:${spec.openAPISpec}`;
default:
assertNever(spec);
}
}
/**
* Get the tags for a computed content source.
*/
export function getComputedContentSourceCacheTags(
inContext: {
spaceId: string;
organizationId: string;
},
source: ComputedContentSource
) {
const tags: string[] = [];
// We add the dependencies as tags, to ensure that the computed content is invalidated
// when the dependencies are updated.
const dependencies = Object.values(source.dependencies ?? {});
if (dependencies.length > 0) {
dependencies.forEach((dependency) => {
switch (dependency.ref.kind) {
case 'space':
tags.push(
getCacheTag({
tag: 'space',
space: dependency.ref.space,
})
);
break;
case 'openapi':
tags.push(
getCacheTag({
tag: 'openapi',
organization: inContext.organizationId,
openAPISpec: dependency.ref.spec,
})
);
break;
default:
// Do not throw for unknown dependency types
// as it might mean we are lacking behind the API version
break;
}
});
} else {
// Push a dummy tag, as the v1 is only using the first tag
tags.push(
getCacheTag({
tag: 'computed-document',
space: inContext.spaceId,
integration: source.integration,
})
);
}
// We invalidate the computed content when a new version of the integration is deployed.
tags.push(
getCacheTag({
tag: 'integration',
integration: source.integration,
})
);
return tags;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": false,
"declaration": true,
"outDir": "dist",
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"types": [
"bun-types" // add Bun global
]
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules"]
}
+1 -6
View File
@@ -17,10 +17,5 @@
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"dev": "tsc -w" "dev": "tsc -w"
}, },
"files": [ "files": ["dist", "src", "README.md", "CHANGELOG.md"]
"dist",
"src",
"README.md",
"CHANGELOG.md"
]
} }
+2 -2
View File
@@ -1,4 +1,4 @@
import { DARK_BASE, LIGHT_BASE, DEFAULT_TINT_COLOR } from './colors'; import { DARK_BASE, DEFAULT_TINT_COLOR, LIGHT_BASE } from './colors';
type ColorShades = { type ColorShades = {
[key: string]: string; [key: string]: string;
@@ -178,7 +178,7 @@ export function colorScale(
background = darkMode ? DARK_BASE : LIGHT_BASE, background = darkMode ? DARK_BASE : LIGHT_BASE,
foreground = darkMode ? LIGHT_BASE : DARK_BASE, foreground = darkMode ? LIGHT_BASE : DARK_BASE,
mix, mix,
}: ColorScaleOptions = {}, }: ColorScaleOptions = {}
) { ) {
const baseColor = rgbToOklch(hexToRgbArray(hex)); const baseColor = rgbToOklch(hexToRgbArray(hex));
const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null; const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null;
+1 -1
View File
@@ -13,7 +13,7 @@
"moduleResolution": "bundler", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "react", "jsx": "react-jsx",
"incremental": true, "incremental": true,
"types": [ "types": [
"bun-types" // add Bun global "bun-types" // add Bun global
+1 -2
View File
@@ -17,12 +17,11 @@ Object.entries(emojis).forEach(([key, value]) => {
if (emoji && key !== emoji) { if (emoji && key !== emoji) {
output[key] = emoji; output[key] = emoji;
} else if (!emoji) { } else if (!emoji) {
console.log('No emoji for', key);
} }
}); });
fs.mkdirSync(path.resolve(__dirname, 'dist'), { recursive: true }); fs.mkdirSync(path.resolve(__dirname, 'dist'), { recursive: true });
fs.writeFileSync( fs.writeFileSync(
path.resolve(__dirname, 'dist/index.ts'), path.resolve(__dirname, 'dist/index.ts'),
`export const emojiCodepoints: Record<string, string> = ${JSON.stringify(output, null, 4)};`, `export const emojiCodepoints: Record<string, string> = ${JSON.stringify(output, null, 4)};`
); );
+14
View File
@@ -1,5 +1,19 @@
# gitbook-v2 # gitbook-v2
## 0.1.2
### Patch Changes
- 05ffd0e: Improving data cache management for computed content
- Updated dependencies [05ffd0e]
- @gitbook/cache-tags@0.1.0
## 0.1.1
### Patch Changes
- 3e11678: fix: lost section groups
## 0.1.0 ## 0.1.0
### Minor Changes ### Minor Changes
+3
View File
@@ -15,6 +15,9 @@ const nextConfig = {
GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL, GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN, GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
// Used to detect if the app is running in V2 mode
GITBOOK_V2: 'true',
}, },
assetPrefix: process.env.GITBOOK_ASSETS_PREFIX, assetPrefix: process.env.GITBOOK_ASSETS_PREFIX,
+5 -4
View File
@@ -1,12 +1,13 @@
{ {
"name": "gitbook-v2", "name": "gitbook-v2",
"version": "0.1.0", "version": "0.1.2",
"private": true, "private": true,
"dependencies": { "dependencies": {
"next": "canary", "next": "^15.2.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"@gitbook/api": "^0.96.0", "@gitbook/api": "0.96.1",
"@gitbook/cache-tags": "workspace:*",
"@sindresorhus/fnv1a": "^3.1.0", "@sindresorhus/fnv1a": "^3.1.0",
"server-only": "^0.0.1" "server-only": "^0.0.1"
}, },
@@ -18,7 +19,7 @@
}, },
"scripts": { "scripts": {
"generate": "rm -rf ./public && cp -r ../gitbook/public ./public", "generate": "rm -rf ./public && cp -r ../gitbook/public ./public",
"dev:v2": "env-cmd --silent -f ../../.env.local next", "dev:v2": "env-cmd --silent -f ../../.env.local next --turbopack",
"build": "next build", "build": "next build",
"build:v2": "next build", "build:v2": "next build",
"start": "next start", "start": "next start",
@@ -1,10 +1,10 @@
import { getDynamicSiteContext, getPagePathFromParams, RouteParams } from '@v2/app/utils';
import { import {
SitePage,
generateSitePageMetadata, generateSitePageMetadata,
generateSitePageViewport, generateSitePageViewport,
SitePage,
} from '@/components/SitePage'; } from '@/components/SitePage';
import { Metadata, Viewport } from 'next'; import { type RouteParams, getDynamicSiteContext, getPagePathFromParams } from '@v2/app/utils';
import type { Metadata, Viewport } from 'next';
type PageProps = { type PageProps = {
params: Promise<RouteParams>; params: Promise<RouteParams>;
@@ -1,18 +1,24 @@
import { CustomizationRootLayout } from '@/components/RootLayout'; import { CustomizationRootLayout } from '@/components/RootLayout';
import { SiteLayout } from '@/components/SiteLayout'; import {
import { getDynamicSiteContext, RouteLayoutParams } from '@v2/app/utils'; SiteLayout,
generateSiteLayoutMetadata,
generateSiteLayoutViewport,
} from '@/components/SiteLayout';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env'; import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
import { getThemeFromMiddleware } from '@v2/lib/middleware'; import { getThemeFromMiddleware, getVisitorAuthTokenFromMiddleware } from '@v2/lib/middleware';
interface SiteDynamicLayoutProps {
params: Promise<RouteLayoutParams>;
}
export default async function SiteDynamicLayout({ export default async function SiteDynamicLayout({
params, params,
children, children,
}: { }: React.PropsWithChildren<SiteDynamicLayoutProps>) {
params: Promise<RouteLayoutParams>;
children: React.ReactNode;
}) {
const context = await getDynamicSiteContext(await params); const context = await getDynamicSiteContext(await params);
const forcedTheme = await getThemeFromMiddleware(); const forcedTheme = await getThemeFromMiddleware();
const visitorAuthToken = await getVisitorAuthTokenFromMiddleware();
return ( return (
<CustomizationRootLayout customization={context.customization}> <CustomizationRootLayout customization={context.customization}>
@@ -20,9 +26,20 @@ export default async function SiteDynamicLayout({
context={context} context={context}
forcedTheme={forcedTheme} forcedTheme={forcedTheme}
withTracking={!GITBOOK_DISABLE_TRACKING} withTracking={!GITBOOK_DISABLE_TRACKING}
visitorAuthToken={visitorAuthToken}
> >
{children} {children}
</SiteLayout> </SiteLayout>
</CustomizationRootLayout> </CustomizationRootLayout>
); );
} }
export async function generateViewport({ params }: SiteDynamicLayoutProps) {
const context = await getDynamicSiteContext(await params);
return generateSiteLayoutViewport(context);
}
export async function generateMetadata({ params }: SiteDynamicLayoutProps) {
const context = await getDynamicSiteContext(await params);
return generateSiteLayoutMetadata(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { serveLLMsTxt } from '@/routes/llms';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveLLMsTxt(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { serveRobotsTxt } from '@/routes/robots';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveRobotsTxt(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { servePagesSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return servePagesSitemap(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { serveRootSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveRootSitemap(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveIcon } from '@/routes/icon';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveIcon(context, request);
}
@@ -0,0 +1,13 @@
import type { NextRequest } from 'next/server';
import type { PageIdParams } from '@/components/SitePage';
import { serveOGImage } from '@/routes/ogimage';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveOGImage(context, await params);
}
@@ -1,5 +0,0 @@
import { SitePageSkeleton } from '@/components/SitePage';
export default function Loading() {
return <SitePageSkeleton />;
}
@@ -1,12 +1,12 @@
import { unstable_cacheTag as cacheTag } from 'next/cache';
import { getSiteCacheTag } from '@v2/lib/cache';
import { getPagePathFromParams, getStaticSiteContext, RouteParams } from '@v2/app/utils';
import { import {
SitePage,
generateSitePageMetadata, generateSitePageMetadata,
generateSitePageViewport, generateSitePageViewport,
SitePage,
} from '@/components/SitePage'; } from '@/components/SitePage';
import { Metadata, Viewport } from 'next'; import { getCacheTag } from '@gitbook/cache-tags';
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@v2/app/utils';
import type { Metadata, Viewport } from 'next';
import { unstable_cacheTag as cacheTag } from 'next/cache';
export const dynamic = 'force-static'; export const dynamic = 'force-static';
@@ -21,7 +21,12 @@ export default async function Page(props: PageProps) {
const context = await getStaticSiteContext(params); const context = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
cacheTag(getSiteCacheTag(context.site.id)); cacheTag(
getCacheTag({
tag: 'site',
site: context.site.id,
})
);
return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />; return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />;
} }
@@ -1,28 +1,52 @@
import { unstable_cacheTag as cacheTag } from 'next/cache';
import { getSiteCacheTag } from '@v2/lib/cache';
import { getStaticSiteContext, RouteLayoutParams } from '@v2/app/utils';
import { CustomizationRootLayout } from '@/components/RootLayout'; import { CustomizationRootLayout } from '@/components/RootLayout';
import { SiteLayout } from '@/components/SiteLayout'; import {
SiteLayout,
generateSiteLayoutMetadata,
generateSiteLayoutViewport,
} from '@/components/SiteLayout';
import { getCacheTag } from '@gitbook/cache-tags';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env'; import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
import { unstable_cacheTag as cacheTag } from 'next/cache';
interface SiteStaticLayoutProps {
params: Promise<RouteLayoutParams>;
}
export default async function SiteStaticLayout({ export default async function SiteStaticLayout({
params, params,
children, children,
}: { }: React.PropsWithChildren<SiteStaticLayoutProps>) {
params: Promise<RouteLayoutParams>;
children: React.ReactNode;
}) {
'use cache'; 'use cache';
const context = await getStaticSiteContext(await params); const context = await getStaticSiteContext(await params);
cacheTag(getSiteCacheTag(context.site.id)); cacheTag(
getCacheTag({
tag: 'site',
site: context.site.id,
})
);
return ( return (
<CustomizationRootLayout customization={context.customization}> <CustomizationRootLayout customization={context.customization}>
<SiteLayout context={context} withTracking={!GITBOOK_DISABLE_TRACKING}> <SiteLayout
context={context}
withTracking={!GITBOOK_DISABLE_TRACKING}
visitorAuthToken={null}
>
{children} {children}
</SiteLayout> </SiteLayout>
</CustomizationRootLayout> </CustomizationRootLayout>
); );
} }
export async function generateViewport({ params }: SiteStaticLayoutProps) {
const context = await getStaticSiteContext(await params);
return generateSiteLayoutViewport(context);
}
export async function generateMetadata({ params }: SiteStaticLayoutProps) {
const context = await getStaticSiteContext(await params);
return generateSiteLayoutMetadata(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveLLMsTxt } from '@/routes/llms';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveLLMsTxt(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveRobotsTxt } from '@/routes/robots';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveRobotsTxt(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { servePagesSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return servePagesSitemap(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveRootSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveRootSitemap(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveIcon } from '@/routes/icon';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveIcon(context, request);
}
@@ -0,0 +1,15 @@
import type { NextRequest } from 'next/server';
import type { PageIdParams } from '@/components/SitePage';
import { serveOGImage } from '@/routes/ogimage';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
) {
const context = await getStaticSiteContext(await params);
return serveOGImage(context, await params);
}
+22 -62
View File
@@ -1,9 +1,9 @@
import { fetchSiteContextByURL } from '@v2/lib/context'; import {
import { createDataFetcher } from '@v2/lib/data'; fetchSiteContextByURL,
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_URL } from '@v2/lib/env'; fetchSiteContextByURLLookup,
import { createNoopImageResizer } from '@v2/lib/images'; getBaseContext,
import { createLinker } from '@v2/lib/links'; } from '@v2/lib/context';
import { headers } from 'next/headers'; import { getSiteURLDataFromMiddleware } from '@v2/lib/middleware';
export type RouteParamMode = 'url-host' | 'url'; export type RouteParamMode = 'url-host' | 'url';
@@ -22,23 +22,17 @@ export type RouteParams = RouteLayoutParams & {
* Get the static context when rendering statically a site. * Get the static context when rendering statically a site.
*/ */
export function getStaticSiteContext(params: RouteLayoutParams) { export function getStaticSiteContext(params: RouteLayoutParams) {
const url = getSiteURLFromParams(params); const siteURL = getSiteURLFromParams(params);
const dataFetcher = createDataFetcher();
const linker = createLinkerFromParams(params);
const imageResizer = createNoopImageResizer();
return fetchSiteContextByURL( return fetchSiteContextByURL(
getBaseContext({
siteURL,
urlMode: getModeFromParams(params.mode),
}),
{ {
dataFetcher, url: siteURL.toString(),
linker,
imageResizer,
},
{
url: url.toString(),
visitorAuthToken: null, visitorAuthToken: null,
redirectOnError: false, redirectOnError: false,
}, }
); );
} }
@@ -47,30 +41,15 @@ export function getStaticSiteContext(params: RouteLayoutParams) {
* The context will depend on the request. * The context will depend on the request.
*/ */
export async function getDynamicSiteContext(params: RouteLayoutParams) { export async function getDynamicSiteContext(params: RouteLayoutParams) {
const url = getSiteURLFromParams(params); const siteURL = getSiteURLFromParams(params);
const headersSet = await headers(); const siteURLData = await getSiteURLDataFromMiddleware();
const dataFetcher = createDataFetcher({ return fetchSiteContextByURLLookup(
apiToken: headersSet.get('x-gitbook-token') ?? GITBOOK_API_TOKEN, getBaseContext({
apiEndpoint: headersSet.get('x-gitbook-api') ?? GITBOOK_API_URL, siteURL,
}); urlMode: getModeFromParams(params.mode),
}),
const linker = createLinkerFromParams(params); siteURLData
const imageResizer = createNoopImageResizer();
return fetchSiteContextByURL(
{
dataFetcher,
linker,
imageResizer,
},
{
url: url.toString(),
visitorAuthToken: headersSet.get('x-gitbook-visitor-token'),
// TODO: set it only when the token comes from the cookies.
redirectOnError: true,
},
); );
} }
@@ -82,28 +61,9 @@ export function getPagePathFromParams(params: RouteParams) {
return decoded; return decoded;
} }
function createLinkerFromParams(params: RouteLayoutParams) {
const url = getSiteURLFromParams(params);
const mode = getModeFromParams(params.mode);
if (mode === 'url-host') {
return createLinker({
host: url.host,
pathname: '/',
});
}
const gitbookURL = new URL(GITBOOK_URL);
return createLinker({
protocol: gitbookURL.protocol,
host: gitbookURL.host,
pathname: `/url/${url.host}`,
});
}
function getSiteURLFromParams(params: RouteLayoutParams) { function getSiteURLFromParams(params: RouteLayoutParams) {
const decoded = decodeURIComponent(params.siteURL); const decoded = decodeURIComponent(params.siteURL);
const url = new URL('https://' + decoded); const url = new URL(`https://${decoded}`);
return url; return url;
} }
-34
View File
@@ -1,34 +0,0 @@
/**
* Get the cache tag for a site.
*/
export function getSiteCacheTag(siteId: string) {
return `site:${siteId}`;
}
/**
* Get the cache tag for a hostname.
*/
export function getHostnameCacheTag(hostname: string) {
return `url:${hostname}`;
}
/**
* Get the cache tag for an OpenAPI spec.
*/
export function getOpenAPISpecCacheTag(organizationId: string, slug: string) {
return `organization:${organizationId}:openapi:${slug}`;
}
/**
* Get the cache tag for a space.
*/
export function getSpaceCacheTag(spaceId: string) {
return `space:${spaceId}`;
}
/**
* Get the cache tag for a change request.
*/
export function getChangeRequestCacheTag(spaceId: string, changeRequestId: string) {
return `space:${spaceId}:change-request:${changeRequestId}`;
}
+117 -32
View File
@@ -1,5 +1,7 @@
import { import { getSiteStructureSections } from '@/lib/sites';
import type {
ChangeRequest, ChangeRequest,
PublishedSiteContentLookup,
RevisionPage, RevisionPage,
RevisionPageDocument, RevisionPageDocument,
Site, Site,
@@ -11,12 +13,12 @@ import {
SiteStructure, SiteStructure,
Space, Space,
} from '@gitbook/api'; } from '@gitbook/api';
import { type GitBookDataFetcher, createDataFetcher } from '@v2/lib/data';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { assert } from 'ts-essentials'; import { assert } from 'ts-essentials';
import { getSiteStructureSections } from '@/lib/sites'; import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_URL } from './env';
import { createDataFetcher, GitBookDataFetcher } from '@v2/lib/data'; import { type ImageResizer, createImageResizer } from './images';
import { GitBookSpaceLinker, appendPrefixToLinker } from './links'; import { type GitBookSpaceLinker, createLinker } from './links';
import { ImageResizer } from './images';
/** /**
* Generic context when rendering content. * Generic context when rendering content.
@@ -35,7 +37,7 @@ export type GitBookBaseContext = {
/** /**
* Image resizer to resize images. * Image resizer to resize images.
*/ */
imageResizer: ImageResizer; imageResizer?: ImageResizer;
}; };
/** /**
@@ -90,9 +92,6 @@ export type GitBookSiteContext = GitBookSpaceContext & {
/** Scripts to load for the site. */ /** Scripts to load for the site. */
scripts: SiteIntegrationScript[]; scripts: SiteIntegrationScript[];
/** Visitor token used to fetch the site */
visitorAuthToken: string | null;
}; };
/** /**
@@ -102,6 +101,58 @@ export type GitBookPageContext = (GitBookSpaceContext | GitBookSiteContext) & {
page: RevisionPageDocument; page: RevisionPageDocument;
}; };
/**
* Get the base context for a request.
*/
export function getBaseContext(input: {
siteURL: URL | string;
urlMode: 'url' | 'url-host';
apiToken?: string | null;
}) {
const url = typeof input.siteURL === 'string' ? new URL(input.siteURL) : input.siteURL;
const urlMode = input.urlMode;
const dataFetcher = createDataFetcher({
apiToken: input.apiToken ?? GITBOOK_API_TOKEN,
apiEndpoint: GITBOOK_API_URL,
});
const gitbookURL = new URL(GITBOOK_URL);
const linker =
urlMode === 'url-host'
? createLinker({
host: url.host,
pathname: url.pathname,
})
: createLinker({
protocol: gitbookURL.protocol,
host: gitbookURL.host,
pathname: `/url/${url.host}${url.pathname}`,
});
if (urlMode === 'url') {
// Create link in the same format for links to other sites/sections.
linker.toLinkForContent = (rawURL: string) => {
const urlObject = new URL(rawURL);
return `/url/${urlObject.host}${urlObject.pathname}`;
};
}
const imageResizer = createImageResizer({
host: urlMode === 'url-host' ? url.host : gitbookURL.host,
// To ensure image resizing work for proxied sites,
// we serve images from the root of the site.
linker: linker,
});
return {
dataFetcher,
linker,
imageResizer,
};
}
/** /**
* Fetch the context of a site for a given URL and a base context. * Fetch the context of a site for a given URL and a base context.
*/ */
@@ -111,7 +162,7 @@ export async function fetchSiteContextByURL(
url: string; url: string;
visitorAuthToken: string | null; visitorAuthToken: string | null;
redirectOnError: boolean; redirectOnError: boolean;
}, }
): Promise<GitBookSiteContext> { ): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext; const { dataFetcher } = baseContext;
const data = await dataFetcher.getPublishedContentByUrl({ const data = await dataFetcher.getPublishedContentByUrl({
@@ -120,15 +171,25 @@ export async function fetchSiteContextByURL(
redirectOnError: input.redirectOnError, redirectOnError: input.redirectOnError,
}); });
return fetchSiteContextByURLLookup(baseContext, data);
}
/**
* Fetch the context of a site using the resolution of a URL
*/
export async function fetchSiteContextByURLLookup(
baseContext: GitBookBaseContext,
data: PublishedSiteContentLookup
): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext;
if ('redirect' in data) { if ('redirect' in data) {
redirect(data.redirect); redirect(data.redirect);
} }
const context = await fetchSiteContextByIds( return await fetchSiteContextByIds(
{ {
...baseContext, ...baseContext,
dataFetcher: createDataFetcher({ dataFetcher: dataFetcher.withToken({
apiEndpoint: dataFetcher.apiEndpoint,
apiToken: data.apiToken, apiToken: data.apiToken,
}), }),
}, },
@@ -141,16 +202,8 @@ export async function fetchSiteContextByURL(
shareKey: data.shareKey, shareKey: data.shareKey,
changeRequest: data.changeRequest, changeRequest: data.changeRequest,
revision: data.revision, revision: data.revision,
visitorAuthToken: input.visitorAuthToken, }
},
); );
const siteContext = {
...context,
linker: appendPrefixToLinker(context.linker, data.basePath),
};
return siteContext;
} }
/** /**
@@ -167,8 +220,7 @@ export async function fetchSiteContextByIds(
shareKey: string | undefined; shareKey: string | undefined;
changeRequest: string | undefined; changeRequest: string | undefined;
revision: string | undefined; revision: string | undefined;
visitorAuthToken: string | null; }
},
): Promise<GitBookSiteContext> { ): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext; const { dataFetcher } = baseContext;
@@ -189,7 +241,9 @@ export async function fetchSiteContextByIds(
...(customizations.site?.title ? { title: customizations.site.title } : {}), ...(customizations.site?.title ? { title: customizations.site.title } : {}),
}; };
const sections = ids.siteSection ? parseSiteSectionsList(siteStructure, ids.siteSection) : null; const sections = ids.siteSection
? parseSiteSectionsAndGroups(siteStructure, ids.siteSection)
: null;
const siteSpace = ( const siteSpace = (
siteStructure.type === 'siteSpaces' && siteStructure.structure siteStructure.type === 'siteSpaces' && siteStructure.structure
@@ -211,11 +265,13 @@ export async function fetchSiteContextByIds(
if (siteSpaceSettings) { if (siteSpaceSettings) {
return siteSpaceSettings; return siteSpaceSettings;
} }
// We got the pointer from an API and customizations from another. // We got the pointer from an API and customizations from another.
// It's possible that the two are unsynced leading to not found customizations for the space. // It's possible that the two are unsynced leading to not found customizations for the space.
// It's better to fallback on customization of the site that displaying an error. // It's better to fallback on customization of the site that displaying an error.
console.warn('Customization not found for site space', ids.siteSpace); console.warn('Customization not found for site space', ids.siteSpace);
} }
return customizations.site; return customizations.site;
})(); })();
@@ -229,7 +285,6 @@ export async function fetchSiteContextByIds(
structure: siteStructure, structure: siteStructure,
sections, sections,
scripts, scripts,
visitorAuthToken: ids.visitorAuthToken,
}; };
} }
@@ -243,7 +298,7 @@ export async function fetchSpaceContextByIds(
shareKey: string | undefined; shareKey: string | undefined;
changeRequest: string | undefined; changeRequest: string | undefined;
revision: string | undefined; revision: string | undefined;
}, }
): Promise<GitBookSpaceContext> { ): Promise<GitBookSpaceContext> {
const { dataFetcher } = baseContext; const { dataFetcher } = baseContext;
@@ -281,9 +336,39 @@ export async function fetchSpaceContextByIds(
}; };
} }
function parseSiteSectionsList(structure: SiteStructure, siteSectionId: string) { /**
const sections = getSiteStructureSections(structure); * Check if the context is the root one for a site.
const section = sections.find((section) => section.id === siteSectionId); * Meaning we are on the default section / space.
assert(section, 'A section must be defined when there are multiple sections'); */
return { list: sections, current: section } satisfies SiteSections; export function checkIsRootSiteContext(context: GitBookSiteContext): boolean {
const { structure } = context;
switch (structure.type) {
case 'sections': {
return getSiteStructureSections(structure, { ignoreGroups: true }).some(
(structure) =>
structure.default &&
structure.id === context.sections?.current.id &&
structure.siteSpaces.some(
(siteSpace) => siteSpace.default && siteSpace.id === context.siteSpace.id
)
);
}
case 'siteSpaces': {
return structure.structure.some(
(siteSpace) => siteSpace.default && siteSpace.id === context.siteSpace.id
);
}
}
}
function parseSiteSectionsAndGroups(structure: SiteStructure, siteSectionId: string) {
const sectionsAndGroups = getSiteStructureSections(structure, { ignoreGroups: false });
const section = parseCurrentSection(structure, siteSectionId);
assert(section, 'A section must be defined when there are multiple sections');
return { list: sectionsAndGroups, current: section } satisfies SiteSections;
}
function parseCurrentSection(structure: SiteStructure, siteSectionId: string) {
const sections = getSiteStructureSections(structure, { ignoreGroups: true });
return sections.find((section) => section.id === siteSectionId);
} }
+160 -38
View File
@@ -1,14 +1,8 @@
import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache'; import { type ComputedContentSource, GitBookAPI } from '@gitbook/api';
import { ComputedContentSource, GitBookAPI } from '@gitbook/api'; import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env'; import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env';
import { GitBookDataFetcher } from './types'; import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache';
import { import type { GitBookDataFetcher } from './types';
getChangeRequestCacheTag,
getHostnameCacheTag,
getOpenAPISpecCacheTag,
getSiteCacheTag,
getSpaceCacheTag,
} from '../cache';
interface DataFetcherInput { interface DataFetcherInput {
/** /**
@@ -35,6 +29,17 @@ export function createDataFetcher(input: DataFetcherInput = commonInput): GitBoo
return { return {
apiEndpoint: input.apiEndpoint, apiEndpoint: input.apiEndpoint,
async api() {
return getAPI(input);
},
withToken({ apiToken }) {
return createDataFetcher({
...input,
apiToken,
});
},
// //
// API that are tied to the token // API that are tied to the token
// //
@@ -114,10 +119,20 @@ export function createDataFetcher(input: DataFetcherInput = commonInput): GitBoo
}, },
getComputedDocument(params) { getComputedDocument(params) {
return getComputedDocument(input, { return getComputedDocument(input, {
organizationId: params.organizationId,
spaceId: params.spaceId, spaceId: params.spaceId,
source: params.source, source: params.source,
}); });
}, },
getEmbedByUrl(params) {
return getEmbedByUrl(input, {
url: params.url,
spaceId: params.spaceId,
});
},
searchSiteContent(params) {
return searchSiteContent(input, params);
},
// //
// API that are not tied to the token // API that are not tied to the token
@@ -139,6 +154,8 @@ export function createDataFetcher(input: DataFetcherInput = commonInput): GitBoo
async function getUserById(input: DataFetcherInput, userId: string) { async function getUserById(input: DataFetcherInput, userId: string) {
'use cache'; 'use cache';
cacheLife('days');
try { try {
const res = await getAPI(input).users.getUserById(userId); const res = await getAPI(input).users.getUserById(userId);
return res.data; return res.data;
@@ -156,11 +173,17 @@ async function getSpace(
params: { params: {
spaceId: string; spaceId: string;
shareKey: string | undefined; shareKey: string | undefined;
}, }
) { ) {
'use cache'; 'use cache';
cacheTag(getSpaceCacheTag(params.spaceId)); cacheLife('days');
cacheTag(
getCacheTag({
tag: 'space',
space: params.spaceId,
})
);
const res = await getAPI(input).spaces.getSpaceById(params.spaceId, { const res = await getAPI(input).spaces.getSpaceById(params.spaceId, {
shareKey: params.shareKey, shareKey: params.shareKey,
@@ -173,16 +196,24 @@ async function getChangeRequest(
params: { params: {
spaceId: string; spaceId: string;
changeRequestId: string; changeRequestId: string;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('minutes');
try { try {
const res = await getAPI(input).spaces.getChangeRequestById( const res = await getAPI(input).spaces.getChangeRequestById(
params.spaceId, params.spaceId,
params.changeRequestId, params.changeRequestId
);
cacheTag(
getCacheTag({
tag: 'change-request',
space: params.spaceId,
changeRequest: res.data.id,
})
); );
cacheTag(getChangeRequestCacheTag(params.spaceId, res.data.id));
return res.data; return res.data;
} catch (error) { } catch (error) {
if (checkHasErrorCode(error, 404)) { if (checkHasErrorCode(error, 404)) {
@@ -199,10 +230,12 @@ async function getRevision(
spaceId: string; spaceId: string;
revisionId: string; revisionId: string;
metadata: boolean; metadata: boolean;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('max');
const res = await getAPI(input).spaces.getRevisionById(params.spaceId, params.revisionId, { const res = await getAPI(input).spaces.getRevisionById(params.spaceId, params.revisionId, {
metadata: params.metadata, metadata: params.metadata,
}); });
@@ -215,16 +248,18 @@ async function getRevisionPages(
spaceId: string; spaceId: string;
revisionId: string; revisionId: string;
metadata: boolean; metadata: boolean;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('max');
const res = await getAPI(input).spaces.listPagesInRevisionById( const res = await getAPI(input).spaces.listPagesInRevisionById(
params.spaceId, params.spaceId,
params.revisionId, params.revisionId,
{ {
metadata: params.metadata, metadata: params.metadata,
}, }
); );
return res.data.pages; return res.data.pages;
} }
@@ -235,15 +270,17 @@ async function getRevisionFile(
spaceId: string; spaceId: string;
revisionId: string; revisionId: string;
fileId: string; fileId: string;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('max');
try { try {
const res = await getAPI(input).spaces.getFileInRevisionById( const res = await getAPI(input).spaces.getFileInRevisionById(
params.spaceId, params.spaceId,
params.revisionId, params.revisionId,
params.fileId, params.fileId
); );
return res.data; return res.data;
} catch (error) { } catch (error) {
@@ -261,17 +298,18 @@ async function getRevisionPageByPath(
spaceId: string; spaceId: string;
revisionId: string; revisionId: string;
path: string; path: string;
}, }
) { ) {
'use cache'; 'use cache';
const encodedPath = encodeURIComponent(params.path); cacheLife('max');
const encodedPath = encodeURIComponent(params.path);
try { try {
const res = await getAPI(input).spaces.getPageInRevisionByPath( const res = await getAPI(input).spaces.getPageInRevisionByPath(
params.spaceId, params.spaceId,
params.revisionId, params.revisionId,
encodedPath, encodedPath
); );
return res.data; return res.data;
@@ -289,10 +327,12 @@ async function getDocument(
params: { params: {
spaceId: string; spaceId: string;
documentId: string; documentId: string;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('max');
const res = await getAPI(input).spaces.getDocumentById(params.spaceId, params.documentId); const res = await getAPI(input).spaces.getDocumentById(params.spaceId, params.documentId);
return res.data; return res.data;
} }
@@ -301,11 +341,24 @@ async function getComputedDocument(
input: DataFetcherInput, input: DataFetcherInput,
params: { params: {
spaceId: string; spaceId: string;
organizationId: string;
source: ComputedContentSource; source: ComputedContentSource;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('days');
cacheTag(
...getComputedContentSourceCacheTags(
{
spaceId: params.spaceId,
organizationId: params.organizationId,
},
params.source
)
);
const res = await getAPI(input).spaces.getComputedDocument(params.spaceId, { const res = await getAPI(input).spaces.getComputedDocument(params.spaceId, {
source: params.source, source: params.source,
}); });
@@ -318,15 +371,17 @@ async function getReusableContent(
spaceId: string; spaceId: string;
revisionId: string; revisionId: string;
reusableContentId: string; reusableContentId: string;
}, }
) { ) {
'use cache'; 'use cache';
cacheLife('max');
try { try {
const res = await getAPI(input).spaces.getReusableContentInRevisionById( const res = await getAPI(input).spaces.getReusableContentInRevisionById(
params.spaceId, params.spaceId,
params.revisionId, params.revisionId,
params.reusableContentId, params.reusableContentId
); );
return res.data; return res.data;
} catch (error) { } catch (error) {
@@ -343,16 +398,23 @@ async function getLatestOpenAPISpecVersionContent(
params: { params: {
organizationId: string; organizationId: string;
slug: string; slug: string;
}, }
) { ) {
'use cache'; 'use cache';
cacheTag(getOpenAPISpecCacheTag(params.organizationId, params.slug)); cacheTag(
getCacheTag({
tag: 'openapi',
organization: params.organizationId,
openAPISpec: params.slug,
})
);
cacheLife('days');
try { try {
const res = await getAPI(input).orgs.getLatestOpenApiSpecVersionContent( const res = await getAPI(input).orgs.getLatestOpenApiSpecVersionContent(
params.organizationId, params.organizationId,
params.slug, params.slug
); );
return res.data; return res.data;
} catch (error) { } catch (error) {
@@ -370,14 +432,20 @@ async function getPublishedContentByUrl(
url: string; url: string;
visitorAuthToken: string | null; visitorAuthToken: string | null;
redirectOnError: boolean; redirectOnError: boolean;
}, }
) { ) {
'use cache'; 'use cache';
const { url, visitorAuthToken, redirectOnError } = params; const { url, visitorAuthToken, redirectOnError } = params;
const hostname = new URL(url).hostname; const hostname = new URL(url).hostname;
cacheTag(getHostnameCacheTag(hostname)); cacheTag(
getCacheTag({
tag: 'url',
hostname,
})
);
cacheLife('days');
const res = await getAPI(input).urls.getPublishedContentByUrl({ const res = await getAPI(input).urls.getPublishedContentByUrl({
url, url,
@@ -386,7 +454,12 @@ async function getPublishedContentByUrl(
}); });
if ('site' in res.data) { if ('site' in res.data) {
cacheTag(getSiteCacheTag(res.data.site)); cacheTag(
getCacheTag({
tag: 'site',
site: res.data.site,
})
);
} }
return res.data; return res.data;
@@ -398,16 +471,24 @@ async function getPublishedContentSite(
organizationId: string; organizationId: string;
siteId: string; siteId: string;
siteShareKey: string | undefined; siteShareKey: string | undefined;
}, }
) { ) {
'use cache'; 'use cache';
cacheTag(getSiteCacheTag(params.siteId));
cacheTag(
getCacheTag({
tag: 'site',
site: params.siteId,
})
);
cacheLife('days');
const res = await getAPI(input).orgs.getPublishedContentSite( const res = await getAPI(input).orgs.getPublishedContentSite(
params.organizationId, params.organizationId,
params.siteId, params.siteId,
{ {
shareKey: params.siteShareKey, shareKey: params.siteShareKey,
}, }
); );
return res.data; return res.data;
} }
@@ -419,10 +500,18 @@ async function getSiteRedirectBySource(
siteId: string; siteId: string;
siteShareKey: string | undefined; siteShareKey: string | undefined;
source: string; source: string;
}, }
) { ) {
'use cache'; 'use cache';
cacheTag(
getCacheTag({
tag: 'site',
site: params.siteId,
})
);
cacheLife('days');
try { try {
const res = await getAPI(input).orgs.getSiteRedirectBySource( const res = await getAPI(input).orgs.getSiteRedirectBySource(
params.organizationId, params.organizationId,
@@ -430,7 +519,7 @@ async function getSiteRedirectBySource(
{ {
shareKey: params.siteShareKey, shareKey: params.siteShareKey,
source: params.source, source: params.source,
}, }
); );
return res.data; return res.data;
@@ -449,6 +538,39 @@ async function getSiteRedirectBySource(
} }
} }
async function getEmbedByUrl(
input: DataFetcherInput,
params: {
url: string;
spaceId: string;
}
) {
'use cache';
cacheLife('weeks');
const api = getAPI(input);
const res = await api.spaces.getEmbedByUrlInSpace(params.spaceId, { url: params.url });
return res.data;
}
async function searchSiteContent(
input: DataFetcherInput,
params: Parameters<GitBookDataFetcher['searchSiteContent']>[0]
) {
'use cache';
const { organizationId, siteId, query, scope } = params;
cacheLife('days');
const res = await getAPI(input).orgs.searchSiteContent(organizationId, siteId, {
query,
...scope,
});
return res.data.items;
}
function getAPI(input: DataFetcherInput) { function getAPI(input: DataFetcherInput) {
const { apiEndpoint, apiToken } = input; const { apiEndpoint, apiToken } = input;
const api = new GitBookAPI({ const api = new GitBookAPI({
+33
View File
@@ -10,6 +10,18 @@ export interface GitBookDataFetcher {
*/ */
apiEndpoint: string; apiEndpoint: string;
/**
* Get an API client for the current context.
*/
api(): Promise<api.GitBookAPI>;
/**
* Create a data fetcher authenticated with a specific token.
*/
withToken(input: {
apiToken: string;
}): GitBookDataFetcher;
/** /**
* Get a user by its ID. * Get a user by its ID.
*/ */
@@ -91,6 +103,7 @@ export interface GitBookDataFetcher {
* Get a computed document by its space ID and computed source. * Get a computed document by its space ID and computed source.
*/ */
getComputedDocument(params: { getComputedDocument(params: {
organizationId: string;
spaceId: string; spaceId: string;
source: api.ComputedContentSource; source: api.ComputedContentSource;
}): Promise<api.JSONDocument>; }): Promise<api.JSONDocument>;
@@ -121,4 +134,24 @@ export interface GitBookDataFetcher {
siteShareKey: string | undefined; siteShareKey: string | undefined;
source: string; source: string;
}): Promise<{ redirect: api.SiteRedirect | null; target: string } | null>; }): Promise<{ redirect: api.SiteRedirect | null; target: string } | null>;
/**
* Get an embed by its URL.
*/
getEmbedByUrl(params: { url: string; spaceId: string }): Promise<api.Embed>;
/**
* Search content in a site.
*/
searchSiteContent(params: {
organizationId: string;
siteId: string;
query: string;
scope:
| { mode: 'all' }
| { mode: 'current'; siteSpaceId: string }
| { mode: 'specific'; siteSpaceIds: string[] };
/** Cache bust to ensure the search results are fresh when the space is updated. */
cacheBust?: string;
}): Promise<api.SearchSpaceResult[]>;
} }
+14 -14
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'bun:test'; import { describe, expect, it } from 'bun:test';
import { getURLLookupAlternatives, normalizeURL } from './urls'; import { getURLLookupAlternatives, normalizeURL } from './urls';
@@ -68,7 +68,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before the variant for a variant url', () => { it('should not match before the variant for a variant url', () => {
expect( expect(
getURLLookupAlternatives(new URL('https://test.gitbook.io/v/variant/space')), getURLLookupAlternatives(new URL('https://test.gitbook.io/v/variant/space'))
).toEqual({ ).toEqual({
revision: undefined, revision: undefined,
changeRequest: undefined, changeRequest: undefined,
@@ -85,7 +85,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before the variant for a variant in a share link', () => { it('should not match before the variant for a variant in a share link', () => {
expect( expect(
getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space')), getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space'))
).toEqual({ ).toEqual({
revision: undefined, revision: undefined,
changeRequest: undefined, changeRequest: undefined,
@@ -103,8 +103,8 @@ describe('getURLLookupAlternatives', () => {
it('should not match before a revision in a variant', () => { it('should not match before a revision in a variant', () => {
expect( expect(
getURLLookupAlternatives( getURLLookupAlternatives(
new URL('https://test.gitbook.io/v/variant/~/revisions/id/rest'), new URL('https://test.gitbook.io/v/variant/~/revisions/id/rest')
), )
).toEqual({ ).toEqual({
revision: 'id', revision: 'id',
changeRequest: undefined, changeRequest: undefined,
@@ -121,7 +121,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before a revision ID', () => { it('should not match before a revision ID', () => {
expect( expect(
getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/revisions/id/a/b/c')), getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/revisions/id/a/b/c'))
).toEqual({ ).toEqual({
revision: 'id', revision: 'id',
changeRequest: undefined, changeRequest: undefined,
@@ -138,7 +138,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before a change request ID', () => { it('should not match before a change request ID', () => {
expect( expect(
getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/changes/id/hello')), getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/changes/id/hello'))
).toEqual({ ).toEqual({
revision: undefined, revision: undefined,
changeRequest: 'id', changeRequest: 'id',
@@ -195,7 +195,7 @@ describe('getURLLookupAlternatives', () => {
it('should match a variant in a share-link', () => { it('should match a variant in a share-link', () => {
expect( expect(
getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space')), getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space'))
).toEqual({ ).toEqual({
revision: undefined, revision: undefined,
changeRequest: undefined, changeRequest: undefined,
@@ -213,8 +213,8 @@ describe('getURLLookupAlternatives', () => {
it('should match a revision in a variant in a share-link', () => { it('should match a revision in a variant in a share-link', () => {
expect( expect(
getURLLookupAlternatives( getURLLookupAlternatives(
new URL('https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c'), new URL('https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c')
), )
).toEqual({ ).toEqual({
revision: 'id', revision: 'id',
changeRequest: undefined, changeRequest: undefined,
@@ -232,8 +232,8 @@ describe('getURLLookupAlternatives', () => {
it('should match a change request in a variant in a share-link', () => { it('should match a change request in a variant in a share-link', () => {
expect( expect(
getURLLookupAlternatives( getURLLookupAlternatives(
new URL('https://test.gitbook.io/sharelink/v/variant/~/changes/id/a/b/c'), new URL('https://test.gitbook.io/sharelink/v/variant/~/changes/id/a/b/c')
), )
).toEqual({ ).toEqual({
revision: undefined, revision: undefined,
changeRequest: 'id', changeRequest: 'id',
@@ -367,13 +367,13 @@ describe('getURLLookupAlternatives', () => {
describe('normalizeURL', () => { describe('normalizeURL', () => {
it('should remove trailing slashes', () => { it('should remove trailing slashes', () => {
expect(normalizeURL(new URL('https://docs.mycompany.com/hello/'))).toEqual( expect(normalizeURL(new URL('https://docs.mycompany.com/hello/'))).toEqual(
new URL('https://docs.mycompany.com/hello'), new URL('https://docs.mycompany.com/hello')
); );
}); });
it('should remove duplicate slashes', () => { it('should remove duplicate slashes', () => {
expect(normalizeURL(new URL('https://docs.mycompany.com//hello//there'))).toEqual( expect(normalizeURL(new URL('https://docs.mycompany.com//hello//there'))).toEqual(
new URL('https://docs.mycompany.com/hello/there'), new URL('https://docs.mycompany.com/hello/there')
); );
}); });
}); });
+5 -9
View File
@@ -19,10 +19,6 @@ export async function getPublishedContentByURL(input: {
const url = stripURLSearch(lookupURL); const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url); const lookup = getURLLookupAlternatives(url);
console.log(
`lookup content for url "${url.toString()}", with ${lookup.urls.length} alternatives`,
);
const result = await race(lookup.urls, async (alternative, { signal }) => { const result = await race(lookup.urls, async (alternative, { signal }) => {
const api = new GitBookAPI({ const api = new GitBookAPI({
authToken: GITBOOK_API_TOKEN ?? undefined, authToken: GITBOOK_API_TOKEN ?? undefined,
@@ -43,8 +39,8 @@ export async function getPublishedContentByURL(input: {
headers: { headers: {
'x-gitbook-force-cache': 'true', 'x-gitbook-force-cache': 'true',
}, },
}, }
), )
); );
if (callResult.error) { if (callResult.error) {
@@ -76,8 +72,8 @@ export async function getPublishedContentByURL(input: {
'location', 'location',
joinPath( joinPath(
redirect.searchParams.get('location') ?? '', redirect.searchParams.get('location') ?? '',
alternative.extraPath, alternative.extraPath
), )
); );
data.redirect = redirect.toString(); data.redirect = redirect.toString();
} }
@@ -155,7 +151,7 @@ export function getURLLookupAlternatives(input: URL) {
throw new Error( throw new Error(
`Invalid extraPath ${extraPath} for url ${adding.toString()}, already set to ${ `Invalid extraPath ${extraPath} for url ${adding.toString()}, already set to ${
existing.extraPath existing.extraPath
}`, }`
); );
} }
return; return;
+12 -7
View File
@@ -1,18 +1,23 @@
import { RevisionPageDocument } from '@gitbook/api'; import type { RevisionPageDocument, Space } from '@gitbook/api';
import { GitBookDataFetcher } from './types'; import type { GitBookDataFetcher } from './types';
/** /**
* Get the document for a page. * Get the document for a page.
*/ */
export async function getPageDocument( export async function getPageDocument(
dataFetcher: GitBookDataFetcher, dataFetcher: GitBookDataFetcher,
spaceId: string, space: Space,
page: RevisionPageDocument, page: RevisionPageDocument
) { ) {
if (page.documentId) { if (page.documentId) {
return dataFetcher.getDocument({ spaceId, documentId: page.documentId }); return dataFetcher.getDocument({ spaceId: space.id, documentId: page.documentId });
} else if (page.computed) { }
return dataFetcher.getComputedDocument({ spaceId, source: page.computed }); if (page.computed) {
return dataFetcher.getComputedDocument({
organizationId: space.organization,
spaceId: space.id,
source: page.computed,
});
} }
return null; return null;
+24 -2
View File
@@ -8,10 +8,18 @@ export const GITBOOK_URL =
process.env.GITBOOK_URL ?? process.env.GITBOOK_URL ??
''); '');
/**
* URL at which static assets are served.
*/
export const GITBOOK_ASSETS_URL =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: (process.env.GITBOOK_ASSETS_PREFIX ?? GITBOOK_URL);
/** /**
* GitBook app URL. * GitBook app URL.
*/ */
export const GITBOOK_APP_URL = process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? `https://app.gitbook.com`; export const GITBOOK_APP_URL = process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? 'https://app.gitbook.com';
/** /**
* Default GitBook API URL endpoint. * Default GitBook API URL endpoint.
@@ -34,5 +42,19 @@ export const GITBOOK_USER_AGENT = process.env.GITBOOK_USER_AGENT ?? 'GitBook-Ope
* This is used to disable tracking in development mode. * This is used to disable tracking in development mode.
*/ */
export const GITBOOK_DISABLE_TRACKING = Boolean( export const GITBOOK_DISABLE_TRACKING = Boolean(
!!process.env.GITBOOK_DISABLE_TRACKING || process.env.NODE_ENV !== 'production', !!process.env.GITBOOK_DISABLE_TRACKING || process.env.NODE_ENV !== 'production'
); );
/**
* Hostname serving the integrations.
*/
export const GITBOOK_INTEGRATIONS_HOST =
process.env.GITBOOK_INTEGRATIONS_HOST ?? 'integrations.gitbook.com';
/**
* Endpoint to use for resizing images.
* It should be a Cloudflare domain with image resizing enabled.
*/
export const GITBOOK_IMAGE_RESIZE_URL = process.env.GITBOOK_IMAGE_RESIZE_URL ?? null;
export const GITBOOK_IMAGE_RESIZE_SIGNING_KEY =
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY ?? null;
@@ -1,8 +1,9 @@
import 'server-only'; import 'server-only';
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_URL } from '../env';
import type { GitBookSpaceLinker } from '../links';
import { type SignatureVersion, generateImageSignature } from './signatures';
import type { ImageResizer } from './types'; import type { ImageResizer } from './types';
import { generateImageSignature, SignatureVersion } from './signatures';
import { GitBookSpaceLinker } from '../links';
interface CloudflareImageJsonFormat { interface CloudflareImageJsonFormat {
width: number; width: number;
@@ -40,8 +41,12 @@ export function createImageResizer({
/** The host name of the current site. */ /** The host name of the current site. */
host: string; host: string;
}): ImageResizer { }): ImageResizer {
if (!GITBOOK_IMAGE_RESIZE_URL || !GITBOOK_IMAGE_RESIZE_SIGNING_KEY) {
return createNoopImageResizer();
}
return { return {
resize: (urlInput) => { getResizedImageURL: (urlInput) => {
if (!checkIsSizableImageURL(urlInput)) { if (!checkIsSizableImageURL(urlInput)) {
return null; return null;
} }
@@ -57,7 +62,9 @@ export function createImageResizer({
url: urlInput, url: urlInput,
}); });
const url = new URL(linker.toAbsoluteURL('/~gitbook/image')); const url = new URL(
linker.toAbsoluteURL(linker.toPathInContent('/~gitbook/image'))
);
url.searchParams.set('url', getImageAPIUrl(urlInput)); url.searchParams.set('url', getImageAPIUrl(urlInput));
if (options.width) { if (options.width) {
@@ -95,18 +102,11 @@ export function createImageResizer({
*/ */
export function createNoopImageResizer(): ImageResizer { export function createNoopImageResizer(): ImageResizer {
return { return {
resize: () => null, getResizedImageURL: () => null,
getImageSize: async (input) => null, getImageSize: async (_input) => null,
}; };
} }
/**
* Return true if images resizing is enabled.
*/
export function isImageResizingEnabled(): boolean {
return !!process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY;
}
/** /**
* Check if a URL is an HTTP URL. * Check if a URL is an HTTP URL.
*/ */
@@ -149,9 +149,9 @@ export function checkIsSizableImageURL(input: string): boolean {
*/ */
export async function getImageSize( export async function getImageSize(
input: string, input: string,
defaultSize: Partial<CloudflareImageOptions> = {}, defaultSize: Partial<CloudflareImageOptions> = {}
): Promise<{ width: number; height: number } | null> { ): Promise<{ width: number; height: number } | null> {
if (!isImageResizingEnabled() || !checkIsSizableImageURL(input)) { if (!checkIsSizableImageURL(input)) {
return null; return null;
} }
@@ -171,12 +171,7 @@ export async function getImageSize(
width: json.original.width, width: json.original.width,
height: json.original.height, height: json.original.height,
}; };
} catch (error) { } catch (_error) {
console.error(
`failed to fetch image size for ${input}: ${
(error as Error).stack ?? (error as Error).message ?? error
}`,
);
return null; return null;
} }
} }
@@ -188,7 +183,7 @@ export async function resizeImage(
input: string, input: string,
options: CloudflareImageOptions & { options: CloudflareImageOptions & {
signal?: AbortSignal; signal?: AbortSignal;
}, }
): Promise<Response> { ): Promise<Response> {
const { signal, ...resizeOptions } = options; const { signal, ...resizeOptions } = options;
@@ -203,10 +198,13 @@ export async function resizeImage(
// Since Cloudflare Images options on fetch are not supported on Cloudflare Pages, // Since Cloudflare Images options on fetch are not supported on Cloudflare Pages,
// we need to use the Cloudflare Image Resize API directly. // we need to use the Cloudflare Image Resize API directly.
if (process.env.GITBOOK_IMAGE_RESIZE_URL) { if (!GITBOOK_IMAGE_RESIZE_URL) {
const response = await fetch( throw new Error('GITBOOK_IMAGE_RESIZE_URL is not set');
`${process.env.GITBOOK_IMAGE_RESIZE_URL}${stringifyOptions( }
resizeOptions,
return await fetch(
`${GITBOOK_IMAGE_RESIZE_URL}${stringifyOptions(
resizeOptions
)}/${encodeURIComponent(input)}`, )}/${encodeURIComponent(input)}`,
{ {
headers: { headers: {
@@ -217,19 +215,8 @@ export async function resizeImage(
: `image/${resizeOptions.format || 'jpeg'}`, : `image/${resizeOptions.format || 'jpeg'}`,
}, },
signal, signal,
},
);
return response;
} }
);
return fetch(parsed, {
// @ts-ignore
cf: {
image: resizeOptions,
},
signal,
});
} }
function stringifyOptions(options: CloudflareImageOptions): string { function stringifyOptions(options: CloudflareImageOptions): string {
@@ -2,6 +2,8 @@ import 'server-only';
import fnv1a from '@sindresorhus/fnv1a'; import fnv1a from '@sindresorhus/fnv1a';
import type { MaybePromise } from 'p-map'; import type { MaybePromise } from 'p-map';
import { assert } from 'ts-essentials';
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY } from '../env';
/** /**
* GitBook has supported different version of image signing in the past. To maintain backwards * GitBook has supported different version of image signing in the past. To maintain backwards
@@ -26,7 +28,7 @@ type SignFn = (input: SignFnInput) => MaybePromise<string>;
*/ */
export async function verifyImageSignature( export async function verifyImageSignature(
input: SignFnInput, input: SignFnInput,
{ signature, version }: { signature: string; version: SignatureVersion }, { signature, version }: { signature: string; version: SignatureVersion }
): Promise<boolean> { ): Promise<boolean> {
const generator = IMAGE_SIGNATURE_FUNCTIONS[version]; const generator = IMAGE_SIGNATURE_FUNCTIONS[version];
const generated = await generator(input); const generated = await generator(input);
@@ -55,10 +57,11 @@ const fnv1aUtf8Buffer = new Uint8Array(512);
* The signature is relative to the current site being rendered to avoid serving images from other sites on the same domain. * The signature is relative to the current site being rendered to avoid serving images from other sites on the same domain.
*/ */
const generateSignatureV2: SignFn = async (input) => { const generateSignatureV2: SignFn = async (input) => {
assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
const all = [ const all = [
input.url, input.url,
input.host, // The hostname is used to avoid serving images from other sites on the same domain input.host, // The hostname is used to avoid serving images from other sites on the same domain
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
] ]
.filter(Boolean) .filter(Boolean)
.join(':'); .join(':');
@@ -74,7 +77,8 @@ const fnv1aUtf8BufferV1 = new Uint8Array(512);
* to know that it was the algorithm that was used. * to know that it was the algorithm that was used.
*/ */
const generateSignatureV1: SignFn = async (input) => { const generateSignatureV1: SignFn = async (input) => {
const all = [input.url, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':'); assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
const all = [input.url, GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
return fnv1a(all, { utf8Buffer: fnv1aUtf8BufferV1 }).toString(16); return fnv1a(all, { utf8Buffer: fnv1aUtf8BufferV1 }).toString(16);
}; };
@@ -84,7 +88,8 @@ const generateSignatureV1: SignFn = async (input) => {
* but still exist in previously generated and cached content. * but still exist in previously generated and cached content.
*/ */
const generateSignatureV0: SignFn = async (input) => { const generateSignatureV0: SignFn = async (input) => {
const all = [input.url, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':'); assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
const all = [input.url, GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(all)); const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(all));
// Convert ArrayBuffer to hex string // Convert ArrayBuffer to hex string
+2 -2
View File
@@ -20,10 +20,10 @@ export type ImageResizer = {
* @param input - The image URL to resize. * @param input - The image URL to resize.
* @param options - The options to resize the image. * @param options - The options to resize the image.
*/ */
resize(input: string): null | ((options: ResizeImageOptions) => Promise<string>); getResizedImageURL(imageURL: string): null | ((options: ResizeImageOptions) => Promise<string>);
/** /**
* Get the size of an image. * Get the size of an image.
*/ */
getImageSize(input: string, options: GetImageSizeOptions): Promise<ImageSize | null>; getImageSize(imageURL: string, options: GetImageSizeOptions): Promise<ImageSize | null>;
}; };
+4 -4
View File
@@ -1,14 +1,14 @@
import { ImageResizer, ResizeImageOptions } from './types'; import type { ImageResizer, ResizeImageOptions } from './types';
/** /**
* Quick utility to get a resized image URL. * Quick utility to get a resized image URL.
*/ */
export async function getResizedImageURL( export async function getResizedImageURL(
resizer: ImageResizer, resizer: ImageResizer | undefined,
url: string, url: string,
options: ResizeImageOptions, options: ResizeImageOptions
) { ) {
const getURL = resizer.resize(url); const getURL = resizer?.getResizedImageURL(url);
if (!getURL) { if (!getURL) {
return url; return url;
} }
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'bun:test';
import { appendBasePathToLinker, createLinker } from './links';
const root = createLinker({
host: 'docs.company.com',
pathname: '/',
});
const variantInSection = createLinker({
host: 'docs.company.com',
pathname: '/section/variant',
});
describe('toPathInContent', () => {
it('should return the correct path', () => {
expect(root.toPathInContent('some/path')).toBe('/some/path');
expect(variantInSection.toPathInContent('some/path')).toBe('/section/variant/some/path');
});
it('should handle leading slash', () => {
expect(root.toPathInContent('/some/path')).toBe('/some/path');
expect(variantInSection.toPathInContent('/some/path')).toBe('/section/variant/some/path');
});
});
describe('toAbsoluteURL', () => {
it('should return the correct path', () => {
expect(root.toAbsoluteURL('some/path')).toBe('https://docs.company.com/some/path');
expect(variantInSection.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
});
});
describe('appendBasePathToLinker', () => {
const prefixedRoot = appendBasePathToLinker(root, '/section/variant');
const prefixedVariantInSection = appendBasePathToLinker(variantInSection, '/base');
describe('toPathInContent', () => {
it('should return the correct path', () => {
expect(prefixedRoot.toPathInContent('some/path')).toBe('/section/variant/some/path');
expect(prefixedVariantInSection.toPathInContent('some/path')).toBe(
'/section/variant/base/some/path'
);
});
});
describe('toAbsoluteURL', () => {
it('should return the correct path', () => {
expect(prefixedRoot.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
expect(prefixedVariantInSection.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
});
});
});
+38 -16
View File
@@ -1,17 +1,26 @@
import { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import { getPagePath } from '@/lib/pages'; import { getPagePath } from '@/lib/pages';
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
/** /**
* Generic interface to generate links based on a given context. * Generic interface to generate links based on a given context.
*
* URL levels:
*
* https://docs.company.com/section/variant/page
*
* toPathInContent('some/path') => /section/variant/some/path
* toPathForPage({ pages, page }) => /section/variant/some/path
* toAbsoluteURL('some/path') => https://docs.company.com/some/path
*/ */
export interface GitBookSpaceLinker { export interface GitBookSpaceLinker {
/** /**
* Generate an absolute path for a relative path in the current space content. * Generate an absolute path for a relative path to the current content.
*/ */
toPathInSpace(relativePath: string): string; toPathInContent(relativePath: string): string;
/** /**
* Generate an absolute path for a page in the current space. * Generate an absolute path for a page in the current content.
* The result should NOT be passed to `toPathInContent`.
*/ */
toPathForPage(input: { toPathForPage(input: {
pages: RevisionPage[]; pages: RevisionPage[];
@@ -20,9 +29,14 @@ export interface GitBookSpaceLinker {
}): string; }): string;
/** /**
* Generate an absolute URL for a given path. * Generate an absolute URL for a given path relative to the host of the current content.
*/ */
toAbsoluteURL(absolutePath: string): string; toAbsoluteURL(absolutePath: string): string;
/**
* Generate a link (URL or path) for a GitBook content URL (url of another site)
*/
toLinkForContent(url: string): string;
} }
/** /**
@@ -34,14 +48,14 @@ export function createLinker(
protocol?: string; protocol?: string;
host: string; host: string;
pathname: string; pathname: string;
}, }
): GitBookSpaceLinker { ): GitBookSpaceLinker {
if (servedOn.host.includes('/')) { if (servedOn.host.includes('/')) {
throw new Error('Host cannot include a slash'); throw new Error('Host cannot include a slash');
} }
const linker: GitBookSpaceLinker = { const linker: GitBookSpaceLinker = {
toPathInSpace(relativePath: string): string { toPathInContent(relativePath: string): string {
return joinPaths(servedOn.pathname, relativePath); return joinPaths(servedOn.pathname, relativePath);
}, },
@@ -50,7 +64,11 @@ export function createLinker(
}, },
toPathForPage({ pages, page, anchor }) { toPathForPage({ pages, page, anchor }) {
return linker.toPathInSpace(getPagePath(pages, page)) + (anchor ? '#' + anchor : ''); return linker.toPathInContent(getPagePath(pages, page)) + (anchor ? `#${anchor}` : '');
},
toLinkForContent(url: string): string {
return url;
}, },
}; };
@@ -60,32 +78,36 @@ export function createLinker(
/** /**
* Append a prefix to a linker. * Append a prefix to a linker.
*/ */
export function appendPrefixToLinker( export function appendBasePathToLinker(
linker: GitBookSpaceLinker, linker: GitBookSpaceLinker,
prefix: string, basePath: string
): GitBookSpaceLinker { ): GitBookSpaceLinker {
const linkerWithPrefix: GitBookSpaceLinker = { const linkerWithPrefix: GitBookSpaceLinker = {
toPathInSpace(relativePath: string): string { toPathInContent(relativePath: string): string {
return linker.toPathInSpace(joinPaths(prefix, relativePath)); return linker.toPathInContent(joinPaths(basePath, relativePath));
}, },
toAbsoluteURL(absolutePath: string): string { toAbsoluteURL(absolutePath: string): string {
return linker.toAbsoluteURL(joinPaths(prefix, absolutePath)); return linker.toAbsoluteURL(absolutePath);
}, },
toPathForPage({ pages, page, anchor }) { toPathForPage({ pages, page, anchor }) {
return ( return (
linkerWithPrefix.toPathInSpace(getPagePath(pages, page)) + linkerWithPrefix.toPathInContent(getPagePath(pages, page)) +
(anchor ? '#' + anchor : '') (anchor ? `#${anchor}` : '')
); );
}, },
toLinkForContent(url: string): string {
return linker.toLinkForContent(url);
},
}; };
return linkerWithPrefix; return linkerWithPrefix;
} }
function joinPaths(prefix: string, path: string): string { function joinPaths(prefix: string, path: string): string {
const prefixPath = prefix.endsWith('/') ? prefix : prefix + '/'; const prefixPath = prefix.endsWith('/') ? prefix : `${prefix}/`;
const suffixPath = path.startsWith('/') ? path.slice(1) : path; const suffixPath = path.startsWith('/') ? path.slice(1) : path;
return prefixPath + suffixPath; return prefixPath + suffixPath;
} }
+84 -1
View File
@@ -1,14 +1,51 @@
import { CustomizationThemeMode } from '@gitbook/api'; import { CustomizationThemeMode, type PublishedSiteContent } from '@gitbook/api';
import { headers } from 'next/headers'; import { headers } from 'next/headers';
export enum MiddlewareHeaders { export enum MiddlewareHeaders {
/**
* Type of the route (static or dynamic)
*/
RouteType = 'x-gitbook-route-type',
/**
* The URL of the site (without the pathname)
*/
SiteURL = 'x-gitbook-site-url',
/**
* The data associated with the URL.
*/
SiteURLData = 'x-gitbook-site-url-data',
/**
* The mode of the URL (url or url-host)
*/
URLMode = 'x-gitbook-url-mode', URLMode = 'x-gitbook-url-mode',
/**
* The theme of the page (light or dark)
*/
Theme = 'x-gitbook-theme', Theme = 'x-gitbook-theme',
/**
* The customization override to apply.
*/
Customization = 'x-gitbook-customization', Customization = 'x-gitbook-customization',
/**
* Token to use for the API.
*/
APIToken = 'x-gitbook-token',
/**
* The visitor token used to access this content
*/
VisitorAuthToken = 'x-gitbook-visitor-token',
} }
/** /**
* Get the URL mode from the middleware headers. * Get the URL mode from the middleware headers.
* This function should only be called in a server action or a dynamic route.
*/ */
export async function getURLModeFromMiddleware(): Promise<'url' | 'url-host'> { export async function getURLModeFromMiddleware(): Promise<'url' | 'url-host'> {
const headersList = await headers(); const headersList = await headers();
@@ -20,8 +57,40 @@ export async function getURLModeFromMiddleware(): Promise<'url' | 'url-host'> {
return mode as 'url' | 'url-host'; return mode as 'url' | 'url-host';
} }
/**
* Get the site URL data from the middleware headers.
* This function should only be called in a server action or a dynamic route.
*/
export async function getSiteURLDataFromMiddleware(): Promise<PublishedSiteContent> {
const headersList = await headers();
const siteURLData = headersList.get(MiddlewareHeaders.SiteURLData);
if (!siteURLData) {
throw new Error(
'Site URL data is not set by the middleware. This should only be called in a server action or a dynamic route.'
);
}
return JSON.parse(siteURLData);
}
/**
* Get the URL from the middleware headers.
* This function should only be called in a server action or a dynamic route.
*/
export async function getSiteURLFromMiddleware(): Promise<string> {
const headersList = await headers();
const siteURL = headersList.get(MiddlewareHeaders.SiteURL);
if (!siteURL) {
throw new Error('URL mode is not set by the middleware');
}
return siteURL;
}
/** /**
* For preview, the theme can be set via query string (?theme=light). * For preview, the theme can be set via query string (?theme=light).
* This function should only be called in a dynamic route.
*/ */
export async function getThemeFromMiddleware() { export async function getThemeFromMiddleware() {
const headersList = await headers(); const headersList = await headers();
@@ -34,3 +103,17 @@ export async function getThemeFromMiddleware() {
? CustomizationThemeMode.Light ? CustomizationThemeMode.Light
: CustomizationThemeMode.Dark; : CustomizationThemeMode.Dark;
} }
/**
* Get the visitor auth token from the middleware headers.
* This function should only be called in a dynamic route.
*/
export async function getVisitorAuthTokenFromMiddleware(): Promise<string | null> {
const headersList = await headers();
const visitorAuthToken = headersList.get(MiddlewareHeaders.VisitorAuthToken);
if (!visitorAuthToken) {
return null;
}
return visitorAuthToken;
}
@@ -0,0 +1,31 @@
import { type GitBookBaseContext, fetchSiteContextByURLLookup, getBaseContext } from './context';
import {
getSiteURLDataFromMiddleware,
getSiteURLFromMiddleware,
getURLModeFromMiddleware,
} from './middleware';
/**
* Get the base context for a server action.
* This function should only be called in a server action.
*/
export async function getServerActionBaseContext() {
const siteURL = await getSiteURLFromMiddleware();
const siteURLData = await getSiteURLDataFromMiddleware();
const urlMode = await getURLModeFromMiddleware();
return getBaseContext({
siteURL,
urlMode,
apiToken: siteURLData.apiToken,
});
}
/**
* Fetch the context for a site in a server action.
* The server action is always dynamic and the request is passed through the middleware.
*/
export async function fetchServerActionSiteContext(baseContext: GitBookBaseContext) {
const siteURLData = await getSiteURLDataFromMiddleware();
return fetchSiteContextByURLLookup(baseContext, siteURLData);
}
+94 -18
View File
@@ -1,10 +1,12 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { GitBookAPIError } from '@gitbook/api'; import { GitBookAPIError } from '@gitbook/api';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { removeTrailingSlash } from '@/lib/paths'; import { getContentSecurityPolicy } from '@/lib/csp';
import { MiddlewareHeaders } from '@v2/lib/middleware'; import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import { serveResizedImage } from '@/routes/image';
import { getPublishedContentByURL } from '@v2/lib/data'; import { getPublishedContentByURL } from '@v2/lib/data';
import { MiddlewareHeaders } from '@v2/lib/middleware';
export const config = { export const config = {
matcher: ['/((?!_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)'], matcher: ['/((?!_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)'],
@@ -13,12 +15,30 @@ export const config = {
type URLWithMode = { url: URL; mode: 'url' | 'url-host' }; type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
try {
/**
* Serve image resizing requests (all requests containing `/~gitbook/image`).
* All URLs containing `/~gitbook/image` are rewritten to `/~gitbook/image`
* and serve from a single route handler.
*
* In GitBook v1: image resizing was done at the root of the hostname (docs.company.com/~gitbook/image)
* In GitBook v2: image resizing is done at the content level (docs.company.com/section/variant/~gitbook/image)
*/
if (request.nextUrl.pathname.endsWith('/~gitbook/image')) {
return serveResizedImage(request);
}
// Route all requests to a site
const extracted = extractURL(request); const extracted = extractURL(request);
if (extracted) { if (extracted) {
return serveSiteByURL(request, extracted); return serveSiteByURL(request, extracted);
} }
// Handle the rest with the router default logic
return NextResponse.next(); return NextResponse.next();
} catch (error) {
return serveErrorResponse(error as Error);
}
} }
/** /**
@@ -35,17 +55,8 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
}); });
if (result.error) { if (result.error) {
if (result.error instanceof GitBookAPIError) {
return NextResponse.json(
{
error: result.error.message,
},
{ status: result.error.code },
);
} else {
throw result.error; throw result.error;
} }
}
const { data } = result; const { data } = result;
@@ -53,33 +64,75 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
return NextResponse.redirect(data.redirect); return NextResponse.redirect(data.redirect);
} }
const routeType = dynamicHeaders ? 'dynamic' : 'static';
const requestHeaders = new Headers(request.headers); const requestHeaders = new Headers(request.headers);
requestHeaders.set(MiddlewareHeaders.RouteType, routeType);
requestHeaders.set(MiddlewareHeaders.URLMode, mode); requestHeaders.set(MiddlewareHeaders.URLMode, mode);
requestHeaders.set(MiddlewareHeaders.SiteURL, `${url.origin}${data.basePath}`);
requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(data));
if (dynamicHeaders) { if (dynamicHeaders) {
for (const [key, value] of Object.entries(dynamicHeaders)) { for (const [key, value] of Object.entries(dynamicHeaders)) {
requestHeaders.set(key, value); requestHeaders.set(key, value);
} }
} }
// Pass a x-forwarded-host and origin that are equal to ensure Next doesn't block server actions when proxied
requestHeaders.set('x-forwarded-host', request.nextUrl.host);
requestHeaders.set('origin', request.nextUrl.origin);
const route = [ const route = [
'sites', 'sites',
dynamicHeaders ? 'dynamic' : 'static', routeType,
mode, mode,
encodeURIComponent(url.host + data.basePath), encodeURIComponent(url.host + data.basePath),
encodeURIComponent(removeTrailingSlash(data.pathname) || '/'), encodePathInSiteContent(data.pathname),
].join('/'); ].join('/');
return NextResponse.rewrite(new URL('/' + route, request.url), { console.log(`rewriting to ${route}`);
const rewrittenURL = new URL(`/${route}`, request.nextUrl.toString());
const response = NextResponse.rewrite(rewrittenURL, {
request: {
headers: requestHeaders, headers: requestHeaders,
},
}); });
// Add Content Security Policy header
response.headers.set('content-security-policy', getContentSecurityPolicy());
return response;
} }
/** /**
* The URL of the GitBook content can be passed in 2 different ways: * Serve an error response.
*/
function serveErrorResponse(error: Error) {
if (error instanceof GitBookAPIError) {
return NextResponse.json(
{ error: error.message },
{ status: 500, headers: { 'content-type': 'application/json' } }
);
}
throw error;
}
/**
* The URL of the GitBook content can be passed in 3 different ways:
* - The request URL is in the `X-GitBook-URL` header.
* - Hostname is in the `X-GitBook-Host` header and the pathname is the path in the request URL. * - Hostname is in the `X-GitBook-Host` header and the pathname is the path in the request URL.
* - The request URL is matching `/url/:url` * - The request URL is matching `/url/:url`
*/ */
function extractURL(request: NextRequest): URLWithMode | null { function extractURL(request: NextRequest): URLWithMode | null {
const xGitbookUrl = request.headers.get('x-gitbook-url');
if (xGitbookUrl) {
return {
url: new URL(xGitbookUrl),
mode: 'url-host',
};
}
const xGitbookHost = request.headers.get('x-gitbook-host'); const xGitbookHost = request.headers.get('x-gitbook-host');
if (xGitbookHost) { if (xGitbookHost) {
return { return {
@@ -102,10 +155,33 @@ function extractURL(request: NextRequest): URLWithMode | null {
/** /**
* Evaluate if a request is dynamic or static. * Evaluate if a request is dynamic or static.
*/ */
function getDynamicHeaders(request: NextRequest): null | Record<string, string> { function getDynamicHeaders(_request: NextRequest): null | Record<string, string> {
// TODO: // TODO:
// - check token in query string // - check token in query string
// - check token in cookies // - check token in cookies
// - check special headers or query string // - check special headers or query string
return null; return null;
} }
/**
* Encode path in a site content.
* Special paths are not encoded and passed to be handled by the route handlers.
*/
function encodePathInSiteContent(rawPathname: string) {
const pathname = removeLeadingSlash(removeTrailingSlash(rawPathname));
if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) {
return pathname;
}
switch (pathname) {
case '~gitbook/icon':
case '~gitbook/image':
case 'llms.txt':
case 'sitemap.xml':
case 'robots.txt':
return pathname;
default:
return encodeURIComponent(pathname || '/');
}
}
-31
View File
@@ -1,31 +0,0 @@
{
"extends": "next/core-web-vitals",
"plugins": ["import"],
"rules": {
"import/order": [
"error",
{
"groups": ["builtin", "external", ["internal", "parent", "sibling", "index"]],
"newlines-between": "always",
"distinctGroup": true,
"pathGroups": [
{
"pattern": "@/**",
"group": "external",
"position": "after"
},
{
"pattern": "@gitbook/**",
"group": "external",
"position": "after"
}
],
"alphabetize": {
"order": "asc",
"caseInsensitive": true
}
}
],
"@next/next/no-img-element": ["off"]
}
}
+28
View File
@@ -1,5 +1,33 @@
# gitbook # gitbook
## 0.6.5
### Patch Changes
- 05ffd0e: Improving data cache management for computed content
- 8beb5d6: Add input elements to ContentKit
- Updated dependencies [53f5dbe]
- Updated dependencies [05ffd0e]
- Updated dependencies [8beb5d6]
- @gitbook/openapi-parser@2.0.2
- @gitbook/cache-tags@0.1.0
- @gitbook/react-contentkit@0.6.1
- @gitbook/react-openapi@1.0.5
## 0.6.4
### Patch Changes
- 9b914d1: Fix getProxyModeBasePath that was computing incorrect base path in some scenarios
- 2ae76f9: Change how a site in proxy mode is resolved
- 027a859: Add support for links style customization option
- 3e11678: fix: lost section groups
- 3319375: Support OpenAPI operation block
- Updated dependencies [722f02e]
- Updated dependencies [0924259]
- @gitbook/react-openapi@1.0.4
- @gitbook/openapi-parser@2.0.1
## 0.6.3 ## 0.6.3
### Patch Changes ### Patch Changes
+1 -6
View File
@@ -1,4 +1,4 @@
import { runTestCases, TestsCase, waitForCookiesDialog } from './util'; import { type TestsCase, runTestCases } from './util';
/** A list of test cases to run on the customers' docs sites. */ /** A list of test cases to run on the customers' docs sites. */
const testCases: TestsCase[] = [ const testCases: TestsCase[] = [
@@ -225,11 +225,6 @@ const testCases: TestsCase[] = [
baseUrl: 'https://docs.raydium.io', baseUrl: 'https://docs.raydium.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{
name: 'docs.solv.finance',
baseUrl: 'https://docs.solv.finance',
tests: [{ name: 'Home', url: '/' }],
},
{ {
name: 'docs.fluentbit.io', name: 'docs.fluentbit.io',
baseUrl: 'https://docs.fluentbit.io', baseUrl: 'https://docs.fluentbit.io',
+87 -68
View File
@@ -9,12 +9,13 @@ import { expect } from '@playwright/test';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { import {
VISITOR_TOKEN_COOKIE,
getVisitorAuthCookieName, getVisitorAuthCookieName,
getVisitorAuthCookieValue, getVisitorAuthCookieValue,
VISITOR_TOKEN_COOKIE,
} from '@/lib/visitor-token'; } from '@/lib/visitor-token';
import { import {
type TestsCase,
allDeprecatedThemePresets, allDeprecatedThemePresets,
allLocales, allLocales,
allSidebarBackgroundStyles, allSidebarBackgroundStyles,
@@ -24,7 +25,6 @@ import {
getCustomizationURL, getCustomizationURL,
headerLinks, headerLinks,
runTestCases, runTestCases,
TestsCase,
waitForCookiesDialog, waitForCookiesDialog,
} from './util'; } from './util';
@@ -43,7 +43,7 @@ const testCases: TestsCase[] = [
url: '', url: '',
run: async (page) => { run: async (page) => {
await expect(page.locator('[data-testid="space-dropdown-button"]')).toHaveCount( await expect(page.locator('[data-testid="space-dropdown-button"]')).toHaveCount(
0, 0
); );
}, },
}, },
@@ -114,20 +114,20 @@ const testCases: TestsCase[] = [
await spaceDrowpdown.click(); await spaceDrowpdown.click();
const variantSelectionDropdown = page.locator( const variantSelectionDropdown = page.locator(
'css=[data-testid="space-dropdown-button"] + div', 'css=[data-testid="space-dropdown-button"] + div'
); );
// the customized space title // the customized space title
await expect( await expect(
variantSelectionDropdown.getByRole('link', { variantSelectionDropdown.getByRole('link', {
name: 'Multi-Variants', name: 'Multi-Variants',
}), })
).toBeVisible(); ).toBeVisible();
// the NON-customized space title // the NON-customized space title
await expect( await expect(
variantSelectionDropdown.getByRole('link', { variantSelectionDropdown.getByRole('link', {
name: 'RFCs', name: 'RFCs',
}), })
).toBeVisible(); ).toBeVisible();
}, },
}, },
@@ -156,7 +156,7 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true', 'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true'
); );
}, },
}, },
@@ -179,7 +179,7 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true', 'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true'
); );
}, },
}, },
@@ -195,7 +195,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`; return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
})(), })(),
@@ -214,7 +214,38 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true', 'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true'
);
},
},
],
},
{
name: 'GitBook Site (Sections and Section Groups)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/sections/',
tests: [
{
name: 'Site with sections and section groups',
url: '',
},
{
name: 'Section group dropdown',
url: '',
run: async (page) => {
await page.getByRole('button', { name: 'Test Section Group 1' }).hover();
await expect(page.getByRole('link', { name: /Section B/ })).toBeVisible();
},
},
{
name: 'Section group link',
url: '',
screenshot: false,
run: async (page) => {
const sectionGroupDropdown = await page.getByText('Test Section Group 1');
await sectionGroupDropdown.hover();
await page.getByText('Section B').click();
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/sections/sections-4'
); );
}, },
}, },
@@ -331,7 +362,7 @@ const testCases: TestsCase[] = [
for (const p of document.querySelectorAll('p')) { for (const p of document.querySelectorAll('p')) {
if ( if (
p.textContent?.includes( p.textContent?.includes(
'This image has intrinsic 400px width, but renders as 300px:', 'This image has intrinsic 400px width, but renders as 300px:'
) )
) { ) {
p.style.color = 'transparent'; p.style.color = 'transparent';
@@ -413,7 +444,7 @@ const testCases: TestsCase[] = [
await page.waitForFunction(() => { await page.waitForFunction(() => {
const fonts = Array.from(document.fonts.values()); const fonts = Array.from(document.fonts.values());
const mjxFonts = fonts.filter( const mjxFonts = fonts.filter(
(font) => font.family === 'MJXZERO' || font.family === 'MJXTEX', (font) => font.family === 'MJXZERO' || font.family === 'MJXTEX'
); );
return ( return (
mjxFonts.length === 2 && mjxFonts.length === 2 &&
@@ -505,9 +536,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: `With duotone icons - Theme mode ${themeMode}`, name: `With duotone icons - Theme mode ${themeMode}`,
url: url: `page-options/page-with-icon${getCustomizationURL({
'page-options/page-with-icon' +
getCustomizationURL({
styling: { styling: {
icons: CustomizationIconsStyle.Duotone, icons: CustomizationIconsStyle.Duotone,
}, },
@@ -515,7 +544,7 @@ const testCases: TestsCase[] = [
default: themeMode, default: themeMode,
toggeable: false, toggeable: false,
}, },
}), })}`,
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
@@ -643,7 +672,7 @@ const testCases: TestsCase[] = [
const sharedSpaceLink = page.locator('a.underline'); const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click(); await sharedSpaceLink.click();
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'shared' }), page.getByRole('heading', { level: 1, name: 'shared' })
).toBeVisible(); ).toBeVisible();
const url = page.url(); const url = page.url();
expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site
@@ -663,7 +692,7 @@ const testCases: TestsCase[] = [
run: async (page) => { run: async (page) => {
await page.locator('a.underline').click(); await page.locator('a.underline').click();
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'shared' }), page.getByRole('heading', { level: 1, name: 'shared' })
).toBeVisible(); ).toBeVisible();
const url = page.url(); const url = page.url();
expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site
@@ -700,7 +729,7 @@ const testCases: TestsCase[] = [
url: 'invalid/', url: 'invalid/',
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByText('Authentication missing to access this content'), page.getByText('Authentication missing to access this content')
).toBeVisible(); ).toBeVisible();
}, },
screenshot: false, screenshot: false,
@@ -709,7 +738,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Space', name: 'Visitor Auth - Space',
baseUrl: `https://gitbook.gitbook.io/gbo-va-space/`, baseUrl: 'https://gitbook.gitbook.io/gbo-va-space/',
tests: [ tests: [
{ {
name: 'First', name: 'First',
@@ -722,13 +751,13 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `first?jwt_token=${token}`; return `first?jwt_token=${token}`;
})(), })(),
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'first' }), page.getByRole('heading', { level: 1, name: 'first' })
).toBeVisible(); ).toBeVisible();
}, },
screenshot: false, screenshot: false,
@@ -744,13 +773,13 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `second?jwt_token=${token}`; return `second?jwt_token=${token}`;
})(), })(),
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'second' }), page.getByRole('heading', { level: 1, name: 'second' })
).toBeVisible(); ).toBeVisible();
}, },
screenshot: false, screenshot: false,
@@ -759,7 +788,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Collection', name: 'Visitor Auth - Collection',
baseUrl: `https://gitbook.gitbook.io/gbo-va-collection/`, baseUrl: 'https://gitbook.gitbook.io/gbo-va-collection/',
tests: [ tests: [
{ {
name: 'Root', name: 'Root',
@@ -772,7 +801,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), })(),
@@ -789,7 +818,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `spacea?jwt_token=${token}`; return `spacea?jwt_token=${token}`;
})(), })(),
@@ -806,7 +835,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `spaceb?jwt_token=${token}`; return `spaceb?jwt_token=${token}`;
})(), })(),
@@ -823,7 +852,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `spacec?jwt_token=${token}`; return `spacec?jwt_token=${token}`;
})(), })(),
@@ -833,7 +862,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Space (custom domain)', name: 'Visitor Auth - Space (custom domain)',
baseUrl: `https://test.gitbook.community/`, baseUrl: 'https://test.gitbook.community/',
tests: [ tests: [
{ {
name: 'Root', name: 'Root',
@@ -846,7 +875,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), })(),
@@ -863,13 +892,13 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `first?jwt_token=${token}`; return `first?jwt_token=${token}`;
})(), })(),
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'first' }), page.getByRole('heading', { level: 1, name: 'first' })
).toBeVisible(); ).toBeVisible();
}, },
screenshot: false, screenshot: false,
@@ -885,7 +914,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `custom-page?jwt_token=${token}`; return `custom-page?jwt_token=${token}`;
})(), })(),
@@ -902,7 +931,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `custom-page/inner-page?jwt_token=${token}`; return `custom-page/inner-page?jwt_token=${token}`;
})(), })(),
@@ -912,7 +941,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Site (redirects to fallback/auth URL)', name: 'Visitor Auth - Site (redirects to fallback/auth URL)',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/`, baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/',
tests: [ tests: [
{ {
name: 'Redirect to fallback on invalid token pulled from cookie', name: 'Redirect to fallback on invalid token pulled from cookie',
@@ -927,7 +956,7 @@ const testCases: TestsCase[] = [
'invalidKey', 'invalidKey',
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return [ return [
{ {
@@ -952,13 +981,13 @@ const testCases: TestsCase[] = [
'invalidKey', 'invalidKey',
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), })(),
run: async (page) => { run: async (page) => {
await expect(page.locator('pre')).toContainText( await expect(page.locator('pre')).toContainText(
'Error while validating the JWT token. Reason: The token signature is invalid.', 'Error while validating the JWT token. Reason: The token signature is invalid.'
); );
}, },
}, },
@@ -985,7 +1014,7 @@ const testCases: TestsCase[] = [
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: `Index by default`, name: 'Index by default',
url: '?x-gitbook-search-indexation=true', url: '?x-gitbook-search-indexation=true',
screenshot: false, screenshot: false,
run: async (page) => { run: async (page) => {
@@ -1033,7 +1062,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Adaptive Content - VA', name: 'Adaptive Content - VA',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/`, baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/',
tests: [ tests: [
{ {
name: 'isAlphaUser', name: 'isAlphaUser',
@@ -1047,7 +1076,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), })(),
@@ -1074,7 +1103,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), })(),
@@ -1102,7 +1131,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), })(),
@@ -1121,7 +1150,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Adaptive Content - Public', name: 'Adaptive Content - Public',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/`, baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/',
tests: [ tests: [
{ {
name: 'No custom cookie', name: 'No custom cookie',
@@ -1154,7 +1183,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return [ return [
{ {
@@ -1193,7 +1222,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return [ return [
{ {
@@ -1233,7 +1262,7 @@ const testCases: TestsCase[] = [
privateKey, privateKey,
{ {
expiresIn: '24h', expiresIn: '24h',
}, }
); );
return [ return [
{ {
@@ -1274,25 +1303,21 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Table with straight corners', name: 'Table with straight corners',
url: url: `blocks/tables${getCustomizationURL({
'blocks/tables' +
getCustomizationURL({
styling: { styling: {
corners: CustomizationCorners.Straight, corners: CustomizationCorners.Straight,
}, },
}), })}`,
run: waitForCookiesDialog, run: waitForCookiesDialog,
fullPage: true, fullPage: true,
}, },
{ {
name: 'Table with primary color', name: 'Table with primary color',
url: url: `blocks/tables${getCustomizationURL({
'blocks/tables' +
getCustomizationURL({
styling: { styling: {
tint: { color: { light: '#346DDB', dark: '#346DDB' } }, tint: { color: { light: '#346DDB', dark: '#346DDB' } },
}, },
}), })}`,
run: waitForCookiesDialog, run: waitForCookiesDialog,
fullPage: true, fullPage: true,
}, },
@@ -1300,22 +1325,18 @@ const testCases: TestsCase[] = [
...allThemeModes.flatMap((theme) => [ ...allThemeModes.flatMap((theme) => [
{ {
name: `Table in ${theme} mode`, name: `Table in ${theme} mode`,
url: url: `blocks/tables${getCustomizationURL({
'blocks/tables' +
getCustomizationURL({
themes: { themes: {
default: theme, default: theme,
toggeable: false, toggeable: false,
}, },
}), })}`,
run: waitForCookiesDialog, run: waitForCookiesDialog,
fullPage: true, fullPage: true,
}, },
{ {
name: `Table with straight corners in ${theme} mode`, name: `Table with straight corners in ${theme} mode`,
url: url: `blocks/tables${getCustomizationURL({
'blocks/tables' +
getCustomizationURL({
styling: { styling: {
corners: CustomizationCorners.Straight, corners: CustomizationCorners.Straight,
}, },
@@ -1323,15 +1344,13 @@ const testCases: TestsCase[] = [
default: theme, default: theme,
toggeable: false, toggeable: false,
}, },
}), })}`,
run: waitForCookiesDialog, run: waitForCookiesDialog,
fullPage: true, fullPage: true,
}, },
{ {
name: `Table with primary color in ${theme} mode`, name: `Table with primary color in ${theme} mode`,
url: url: `blocks/tables${getCustomizationURL({
'blocks/tables' +
getCustomizationURL({
styling: { styling: {
tint: { color: { light: '#346DDB', dark: '#346DDB' } }, tint: { color: { light: '#346DDB', dark: '#346DDB' } },
}, },
@@ -1339,7 +1358,7 @@ const testCases: TestsCase[] = [
default: theme, default: theme,
toggeable: false, toggeable: false,
}, },
}), })}`,
run: waitForCookiesDialog, run: waitForCookiesDialog,
fullPage: true, fullPage: true,
}, },
+26 -10
View File
@@ -3,7 +3,7 @@ import {
CustomizationBackground, CustomizationBackground,
CustomizationCorners, CustomizationCorners,
CustomizationFont, CustomizationFont,
CustomizationHeaderItem, type CustomizationHeaderItem,
CustomizationHeaderPreset, CustomizationHeaderPreset,
CustomizationIconsStyle, CustomizationIconsStyle,
CustomizationLinksStyle, CustomizationLinksStyle,
@@ -11,14 +11,14 @@ import {
CustomizationSidebarBackgroundStyle, CustomizationSidebarBackgroundStyle,
CustomizationSidebarListStyle, CustomizationSidebarListStyle,
CustomizationTheme, CustomizationTheme,
CustomizationThemedColor,
CustomizationThemeMode, CustomizationThemeMode,
SiteCustomizationSettings, type CustomizationThemedColor,
type SiteCustomizationSettings,
} from '@gitbook/api'; } from '@gitbook/api';
import { BrowserContext, expect, Page, test } from '@playwright/test'; import { type BrowserContext, type Page, expect, test } from '@playwright/test';
import deepMerge from 'deepmerge'; import deepMerge from 'deepmerge';
import rison from 'rison'; import rison from 'rison';
import { DeepPartial } from 'ts-essentials'; import type { DeepPartial } from 'ts-essentials';
import { getContentTestURL } from '../tests/utils'; import { getContentTestURL } from '../tests/utils';
@@ -151,9 +151,25 @@ export function runTestCases(testCases: TestsCase[]) {
...cookie, ...cookie,
domain: new URL(url).host, domain: new URL(url).host,
path: '/', path: '/',
})), }))
); );
} }
// Set the header to disable the Vercel toolbar
// But only on the main document as it'd cause CORS issues on other resources
await page.route('**/*', async (route, request) => {
if (request.resourceType() === 'document') {
await route.continue({
headers: {
...request.headers(),
'x-vercel-skip-toolbar': '1',
},
});
} else {
await route.continue();
}
});
await page.goto(url); await page.goto(url);
if (testEntry.run) { if (testEntry.run) {
await testEntry.run(page); await testEntry.run(page);
@@ -231,11 +247,11 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
font: CustomizationFont.Inter, font: CustomizationFont.Inter,
background: CustomizationBackground.Plain, background: CustomizationBackground.Plain,
icons: CustomizationIconsStyle.Regular, icons: CustomizationIconsStyle.Regular,
links: CustomizationLinksStyle.Default,
sidebar: { sidebar: {
background: CustomizationSidebarBackgroundStyle.Default, background: CustomizationSidebarBackgroundStyle.Default,
list: CustomizationSidebarListStyle.Default, list: CustomizationSidebarListStyle.Default,
}, },
links: CustomizationLinksStyle.Default,
}, },
internationalization: { internationalization: {
locale: CustomizationLocale.En, locale: CustomizationLocale.En,
@@ -296,7 +312,7 @@ async function waitForIcons(page: Page) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = () => resolve(img); img.onload = () => resolve(img);
img.onerror = (error) => reject(new Error(`Failed to load image: ${src}`)); img.onerror = (_error) => reject(new Error(`Failed to load image: ${src}`));
img.src = src; img.src = src;
}); });
} }
@@ -312,7 +328,7 @@ async function waitForIcons(page: Page) {
throw new Error('No mask-image'); throw new Error('No mask-image');
} }
await loadImage(url); await loadImage(url);
}), })
); );
}); });
} }
@@ -327,7 +343,7 @@ async function waitForTOCScrolling(page: Page) {
await expect(toc).toBeVisible(); await expect(toc).toBeVisible();
await page.evaluate(() => { await page.evaluate(() => {
const tocScrollContainer = document.querySelector( const tocScrollContainer = document.querySelector(
'[data-testid="table-of-contents"] [data-testid="toc-scroll-container"]', '[data-testid="table-of-contents"] [data-testid="toc-scroll-container"]'
); );
if (!tocScrollContainer) { if (!tocScrollContainer) {
throw new Error('TOC scroll container not found'); throw new Error('TOC scroll container not found');
+2 -2
View File
@@ -34,7 +34,7 @@ module.exports = withSentryConfig(
__RRWEB_EXCLUDE_IFRAME__: true, __RRWEB_EXCLUDE_IFRAME__: true,
__RRWEB_EXCLUDE_SHADOW_DOM__: true, __RRWEB_EXCLUDE_SHADOW_DOM__: true,
__SENTRY_EXCLUDE_REPLAY_WORKER__: true, __SENTRY_EXCLUDE_REPLAY_WORKER__: true,
}), })
); );
} }
@@ -79,5 +79,5 @@ module.exports = withSentryConfig(
// Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load) // Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load)
tunnelRoute: '/~gitbook/monitoring', tunnelRoute: '/~gitbook/monitoring',
disableLogger: true, disableLogger: true,
}, }
); );
+5 -8
View File
@@ -1,13 +1,12 @@
{ {
"name": "gitbook", "name": "gitbook",
"version": "0.6.3", "version": "0.6.5",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev", "dev": "env-cmd --silent -f ../../.env.local next dev",
"build": "next build", "build": "next build",
"build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts", "build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts",
"start": "next start", "start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"e2e": "playwright test e2e/internal.spec.ts", "e2e": "playwright test e2e/internal.spec.ts",
"e2e-customers": "playwright test e2e/customers.spec.ts", "e2e-customers": "playwright test e2e/customers.spec.ts",
@@ -17,8 +16,9 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math" "clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math"
}, },
"dependencies": { "dependencies": {
"@gitbook/api": "^0.96.0", "@gitbook/api": "0.96.1",
"@gitbook/cache-do": "workspace:*", "@gitbook/cache-do": "workspace:*",
"@gitbook/cache-tags": "workspace:*",
"@gitbook/colors": "workspace:*", "@gitbook/colors": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*", "@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*", "@gitbook/icons": "workspace:*",
@@ -38,7 +38,6 @@
"assert-never": "^1.2.1", "assert-never": "^1.2.1",
"bun-types": "^1.1.20", "bun-types": "^1.1.20",
"classnames": "^2.5.1", "classnames": "^2.5.1",
"content-security-policy-merger": "^1.0.0",
"framer-motion": "^10.16.14", "framer-motion": "^10.16.14",
"js-cookie": "^3.0.5", "js-cookie": "^3.0.5",
"jsontoxml": "^1.0.1", "jsontoxml": "^1.0.1",
@@ -64,7 +63,8 @@
"tailwind-merge": "^2.2.0", "tailwind-merge": "^2.2.0",
"tailwind-shades": "^1.1.2", "tailwind-shades": "^1.1.2",
"url-join": "^5.0.0", "url-join": "^5.0.0",
"usehooks-ts": "^3.1.0" "usehooks-ts": "^3.1.0",
"ai": "^4.1.46"
}, },
"devDependencies": { "devDependencies": {
"@argos-ci/playwright": "^3.10.0", "@argos-ci/playwright": "^3.10.0",
@@ -86,9 +86,6 @@
"autoprefixer": "^10", "autoprefixer": "^10",
"deepmerge": "^4.3.1", "deepmerge": "^4.3.1",
"env-cmd": "^10.1.0", "env-cmd": "^10.1.0",
"eslint": "^8",
"eslint-config-next": "^14.2.5",
"eslint-plugin-import": "^2.29.1",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"postcss": "^8", "postcss": "^8",
"psi": "^4.1.0", "psi": "^4.1.0",
@@ -1,124 +1,9 @@
import { import type { NextRequest } from 'next/server';
resizeImage,
checkIsSizableImageURL,
CloudflareImageOptions,
CURRENT_SIGNATURE_VERSION,
isSignatureVersion,
SignatureVersion,
verifyImageSignature,
parseImageAPIURL,
} from '@v2/lib/images';
import { NextRequest, NextResponse } from 'next/server';
import { getHost } from '@/lib/links'; import { serveResizedImage } from '@/routes/image';
export const runtime = 'edge'; export const runtime = 'edge';
/**
* Only on Cloudflare Workers:
*
* Fetch and resize an image.
*/
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
let urlParam = request.nextUrl.searchParams.get('url'); return serveResizedImage(request);
const signature = request.nextUrl.searchParams.get('sign');
if (!urlParam || !signature) {
return new Response('Missing url/sign parameters', { status: 400 });
}
const signatureVersion = parseSignatureVersion(request.nextUrl.searchParams.get('sv'));
if (!signatureVersion) {
return new Response(`Invalid sv parameter`, { status: 400 });
}
const url = parseImageAPIURL(urlParam);
// Check again if the image can be sized, even though we checked when rendering the Image component
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
// Also prevent infinite redirects.
if (!checkIsSizableImageURL(url)) {
return new Response('Invalid url parameter', { status: 400 });
}
// Verify the signature
const verified = await verifyImageSignature(
{
url,
host: await getHost(),
},
{ signature, version: signatureVersion },
);
if (!verified) {
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
}
if (signatureVersion !== CURRENT_SIGNATURE_VERSION) {
return NextResponse.redirect(url, 302);
}
// Cloudflare-specific options are in the cf object.
const options: CloudflareImageOptions = {
fit: 'scale-down',
format: 'jpeg',
quality: 100,
};
const width = request.nextUrl.searchParams.get('width');
if (width) {
options.width = Number(width);
}
const height = request.nextUrl.searchParams.get('height');
if (height) {
options.height = Number(height);
}
const dpr = request.nextUrl.searchParams.get('dpr');
if (dpr) {
options.dpr = Number(dpr);
}
const quality = request.nextUrl.searchParams.get('quality');
if (quality) {
options.quality = Number(quality);
}
// Check the Accept header to handle content negotiation
const accept = request.headers.get('accept');
if (accept && /image\/avif/.test(accept)) {
options.format = 'avif';
} else if (accept && /image\/webp/.test(accept)) {
options.format = 'webp';
}
try {
const response = await resizeImage(url, options);
if (!response.ok) {
throw new Error('Failed to resize image');
}
return response;
} catch (error) {
// Redirect to the original image if resizing fails
return NextResponse.redirect(url, 302);
}
}
/**
* Parse the image signature version from a query param. Returns null if the version is invalid.
*/
function parseSignatureVersion(input: string | null): SignatureVersion | null {
// Before introducing the sv parameter, all signatures were generated with version 0.
if (!input) {
return '0';
}
// If the query param explicitly asks for a signature version.
if (isSignatureVersion(input)) {
return input;
}
// Otherwise the version is invalid.
return null;
} }
@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from 'next/server'; import { type NextRequest, NextResponse } from 'next/server';
import { revalidateTags } from '@/lib/cache'; import { revalidateTags } from '@/lib/cache';
@@ -21,7 +21,7 @@ export async function POST(req: NextRequest) {
{ {
error: 'tags must be an array', error: 'tags must be an array',
}, },
{ status: 400 }, { status: 400 }
); );
} }
+3 -3
View File
@@ -1,7 +1,7 @@
'use client'; 'use client';
import { captureException } from '@sentry/nextjs'; import { captureException } from '@sentry/nextjs';
import Error from 'next/error'; import NextError from 'next/error';
import { useEffect } from 'react'; import { useEffect } from 'react';
export default function GlobalError({ error }: { error: Error }) { export default function GlobalError({ error }: { error: Error }) {
@@ -10,9 +10,9 @@ export default function GlobalError({ error }: { error: Error }) {
}, [error]); }, [error]);
return ( return (
<html> <html lang="en">
<body> <body>
<Error statusCode={undefined as any} /> <NextError statusCode={undefined as any} />
</body> </body>
</html> </html>
); );
@@ -1,11 +1,10 @@
import { Metadata, Viewport } from 'next'; import type { Metadata, Viewport } from 'next';
import React from 'react';
import { import {
type PagePathParams,
SitePage,
generateSitePageMetadata, generateSitePageMetadata,
generateSitePageViewport, generateSitePageViewport,
SitePage,
PagePathParams,
} from '@/components/SitePage'; } from '@/components/SitePage';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
@@ -1,13 +1,12 @@
import { getThemeFromMiddleware } from '@v2/lib/middleware'; import { getThemeFromMiddleware, getVisitorAuthTokenFromMiddleware } from '@v2/lib/middleware';
import { Metadata, Viewport } from 'next'; import type { Metadata, Viewport } from 'next';
import React from 'react'; import type React from 'react';
import { import {
SiteLayout,
generateSiteLayoutMetadata, generateSiteLayoutMetadata,
generateSiteLayoutViewport, generateSiteLayoutViewport,
SiteLayout,
} from '@/components/SiteLayout'; } from '@/components/SiteLayout';
import { getContentSecurityPolicyNonce } from '@/lib/csp';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { shouldTrackEvents } from '@/lib/tracking'; import { shouldTrackEvents } from '@/lib/tracking';
import { fetchV1ContextForSitePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
@@ -21,16 +20,16 @@ export const dynamic = 'force-dynamic';
export default async function ContentLayout(props: { children: React.ReactNode }) { export default async function ContentLayout(props: { children: React.ReactNode }) {
const { children } = props; const { children } = props;
const nonce = await getContentSecurityPolicyNonce();
const context = await fetchLayoutData(); const context = await fetchLayoutData();
const queryStringTheme = await getThemeFromMiddleware(); const queryStringTheme = await getThemeFromMiddleware();
const visitorAuthToken = await getVisitorAuthTokenFromMiddleware();
return ( return (
<SiteLayout <SiteLayout
context={context} context={context}
nonce={nonce}
forcedTheme={queryStringTheme} forcedTheme={queryStringTheme}
withTracking={await shouldTrackEvents()} withTracking={await shouldTrackEvents()}
visitorAuthToken={visitorAuthToken}
> >
{children} {children}
</SiteLayout> </SiteLayout>
@@ -1,154 +1,14 @@
import { SiteSection, SiteSpace, SiteStructure } from '@gitbook/api'; import type { NextRequest } from 'next/server';
import assertNever from 'assert-never';
import { ListItem, Paragraph, Root, RootContent } from 'mdast';
import { toMarkdown } from 'mdast-util-to-markdown';
import { NextRequest } from 'next/server';
import { getPublishedContentSite, getRevisionPages } from '@/lib/api'; import { getSiteContentPointer } from '@/lib/pointer';
import { getAbsoluteHref } from '@/lib/links'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { getPagePath } from '@/lib/pages'; import { serveLLMsTxt } from '@/routes/llms';
import { joinPath } from '@/lib/paths';
import { checkIsRootPointer, getSiteContentPointer } from '@/lib/pointer';
import { getIndexablePages } from '@/lib/sitemap';
import { getSiteStructureSections } from '@/lib/sites';
export const runtime = 'edge'; export const runtime = 'edge';
/** export async function GET(_req: NextRequest) {
* Generate a llms.txt file for the site.
*/
export async function GET(req: NextRequest) {
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const { structure: siteStructure, site } = await getPublishedContentSite({ return serveLLMsTxt(context);
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
if (!checkIsRootPointer(pointer, siteStructure)) {
return new Response('llms.txt is only served from the root of the site', { status: 404 });
}
const tree: Root = {
type: 'root',
children: [
{
type: 'heading',
depth: 1,
children: [{ type: 'text', value: site.title }],
},
...(await getNodesFromSiteStructure(siteStructure)),
],
};
return new Response(
toMarkdown(tree, {
bullet: '-',
}),
{
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
},
);
}
/**
* Get MDAST nodes from site structure.
*/
async function getNodesFromSiteStructure(siteStructure: SiteStructure): Promise<RootContent[]> {
switch (siteStructure.type) {
case 'sections':
return getNodesFromSections(getSiteStructureSections(siteStructure));
case 'siteSpaces':
return getNodesFromSiteSpaces(siteStructure.structure, { heading: true });
default:
assertNever(siteStructure);
}
}
/**
* Get MDAST nodes from site sections.
*/
async function getNodesFromSections(siteSections: SiteSection[]): Promise<RootContent[]> {
const all = await Promise.all(
siteSections.map(async (siteSection): Promise<RootContent[]> => {
const siteSpaceNodes = await getNodesFromSiteSpaces(siteSection.siteSpaces, {
heading: false,
});
return [
{
type: 'heading',
depth: 2,
children: [{ type: 'text', value: siteSection.title }],
},
...siteSpaceNodes,
];
}),
);
return all.flat();
}
/**
* Get MDAST nodes from site spaces.
*/
async function getNodesFromSiteSpaces(
siteSpaces: SiteSpace[],
options: {
/**
* Includes a heading for each site space.
*/
heading?: boolean;
},
): Promise<RootContent[]> {
const all = await Promise.all(
siteSpaces.map(async (siteSpace): Promise<RootContent[]> => {
const siteSpaceUrl = siteSpace.urls.published;
if (!siteSpaceUrl) {
return [];
}
const rootPages = await getRevisionPages(siteSpace.space.id, siteSpace.space.revision, {
metadata: false,
});
const pages = getIndexablePages(rootPages);
const listChildren = await Promise.all(
pages.map(async ({ page }): Promise<ListItem> => {
const url = await getAbsoluteHref(
joinPath(new URL(siteSpaceUrl).pathname, getPagePath(rootPages, page)),
true,
);
const children: Paragraph['children'] = [
{
type: 'link',
url,
children: [{ type: 'text', value: page.title }],
},
];
if (page.description) {
children.push({ type: 'text', value: `: ${page.description}` });
}
return {
type: 'listItem',
children: [{ type: 'paragraph', children }],
};
}),
);
const nodes: RootContent[] = [];
if (options.heading) {
nodes.push({
type: 'heading',
depth: 2,
children: [{ type: 'text', value: siteSpace.title }],
});
}
nodes.push({
type: 'list',
spread: false,
children: listChildren,
});
return nodes;
}),
);
return all.flat();
} }
@@ -1,31 +1,14 @@
import { NextRequest } from 'next/server'; import type { NextRequest } from 'next/server';
import { getSite } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { isSiteIndexable } from '@/lib/seo'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveRobotsTxt } from '@/routes/robots';
export const runtime = 'edge'; export const runtime = 'edge';
/** export async function GET(_request: NextRequest) {
* Generate a robots.txt for the current space.
*/
export async function GET(req: NextRequest) {
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const site = await getSite(pointer.organizationId, pointer.siteId); const context = await fetchV1ContextForSitePointer(pointer);
const lines = [ return serveRobotsTxt(context);
`User-agent: *`,
'Disallow: /~gitbook/',
...((await isSiteIndexable(site))
? [`Allow: /`, `Sitemap: ${await getAbsoluteHref(`/sitemap.xml`, true)}`]
: [`Disallow: /`]),
];
const content = lines.join('\n');
return new Response(content, {
headers: {
'Content-Type': 'text/plain',
},
});
} }
@@ -1,66 +1,12 @@
import jsontoxml from 'jsontoxml';
import { getRevisionPages, getSpace } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { getIndexablePages } from '@/lib/sitemap'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { servePagesSitemap } from '@/routes/sitemap';
export const runtime = 'edge'; export const runtime = 'edge';
/**
* Generate a sitemap.xml for the current section / space.
*/
export async function GET() { export async function GET() {
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const revisionId = return servePagesSitemap(context);
pointer.revisionId ?? (await getSpace(pointer.spaceId, pointer.siteShareKey)).revision;
const rootPages = await getRevisionPages(pointer.spaceId, revisionId, { metadata: false });
const pages = getIndexablePages(rootPages);
const urls = await Promise.all(
pages.map(async ({ page, depth }) => {
// Decay priority with depth
const priority = Math.pow(2, -0.25 * depth);
// Normalize to keep 2 decimals
const normalizedPriority = Math.floor(100 * priority) / 100;
const lastModified = page.updatedAt || page.createdAt;
const url: { loc: string; priority: number; lastmod?: string } = {
priority: normalizedPriority,
loc: await getAbsoluteHref(getPagePath(rootPages, page), true),
};
if (lastModified) {
url.lastmod = new Date(lastModified).toISOString();
}
return { url };
}),
);
const xml = jsontoxml(
[
{
name: 'urlset',
children: urls,
attrs: {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
} }
@@ -1,98 +1,12 @@
import { SiteSection, SiteSpace, SiteStructure } from '@gitbook/api'; import { getSiteContentPointer } from '@/lib/pointer';
import assertNever from 'assert-never'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
import jsontoxml from 'jsontoxml'; import { serveRootSitemap } from '@/routes/sitemap';
import { getPublishedContentSite } from '@/lib/api';
import { joinPath } from '@/lib/paths';
import { checkIsRootPointer, getSiteContentPointer } from '@/lib/pointer';
import { getSiteStructureSections } from '@/lib/sites';
import { filterOutNullable } from '@/lib/typescript';
export const runtime = 'edge'; export const runtime = 'edge';
/**
* Generate a root sitemap that point to all sitemap-pages.xml.
*/
export async function GET() { export async function GET() {
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const { structure: siteStructure } = await getPublishedContentSite({ return serveRootSitemap(context);
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
if (!checkIsRootPointer(pointer, siteStructure)) {
return new Response('Root sitemap is only served from the root of the site', {
status: 404,
});
}
const urls = await getUrlsFromSiteStructure(siteStructure);
const xml = jsontoxml(
[
{
name: 'sitemapindex',
children: urls.map((url) => ({
name: 'sitemap',
children: [{ name: 'loc', text: url }],
})),
attrs: {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
}
/**
* Get Sitemap URLs from site structure.
*/
async function getUrlsFromSiteStructure(siteStructure: SiteStructure): Promise<string[]> {
switch (siteStructure.type) {
case 'sections':
return getUrlsFromSiteSections(getSiteStructureSections(siteStructure));
case 'siteSpaces':
return getUrlsFromSiteSpaces(siteStructure.structure);
default:
assertNever(siteStructure);
}
}
/**
* Get Sitemap URLs from site sections.
*/
async function getUrlsFromSiteSections(siteSections: SiteSection[]): Promise<string[]> {
const urls = await Promise.all(
siteSections.map(async (siteSection) => getUrlsFromSiteSpaces(siteSection.siteSpaces), []),
);
return urls.flat();
}
/**
* Get Sitemap URLs from site spaces.
*/
async function getUrlsFromSiteSpaces(siteSpaces: SiteSpace[]): Promise<string[]> {
const urls = await Promise.all(
siteSpaces.map(async (siteSpace) => {
if (!siteSpace.urls.published) {
return null;
}
const url = new URL(siteSpace.urls.published);
url.pathname = joinPath(url.pathname, 'sitemap-pages.xml');
return url.toString();
}, []),
);
return urls.filter(filterOutNullable);
} }
@@ -1,93 +1,14 @@
import { notFound } from 'next/navigation'; import type { NextRequest } from 'next/server';
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import { getEmojiForCode } from '@/lib/emojis';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind';
import { fetchV1ContextForSitePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveIcon } from '@/routes/icon';
export const runtime = 'edge'; export const runtime = 'edge';
const SIZES = {
/** Size for a favicon */
small: {
width: 48,
height: 48,
textSize: 'text-[32px]',
boxStyle: 'rounded-[8px]',
},
/** Size for display as an app icon or in the header */
medium: {
width: 256,
height: 256,
textSize: 'text-[164px]',
boxStyle: 'rounded-[32px]',
},
};
/**
* Render an icon for the space.
*/
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const options = getOptions(req.url);
const size = SIZES[options.size];
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const { site, customization } = await fetchV1ContextForSitePointer(pointer); return serveIcon(context, req);
const contentTitle = site.title;
return new ImageResponse(
(
<div
tw={tcls(options.theme === 'light' ? 'bg-white' : 'bg-black', size.boxStyle)}
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<h2
tw={tcls(
size.textSize,
'font-bold',
'tracking-tight',
options.theme === 'light' ? 'text-black' : 'text-white',
)}
>
{'emoji' in customization.favicon
? getEmojiForCode(customization.favicon.emoji)
: contentTitle.slice(0, 1).toUpperCase()}
</h2>
</div>
),
{
width: size.width,
height: size.height,
},
);
}
function getOptions(inputUrl: string): {
size: keyof typeof SIZES;
theme: 'light' | 'dark';
} {
const url = new URL(inputUrl);
const sizeParam = (url.searchParams.get('size') ?? 'small') as keyof typeof SIZES;
const themeParam = url.searchParams.get('theme') ?? 'light';
if (!SIZES[sizeParam] || !['light', 'dark'].includes(themeParam)) {
notFound();
}
return {
// @ts-ignore
size: sizeParam,
// @ts-ignore
theme: themeParam,
};
} }
@@ -1,232 +1,15 @@
import { CustomizationHeaderPreset } from '@gitbook/api'; import type { NextRequest } from 'next/server';
import { colorContrast } from '@gitbook/colors';
import { redirect } from 'next/navigation';
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import { PageIdParams, fetchPageData } from '@/components/SitePage'; import type { PageIdParams } from '@/components/SitePage';
import { googleFontsMap } from '@/fonts';
import { getAbsoluteHref } from '@/lib/links';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { filterOutNullable } from '@/lib/typescript';
import { fetchV1ContextForSitePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveOGImage } from '@/routes/ogimage';
export const runtime = 'edge'; export const runtime = 'edge';
async function loadGoogleFont(input: { fontFamily: string; text: string; weight: 400 | 700 }) { export async function GET(_req: NextRequest, { params }: { params: Promise<PageIdParams> }) {
const { fontFamily, text, weight } = input;
if (!text.trim()) {
return null;
}
const url = new URL('https://fonts.googleapis.com/css2');
url.searchParams.set('family', `${fontFamily}:wght@${weight}`);
url.searchParams.set('text', text);
const result = await fetch(url.href);
if (!result.ok) {
return null;
}
const css = await result.text();
const resource = css.match(/src: url\((.+)\) format\('(opentype|truetype)'\)/);
const resourceUrl = resource ? resource[1] : null;
if (resourceUrl) {
const response = await fetch(resourceUrl);
if (response.ok) {
const data = await response.arrayBuffer();
return {
name: fontFamily,
data,
style: 'normal' as const,
weight,
};
}
}
// If for some reason we can't load the font, we'll just use the default one
return null;
}
/**
* Render the OpenGraph image for a space.
*/
export async function GET(req: NextRequest, { params }: { params: Promise<PageIdParams> }) {
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const baseContext = await fetchV1ContextForSitePointer(pointer); const baseContext = await fetchV1ContextForSitePointer(pointer);
const { context, pageTarget } = await fetchPageData(baseContext, await params); return serveOGImage(baseContext, await params);
const { customization, site } = context;
const page = pageTarget?.page;
// If user configured a custom social preview, we redirect to it.
if (customization.socialPreview.url) {
redirect(customization.socialPreview.url);
}
// Compute all text to load only the necessary fonts
const contentTitle = customization.header.logo ? '' : site.title;
const pageTitle = page
? page.title.length > 64
? page.title.slice(0, 64) + '...'
: page.title
: 'Not found';
const pageDescription =
page?.description && page?.title.length <= 64
? page.description.length > 164
? page.description.slice(0, 164) + '...'
: page.description
: '';
const fontFamily = googleFontsMap[customization.styling.font] ?? 'Inter';
const regularText = pageDescription;
const boldText = `${contentTitle}${pageTitle}`;
const fonts = (
await Promise.all([
loadGoogleFont({ fontFamily, text: regularText, weight: 400 }),
loadGoogleFont({ fontFamily, text: boldText, weight: 700 }),
])
).filter(filterOutNullable);
const theme = customization.themes.default;
const useLightTheme = theme === 'light';
// We have no access to CSS variables, so we'll have to hardcode some values
const baseColors = { light: '#ffffff', dark: '#111827' };
let colors = {
background: baseColors[theme],
gradient: customization.styling.primaryColor[theme],
title: customization.styling.primaryColor[theme],
body: baseColors[useLightTheme ? 'dark' : 'light'], // Invert text on background
};
const [gridWhite, gridBlack] = await Promise.all([
getAbsoluteHref('~gitbook/static/images/ogimage-grid-white.png', true),
getAbsoluteHref('~gitbook/static/images/ogimage-grid-black.png', true),
]);
let gridAsset = useLightTheme ? gridBlack : gridWhite;
switch (customization.header.preset) {
case CustomizationHeaderPreset.Custom:
colors = {
background: customization.header.backgroundColor?.[theme] || colors.background,
gradient: customization.header.linkColor?.[theme] || colors.gradient,
title: customization.header.linkColor?.[theme] || colors.title,
body: colorContrast(
customization.header.backgroundColor?.[theme] || colors.background,
[baseColors.light, baseColors.dark],
),
};
gridAsset = colors.body == baseColors.light ? gridWhite : gridBlack;
break;
case CustomizationHeaderPreset.Bold:
colors = {
background: customization.styling.primaryColor[theme],
gradient: colorContrast(customization.styling.primaryColor[theme], [
baseColors.light,
baseColors.dark,
]),
title: colorContrast(customization.styling.primaryColor[theme], [
baseColors.light,
baseColors.dark,
]),
body: colorContrast(customization.styling.primaryColor[theme], [
baseColors.light,
baseColors.dark,
]),
};
gridAsset = colors.body == baseColors.light ? gridWhite : gridBlack;
break;
}
const favicon = await (async () => {
if ('icon' in customization.favicon)
return (
<img
src={customization.favicon.icon[theme]}
width={40}
height={40}
tw="mr-4"
alt="Icon"
/>
);
if ('emoji' in customization.favicon)
return (
<span tw="text-4xl mr-4">
{String.fromCodePoint(parseInt('0x' + customization.favicon.emoji))}
</span>
);
const src = await getAbsoluteHref(
`~gitbook/icon?size=medium&theme=${customization.themes.default}`,
true,
);
return <img src={src} alt="Icon" width={40} height={40} tw="mr-4" />;
})();
return new ImageResponse(
(
<div
tw={`justify-between p-20 relative w-full h-full flex flex-col bg-[${colors.background}] text-[${colors.body}]`}
style={{
fontFamily,
}}
>
{/* Gradient */}
<div
tw="absolute inset-0"
style={{
backgroundImage: `radial-gradient(ellipse 100% 100% at top right , ${colors.gradient}, ${colors.gradient}00)`,
opacity: 0.5,
}}
></div>
{/* Grid */}
<img tw="absolute inset-0 w-[100vw] h-[100vh]" src={gridAsset} alt="Grid" />
{/* Logo */}
{customization.header.logo ? (
<img
alt="Logo"
height={60}
src={
useLightTheme
? customization.header.logo.light
: customization.header.logo.dark
}
/>
) : (
<div tw="flex">
{favicon}
<h3 tw="text-4xl my-0 font-bold">{contentTitle}</h3>
</div>
)}
{/* Title and description */}
<div tw="flex flex-col">
<h1
tw={`text-8xl my-0 tracking-tight leading-none text-left text-[${colors.title}] font-bold`}
>
{pageTitle}
</h1>
{pageDescription ? (
<h2 tw="text-4xl mb-0 mt-8 w-[75%] font-normal">{pageDescription}</h2>
) : null}
</div>
</div>
),
{
width: 1200,
height: 630,
fonts: fonts.length ? fonts : undefined,
},
);
} }
@@ -32,7 +32,7 @@ export default function ErrorPage(props: {
'flex', 'flex',
'items-center', 'items-center',
'justify-center', 'justify-center',
'p-7', 'p-7'
)} )}
> >
<div> <div>
@@ -50,7 +50,7 @@ export function PageControlButtons(props: {
'flex-col', 'flex-col',
'gap-2', 'gap-2',
'print:hidden', 'print:hidden',
'z-50', 'z-50'
)} )}
> >
{singlePageMode ? null : ( {singlePageMode ? null : (
@@ -84,7 +84,7 @@ export function PageControlButtons(props: {
'items-end', 'items-end',
'gap-2', 'gap-2',
'print:hidden', 'print:hidden',
'z-50', 'z-50'
)} )}
> >
{total !== pageIds.length ? ( {total !== pageIds.length ? (
@@ -102,7 +102,7 @@ export function PageControlButtons(props: {
'border', 'border',
'rounded-md', 'rounded-md',
'p-4', 'p-4',
'max-w-sm', 'max-w-sm'
)} )}
> >
<Icon <Icon
@@ -140,7 +140,7 @@ export function PageControlButtons(props: {
'rounded-full', 'rounded-full',
'shadow-sm', 'shadow-sm',
'border-slate-300', 'border-slate-300',
'border', 'border'
)} )}
> >
{t(language, 'pdf_page_of', activeIndex, pageIds.length)} {t(language, 'pdf_page_of', activeIndex, pageIds.length)}
@@ -2,7 +2,7 @@
import * as React from 'react'; import * as React from 'react';
import { PolymorphicComponentProp } from '@/components/utils/types'; import type { PolymorphicComponentProp } from '@/components/utils/types';
export function PrintButton(props: PolymorphicComponentProp<'button'>) { export function PrintButton(props: PolymorphicComponentProp<'button'>) {
const { className, children, ...rest } = props; const { className, children, ...rest } = props;
@@ -1,36 +1,36 @@
import { import {
CustomizationSettings, type CustomizationSettings,
Revision, type Revision,
RevisionPageDocument, type RevisionPageDocument,
RevisionPageGroup, type RevisionPageGroup,
RevisionPageType, RevisionPageType,
SiteCustomizationSettings, type SiteCustomizationSettings,
SiteInsightsTrademarkPlacement, SiteInsightsTrademarkPlacement,
Space, type Space,
} from '@gitbook/api'; } from '@gitbook/api';
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import { GitBookSpaceContext } from '@v2/lib/context'; import type { GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data'; import { getPageDocument } from '@v2/lib/data';
import { GitBookSpaceLinker } from '@v2/lib/links'; import type { GitBookSpaceLinker } from '@v2/lib/links';
import { Metadata } from 'next'; import type { Metadata } from 'next';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import * as React from 'react'; import * as React from 'react';
import { DocumentView } from '@/components/DocumentView'; import { DocumentView } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark'; import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import { PolymorphicComponentProp } from '@/components/utils/types'; import type { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server'; import { getSpaceLanguage } from '@/intl/server';
import { tString } from '@/intl/translate'; import { tString } from '@/intl/translate';
import { getPagePDFContainerId, getAbsoluteHref } from '@/lib/links'; import { getAbsoluteHref, getPagePDFContainerId } from '@/lib/links';
import { resolvePageId } from '@/lib/pages'; import { resolvePageId } from '@/lib/pages';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { PDFSearchParams, getPDFSearchParams } from '@/lib/urls'; import { type PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
import { defaultCustomizationForSpace } from '@/lib/utils'; import { defaultCustomizationForSpace } from '@/lib/utils';
import './pdf.css';
import { PageControlButtons } from './PageControlButtons'; import { PageControlButtons } from './PageControlButtons';
import { getV1ContextForPDF } from './pointer';
import { PrintButton } from './PrintButton'; import { PrintButton } from './PrintButton';
import './pdf.css';
import { getV1ContextForPDF } from './pointer';
const DEFAULT_LIMIT = 100; const DEFAULT_LIMIT = 100;
@@ -57,7 +57,7 @@ export default async function PDFHTMLOutput(props: {
// Build current PDF URL and preserve all search params // Build current PDF URL and preserve all search params
let currentPDFUrl = await getAbsoluteHref('~gitbook/pdf', true); let currentPDFUrl = await getAbsoluteHref('~gitbook/pdf', true);
currentPDFUrl += '?' + searchParams.toString(); currentPDFUrl += `?${searchParams.toString()}`;
// Fetch the context // Fetch the context
const baseContext = await getV1ContextForPDF(); const baseContext = await getV1ContextForPDF();
@@ -69,7 +69,7 @@ export default async function PDFHTMLOutput(props: {
// Compute the pages to render // Compute the pages to render
const { pages, total } = selectPages(baseContext.pages, pdfParams); const { pages, total } = selectPages(baseContext.pages, pdfParams);
const pageIds = pages.map( const pageIds = pages.map(
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string], ({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string]
); );
// Build a linker that create anchor links for the pages rendered in the PDF page. // Build a linker that create anchor links for the pages rendered in the PDF page.
@@ -77,15 +77,14 @@ export default async function PDFHTMLOutput(props: {
...baseContext.linker, ...baseContext.linker,
toPathForPage(input) { toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) { if (pages.some((p) => p.page.id === input.page.id)) {
return '#' + getPagePDFContainerId(input.page, input.anchor); return `#${getPagePDFContainerId(input.page, input.anchor)}`;
} else { }
if (input.page.type === RevisionPageType.Group) { if (input.page.type === RevisionPageType.Group) {
return '#'; return '#';
} }
// Use an absolute URL to the page // Use an absolute URL to the page
return input.page.urls.app; return input.page.urls.app;
}
}, },
}; };
@@ -100,7 +99,7 @@ export default async function PDFHTMLOutput(props: {
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}> <div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a <a
title={tString(language, 'pdf_goback')} title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? context.linker.toAbsoluteURL('')} href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))}
className={tcls( className={tcls(
'flex', 'flex',
'flex-row', 'flex-row',
@@ -115,7 +114,7 @@ export default async function PDFHTMLOutput(props: {
'shadow-sm', 'shadow-sm',
'hover:shadow-md', 'hover:shadow-md',
'border-slate-300', 'border-slate-300',
'border', 'border'
)} )}
> >
<Icon icon="arrow-left" className={tcls('size-6')} /> <Icon icon="arrow-left" className={tcls('size-6')} />
@@ -140,7 +139,7 @@ export default async function PDFHTMLOutput(props: {
'shadow-sm', 'shadow-sm',
'hover:shadow-md', 'hover:shadow-md',
'border-slate-300', 'border-slate-300',
'border', 'border'
)} )}
> >
<Icon icon="print" className={tcls('size-6')} /> <Icon icon="print" className={tcls('size-6')} />
@@ -181,7 +180,7 @@ export default async function PDFHTMLOutput(props: {
> >
<PDFPageDocument page={page} context={context} /> <PDFPageDocument page={page} context={context} />
</React.Suspense> </React.Suspense>
), )
)} )}
</div> </div>
); );
@@ -217,7 +216,7 @@ async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
'flex', 'flex',
'items-center', 'items-center',
'justify-center', 'justify-center',
'py-12', 'py-12'
)} )}
> >
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1> <h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
@@ -232,7 +231,7 @@ async function PDFPageDocument(props: {
}) { }) {
const { page, context } = props; const { page, context } = props;
const { space } = context; const { space } = context;
const document = await getPageDocument(context.dataFetcher, space.id, page); const document = await getPageDocument(context.dataFetcher, space, page);
return ( return (
<PrintPage id={getPagePDFContainerId(page)}> <PrintPage id={getPagePDFContainerId(page)}>
@@ -266,7 +265,7 @@ function PrintPage(
{ {
isFirst?: boolean; isFirst?: boolean;
} }
>, >
) { ) {
const { children, isFirst, className, ...rest } = props; const { children, isFirst, className, ...rest } = props;
@@ -289,7 +288,7 @@ function PrintPage(
'min-h-[29.7cm]', 'min-h-[29.7cm]',
'print:min-h-0', 'print:min-h-0',
isFirst ? null : 'break-before-page', isFirst ? null : 'break-before-page',
'break-anywhere', 'break-anywhere'
)} )}
> >
{children} {children}
@@ -304,11 +303,11 @@ type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: nu
*/ */
function selectPages( function selectPages(
rootPages: Revision['pages'], rootPages: Revision['pages'],
params: PDFSearchParams, params: PDFSearchParams
): { pages: FlatPageEntry[]; total: number } { ): { pages: FlatPageEntry[]; total: number } {
const flattenPage = ( const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup, page: RevisionPageDocument | RevisionPageGroup,
depth: number, depth: number
): FlatPageEntry[] => { ): FlatPageEntry[] => {
return [ return [
{ page, depth }, { page, depth },
@@ -1,6 +1,6 @@
import { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context'; import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
import { SiteContentPointer, SpaceContentPointer } from '@/lib/api'; import type { SiteContentPointer, SpaceContentPointer } from '@/lib/api';
import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer'; import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1';
@@ -16,7 +16,7 @@ export async function getSiteOrSpacePointerForPDF(): Promise<
> { > {
try { try {
return await getSiteContentPointer(); return await getSiteContentPointer();
} catch (error) { } catch (_error) {
return getSpacePointer(); return getSpacePointer();
} }
} }
@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from 'next/server'; import { type NextRequest, NextResponse } from 'next/server';
type ProxyRequest = { type ProxyRequest = {
url: string; url: string;
@@ -67,11 +67,7 @@ export async function POST(req: NextRequest) {
// TODO: transform cookie data // TODO: transform cookie data
cookies: response.headers.get('cookies'), cookies: response.headers.get('cookies'),
}); });
} catch (error) { } catch (_error) {
console.error(
'Scalar API Client Proxy Error',
(error as Error).stack ?? (error as Error).message ?? error,
);
return NextResponse.json({ return NextResponse.json({
data: 'Scalar API Client Proxy Error', data: 'Scalar API Client Proxy Error',
}); });
@@ -10,7 +10,7 @@ import { withMiddlewareHeadersStorage } from './lib/middleware';
export default { export default {
async fetch(request, env, ctx) { async fetch(request, env, ctx) {
const response = await withMiddlewareHeadersStorage(() => const response = await withMiddlewareHeadersStorage(() =>
nextOnPagesHandler.fetch(request, env, ctx), nextOnPagesHandler.fetch(request, env, ctx)
); );
return response; return response;
@@ -1,13 +1,13 @@
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import { GitBookSiteContext } from '@v2/lib/context'; import type { GitBookSiteContext } from '@v2/lib/context';
import { headers } from 'next/headers'; import { headers } from 'next/headers';
import React from 'react'; import React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { DateRelative } from '../primitives';
import { RefreshChangeRequestButton } from './RefreshChangeRequestButton'; import { RefreshChangeRequestButton } from './RefreshChangeRequestButton';
import { Toolbar, ToolbarBody, ToolbarButton, ToolbarButtonGroups } from './Toolbar'; import { Toolbar, ToolbarBody, ToolbarButton, ToolbarButtonGroups } from './Toolbar';
import { DateRelative } from '../primitives';
interface AdminToolbarProps { interface AdminToolbarProps {
context: GitBookSiteContext; context: GitBookSiteContext;
@@ -34,7 +34,7 @@ function ToolbarLayout(props: { children: React.ReactNode }) {
'p-2', 'p-2',
'max-w-md', 'max-w-md',
'border-tint-12/1', 'border-tint-12/1',
'backdrop-blur-md', 'backdrop-blur-md'
)} )}
> >
<React.Suspense fallback={null}>{props.children}</React.Suspense> <React.Suspense fallback={null}>{props.children}</React.Suspense>
@@ -83,7 +83,7 @@ async function ChangeRequestToolbar(props: { context: GitBookSiteContext }) {
<p> <p>
#{changeRequest.number}: {changeRequest.subject ?? 'No subject'} #{changeRequest.number}: {changeRequest.subject ?? 'No subject'}
</p> </p>
<p className="text-xs text-tint-2 dark:text-tint-11"> <p className="text-tint-2 text-xs dark:text-tint-11">
Change request updated <DateRelative value={changeRequest.updatedAt} /> Change request updated <DateRelative value={changeRequest.updatedAt} />
</p> </p>
</ToolbarBody> </ToolbarBody>
@@ -124,7 +124,7 @@ async function RevisionToolbar(props: { context: GitBookSiteContext }) {
Revision created <DateRelative value={revision.createdAt} /> Revision created <DateRelative value={revision.createdAt} />
</p> </p>
{revision.git ? ( {revision.git ? (
<p className="text-xs text-tint-2 dark:text-tint-11"> <p className="text-tint-2 text-xs dark:text-tint-11">
{revision.git.message} {revision.git.message}
</p> </p>
) : null} ) : null}
@@ -1,6 +1,6 @@
'use client'; 'use client';
import * as React from 'react'; import type * as React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -20,7 +20,7 @@ export function Toolbar(props: { children: React.ReactNode }) {
'rounded-full', 'rounded-full',
'truncate', 'truncate',
'text-tint-1', 'text-tint-1',
'dark:text-tint-12', 'dark:text-tint-12'
)} )}
> >
{children} {children}
@@ -56,7 +56,7 @@ export function ToolbarButton(props: React.HTMLProps<HTMLAnchorElement>) {
'hover:bg-tint-12', 'hover:bg-tint-12',
'dark:hover:bg-tint-1', 'dark:hover:bg-tint-1',
'hover:shadow-lg', 'hover:shadow-lg',
'cursor-pointer', 'cursor-pointer'
)} )}
> >
{children} {children}
+6 -7
View File
@@ -1,21 +1,21 @@
'use client'; 'use client';
import { import {
SiteAds, type SiteAds,
SiteAdsStatus, SiteAdsStatus,
SiteInsightsAdPlacement, type SiteInsightsAd,
SiteInsightsAd, type SiteInsightsAdPlacement,
SiteInsightsTrademarkPlacement, SiteInsightsTrademarkPlacement,
} from '@gitbook/api'; } from '@gitbook/api';
import * as React from 'react'; import * as React from 'react';
import { t, useLanguage } from '@/intl/client'; import { t, useLanguage } from '@/intl/client';
import { ClassValue, tcls } from '@/lib/tailwind'; import { type ClassValue, tcls } from '@/lib/tailwind';
import { renderAd } from './renderAd';
import { useHasBeenInViewport } from '../hooks/useHasBeenInViewport';
import { useTrackEvent } from '../Insights'; import { useTrackEvent } from '../Insights';
import { useHasBeenInViewport } from '../hooks/useHasBeenInViewport';
import { Link } from '../primitives'; import { Link } from '../primitives';
import { renderAd } from './renderAd';
/** /**
* Zone ID provided by BuySellAds for the preview. * Zone ID provided by BuySellAds for the preview.
@@ -125,7 +125,6 @@ export function Ad({
function AdSponsoredLink(props: { spaceId: string }) { function AdSponsoredLink(props: { spaceId: string }) {
const { spaceId } = props; const { spaceId } = props;
const language = useLanguage(); const language = useLanguage();
const trackEvent = useTrackEvent();
const viaUrl = new URL('https://www.gitbook.com'); const viaUrl = new URL('https://www.gitbook.com');
viaUrl.searchParams.set('utm_source', 'content'); viaUrl.searchParams.set('utm_source', 'content');
@@ -1,12 +1,11 @@
import { SiteInsightsAd } from '@gitbook/api'; import type { SiteInsightsAd } from '@gitbook/api';
import { GitBookBaseContext } from '@v2/lib/context'; import type { GitBookBaseContext } from '@v2/lib/context';
import { getResizedImageURL } from '@v2/lib/images'; import { getResizedImageURL } from '@v2/lib/images';
import * as React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { AdItem } from './types';
import { Link } from '../primitives'; import { Link } from '../primitives';
import type { AdItem } from './types';
/** /**
* Classic rendering for an ad. * Classic rendering for an ad.
@@ -48,7 +47,7 @@ export async function AdClassicRendering({
'text-tint', 'text-tint',
'hover:text-tint-strong', 'hover:text-tint-strong',
'rounded-lg', 'rounded-lg',
'p-4', 'p-4'
)} )}
href={ad.statlink} href={ad.statlink}
> >
@@ -1,13 +1,12 @@
import { SiteInsightsAd } from '@gitbook/api'; import type { SiteInsightsAd } from '@gitbook/api';
import { hexToRgba } from '@gitbook/colors'; import { hexToRgba } from '@gitbook/colors';
import { GitBookBaseContext } from '@v2/lib/context'; import type { GitBookBaseContext } from '@v2/lib/context';
import { getResizedImageURL } from '@v2/lib/images'; import { getResizedImageURL } from '@v2/lib/images';
import * as React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { AdCover } from './types';
import { Link } from '../primitives'; import { Link } from '../primitives';
import type { AdCover } from './types';
/** /**
* Cover rendering for an ad. * Cover rendering for an ad.
@@ -50,7 +49,7 @@ export async function AdCoverRendering({
'rounded-lg', 'rounded-lg',
'p-4', 'p-4',
'overflow-hidden', 'overflow-hidden',
'shadow-sm', 'shadow-sm'
)} )}
style={{ backgroundColor: ad.backgroundColor, color: ad.textColor ?? '#ffffff' }} style={{ backgroundColor: ad.backgroundColor, color: ad.textColor ?? '#ffffff' }}
href={ad.statlink} href={ad.statlink}
@@ -62,7 +61,7 @@ export async function AdCoverRendering({
'bg-center', 'bg-center',
'bg-cover', 'bg-cover',
'bg-no-repeat', 'bg-no-repeat',
'z-0', 'z-0'
)} )}
style={{ style={{
backgroundImage: `url(${largeImage})`, backgroundImage: `url(${largeImage})`,
@@ -71,14 +70,14 @@ export async function AdCoverRendering({
<div className={tcls('z-[2]')}> <div className={tcls('z-[2]')}>
<img <img
alt="Large image" alt="Large cover"
src={largeImage} src={largeImage}
className={tcls( className={tcls(
'rounded-md', 'rounded-md',
'shadow-md', 'shadow-md',
'max-h-32', 'max-h-32',
'group-hover/ad:max-h-16', 'group-hover/ad:max-h-16',
'transition-all', 'transition-all'
)} )}
/> />
</div> </div>
@@ -94,7 +93,7 @@ export async function AdCoverRendering({
'opacity-0', 'opacity-0',
'group-hover/ad:h-16', 'group-hover/ad:h-16',
'group-hover/ad:opacity-10', 'group-hover/ad:opacity-10',
'transition-all', 'transition-all'
)} )}
> >
{ad.description} {ad.description}
@@ -109,7 +108,7 @@ export async function AdCoverRendering({
'rounded-md', 'rounded-md',
'bg-white', 'bg-white',
'py-2', 'py-2',
'px-4', 'px-4'
)} )}
style={{ style={{
backgroundColor: ad.ctaBackgroundColor, backgroundColor: ad.ctaBackgroundColor,
@@ -1,5 +1,3 @@
import * as React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
/** /**
@@ -1,15 +1,17 @@
'use server'; 'use server';
import { SiteInsightsAd, SiteInsightsAdPlacement } from '@gitbook/api'; import type { SiteInsightsAd, SiteInsightsAdPlacement } from '@gitbook/api';
import { headers } from 'next/headers'; import { headers } from 'next/headers';
import { getV1BaseContext } from '@/lib/v1'; import { getV1BaseContext } from '@/lib/v1';
import { isV2 } from '@/lib/v2';
import { getServerActionBaseContext } from '@v2/lib/server-actions';
import { AdClassicRendering } from './AdClassicRendering'; import { AdClassicRendering } from './AdClassicRendering';
import { AdCoverRendering } from './AdCoverRendering'; import { AdCoverRendering } from './AdCoverRendering';
import { AdPixels } from './AdPixels'; import { AdPixels } from './AdPixels';
import adRainbow from './assets/ad-rainbow.svg'; import adRainbow from './assets/ad-rainbow.svg';
import { AdItem, AdsResponse } from './types'; import type { AdItem, AdsResponse } from './types';
type FetchAdOptions = FetchLiveAdOptions | FetchPlaceholderAdOptions; type FetchAdOptions = FetchLiveAdOptions | FetchPlaceholderAdOptions;
@@ -41,7 +43,7 @@ interface FetchPlaceholderAdOptions {
* and properly access user-agent and IP. * and properly access user-agent and IP.
*/ */
export async function renderAd(options: FetchAdOptions) { export async function renderAd(options: FetchAdOptions) {
const baseContext = await getV1BaseContext(); const context = isV2() ? await getServerActionBaseContext() : await getV1BaseContext();
const mode = options.source === 'live' ? options.mode : 'classic'; const mode = options.source === 'live' ? options.mode : 'classic';
const result = options.source === 'live' ? await fetchAd(options) : await getPlaceholderAd(); const result = options.source === 'live' ? await fetchAd(options) : await getPlaceholderAd();
@@ -64,9 +66,9 @@ export async function renderAd(options: FetchAdOptions) {
children: ( children: (
<> <>
{mode === 'classic' || !('callToAction' in ad) ? ( {mode === 'classic' || !('callToAction' in ad) ? (
<AdClassicRendering ad={ad} insightsAd={insightsAd} context={baseContext} /> <AdClassicRendering ad={ad} insightsAd={insightsAd} context={context} />
) : ( ) : (
<AdCoverRendering ad={ad} insightsAd={insightsAd} context={baseContext} /> <AdCoverRendering ad={ad} insightsAd={insightsAd} context={context} />
)} )}
{ad.pixel ? <AdPixels rawPixel={ad.pixel} /> : null} {ad.pixel ? <AdPixels rawPixel={ad.pixel} /> : null}
</> </>
@@ -3,7 +3,7 @@
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import * as React from 'react'; import * as React from 'react';
import { Button } from '@/components/primitives'; import { Button, StyledLink } from '@/components/primitives';
import { useLanguage } from '@/intl/client'; import { useLanguage } from '@/intl/client';
import { t, tString } from '@/intl/translate'; import { t, tString } from '@/intl/translate';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -57,25 +57,16 @@ export function CookiesToast(props: { privacyPolicy?: string }) {
'left-16', 'left-16',
'max-w-md', 'max-w-md',
'text-balance', 'text-balance',
'sm:left-auto', 'sm:left-auto'
)} )}
> >
<p id={describedById} className={tcls('text-sm')}> <p id={describedById} className={tcls('text-sm')}>
{t( {t(
language, language,
'cookies_prompt', 'cookies_prompt',
<a <StyledLink href={privacyPolicy}>
href={privacyPolicy}
className={tcls(
'text-primary-subtle',
'hover:text-primary',
'contrast-more:text-primary',
'contrast-more:hover:text-primary-strong',
'underline',
)}
>
{t(language, 'cookies_prompt_privacy')} {t(language, 'cookies_prompt_privacy')}
</a>, </StyledLink>
)} )}
</p> </p>
<button <button
@@ -92,7 +83,7 @@ export function CookiesToast(props: { privacyPolicy?: string }) {
'justify-center', 'justify-center',
'items-center', 'items-center',
'rounded-sm', 'rounded-sm',
'hover:bg-tint-hover', 'hover:bg-tint-hover'
)} )}
title={tString(language, 'cookies_close')} title={tString(language, 'cookies_close')}
> >
@@ -1,11 +1,11 @@
import { DocumentInlineAnnotation } from '@gitbook/api'; import type { DocumentInlineAnnotation } from '@gitbook/api';
import { getNodeFragmentByType } from '@/lib/document'; import { getNodeFragmentByType } from '@/lib/document';
import { AnnotationPopover } from './AnnotationPopover';
import { Blocks } from '../Blocks'; import { Blocks } from '../Blocks';
import { InlineProps } from '../Inline'; import type { InlineProps } from '../Inline';
import { Inlines } from '../Inlines'; import { Inlines } from '../Inlines';
import { AnnotationPopover } from './AnnotationPopover';
export function Annotation(props: InlineProps<DocumentInlineAnnotation>) { export function Annotation(props: InlineProps<DocumentInlineAnnotation>) {
const { inline, context, document, children } = props; const { inline, context, document, children } = props;
@@ -1,9 +1,9 @@
'use client'; 'use client';
import * as Popover from '@radix-ui/react-popover'; import * as Popover from '@radix-ui/react-popover';
import React from 'react'; import type React from 'react';
import { useLanguage, tString } from '@/intl/client'; import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
export function AnnotationPopover(props: { children: React.ReactNode; body: React.ReactNode }) { export function AnnotationPopover(props: { children: React.ReactNode; body: React.ReactNode }) {
@@ -20,7 +20,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
'decoration-dotted', 'decoration-dotted',
'decoration-1', 'decoration-1',
'underline', 'underline',
'underline-offset-2', 'underline-offset-2'
)} )}
> >
{children} {children}
@@ -43,7 +43,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
'-outline-offset-2', '-outline-offset-2',
'outline-2', 'outline-2',
'outline-primary/8', 'outline-primary/8',
'z-20', 'z-20'
)} )}
sideOffset={4} sideOffset={4}
> >
@@ -56,7 +56,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
'z-[2]', 'z-[2]',
'fill-tint-3', // Same as bg-tint 'fill-tint-3', // Same as bg-tint
'stroke-tint-7', // Same as ring-tint 'stroke-tint-7', // Same as ring-tint
'[paint-order:stroke_fill]', '[paint-order:stroke_fill]'
)} )}
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
@@ -1,19 +1,19 @@
import { DocumentBlock, JSONDocument } from '@gitbook/api'; import type { DocumentBlock, JSONDocument } from '@gitbook/api';
import React from 'react'; import React from 'react';
import { import {
SkeletonParagraph,
SkeletonHeading,
SkeletonCard, SkeletonCard,
SkeletonHeading,
SkeletonImage, SkeletonImage,
SkeletonParagraph,
SkeletonSmall, SkeletonSmall,
} from '@/components/primitives'; } from '@/components/primitives';
import { ClassValue } from '@/lib/tailwind'; import type { ClassValue } from '@/lib/tailwind';
import { BlockContentRef } from './BlockContentRef'; import { BlockContentRef } from './BlockContentRef';
import { CodeBlock } from './CodeBlock'; import { CodeBlock } from './CodeBlock';
import { Divider } from './Divider'; import { Divider } from './Divider';
import { DocumentContextProps } from './DocumentView'; import type { DocumentContextProps } from './DocumentView';
import { Drawing } from './Drawing'; import { Drawing } from './Drawing';
import { Embed } from './Embed'; import { Embed } from './Embed';
import { Expandable } from './Expandable'; import { Expandable } from './Expandable';
@@ -47,7 +47,7 @@ export interface BlockProps<Block extends DocumentBlock> extends DocumentContext
/** /**
* Alternative to `assertNever` that returns `null` instead of throwing an error. * Alternative to `assertNever` that returns `null` instead of throwing an error.
*/ */
function nullIfNever(value: never): null { function nullIfNever(_value: never): null {
return null; return null;
} }
@@ -81,6 +81,7 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
case 'table': case 'table':
return <Table {...props} block={block} />; return <Table {...props} block={block} />;
case 'swagger': case 'swagger':
case 'openapi-operation':
return <OpenAPI {...props} block={block} />; return <OpenAPI {...props} block={block} />;
case 'embed': case 'embed':
return <Embed {...props} block={block} />; return <Embed {...props} block={block} />;
@@ -154,6 +155,7 @@ export function BlockSkeleton(props: { block: DocumentBlock; style: ClassValue }
case 'expandable': case 'expandable':
case 'table': case 'table':
case 'swagger': case 'swagger':
case 'openapi-operation':
case 'math': case 'math':
case 'divider': case 'divider':
case 'content-ref': case 'content-ref':
@@ -1,9 +1,9 @@
import { DocumentBlockContentRef, SiteInsightsLinkPosition } from '@gitbook/api'; import { type DocumentBlockContentRef, SiteInsightsLinkPosition } from '@gitbook/api';
import { Card } from '@/components/primitives'; import { Card } from '@/components/primitives';
import { resolveContentRef, ResolvedContentRef } from '@/lib/references'; import { type ResolvedContentRef, resolveContentRef } from '@/lib/references';
import { BlockProps } from './Block'; import type { BlockProps } from './Block';
export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>) { export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>) {
const { block, context, style } = props; const { block, context, style } = props;
@@ -46,7 +46,7 @@ export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>
} }
async function SpaceRefCard( async function SpaceRefCard(
props: { resolved: ResolvedContentRef } & BlockProps<DocumentBlockContentRef>, props: { resolved: ResolvedContentRef } & BlockProps<DocumentBlockContentRef>
) { ) {
const { context, style, resolved } = props; const { context, style, resolved } = props;
const spaceId = context.contentContext?.space.id; const spaceId = context.contentContext?.space.id;
@@ -1,9 +1,9 @@
import { DocumentBlock, JSONDocument } from '@gitbook/api'; import type { DocumentBlock, JSONDocument } from '@gitbook/api';
import { tcls, ClassValue } from '@/lib/tailwind'; import { type ClassValue, tcls } from '@/lib/tailwind';
import { Block } from './Block'; import { Block } from './Block';
import { DocumentContextProps } from './DocumentView'; import type { DocumentContextProps } from './DocumentView';
import { isBlockOffscreen } from './utils'; import { isBlockOffscreen } from './utils';
/** /**
@@ -19,7 +19,7 @@ export function Blocks<TBlock extends DocumentBlock, Tag extends React.ElementTy
/** Props to pass to the wrapper element */ /** Props to pass to the wrapper element */
wrapperProps?: React.ComponentProps<Tag>; wrapperProps?: React.ComponentProps<Tag>;
}, }
) { ) {
const { tag: Tag = 'div', style, wrapperProps, ...blocksProps } = props; const { tag: Tag = 'div', style, wrapperProps, ...blocksProps } = props;
@@ -68,7 +68,7 @@ export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBl
key={node.key} key={node.key}
block={node} block={node}
style={[ style={[
'w-full mx-auto decoration-primary/6', 'mx-auto w-full decoration-primary/6',
node.data && 'fullWidth' in node.data && node.data.fullWidth node.data && 'fullWidth' in node.data && node.data.fullWidth
? 'max-w-screen-xl' ? 'max-w-screen-xl'
: 'max-w-3xl', : 'max-w-3xl',

Some files were not shown because too many files have changed in this diff Show More