mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
refactor(www): split redirects into static and dynamic files and add redirect checks (#54194)
## Problem `apps/www/lib/redirects.js` was a single file with static and dynamic rules mixed together, and the redirects had no automated checks. `/docs` redirects already moved to `apps/docs/lib/redirects/`, so www was the odd one out. ## Solution I applied the docs layout to www without changing how redirects are served: - `apps/www/lib/redirects/static-redirects.json`: 220 one-to-one entries, including fixed redirects to external `https://` URLs. - `apps/www/lib/redirects/dynamic-redirects.js`: 14 entries with params, splats, regex, escapes, or `has`. - `apps/www/lib/redirects/index.js`: combines both (static first) for `next.config.mjs` and `scripts/generateMdContent.mjs`. - `apps/www/lib/redirects/redirects.test.ts`: checks for loops, chains, duplicate sources, invalid sources and destinations (anchors, missing `/` or `https://`), dynamic entries in the static file, and internal destinations that do not exist. - README for the folder, plus updates to `apps/www/README.md`, `DEVELOPERS.md`, `CODEOWNERS`, and the `www-tests` path filter and sparse checkout. Bulk redirects are not part of this PR: www has 234 redirects, well under the route limit, so they stay in `next.config.mjs`. ### Missing-destination check Internal destinations are checked against the same sources the site serves from: - `app/` and `pages/` routes, and `public/` files. - Blog, customer, event, and alternative slugs, derived the way `lib/posts.tsx` derives them. Events with `disable_page_build` do not count. - Feature and `/go` page slugs. - `.md` destinations must be a page that `generateMdContent.mjs` publishes. An existing HTML page is not enough. - `/docs/guides` destinations, against the docs content and guide routes. Other zones and build-generated files are not checked. A destination with params is probed with one sample value, so value-specific loops or chains are not caught. The README lists these limits. ### Behavior notes - The rule set matches `master`, with one exception: `/blog/2021/07/30/1-the-supabase-hackathon` now points at the canonical slug `/blog/1-the-supabase-hackathon`. The old destination `/blog/the-supabase-hackathon` also resolves today, because the blog route matches posts by filename suffix. The check requires canonical slugs. - First-match results on `supabase.com` are identical on 241 probe paths. - Static entries now precede dynamic ones. On the `supabase.design` host, 25 static sources that used to sit after its catch-all rule now come before it. Those paths now take two hops to reach the design system instead of one. - Comments on static entries were dropped, because JSON has no comments. ## To test 1. Open the www preview and visit `/about`. It redirects to `/company`. 2. Visit `/buildersday`. It redirects to `/builderday`. 3. Visit `/sign-in`. It redirects to the dashboard sign-in page. 4. Visit `/blog/2021/07/30/1-the-supabase-hackathon`. It lands on the hackathon post. ## Linear - fixes GROWTH-1571
This commit is contained in:
1 parent
c2edb29076
commit
fe8e912993
14 files changed
+1548
-1128
No files matched your search
+1
-1
@@ -24,7 +24,7 @@
|
||||
/apps/www/ @supabase/marketing
|
||||
/apps/www/public/images/blog @supabase/marketing
|
||||
/apps/www/public/schemas/ @supabase/cli
|
||||
/apps/www/lib/redirects.js
|
||||
/apps/www/lib/redirects/
|
||||
/apps/www/data/legal/ @supabase/frontend
|
||||
/apps/www/pages/legal/ @supabase/frontend
|
||||
/apps/www/public/legal/ @supabase/frontend
|
||||
|
||||
@@ -14,16 +14,19 @@ on:
|
||||
- 'apps/www/next.config.js'
|
||||
- 'apps/www/lib/**/*.js'
|
||||
- 'apps/www/lib/**/*.mjs'
|
||||
- 'apps/www/lib/redirects/**'
|
||||
- 'apps/www/content/md/**'
|
||||
- 'apps/www/scripts/**/*.mjs'
|
||||
- 'apps/www/internals/**/*.mjs'
|
||||
- 'apps/www/_blog/**'
|
||||
- 'apps/www/_alternatives/**'
|
||||
- 'apps/www/_customers/**'
|
||||
- 'apps/www/_events/**'
|
||||
- 'apps/www/public/.well-known/**'
|
||||
# www catalog tests check that linked docs guides exist, so guide changes
|
||||
# must trigger these tests and their sources must be included in checkout.
|
||||
- 'apps/docs/content/guides/**'
|
||||
- 'apps/docs/app/guides/**'
|
||||
|
||||
# Cancel old builds on new commit for same workflow + branch/PR
|
||||
concurrency:
|
||||
@@ -47,6 +50,7 @@ jobs:
|
||||
sparse-checkout: |
|
||||
apps/www
|
||||
apps/docs/content/guides
|
||||
apps/docs/app/guides
|
||||
packages
|
||||
scripts
|
||||
supabase
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
^./i18n
|
||||
^./packages/api-types
|
||||
^./apps/www/lib/redirects.js
|
||||
^./apps/www/lib/redirects/
|
||||
^./apps/studio/public/*
|
||||
+1
-1
@@ -178,7 +178,7 @@ We review PRs in the order of their submission. We try to accept the earliest on
|
||||
Where the redirect goes depends on the URL:
|
||||
|
||||
- **`/docs` URLs:** add the entry to [`apps/docs/lib/redirects/`](https://github.com/supabase/supabase/blob/master/apps/docs/lib/redirects/README.md). Static one-to-one entries go in `static-redirects.json`, and entries with params, splats, or conditions go in `dynamic-redirects.js`.
|
||||
- **All other URLs:** add the entry to [`redirects.js`](https://github.com/supabase/supabase/blob/master/apps/www/lib/redirects.js) in the main site.
|
||||
- **All other URLs:** add the entry to [`apps/www/lib/redirects/`](https://github.com/supabase/supabase/blob/master/apps/www/lib/redirects/README.md) in the main site. Static one-to-one entries go in `static-redirects.json`, and entries with params, splats, or conditions go in `dynamic-redirects.js`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -177,7 +177,7 @@ for coverage and limits.
|
||||
|
||||
## Redirects
|
||||
|
||||
Redirects for non-docs URLs live in [`lib/redirects.js`](lib/redirects.js). Redirects for `/docs` URLs moved to the docs app, so add new `/docs` redirects in [`apps/docs/lib/redirects/`](../docs/lib/redirects/README.md) instead.
|
||||
Redirects for non-docs URLs live in [`lib/redirects/`](lib/redirects/README.md), split into static one-to-one entries and dynamic entries, with tests that check for loops, chains, and missing destinations. Redirects for `/docs` URLs live in the docs app, so add new `/docs` redirects in [`apps/docs/lib/redirects/`](../docs/lib/redirects/README.md) instead.
|
||||
|
||||
## Go pages (`/go/*`)
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ function textResponse(content: string) {
|
||||
}
|
||||
|
||||
// Product overview slugs and pricing.txt are 301-redirected to /<slug>.md in
|
||||
// apps/www/lib/redirects.js, so this handler typically only sees per-SDK
|
||||
// apps/www/lib/redirects/, so this handler typically only sees per-SDK
|
||||
// reference files. The pricing branch stays as a fallback in case the redirect
|
||||
// is bypassed.
|
||||
export async function GET(_request: Request, { params }: { params: Promise<{ slug: string }> }) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,42 @@
|
||||
# www redirects
|
||||
|
||||
Redirects for non-docs URLs on `supabase.com`. Redirects for `/docs` URLs live in [`apps/docs/lib/redirects/`](../../../docs/lib/redirects/README.md).
|
||||
|
||||
Sources and destinations are full public paths (for example `/blog/old-post`), or `https://` URLs for external destinations.
|
||||
|
||||
| File | Contains | Served by |
|
||||
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
||||
| `static-redirects.json` | One-to-one mappings: a fixed `source` maps to a fixed `destination`, with no params, splats, regex, or `has`/`missing`. | Next.js `redirects()` in `apps/www/next.config.mjs`, via `index.js` |
|
||||
| `dynamic-redirects.js` | Anything with conditional logic: `:param`, `*` / `:path*` splats, regex groups, `has`, or `missing`. | Next.js `redirects()` in `apps/www/next.config.mjs`, via `index.js` |
|
||||
| `index.js` | Combines both files. Static entries come first, then dynamic ones. | `next.config.mjs` and `scripts/generateMdContent.mjs` |
|
||||
|
||||
Next.js serves the first rule that matches, so the order matters. Keep a more specific entry in the static file when a dynamic rule would otherwise catch it.
|
||||
|
||||
## Adding a redirect
|
||||
|
||||
1. If it has no params, splats, regex, or conditions, add it to `static-redirects.json`. Otherwise add it to `dynamic-redirects.js`. A fixed redirect to an external `https://` URL is static.
|
||||
2. In `static-redirects.json`, use the same shape as the existing entries:
|
||||
|
||||
```json
|
||||
{ "source": "/old-path", "destination": "/new-path", "permanent": true }
|
||||
```
|
||||
|
||||
3. Use `permanent: true` for permanent (308) redirects and `permanent: false` for temporary (307) redirects.
|
||||
4. JSON does not support comments, so put the reason for a static entry in the PR description.
|
||||
5. Run `pnpm test` in `apps/www`.
|
||||
|
||||
## Checks
|
||||
|
||||
`redirects.test.ts` runs in CI and fails when a redirect has any of these problems:
|
||||
|
||||
- **Loops:** following the redirect leads back to a path it already passed through.
|
||||
- **Chains:** the destination is itself redirected, which costs the visitor an extra hop. Point the source at the final destination instead.
|
||||
- **Duplicate sources:** two unconditional rules share a source, so the second never applies.
|
||||
- **Invalid locations:** a source or destination that does not start with `/` or `https://`, or a source with an anchor (`#`), which never reaches the server.
|
||||
- **Misplaced entries:** a `:param`, splat, regex group, escape, `has`, or `missing` in `static-redirects.json`.
|
||||
- **Missing destinations:** an internal destination that has no page. The check looks at the `app/` and `pages/` routes, the blog, customer, event, alternative, feature, and `/go` page slugs, `public/` files, published markdown pages (`.md`), and `/docs/guides` pages. Other zones and build-generated files (`/rss.xml`, `/changelog/*`) are not checked.
|
||||
|
||||
Limits:
|
||||
|
||||
- Rules with a `has` condition, such as the `supabase.design` host rule, are left out of the loop and chain checks, because they only apply to some requests.
|
||||
- A destination with params (`/new/:slug`) is probed with one sample value, so a loop or chain that only happens for a specific value (`/new/special`) is not caught, and its target page is not checked.
|
||||
@@ -0,0 +1,84 @@
|
||||
module.exports = [
|
||||
{
|
||||
permanent: true,
|
||||
source: '/images/customers/logos/light/:path*',
|
||||
destination: '/images/customers/logos/on-dark/:path*',
|
||||
},
|
||||
// Legacy root wordmarks moved to on-light/. Keep dreambase-mark.png at logos/ root.
|
||||
{
|
||||
permanent: true,
|
||||
source: '/images/customers/logos/:slug((?!dreambase-mark\\.png)[^/.]+).png',
|
||||
destination: '/images/customers/logos/on-light/:slug.png',
|
||||
},
|
||||
{
|
||||
permanent: true,
|
||||
source: '/ui/:path*',
|
||||
destination: '/library/:path*',
|
||||
},
|
||||
{ permanent: false, source: '/blog/page/:number', destination: '/blog' },
|
||||
{
|
||||
permanent: true,
|
||||
source: '/project/:path+',
|
||||
destination: 'https://supabase.com/dashboard/project/:path+',
|
||||
},
|
||||
// Catch-all: any other /partners/integrations/<slug> not covered by a specific rule above.
|
||||
// Must come after all specific /partners/integrations/* rules
|
||||
{
|
||||
permanent: true,
|
||||
source: '/partners/integrations/:slug*',
|
||||
destination: '/partners/catalog/:slug*',
|
||||
},
|
||||
{
|
||||
permanent: false,
|
||||
source: '/special-announcement/tickets/:path*',
|
||||
destination: '/ga-week/tickets/:path*',
|
||||
},
|
||||
{
|
||||
permanent: true,
|
||||
source: '/partners/experts/:path*',
|
||||
destination: '/partners',
|
||||
},
|
||||
// design
|
||||
{
|
||||
permanent: true,
|
||||
source: '/:path*',
|
||||
has: [
|
||||
{
|
||||
type: 'host',
|
||||
value: 'supabase.design',
|
||||
},
|
||||
],
|
||||
destination: 'https://supabase.com/design-system/:path*',
|
||||
},
|
||||
{
|
||||
source: '/redeem',
|
||||
has: [
|
||||
{
|
||||
type: 'query',
|
||||
key: 'code',
|
||||
},
|
||||
],
|
||||
destination: '/dashboard/redeem?code=:code',
|
||||
permanent: false,
|
||||
},
|
||||
{
|
||||
permanent: true,
|
||||
source: '/downloads/docs/Supabase\\+DPA\\+:version.pdf',
|
||||
destination: '/legal/customer-resources/data-processing-addendum',
|
||||
},
|
||||
{
|
||||
permanent: true,
|
||||
source: '/downloads/docs/Supabase\\+TIA\\+250314.pdf',
|
||||
destination: 'https://trust.supabase.io',
|
||||
},
|
||||
{
|
||||
permanent: true,
|
||||
source: '/builder-day/:path*',
|
||||
destination: '/builderday/:path*',
|
||||
},
|
||||
{
|
||||
permanent: true,
|
||||
source: '/buildersday/:path*',
|
||||
destination: '/builderday/:path*',
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
// All www redirects: one-to-one entries first, then entries with params, splats, or conditions.
|
||||
// Order matters because Next serves the first matching rule. See README.md in this folder.
|
||||
const staticRedirects = require('./static-redirects.json')
|
||||
const dynamicRedirects = require('./dynamic-redirects.js')
|
||||
|
||||
module.exports = [...staticRedirects, ...dynamicRedirects]
|
||||
@@ -0,0 +1,303 @@
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import matter from 'gray-matter'
|
||||
import { getPathMatch } from 'next/dist/shared/lib/router/utils/path-match'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { FILENAME_SUBSTRING } from '@/lib/posts'
|
||||
|
||||
import redirects from './index.js'
|
||||
import staticRedirects from './static-redirects.json'
|
||||
|
||||
const WWW_ROOT = join(import.meta.dirname, '..', '..')
|
||||
const DOCS_GUIDES_DIRECTORY = join(WWW_ROOT, '..', 'docs', 'content', 'guides')
|
||||
|
||||
// Paths served by other zones (see lib/rewrites.js). Their pages are not in this app, so only
|
||||
// /docs/guides destinations are checked, against the docs content.
|
||||
const OTHER_ZONE_PREFIXES = [
|
||||
'/docs',
|
||||
'/dashboard',
|
||||
'/library',
|
||||
'/design-system',
|
||||
'/kb',
|
||||
'/evals',
|
||||
'/migrate',
|
||||
'/builderday',
|
||||
]
|
||||
|
||||
// Guides fetched from external repos at build time, so their files are absent from a fresh checkout
|
||||
const FEDERATED_GUIDES = ['graphql', 'deployment/terraform', 'deployment/ci']
|
||||
|
||||
// Generated at build time or fetched remotely, so they cannot be checked from a fresh checkout
|
||||
const UNVERIFIABLE_PATTERNS = [/^\/rss\.xml$/, /^\/changelog-rss\.xml$/, /^\/sitemap_www\.xml$/]
|
||||
const REMOTE_CONTENT_PREFIXES = ['/changelog/']
|
||||
|
||||
type Redirect = {
|
||||
source: string
|
||||
destination: string
|
||||
permanent: boolean
|
||||
has?: unknown[]
|
||||
missing?: unknown[]
|
||||
}
|
||||
|
||||
const allRedirects = redirects as Redirect[]
|
||||
|
||||
// Redirects that apply to every visitor. Conditional rules (host or query) are left out so that,
|
||||
// for example, the supabase.design host rule does not make every path look like a chain.
|
||||
const unconditionalRedirects = allRedirects.filter((r) => !r.has && !r.missing)
|
||||
|
||||
const isExternal = (value: string) => value.startsWith('https://')
|
||||
|
||||
// Strip query and hash, and replace params (:slug, :path*, regex groups) with a sample segment, so
|
||||
// a destination can be matched against other sources.
|
||||
const toProbePath = (destination: string) =>
|
||||
destination
|
||||
.split(/[?#]/)[0]
|
||||
.replace(/:[A-Za-z0-9_]+(\([^)]*\))?[*+?]?/g, '__probe__')
|
||||
.replace(/(.)\/$/, '$1')
|
||||
|
||||
const matchers = unconditionalRedirects.map((redirect) => ({
|
||||
redirect,
|
||||
matches: getPathMatch(redirect.source, { strict: false, removeUnnamedParams: true }),
|
||||
}))
|
||||
|
||||
// Next serves the first matching rule, so follow the first match for a path.
|
||||
const nextHop = (path: string): Redirect | undefined =>
|
||||
matchers.find(({ matches }) => matches(path))?.redirect
|
||||
|
||||
// Params, splats, regex groups, or escapes. The colon in "https://" is not a param.
|
||||
const hasPattern = (value: string) => /[:*()\\]/.test(value.replace(/^https:\/\//, ''))
|
||||
|
||||
const format = (r: Redirect) => `${r.source} -> ${r.destination}`
|
||||
|
||||
describe('www redirects', () => {
|
||||
it('has no redirect loops', () => {
|
||||
const loops = unconditionalRedirects
|
||||
.filter((r) => !isExternal(r.destination))
|
||||
// Follow the redirect hop by hop and keep those that revisit a path they already passed
|
||||
// through (/a -> /b -> /a, or /a -> /a)
|
||||
.filter((r) => {
|
||||
const seen = new Set<string>([toProbePath(r.source)])
|
||||
let current: Redirect | undefined = r
|
||||
while (current && !isExternal(current.destination)) {
|
||||
const path = toProbePath(current.destination)
|
||||
if (seen.has(path)) return true
|
||||
seen.add(path)
|
||||
current = nextHop(path)
|
||||
}
|
||||
return false
|
||||
})
|
||||
.map(format)
|
||||
|
||||
expect(loops).toEqual([])
|
||||
})
|
||||
|
||||
it('has no redirect chains', () => {
|
||||
const chains = unconditionalRedirects
|
||||
.filter((r) => !isExternal(r.destination))
|
||||
// Keep redirects whose destination is itself redirected (/a -> /b, /b -> /c), which costs
|
||||
// the visitor an extra hop
|
||||
.filter((r) => nextHop(toProbePath(r.destination)))
|
||||
.map((r) => `${format(r)} -> ${nextHop(toProbePath(r.destination))!.destination}`)
|
||||
|
||||
expect(chains).toEqual([])
|
||||
})
|
||||
|
||||
it('has unique sources', () => {
|
||||
const seen = new Set<string>()
|
||||
const duplicates = unconditionalRedirects
|
||||
.filter((r) => (seen.has(r.source) ? true : (seen.add(r.source), false)))
|
||||
.map((r) => r.source)
|
||||
|
||||
expect(duplicates).toEqual([])
|
||||
})
|
||||
|
||||
it('uses valid sources and destinations', () => {
|
||||
const isValidLocation = (value: string) => value.startsWith('/') || isExternal(value)
|
||||
|
||||
const invalid = allRedirects
|
||||
// Keep redirects where the source or destination starts with neither "/" nor "https://"
|
||||
.filter((r) => !isValidLocation(r.source) || !isValidLocation(r.destination))
|
||||
.map(format)
|
||||
// Anchors never reach the server, so a source with one can never match
|
||||
const anchorSources = allRedirects.filter((r) => r.source.includes('#')).map((r) => r.source)
|
||||
|
||||
expect(invalid).toEqual([])
|
||||
expect(anchorSources).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps params, splats, regex and conditions out of the static file', () => {
|
||||
const notStatic = staticRedirects
|
||||
.filter(
|
||||
(r: Record<string, unknown>) =>
|
||||
hasPattern(r.source as string) ||
|
||||
hasPattern(r.destination as string) ||
|
||||
'has' in r ||
|
||||
'missing' in r
|
||||
)
|
||||
.map((r) => r.source)
|
||||
|
||||
expect(notStatic).toEqual([])
|
||||
})
|
||||
|
||||
it('points internal redirects at pages that exist', () => {
|
||||
const missing = allRedirects
|
||||
// Destinations with params depend on the incoming path, so they cannot be checked
|
||||
.filter((r) => !isExternal(r.destination) && !hasPattern(r.destination))
|
||||
.filter((r) => !pathExists(r.destination.split(/[?#]/)[0].replace(/(.)\/$/, '$1')))
|
||||
.map(format)
|
||||
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
// --- Destination lookup ---------------------------------------------------------------------
|
||||
|
||||
const exists = (...segments: string[]) => existsSync(join(WWW_ROOT, ...segments))
|
||||
|
||||
const mdxFilesIn = (directory: string) =>
|
||||
existsSync(join(WWW_ROOT, directory))
|
||||
? readdirSync(join(WWW_ROOT, directory)).filter((name) => name.endsWith('.mdx'))
|
||||
: []
|
||||
|
||||
// Same derivation as getAllPostSlugs in lib/posts.tsx: blog and event filenames lose their
|
||||
// YYYY-MM-DD- prefix, so 2024-08-30__name.mdx is served at /events/_name.
|
||||
const datedSlugs = (filenames: string[]) =>
|
||||
new Set(filenames.map((name) => name.replace('.mdx', '').substring(FILENAME_SUBSTRING)))
|
||||
const plainSlugs = (filenames: string[]) =>
|
||||
new Set(filenames.map((name) => name.replace('.mdx', '')))
|
||||
|
||||
// pages/events/[slug].tsx returns notFound for events that set disable_page_build
|
||||
const eventFilesWithPages = mdxFilesIn('_events').filter(
|
||||
(name) =>
|
||||
matter(readFileSync(join(WWW_ROOT, '_events', name), 'utf8')).data.disable_page_build !== true
|
||||
)
|
||||
|
||||
// Slugs declared as `slug: '...'` in a TypeScript file, or in every file under a directory
|
||||
function slugLiteralsIn(relativePath: string): Set<string> {
|
||||
const full = join(WWW_ROOT, relativePath)
|
||||
const files = relativePath.endsWith('.tsx')
|
||||
? [full]
|
||||
: readdirSync(full, { recursive: true, encoding: 'utf8' })
|
||||
.filter((name) => name.endsWith('.tsx'))
|
||||
.map((name) => join(full, name))
|
||||
return new Set(
|
||||
files.flatMap((file) =>
|
||||
[...readFileSync(file, 'utf8').matchAll(/^\s*slug: '([^']+)'/gm)].map((match) => match[1])
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const COLLECTION_SLUGS = new Map<string, Set<string>>([
|
||||
['blog', datedSlugs(mdxFilesIn('_blog'))],
|
||||
['customers', plainSlugs(mdxFilesIn('_customers'))],
|
||||
['events', datedSlugs(eventFilesWithPages)],
|
||||
['alternatives', plainSlugs(mdxFilesIn('_alternatives'))],
|
||||
['features', slugLiteralsIn('data/features.tsx')],
|
||||
])
|
||||
|
||||
// Go pages are TypeScript objects, and their slugs can span several segments (legal/amoe)
|
||||
const GO_SLUGS = slugLiteralsIn('_go')
|
||||
|
||||
// Sections that scripts/generateMdContent.mjs publishes as markdown, plus its dynamic slugs
|
||||
const MD_COLLECTIONS = ['blog', 'customers', 'events']
|
||||
const MD_DYNAMIC_SLUGS = ['pricing', 'customers']
|
||||
|
||||
// The proxy only serves markdown for slugs in MD_PAGES, so an existing HTML page is not enough.
|
||||
function markdownExists(path: string) {
|
||||
const slug = path.slice(1, -'.md'.length)
|
||||
// generateMdContent.mjs drops the markdown of any page that is itself redirected
|
||||
if (slug !== 'index' && nextHop(`/${slug}`)) return false
|
||||
if (exists('content', 'md', `${slug}.md`) || MD_DYNAMIC_SLUGS.includes(slug)) return true
|
||||
const [collection, entry, ...rest] = slug.split('/')
|
||||
return (
|
||||
rest.length === 0 &&
|
||||
MD_COLLECTIONS.includes(collection) &&
|
||||
Boolean(COLLECTION_SLUGS.get(collection)?.has(entry))
|
||||
)
|
||||
}
|
||||
|
||||
const isDynamicSegment = (name: string) => /^\[.+\]$/.test(name)
|
||||
const stripExtension = (name: string) => name.replace(/\.(tsx|ts|mdx)$/, '')
|
||||
|
||||
// Walk app/ or pages/ for a route. Route groups ("(name)") do not add a segment, and a dynamic
|
||||
// segment ("[slug]") matches any value unless `allowDynamic` is off.
|
||||
function routeExists(
|
||||
root: 'app' | 'pages',
|
||||
segments: string[],
|
||||
allowDynamic = true,
|
||||
directory: string = root
|
||||
): boolean {
|
||||
const [segment, ...rest] = segments
|
||||
const full = join(WWW_ROOT, directory)
|
||||
if (!existsSync(full)) return false
|
||||
|
||||
const entries = readdirSync(full, { withFileTypes: true })
|
||||
const files = entries.filter((e) => e.isFile()).map((e) => e.name)
|
||||
const matchesSegment = (name: string) =>
|
||||
name === segment || (allowDynamic && isDynamicSegment(name))
|
||||
|
||||
if (segment === undefined) {
|
||||
return files.some((name) =>
|
||||
root === 'app' ? /^(page|route)\.(tsx|ts)$/.test(name) : /^index\.(tsx|ts|mdx)$/.test(name)
|
||||
)
|
||||
}
|
||||
|
||||
// pages/<segment>.tsx or pages/[slug].tsx as the last segment
|
||||
if (
|
||||
root === 'pages' &&
|
||||
rest.length === 0 &&
|
||||
files.some((f) => matchesSegment(stripExtension(f)))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
return entries
|
||||
.filter((e) => e.isDirectory())
|
||||
.some((e) => {
|
||||
const next = join(directory, e.name)
|
||||
if (/^\(.+\)$/.test(e.name)) return routeExists(root, segments, allowDynamic, next)
|
||||
return matchesSegment(e.name) && routeExists(root, rest, allowDynamic, next)
|
||||
})
|
||||
}
|
||||
|
||||
function guideExists(path: string) {
|
||||
const guide = path.replace(/^\/docs\/guides\//, '').replace(/\/$/, '')
|
||||
if (FEDERATED_GUIDES.some((g) => guide === g || guide.startsWith(`${g}/`))) return true
|
||||
return (
|
||||
existsSync(join(DOCS_GUIDES_DIRECTORY, `${guide}.mdx`)) ||
|
||||
existsSync(join(DOCS_GUIDES_DIRECTORY, guide, 'index.mdx')) ||
|
||||
// Some guides are dedicated Next.js routes in apps/docs/app/guides rather than MDX files
|
||||
existsSync(join(WWW_ROOT, '..', 'docs', 'app', 'guides', guide, 'page.tsx'))
|
||||
)
|
||||
}
|
||||
|
||||
function pathExists(path: string): boolean {
|
||||
if (path === '/') return true
|
||||
if (UNVERIFIABLE_PATTERNS.some((p) => p.test(path))) return true
|
||||
if (REMOTE_CONTENT_PREFIXES.some((p) => path.startsWith(p))) return true
|
||||
|
||||
if (path.startsWith('/docs/guides/')) return guideExists(path)
|
||||
if (OTHER_ZONE_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`))) return true
|
||||
|
||||
if (path.endsWith('.md')) return markdownExists(path)
|
||||
|
||||
if (exists('public', path)) return true
|
||||
|
||||
const segments = path.split('/').filter(Boolean)
|
||||
|
||||
// Collection entries have a dynamic route, so check their slug against the content. A static
|
||||
// route with the same segments (for example /blog/tags) still counts.
|
||||
const [collection, slug] = segments
|
||||
if (collection === 'go' && segments.length > 1) return GO_SLUGS.has(segments.slice(1).join('/'))
|
||||
const collectionSlugs = COLLECTION_SLUGS.get(collection)
|
||||
if (segments.length === 2 && collectionSlugs) {
|
||||
return (
|
||||
collectionSlugs.has(slug) ||
|
||||
routeExists('app', segments, false) ||
|
||||
routeExists('pages', segments, false)
|
||||
)
|
||||
}
|
||||
|
||||
return routeExists('app', segments) || routeExists('pages', segments)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@ import codeHikeTheme from 'config/code-hike.theme.json' with { type: 'json' }
|
||||
import rehypeSlug from 'rehype-slug'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
|
||||
import redirects from './lib/redirects.js'
|
||||
import redirects from './lib/redirects/index.js'
|
||||
import remotePatterns from './lib/remotePatterns.js'
|
||||
import rewrites from './lib/rewrites.js'
|
||||
import securityHeaders from './lib/security-headers.js'
|
||||
|
||||
@@ -11,7 +11,7 @@ import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import matter from 'gray-matter'
|
||||
|
||||
import redirects from '../lib/redirects.js'
|
||||
import redirects from '../lib/redirects/index.js'
|
||||
import { mdxBodyToMarkdown } from './lib/mdxToMarkdown.mjs'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
Reference in new issue
Block a user