Search leaves out the 404 page: searchContent, the search route, MCP search_content
searchContent / listContent read Site settings once (depth 0, homepage + notFound) and skip unlistedPageIds; createSearchRoute and the MCP route pass settingsSlug. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3645e61f7d
commit
6b2c9b3cc6
+2
-1
@@ -47,7 +47,8 @@ fifteen ready page sections and ten page templates.
|
||||
`skip (not listed)`. The seed templates (`ipal-site`, `ipal-form`) read it.
|
||||
|
||||
### Fixed
|
||||
- **Sitemap, llms.txt, the site index (MCP `list_pages`):** the page assigned as the 404 page is no longer listed —
|
||||
- **Sitemap, llms.txt, the site index (MCP `list_pages`), search (`searchContent`, the search route, MCP
|
||||
`search_content`):** the page assigned as the 404 page is no longer listed —
|
||||
it answers 404 at its own address (`unlistedPageIds(settings)`). A 404 page that is also the homepage stays.
|
||||
- **`buildImagesConfig` in production without R2:** with `R2_PUBLIC_URL` empty (the default: media served by the
|
||||
app) the site's own `/api/media/file/**` on `NEXT_PUBLIC_SERVER_URL` is allowed, so next/image no longer answers
|
||||
|
||||
+3
-2
@@ -390,7 +390,8 @@ Query: `?q=` (required), `?locale=`, `?limit=`. Response:
|
||||
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
|
||||
```
|
||||
|
||||
No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`),
|
||||
No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`) and without the page assigned as the
|
||||
404 page (Site settings → System pages, read through `settingsSlug`, default `site-settings`),
|
||||
10 by default (`defaultLimit`), max 50 results. Under-construction mode:
|
||||
pass `isPathVisible` from `createContentHelpers`, and hidden pages drop out of the results. Error/database
|
||||
offline → empty result (200), not 500. **Rate limit:** 120/min per IP (in memory,
|
||||
@@ -407,7 +408,7 @@ const results = await searchContent({ payload, query, config, locale, limit, bas
|
||||
// SearchResult[] = { title, url, description?, slug }[]
|
||||
```
|
||||
|
||||
`searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `locale`
|
||||
`searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `settingsSlug` (`'site-settings'`, for the 404 page), `locale`
|
||||
(default/invalid → `defaultLocale`), `limit` (10, clamped to 1–50),
|
||||
`summaryField` (e.g. `'aiSummary'` — prefers the richer description from
|
||||
`buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws
|
||||
|
||||
+3
-2
@@ -51,8 +51,9 @@ locale — the caller decides the fallback (404, redirect). A slug equal to
|
||||
with a different slug, pass `homeSlug`.
|
||||
|
||||
**Pages with no URL of their own:** `unlistedPageIds(settings)` (root) → the ids of pages assigned to a role that
|
||||
renders elsewhere — today the 404 page (unless it is also the homepage). The sitemap, llms.txt and the site index
|
||||
(MCP `list_pages`) leave them out; use it in your own lists of pages too.
|
||||
renders elsewhere — today the 404 page (unless it is also the homepage). The sitemap, llms.txt, the site index
|
||||
(MCP `list_pages`) and search (`searchContent`, `createSearchRoute`, MCP `search_content`) leave them out; use it in your
|
||||
own lists of pages too.
|
||||
|
||||
## Typical case: `/{locale}` → home page
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ type CreateSearchRouteArgs = {
|
||||
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
||||
*/
|
||||
rateLimit?: { max?: number; windowMs?: number } | false
|
||||
/** SiteSettings global (the assigned 404 page is left out of results). Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string
|
||||
}
|
||||
@@ -50,7 +52,7 @@ type CreateSearchRouteArgs = {
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/
|
||||
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, summaryField } = args
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, settingsSlug, summaryField } = args
|
||||
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
|
||||
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
|
||||
|
||||
@@ -85,6 +87,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
})
|
||||
const shownLocale = locale ?? config.defaultLocale
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'
|
||||
import { unlistedPageIds } from '../pages/unlistedPages.js'
|
||||
|
||||
export type SearchResult = {
|
||||
description?: string
|
||||
@@ -27,6 +28,8 @@ type SearchContentArgs = {
|
||||
payload: BasePayload
|
||||
/** Keywords. */
|
||||
query: string
|
||||
/** SiteSettings global — the assigned 404 page is left out (unlistedPageIds). Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/**
|
||||
* Field holding a richer AI summary (see buildSummaryField). When set and
|
||||
* present on a doc, it's preferred over meta.description for the result's
|
||||
@@ -64,6 +67,7 @@ export async function searchContent({
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
}: SearchContentArgs): Promise<SearchResult[]> {
|
||||
const q = query.trim()
|
||||
@@ -89,7 +93,25 @@ export async function searchContent({
|
||||
return []
|
||||
}
|
||||
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
|
||||
const unlisted = await readUnlisted(payload, settingsSlug)
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField, unlisted })
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids of pages with no URL of their own (the assigned 404 page), from Site settings — one small read
|
||||
* (depth 0, two fields). A missing global means none.
|
||||
*/
|
||||
async function readUnlisted(payload: BasePayload, settingsSlug = 'site-settings'): Promise<Set<number | string>> {
|
||||
try {
|
||||
const settings = (await payload.findGlobal({
|
||||
slug: settingsSlug as never,
|
||||
depth: 0,
|
||||
select: { homepage: true, notFound: true } as never,
|
||||
})) as Record<string, unknown>
|
||||
return unlistedPageIds(settings)
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
type ToResultsArgs = {
|
||||
@@ -99,13 +121,15 @@ type ToResultsArgs = {
|
||||
max: number
|
||||
origin: string
|
||||
summaryField?: string
|
||||
unlisted: Set<number | string>
|
||||
}
|
||||
|
||||
/** Published, indexable docs → results. Shared by searchContent and listContent. */
|
||||
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField }: ToResultsArgs): SearchResult[] {
|
||||
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField, unlisted }: ToResultsArgs): SearchResult[] {
|
||||
const results: SearchResult[] = []
|
||||
for (const doc of docs) {
|
||||
if (doc._status && doc._status !== 'published') {continue}
|
||||
if (unlisted.has(doc.id)) {continue}
|
||||
if (doc.noindex || doc.meta?.noindex) {continue}
|
||||
const title = typeof doc.title === 'string' ? doc.title : undefined
|
||||
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
|
||||
@@ -145,6 +169,7 @@ export async function listContent({
|
||||
limit = 50,
|
||||
locale,
|
||||
payload,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
}: Omit<SearchContentArgs, 'query'>): Promise<SearchResult[]> {
|
||||
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
|
||||
@@ -164,5 +189,6 @@ export async function listContent({
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
|
||||
const unlisted = await readUnlisted(payload, settingsSlug)
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField, unlisted })
|
||||
}
|
||||
|
||||
@@ -246,6 +246,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
}), locale)
|
||||
if (results.length === 0) {return `No pages matched "${query}".`}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { createSearchRoute } from '../src/modules/content/createSearchRoute.js'
|
||||
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
|
||||
|
||||
const config: I18nConfig = {
|
||||
@@ -86,6 +87,21 @@ describe('createMcpRoute', () => {
|
||||
expect((await call('search_content', { query: 'nas' })).content[0].text).toContain('O nas')
|
||||
})
|
||||
|
||||
test('search_content and the search route leave out the page assigned as the 404 page', async () => {
|
||||
const withNotFound = [...pages, { id: 5, slug: 'nie-znaleziono', _status: 'published', title: 'Nie znaleziono nas' }]
|
||||
;(payload.find as ReturnType<typeof vi.fn>).mockResolvedValue({ docs: withNotFound })
|
||||
;(payload.findGlobal as ReturnType<typeof vi.fn>).mockResolvedValue({ homepage: 4, notFound: 5, siteName: 'Acme' })
|
||||
const text = (await call('search_content', { query: 'nas' })).content[0].text
|
||||
expect(text).toContain('O nas')
|
||||
expect(text).not.toContain('nie-znaleziono')
|
||||
// The site search route uses the same searchContent.
|
||||
const search = createSearchRoute({ config, getCachedPayload: async () => payload, rateLimit: false })
|
||||
const body = (await (await search(new Request('https://acme.pl/api/search?q=nas'))).json()) as { results: { slug: string }[] }
|
||||
// (the fake find ignores the query, so every published page comes back — except the 404 page)
|
||||
expect(body.results.map((r) => r.slug)).toEqual(['o-nas', 'strona-glowna'])
|
||||
;(payload.find as ReturnType<typeof vi.fn>).mockResolvedValue({ docs: pages })
|
||||
})
|
||||
|
||||
test('tool errors stay generic (no internals leak)', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
;(payload.find as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ECONNREFUSED db:5432'))
|
||||
|
||||
Reference in New Issue
Block a user