The main entry and next/middleware re-exported module barrels that also export React client components (LanguageSwitcher, AlternateLinks*, AccessibilityWidget), so payload.config, the CLI and the proxy bundle evaluated React UI. They now import concrete files; i18n client components moved to modules/i18n/client.ts. test/entryGraph guards it. Also lint fixes in tests added on this branch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
107 lines
4.4 KiB
TypeScript
107 lines
4.4 KiB
TypeScript
import type { BasePayload } from 'payload'
|
|
|
|
import type { I18nConfig } from '../i18n/index.js'
|
|
import type { ClientIpOptions } from '../shared/rateLimit.js'
|
|
|
|
import { pathOf, type PathVisibility } from '../construction/visibility.js'
|
|
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
|
import { searchContent } from './searchContent.js'
|
|
|
|
type CreateSearchRouteArgs = {
|
|
/** Absolute origin to prefix result URLs with. */
|
|
baseUrl?: string
|
|
/** How to read the client IP for the rate limit — see clientIp(). */
|
|
clientIp?: ClientIpOptions
|
|
/** Pages collection. Default 'pages'. */
|
|
collection?: string
|
|
config: I18nConfig
|
|
/** Default result cap when ?limit is absent. Default 10. */
|
|
defaultLimit?: number
|
|
getCachedPayload: () => Promise<BasePayload>
|
|
/** Home slug map/string so the home result collapses to root. */
|
|
homeSlug?: Record<string, string> | string
|
|
/** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */
|
|
isPathVisible?: PathVisibility
|
|
/**
|
|
* Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }.
|
|
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
|
*/
|
|
rateLimit?: { max?: number; windowMs?: number } | false
|
|
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
|
summaryField?: string
|
|
}
|
|
|
|
/**
|
|
* A JSON content-search endpoint. Powers both the site's own search UI and
|
|
* external agents — one ranking, one source of truth (shares searchContent with
|
|
* the MCP server's search_content tool).
|
|
*
|
|
* // app/api/search/route.ts
|
|
* import { createSearchRoute } from '@intecion/ipal-kit'
|
|
* import { getCachedPayload } from '@/lib/content'
|
|
* import { i18nConfig } from '@/i18n.config'
|
|
* export const dynamic = 'force-dynamic'
|
|
* export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,
|
|
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
|
*
|
|
* Query params: `q` (required), `locale`, `limit`. Response:
|
|
* { query, locale, count, results: [{ title, url, description?, slug }] }
|
|
*
|
|
* 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
|
|
// 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 }
|
|
|
|
return async (req: Request) => {
|
|
if (rl) {
|
|
const limit = await consumeRateLimit({ key: clientIp(req, args.clientIp), scope: 'search', ...rl })
|
|
if (!limit.ok) {
|
|
return tooManyRequests(limit.retryAfter, { count: 0, error: 'Too many requests', query: '', results: [] })
|
|
}
|
|
}
|
|
const url = new URL(req.url)
|
|
const query = url.searchParams.get('q')?.trim() ?? ''
|
|
const locale = url.searchParams.get('locale') ?? undefined
|
|
const limitParam = url.searchParams.get('limit')
|
|
const limit = limitParam ? Number(limitParam) : defaultLimit
|
|
|
|
if (!query) {
|
|
return Response.json(
|
|
{ count: 0, error: 'Missing ?q', query: '', results: [] },
|
|
{ headers: { 'cache-control': 'no-store' }, status: 400 },
|
|
)
|
|
}
|
|
|
|
try {
|
|
const payload = await getCachedPayload()
|
|
const found = await searchContent({
|
|
baseUrl,
|
|
collection,
|
|
config,
|
|
homeSlug,
|
|
limit,
|
|
locale,
|
|
payload,
|
|
query,
|
|
summaryField,
|
|
})
|
|
const shownLocale = locale ?? config.defaultLocale
|
|
const keep = isPathVisible ? await Promise.all(found.map((r) => isPathVisible(pathOf(r.url), shownLocale))) : null
|
|
const results = keep ? found.filter((_, i) => keep[i]) : found
|
|
return Response.json(
|
|
{ count: results.length, locale: locale ?? config.defaultLocale, query, results },
|
|
{ headers: { 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' } },
|
|
)
|
|
} catch (err) {
|
|
// DB unreachable (build) or unexpected — empty result rather than 500.
|
|
console.warn('[ipal] createSearchRoute: search failed:', err)
|
|
return Response.json(
|
|
{ count: 0, query, results: [] },
|
|
{ headers: { 'cache-control': 'no-store' }, status: 200 },
|
|
)
|
|
}
|
|
}
|
|
}
|