feat: v1.7.0 — AI-readability suite, form engine & boilerplate helpers
AI / GEO: - feat(content): lexicalToMarkdown, blocksToMarkdown, createMarkdownRenderer (+markdownResponse) — per-page Markdown for AI agents - feat(content): markdown content negotiation + discovery (prefersMarkdown, markdownHref) - feat(seo): buildRobots aiBots policy (allow/block-training/disallow) - feat(seo): llms-full.txt mode in buildLlmsTxt/createLlmsTxtRoute - feat(mcp): createMcpRoute — read-only MCP server (search_content, get_page) - feat(content): searchContent + createSearchRoute — shared JSON search - feat(seo): buildSpeakableJsonLd + buildSummaryField (aiSummary, auto-fill) Forms: - feat(forms): useForm/useContactForm + validators (logic-only, no markup) - feat(forms): honeypot anti-spam (honeypotInputProps, isHoneypotTripped) Helpers / hardening: - feat(i18n): resolveLocalized — replaces ad-hoc getSafeString - feat(hooks): buildCrossLocaleFieldSync — locales from config, no hardcoded list - feat(seo): buildNoindexField — checkbox → meta.noindex, no - feat(content): resolveRedirect — 301/308 from slugHistory - feat(env): assertEnv + ipalEnvRules — fail-fast env validation - feat(consent): ConsentScript — load third-party only after consent - feat(health): createHealthRoute — Coolify/Docker DB liveness Fixes: - fix(seo): wrap getCachedPayload in try/catch in createManifestHandler (Docker/CI build no longer crashes when DB unreachable) docs: migration.md (20 sections), new env.md/mcp.md, updated agents.md, AGENTS-TEMPLATE.md, forms/hooks/content/seo/consent/deployment/richtext
This commit is contained in:
+26
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Converts a page's `blocks` layout to Markdown by CONVENTION — the same field
|
||||
* names the project already standardises on (heading, subheading, body,
|
||||
* content, image, items/faq/…; see the naming rules in agents.md). The plugin
|
||||
* can't know each project's block shapes, but it CAN rely on those conventions,
|
||||
* so most blocks convert with zero per-project wiring. Special blocks get an
|
||||
* `overrides` entry keyed by blockType.
|
||||
*
|
||||
* Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not
|
||||
* on-page rendering — it extracts readable text, not pixel-perfect layout.
|
||||
*
|
||||
* blocksToMarkdown(page.layout)
|
||||
* blocksToMarkdown(page.layout, {
|
||||
* overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` },
|
||||
* })
|
||||
*/
|
||||
type Block = Record<string, unknown> & {
|
||||
blockType?: string;
|
||||
};
|
||||
type BlockToMarkdown = (block: Block) => string;
|
||||
type BlocksToMarkdownArgs = {
|
||||
/** Per-blockType custom renderers. Return '' to omit a block. */
|
||||
overrides?: Record<string, BlockToMarkdown>;
|
||||
};
|
||||
export declare function blocksToMarkdown(layout: unknown, args?: BlocksToMarkdownArgs): string;
|
||||
export {};
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
// Import the leaf, not the richtext barrel — the barrel re-exports
|
||||
// RenderRichText (a React component), which would pull React into this pure,
|
||||
// server-usable module.
|
||||
import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js';
|
||||
const HEADING_KEYS = new Set([
|
||||
'heading',
|
||||
'title'
|
||||
]);
|
||||
const SUBHEADING_KEYS = new Set([
|
||||
'subheading',
|
||||
'subtitle'
|
||||
]);
|
||||
const QUESTION_KEYS = new Set([
|
||||
'question'
|
||||
]);
|
||||
const TEXT_KEYS = new Set([
|
||||
'body',
|
||||
'text',
|
||||
'description',
|
||||
'excerpt',
|
||||
'summary',
|
||||
'answer',
|
||||
'caption',
|
||||
'label',
|
||||
'content'
|
||||
]);
|
||||
const ARRAY_KEYS = new Set([
|
||||
'items',
|
||||
'features',
|
||||
'faq',
|
||||
'faqs',
|
||||
'cards',
|
||||
'columns',
|
||||
'rows',
|
||||
'questions',
|
||||
'services',
|
||||
'steps',
|
||||
'points',
|
||||
'benefits',
|
||||
'list'
|
||||
]);
|
||||
/** A populated richText value is an object with a `root`. */ function isRichText(v) {
|
||||
return !!v && typeof v === 'object' && 'root' in v;
|
||||
}
|
||||
/** A populated upload (image) is an object with a `url`. */ function imageMarkdown(v) {
|
||||
if (!v || typeof v !== 'object') return '';
|
||||
const o = v;
|
||||
const url = typeof o.url === 'string' ? o.url : '';
|
||||
const alt = typeof o.alt === 'string' ? o.alt : '';
|
||||
return url ? `` : '';
|
||||
}
|
||||
/** Extract readable Markdown from one block's known content fields. */ function extractBlock(block, depth) {
|
||||
const lines = [];
|
||||
for (const [key, value] of Object.entries(block)){
|
||||
if (value == null) continue;
|
||||
if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`## ${value.trim()}`);
|
||||
} else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`### ${value.trim()}`);
|
||||
} else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`**${value.trim()}**`);
|
||||
} else if (key === 'image') {
|
||||
const img = imageMarkdown(value);
|
||||
if (img) lines.push(img);
|
||||
} else if (isRichText(value)) {
|
||||
const md = lexicalToMarkdown(value);
|
||||
if (md) lines.push(md);
|
||||
} else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(value.trim());
|
||||
} else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {
|
||||
for (const item of value){
|
||||
if (item && typeof item === 'object') {
|
||||
const sub = extractBlock(item, depth + 1);
|
||||
if (sub.trim()) lines.push(sub);
|
||||
} else if (typeof item === 'string' && item.trim()) {
|
||||
lines.push(`- ${item.trim()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join('\n\n');
|
||||
}
|
||||
export function blocksToMarkdown(layout, args = {}) {
|
||||
if (!Array.isArray(layout)) return '';
|
||||
const { overrides = {} } = args;
|
||||
const out = [];
|
||||
for (const block of layout){
|
||||
if (!block || typeof block !== 'object') continue;
|
||||
const b = block;
|
||||
const type = typeof b.blockType === 'string' ? b.blockType : '';
|
||||
if (type && overrides[type]) {
|
||||
const md = overrides[type](b);
|
||||
if (md.trim()) out.push(md.trim());
|
||||
continue;
|
||||
}
|
||||
const md = extractBlock(b, 0);
|
||||
if (md.trim()) out.push(md.trim());
|
||||
}
|
||||
return out.join('\n\n').trim();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=blocksToMarkdown.js.map
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,52 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { ContentOption } from './types.js';
|
||||
type CreateMarkdownRendererArgs = {
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string;
|
||||
/** Archive-backed collections, same value as the plugin option (optional). */
|
||||
content?: ContentOption;
|
||||
/** Prepend a YAML frontmatter block (title/description/locale). Default true. */
|
||||
frontmatter?: boolean;
|
||||
/** Field holding the block layout. Default 'layout'. */
|
||||
layoutField?: string;
|
||||
/** Per-blockType overrides passed to blocksToMarkdown. */
|
||||
overrides?: Record<string, (block: Record<string, unknown>) => string>;
|
||||
/** SiteSettings global slug. Default 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
type MarkdownContext = {
|
||||
locale: string;
|
||||
payload: BasePayload;
|
||||
/** Route slug segments; empty/undefined = locale root (home). */
|
||||
slug?: string[];
|
||||
};
|
||||
/**
|
||||
* Returns a function that renders a page (or archive/entry) to clean Markdown —
|
||||
* title, meta description, then the block layout via blocksToMarkdown. The
|
||||
* point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets
|
||||
* structured Markdown instead of parsing HTML, so it reads the page reliably.
|
||||
*
|
||||
* Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a
|
||||
* function the project invokes from its route handler.
|
||||
*
|
||||
* // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown)
|
||||
* import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
|
||||
* import { getPayload } from 'payload'
|
||||
* import config from '@payload-config'
|
||||
* const render = createMarkdownRenderer({ content })
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
|
||||
* const { locale, slug } = await params
|
||||
* const md = await render({ payload: await getPayload({ config }), locale, slug })
|
||||
* return markdownResponse(md)
|
||||
* }
|
||||
*
|
||||
* Returns null when the route doesn't resolve (so the handler can 404).
|
||||
*/
|
||||
export declare function createMarkdownRenderer(args?: CreateMarkdownRendererArgs): ({ slug, locale, payload }: MarkdownContext) => Promise<null | string>;
|
||||
/**
|
||||
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
|
||||
* Uses the global Response — no next/server import.
|
||||
*/
|
||||
export declare function markdownResponse(md: null | string): Response;
|
||||
export {};
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { blocksToMarkdown } from './blocksToMarkdown.js';
|
||||
import { resolveRoute } from './resolveRoute.js';
|
||||
function yamlEscape(v) {
|
||||
return `"${v.replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
/**
|
||||
* Returns a function that renders a page (or archive/entry) to clean Markdown —
|
||||
* title, meta description, then the block layout via blocksToMarkdown. The
|
||||
* point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets
|
||||
* structured Markdown instead of parsing HTML, so it reads the page reliably.
|
||||
*
|
||||
* Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a
|
||||
* function the project invokes from its route handler.
|
||||
*
|
||||
* // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown)
|
||||
* import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
|
||||
* import { getPayload } from 'payload'
|
||||
* import config from '@payload-config'
|
||||
* const render = createMarkdownRenderer({ content })
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
|
||||
* const { locale, slug } = await params
|
||||
* const md = await render({ payload: await getPayload({ config }), locale, slug })
|
||||
* return markdownResponse(md)
|
||||
* }
|
||||
*
|
||||
* Returns null when the route doesn't resolve (so the handler can 404).
|
||||
*/ export function createMarkdownRenderer(args = {}) {
|
||||
const { collection = 'pages', content, frontmatter = true, layoutField = 'layout', overrides, settingsSlug = 'site-settings' } = args;
|
||||
return async function render({ slug, locale, payload }) {
|
||||
const route = await resolveRoute({
|
||||
content,
|
||||
locale,
|
||||
pagesSlug: collection,
|
||||
payload,
|
||||
segments: slug,
|
||||
settingsSlug
|
||||
});
|
||||
if (!route) {
|
||||
return null;
|
||||
}
|
||||
const doc = route.doc;
|
||||
const title = typeof doc.title === 'string' ? doc.title : '';
|
||||
const description = typeof doc.meta?.description === 'string' ? doc.meta.description : '';
|
||||
const body = blocksToMarkdown(doc[layoutField], {
|
||||
overrides
|
||||
});
|
||||
const parts = [];
|
||||
if (frontmatter) {
|
||||
const fm = [
|
||||
'---',
|
||||
`locale: ${locale}`
|
||||
];
|
||||
if (title) {
|
||||
fm.push(`title: ${yamlEscape(title)}`);
|
||||
}
|
||||
if (description) {
|
||||
fm.push(`description: ${yamlEscape(description)}`);
|
||||
}
|
||||
fm.push('---');
|
||||
parts.push(fm.join('\n'));
|
||||
}
|
||||
if (title) {
|
||||
parts.push(`# ${title}`);
|
||||
}
|
||||
if (description) {
|
||||
parts.push(`_${description}_`);
|
||||
}
|
||||
if (body) {
|
||||
parts.push(body);
|
||||
}
|
||||
const md = parts.join('\n\n').trim();
|
||||
return md || null;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
|
||||
* Uses the global Response — no next/server import.
|
||||
*/ export function markdownResponse(md) {
|
||||
if (md == null) {
|
||||
return new Response('Not found', {
|
||||
headers: {
|
||||
'content-type': 'text/plain'
|
||||
},
|
||||
status: 404
|
||||
});
|
||||
}
|
||||
return new Response(md, {
|
||||
headers: {
|
||||
'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',
|
||||
'content-type': 'text/markdown; charset=utf-8'
|
||||
},
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=createMarkdownRenderer.js.map
|
||||
File diff suppressed because one or more lines are too long
+36
@@ -0,0 +1,36 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
type CreateSearchRouteArgs = {
|
||||
/** Absolute origin to prefix result URLs with. */
|
||||
baseUrl?: string;
|
||||
/** 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;
|
||||
/** 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 declare function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response>;
|
||||
export {};
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { searchContent } from './searchContent.js';
|
||||
/**
|
||||
* 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) {
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args;
|
||||
return async (req)=>{
|
||||
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 results = await searchContent({
|
||||
baseUrl,
|
||||
collection,
|
||||
config,
|
||||
homeSlug,
|
||||
limit,
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
summaryField
|
||||
});
|
||||
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
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=createSearchRoute.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/createSearchRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { searchContent } from './searchContent.js'\n\ntype CreateSearchRouteArgs = {\n /** Absolute origin to prefix result URLs with. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Default result cap when ?limit is absent. Default 10. */\n defaultLimit?: number\n getCachedPayload: () => Promise<BasePayload>\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record<string, string> | string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}\n\n/**\n * A JSON content-search endpoint. Powers both the site's own search UI and\n * external agents — one ranking, one source of truth (shares searchContent with\n * the MCP server's search_content tool).\n *\n * // app/api/search/route.ts\n * import { createSearchRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * Query params: `q` (required), `locale`, `limit`. Response:\n * { query, locale, count, results: [{ title, url, description?, slug }] }\n *\n * Uses the global Request/Response — no next/server import.\n */\nexport function createSearchRoute(\n args: CreateSearchRouteArgs,\n): (req: Request) => Promise<Response> {\n const {\n baseUrl,\n collection = 'pages',\n config,\n defaultLimit = 10,\n getCachedPayload,\n homeSlug,\n summaryField,\n } = args\n\n return async (req: Request) => {\n const url = new URL(req.url)\n const query = url.searchParams.get('q')?.trim() ?? ''\n const locale = url.searchParams.get('locale') ?? undefined\n const limitParam = url.searchParams.get('limit')\n const limit = limitParam ? Number(limitParam) : defaultLimit\n\n if (!query) {\n return Response.json(\n { count: 0, error: 'Missing ?q', query: '', results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 400 },\n )\n }\n\n try {\n const payload = await getCachedPayload()\n const results = await searchContent({\n baseUrl,\n collection,\n config,\n homeSlug,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n return Response.json(\n { count: results.length, locale: locale ?? config.defaultLocale, query, results },\n {\n headers: {\n 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',\n },\n },\n )\n } catch (err) {\n // DB unreachable (build) or unexpected — empty result rather than 500.\n console.warn('[ipal] createSearchRoute: search failed:', err)\n return Response.json(\n { count: 0, query, results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 200 },\n )\n }\n }\n}\n"],"names":["searchContent","createSearchRoute","args","baseUrl","collection","config","defaultLimit","getCachedPayload","homeSlug","summaryField","req","url","URL","query","searchParams","get","trim","locale","undefined","limitParam","limit","Number","Response","json","count","error","results","headers","status","payload","length","defaultLocale","err","console","warn"],"mappings":"AAIA,SAASA,aAAa,QAAQ,qBAAoB;AAiBlD;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,kBACdC,IAA2B;IAE3B,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,eAAe,EAAE,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACb,GAAGP;IAEJ,OAAO,OAAOQ;QACZ,MAAMC,MAAM,IAAIC,IAAIF,IAAIC,GAAG;QAC3B,MAAME,QAAQF,IAAIG,YAAY,CAACC,GAAG,CAAC,MAAMC,UAAU;QACnD,MAAMC,SAASN,IAAIG,YAAY,CAACC,GAAG,CAAC,aAAaG;QACjD,MAAMC,aAAaR,IAAIG,YAAY,CAACC,GAAG,CAAC;QACxC,MAAMK,QAAQD,aAAaE,OAAOF,cAAcb;QAEhD,IAAI,CAACO,OAAO;YACV,OAAOS,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGC,OAAO;gBAAcZ,OAAO;gBAAIa,SAAS,EAAE;YAAC,GACxD;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;QAEA,IAAI;YACF,MAAMC,UAAU,MAAMtB;YACtB,MAAMmB,UAAU,MAAM1B,cAAc;gBAClCG;gBACAC;gBACAC;gBACAG;gBACAY;gBACAH;gBACAY;gBACAhB;gBACAJ;YACF;YACA,OAAOa,SAASC,IAAI,CAClB;gBAAEC,OAAOE,QAAQI,MAAM;gBAAEb,QAAQA,UAAUZ,OAAO0B,aAAa;gBAAElB;gBAAOa;YAAQ,GAChF;gBACEC,SAAS;oBACP,iBAAiB;gBACnB;YACF;QAEJ,EAAE,OAAOK,KAAK;YACZ,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,4CAA4CF;YACzD,OAAOV,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGX;gBAAOa,SAAS,EAAE;YAAC,GAC/B;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;IACF;AACF"}
|
||||
Vendored
+6
@@ -1,9 +1,15 @@
|
||||
export { buildArchiveFields } from './archiveFields.js';
|
||||
export { blocksToMarkdown } from './blocksToMarkdown.js';
|
||||
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js';
|
||||
export { createSearchRoute } from './createSearchRoute.js';
|
||||
export { getArchiveEntries } from './getArchiveEntries.js';
|
||||
export type { ArchiveEntries } from './getArchiveEntries.js';
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
|
||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
||||
export { resolveRedirect } from './resolveRedirect.js';
|
||||
export { resolveRoute } from './resolveRoute.js';
|
||||
export type { ResolvedRoute } from './resolveRoute.js';
|
||||
export { searchContent } from './searchContent.js';
|
||||
export type { SearchResult } from './searchContent.js';
|
||||
export type { ContentCollectionOption, ContentOption } from './types.js';
|
||||
export { archiveFieldName } from './types.js';
|
||||
|
||||
Vendored
+5
@@ -1,8 +1,13 @@
|
||||
export { buildArchiveFields } from './archiveFields.js';
|
||||
export { blocksToMarkdown } from './blocksToMarkdown.js';
|
||||
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js';
|
||||
export { createSearchRoute } from './createSearchRoute.js';
|
||||
export { getArchiveEntries } from './getArchiveEntries.js';
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
|
||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
||||
export { resolveRedirect } from './resolveRedirect.js';
|
||||
export { resolveRoute } from './resolveRoute.js';
|
||||
export { searchContent } from './searchContent.js';
|
||||
export { archiveFieldName } from './types.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAGhD,SAASC,gBAAgB,QAAQ,aAAY"}
|
||||
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable
|
||||
* and negotiable, so AI agents reliably find and read it.
|
||||
*
|
||||
* Two mechanisms:
|
||||
* - `markdownHref` — the `<link rel="alternate" type="text/markdown">` href a
|
||||
* page advertises, so an agent fetching the HTML sees there's a Markdown
|
||||
* version and can switch to it.
|
||||
* - `prefersMarkdown` — reads the Accept header, so the same URL can serve
|
||||
* Markdown when asked (content negotiation via a proxy rewrite).
|
||||
*/
|
||||
/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */
|
||||
export declare const MARKDOWN_PREFIX = "/md";
|
||||
/**
|
||||
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
|
||||
* the discovery link and the route agree.
|
||||
*
|
||||
* markdownHref('/pl/o-nas') // '/md/pl/o-nas'
|
||||
* markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'
|
||||
*
|
||||
* Advertise it from Next metadata so every page's <head> points to its Markdown:
|
||||
*
|
||||
* // generateMetadata
|
||||
* return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
|
||||
*/
|
||||
export declare function markdownHref(pathname: string, prefix?: string): string;
|
||||
/**
|
||||
* True when the client asked for Markdown via the Accept header (q-values
|
||||
* respected: a higher-weighted text/html wins). Accepts a header string, a
|
||||
* Headers object, or a Request. Use it in proxy.ts to serve the same URL as
|
||||
* Markdown when an agent negotiates for it:
|
||||
*
|
||||
* // proxy.ts
|
||||
* if (prefersMarkdown(request)) {
|
||||
* return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))
|
||||
* }
|
||||
*/
|
||||
export declare function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean;
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable
|
||||
* and negotiable, so AI agents reliably find and read it.
|
||||
*
|
||||
* Two mechanisms:
|
||||
* - `markdownHref` — the `<link rel="alternate" type="text/markdown">` href a
|
||||
* page advertises, so an agent fetching the HTML sees there's a Markdown
|
||||
* version and can switch to it.
|
||||
* - `prefersMarkdown` — reads the Accept header, so the same URL can serve
|
||||
* Markdown when asked (content negotiation via a proxy rewrite).
|
||||
*/ /** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ export const MARKDOWN_PREFIX = '/md';
|
||||
/**
|
||||
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
|
||||
* the discovery link and the route agree.
|
||||
*
|
||||
* markdownHref('/pl/o-nas') // '/md/pl/o-nas'
|
||||
* markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'
|
||||
*
|
||||
* Advertise it from Next metadata so every page's <head> points to its Markdown:
|
||||
*
|
||||
* // generateMetadata
|
||||
* return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
|
||||
*/ export function markdownHref(pathname, prefix = MARKDOWN_PREFIX) {
|
||||
const clean = pathname.startsWith('/') ? pathname : `/${pathname}`;
|
||||
const p = prefix.replace(/\/$/, '');
|
||||
return `${p}${clean === '/' ? '' : clean}` || p;
|
||||
}
|
||||
/**
|
||||
* True when the client asked for Markdown via the Accept header (q-values
|
||||
* respected: a higher-weighted text/html wins). Accepts a header string, a
|
||||
* Headers object, or a Request. Use it in proxy.ts to serve the same URL as
|
||||
* Markdown when an agent negotiates for it:
|
||||
*
|
||||
* // proxy.ts
|
||||
* if (prefersMarkdown(request)) {
|
||||
* return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))
|
||||
* }
|
||||
*/ export function prefersMarkdown(input) {
|
||||
let accept = null;
|
||||
if (!input) {
|
||||
return false;
|
||||
}
|
||||
if (typeof input === 'string') {
|
||||
accept = input;
|
||||
} else if (input instanceof Headers) {
|
||||
accept = input.get('accept');
|
||||
} else if ('headers' in input && input.headers) {
|
||||
accept = input.headers.get('accept');
|
||||
}
|
||||
if (!accept) {
|
||||
return false;
|
||||
}
|
||||
// Parse "type/subtype;q=0.8" entries into {type, q}.
|
||||
const entries = accept.split(',').map((part)=>{
|
||||
const [type, ...params] = part.trim().split(';');
|
||||
const qParam = params.find((p)=>p.trim().startsWith('q='));
|
||||
const q = qParam ? Number(qParam.split('=')[1]) : 1;
|
||||
return {
|
||||
type: type.trim().toLowerCase(),
|
||||
q: Number.isFinite(q) ? q : 1
|
||||
};
|
||||
});
|
||||
const md = entries.find((e)=>e.type === 'text/markdown');
|
||||
if (!md) {
|
||||
return false;
|
||||
}
|
||||
// Markdown must be at least as preferred as html (and html not strictly higher).
|
||||
const html = entries.find((e)=>e.type === 'text/html');
|
||||
return !html || md.q >= html.q;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=markdownNegotiation.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/markdownNegotiation.ts"],"sourcesContent":["/**\n * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable\n * and negotiable, so AI agents reliably find and read it.\n *\n * Two mechanisms:\n * - `markdownHref` — the `<link rel=\"alternate\" type=\"text/markdown\">` href a\n * page advertises, so an agent fetching the HTML sees there's a Markdown\n * version and can switch to it.\n * - `prefersMarkdown` — reads the Accept header, so the same URL can serve\n * Markdown when asked (content negotiation via a proxy rewrite).\n */\n\n/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */\nexport const MARKDOWN_PREFIX = '/md'\n\n/**\n * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so\n * the discovery link and the route agree.\n *\n * markdownHref('/pl/o-nas') // '/md/pl/o-nas'\n * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'\n *\n * Advertise it from Next metadata so every page's <head> points to its Markdown:\n *\n * // generateMetadata\n * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }\n */\nexport function markdownHref(pathname: string, prefix: string = MARKDOWN_PREFIX): string {\n const clean = pathname.startsWith('/') ? pathname : `/${pathname}`\n const p = prefix.replace(/\\/$/, '')\n return `${p}${clean === '/' ? '' : clean}` || p\n}\n\n/**\n * True when the client asked for Markdown via the Accept header (q-values\n * respected: a higher-weighted text/html wins). Accepts a header string, a\n * Headers object, or a Request. Use it in proxy.ts to serve the same URL as\n * Markdown when an agent negotiates for it:\n *\n * // proxy.ts\n * if (prefersMarkdown(request)) {\n * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))\n * }\n */\nexport function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean {\n let accept: null | string = null\n if (!input) {return false}\n if (typeof input === 'string') {accept = input}\n else if (input instanceof Headers) {accept = input.get('accept')}\n else if ('headers' in input && input.headers) {accept = input.headers.get('accept')}\n if (!accept) {return false}\n\n // Parse \"type/subtype;q=0.8\" entries into {type, q}.\n const entries = accept.split(',').map((part) => {\n const [type, ...params] = part.trim().split(';')\n const qParam = params.find((p) => p.trim().startsWith('q='))\n const q = qParam ? Number(qParam.split('=')[1]) : 1\n return { type: type.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1 }\n })\n\n const md = entries.find((e) => e.type === 'text/markdown')\n if (!md) {return false}\n // Markdown must be at least as preferred as html (and html not strictly higher).\n const html = entries.find((e) => e.type === 'text/html')\n return !html || md.q >= html.q\n}\n"],"names":["MARKDOWN_PREFIX","markdownHref","pathname","prefix","clean","startsWith","p","replace","prefersMarkdown","input","accept","Headers","get","headers","entries","split","map","part","type","params","trim","qParam","find","q","Number","toLowerCase","isFinite","md","e","html"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,sFAAsF,GACtF,OAAO,MAAMA,kBAAkB,MAAK;AAEpC;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,aAAaC,QAAgB,EAAEC,SAAiBH,eAAe;IAC7E,MAAMI,QAAQF,SAASG,UAAU,CAAC,OAAOH,WAAW,CAAC,CAAC,EAAEA,UAAU;IAClE,MAAMI,IAAIH,OAAOI,OAAO,CAAC,OAAO;IAChC,OAAO,GAAGD,IAAIF,UAAU,MAAM,KAAKA,OAAO,IAAIE;AAChD;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASE,gBAAgBC,KAAoD;IAClF,IAAIC,SAAwB;IAC5B,IAAI,CAACD,OAAO;QAAC,OAAO;IAAK;IACzB,IAAI,OAAOA,UAAU,UAAU;QAACC,SAASD;IAAK,OACzC,IAAIA,iBAAiBE,SAAS;QAACD,SAASD,MAAMG,GAAG,CAAC;IAAS,OAC3D,IAAI,aAAaH,SAASA,MAAMI,OAAO,EAAE;QAACH,SAASD,MAAMI,OAAO,CAACD,GAAG,CAAC;IAAS;IACnF,IAAI,CAACF,QAAQ;QAAC,OAAO;IAAK;IAE1B,qDAAqD;IACrD,MAAMI,UAAUJ,OAAOK,KAAK,CAAC,KAAKC,GAAG,CAAC,CAACC;QACrC,MAAM,CAACC,MAAM,GAAGC,OAAO,GAAGF,KAAKG,IAAI,GAAGL,KAAK,CAAC;QAC5C,MAAMM,SAASF,OAAOG,IAAI,CAAC,CAAChB,IAAMA,EAAEc,IAAI,GAAGf,UAAU,CAAC;QACtD,MAAMkB,IAAIF,SAASG,OAAOH,OAAON,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI;QAClD,OAAO;YAAEG,MAAMA,KAAKE,IAAI,GAAGK,WAAW;YAAIF,GAAGC,OAAOE,QAAQ,CAACH,KAAKA,IAAI;QAAE;IAC1E;IAEA,MAAMI,KAAKb,QAAQQ,IAAI,CAAC,CAACM,IAAMA,EAAEV,IAAI,KAAK;IAC1C,IAAI,CAACS,IAAI;QAAC,OAAO;IAAK;IACtB,iFAAiF;IACjF,MAAME,OAAOf,QAAQQ,IAAI,CAAC,CAACM,IAAMA,EAAEV,IAAI,KAAK;IAC5C,OAAO,CAACW,QAAQF,GAAGJ,CAAC,IAAIM,KAAKN,CAAC;AAChC"}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
export type SearchResult = {
|
||||
description?: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
/** Locale-aware path, prefixed with baseUrl when given. */
|
||||
url: string;
|
||||
};
|
||||
type SearchContentArgs = {
|
||||
/** Absolute origin to prefix URLs with. Omit for relative paths. */
|
||||
baseUrl?: string;
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string;
|
||||
config: I18nConfig;
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string;
|
||||
/** Max results. Default 10, clamped 1–50. */
|
||||
limit?: number;
|
||||
/** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */
|
||||
locale?: string;
|
||||
payload: BasePayload;
|
||||
/** Keywords. */
|
||||
query: 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
|
||||
* description.
|
||||
*/
|
||||
summaryField?: string;
|
||||
};
|
||||
/**
|
||||
* Shared content search: title / meta-description keyword match over a
|
||||
* collection, returning structured results (published, non-noindex only). One
|
||||
* implementation behind BOTH the JSON search route (createSearchRoute) and the
|
||||
* MCP server's search_content tool — so site search, API and AI all rank the
|
||||
* same way.
|
||||
*
|
||||
* Degrades to [] (never throws) when the collection's fields aren't queryable —
|
||||
* same guard class as the drafts/_status lesson.
|
||||
*/
|
||||
export declare function searchContent({ baseUrl, collection, config, homeSlug, limit, locale, payload, query, summaryField, }: SearchContentArgs): Promise<SearchResult[]>;
|
||||
export {};
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js';
|
||||
/**
|
||||
* Shared content search: title / meta-description keyword match over a
|
||||
* collection, returning structured results (published, non-noindex only). One
|
||||
* implementation behind BOTH the JSON search route (createSearchRoute) and the
|
||||
* MCP server's search_content tool — so site search, API and AI all rank the
|
||||
* same way.
|
||||
*
|
||||
* Degrades to [] (never throws) when the collection's fields aren't queryable —
|
||||
* same guard class as the drafts/_status lesson.
|
||||
*/ export async function searchContent({ baseUrl, collection = 'pages', config, homeSlug, limit = 10, locale, payload, query, summaryField }) {
|
||||
const q = query.trim();
|
||||
if (!q) {
|
||||
return [];
|
||||
}
|
||||
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config);
|
||||
const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50);
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? '';
|
||||
let docs = [];
|
||||
try {
|
||||
const res = await payload.find({
|
||||
collection: collection,
|
||||
depth: 0,
|
||||
limit: max * 3,
|
||||
locale: loc,
|
||||
where: {
|
||||
or: [
|
||||
{
|
||||
title: {
|
||||
like: q
|
||||
}
|
||||
},
|
||||
{
|
||||
'meta.description': {
|
||||
like: q
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
docs = res?.docs ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const results = [];
|
||||
for (const doc of docs){
|
||||
if (doc._status && doc._status !== 'published') {
|
||||
continue;
|
||||
}
|
||||
if (doc.meta?.noindex) {
|
||||
continue;
|
||||
}
|
||||
const title = typeof doc.title === 'string' ? doc.title : undefined;
|
||||
const slug = typeof doc.slug === 'string' ? doc.slug : undefined;
|
||||
if (!title || !slug) {
|
||||
continue;
|
||||
}
|
||||
const path = buildLocalizedPath({
|
||||
config,
|
||||
homeSlug,
|
||||
locale: loc,
|
||||
slugs: {
|
||||
[loc]: slug
|
||||
}
|
||||
});
|
||||
// Prefer the richer AI summary when configured and present, else meta.description.
|
||||
const summary = summaryField && typeof doc[summaryField] === 'string' ? doc[summaryField] : undefined;
|
||||
const description = summary?.trim() || (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined);
|
||||
results.push({
|
||||
slug,
|
||||
title,
|
||||
url: `${origin}${path ?? `/${slug}`}`,
|
||||
...description ? {
|
||||
description
|
||||
} : {}
|
||||
});
|
||||
if (results.length >= max) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=searchContent.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { ContentOption } from '../content/index.js';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
type CreateMcpRouteArgs = {
|
||||
/** Absolute origin for building result URLs. */
|
||||
baseUrl?: string;
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string;
|
||||
config: I18nConfig;
|
||||
/** Archive-backed collections (same as the plugin option) for get_page. */
|
||||
content?: ContentOption;
|
||||
getCachedPayload: () => Promise<BasePayload>;
|
||||
/** Server name advertised in `initialize`. Default 'ipal-site'. */
|
||||
serverName?: string;
|
||||
/** Server version advertised in `initialize`. Default '1.0.0'. */
|
||||
serverVersion?: string;
|
||||
/** SiteSettings slug. Default 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */
|
||||
summaryField?: string;
|
||||
};
|
||||
export declare function createMcpRoute(args: CreateMcpRouteArgs): {
|
||||
GET: () => Promise<Response>;
|
||||
POST: (req: Request) => Promise<Response>;
|
||||
};
|
||||
export {};
|
||||
Vendored
+257
@@ -0,0 +1,257 @@
|
||||
import { createMarkdownRenderer, searchContent } from '../content/index.js';
|
||||
import { getDefaultLocale, isValidLocale } from '../i18n/index.js';
|
||||
/**
|
||||
* A read-only MCP (Model Context Protocol) server for the client site, as a Next
|
||||
* route handler. Lets Claude / any MCP client CONNECT to the site and query it
|
||||
* directly — search content, fetch a page as Markdown — instead of scraping
|
||||
* HTML. This is the "better integration" layer on top of the Markdown/llms work.
|
||||
*
|
||||
* Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk
|
||||
* (that would be an imposed dependency, and its API moves). It implements the
|
||||
* minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP
|
||||
* transport: initialize, tools/list, tools/call, ping. Uses the global
|
||||
* Request/Response — no next/server import.
|
||||
*
|
||||
* Exposes two tools:
|
||||
* - search_content({ query, locale?, limit? }) → matching pages (title, url, description)
|
||||
* - get_page({ path }) → that page as Markdown
|
||||
*
|
||||
* // app/api/mcp/route.ts
|
||||
* import { createMcpRoute } from '@intecion/ipal-kit'
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' })
|
||||
* export const POST = mcp.POST
|
||||
* export const GET = mcp.GET
|
||||
*
|
||||
* Add it in Claude as a custom connector pointing at https://site/api/mcp.
|
||||
*/ const DEFAULT_PROTOCOL = '2025-06-18';
|
||||
function rpcResult(id, result) {
|
||||
return {
|
||||
id,
|
||||
jsonrpc: '2.0',
|
||||
result
|
||||
};
|
||||
}
|
||||
function rpcError(id, code, message) {
|
||||
return {
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message
|
||||
},
|
||||
jsonrpc: '2.0'
|
||||
};
|
||||
}
|
||||
function toolText(text, isError = false) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text
|
||||
}
|
||||
],
|
||||
...isError ? {
|
||||
isError: true
|
||||
} : {}
|
||||
};
|
||||
}
|
||||
export function createMcpRoute(args) {
|
||||
const { baseUrl, collection = 'pages', config, content, getCachedPayload, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args;
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? '';
|
||||
const renderMarkdown = createMarkdownRenderer({
|
||||
collection,
|
||||
content,
|
||||
settingsSlug
|
||||
});
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'search_content',
|
||||
description: 'Search the site content by keyword. Returns matching pages with title, URL and description.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: {
|
||||
type: 'number',
|
||||
description: 'Max results (default 10)'
|
||||
},
|
||||
locale: {
|
||||
type: 'string',
|
||||
description: `Locale code (default ${config.defaultLocale})`
|
||||
},
|
||||
query: {
|
||||
type: 'string',
|
||||
description: 'Search keywords'
|
||||
}
|
||||
},
|
||||
required: [
|
||||
'query'
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'get_page',
|
||||
description: 'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: {
|
||||
type: 'string',
|
||||
description: 'Page path, e.g. /pl/o-nas or /en/about'
|
||||
}
|
||||
},
|
||||
required: [
|
||||
'path'
|
||||
]
|
||||
}
|
||||
}
|
||||
];
|
||||
async function runSearch(params) {
|
||||
const query = typeof params.query === 'string' ? params.query.trim() : '';
|
||||
if (!query) {
|
||||
return 'No query provided.';
|
||||
}
|
||||
const locale = typeof params.locale === 'string' && isValidLocale(params.locale, config) ? params.locale : getDefaultLocale(config);
|
||||
const limit = typeof params.limit === 'number' ? params.limit : 10;
|
||||
const payload = await getCachedPayload();
|
||||
// Shared with the JSON search route — one ranking everywhere.
|
||||
const results = await searchContent({
|
||||
baseUrl: origin,
|
||||
collection,
|
||||
config,
|
||||
limit,
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
summaryField
|
||||
});
|
||||
if (results.length === 0) {
|
||||
return `No pages matched "${query}".`;
|
||||
}
|
||||
return results.map((r)=>`- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n');
|
||||
}
|
||||
async function getPage(params) {
|
||||
const raw = typeof params.path === 'string' ? params.path.trim() : '';
|
||||
if (!raw) {
|
||||
return 'No path provided.';
|
||||
}
|
||||
const segments = raw.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean);
|
||||
let locale = getDefaultLocale(config);
|
||||
let slug = segments;
|
||||
if (segments.length && isValidLocale(segments[0], config)) {
|
||||
locale = segments[0];
|
||||
slug = segments.slice(1);
|
||||
}
|
||||
const payload = await getCachedPayload();
|
||||
const md = await renderMarkdown({
|
||||
slug,
|
||||
locale,
|
||||
payload
|
||||
});
|
||||
return md ?? `No page found at ${raw}.`;
|
||||
}
|
||||
async function handleOne(msg) {
|
||||
const { id = null, method, params } = msg;
|
||||
// Notifications (no id) get no response body.
|
||||
if (id === null && typeof method === 'string' && method.startsWith('notifications/')) {
|
||||
return null;
|
||||
}
|
||||
switch(method){
|
||||
case 'initialize':
|
||||
{
|
||||
const requested = params?.protocolVersion;
|
||||
return rpcResult(id, {
|
||||
capabilities: {
|
||||
tools: {
|
||||
listChanged: false
|
||||
}
|
||||
},
|
||||
protocolVersion: requested || DEFAULT_PROTOCOL,
|
||||
serverInfo: {
|
||||
name: serverName,
|
||||
version: serverVersion
|
||||
}
|
||||
});
|
||||
}
|
||||
case 'ping':
|
||||
return rpcResult(id, {});
|
||||
case 'tools/call':
|
||||
{
|
||||
const p = params ?? {};
|
||||
const toolArgs = p.arguments ?? {};
|
||||
try {
|
||||
if (p.name === 'search_content') {
|
||||
return rpcResult(id, toolText(await runSearch(toolArgs)));
|
||||
}
|
||||
if (p.name === 'get_page') {
|
||||
return rpcResult(id, toolText(await getPage(toolArgs)));
|
||||
}
|
||||
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true));
|
||||
} catch (err) {
|
||||
return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true));
|
||||
}
|
||||
}
|
||||
case 'tools/list':
|
||||
return rpcResult(id, {
|
||||
tools: TOOLS
|
||||
});
|
||||
default:
|
||||
if (id === null) {
|
||||
return null;
|
||||
} // unknown notification
|
||||
return rpcError(id, -32601, `Method not found: ${method}`);
|
||||
}
|
||||
}
|
||||
async function POST(req) {
|
||||
let body;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return Response.json(rpcError(null, -32700, 'Parse error'), {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
// Batch or single.
|
||||
if (Array.isArray(body)) {
|
||||
const out = (await Promise.all(body.map((m)=>handleOne(m)))).filter((r)=>r !== null);
|
||||
if (out.length === 0) {
|
||||
return new Response(null, {
|
||||
status: 202
|
||||
});
|
||||
}
|
||||
return Response.json(out, {
|
||||
headers: {
|
||||
'cache-control': 'no-store'
|
||||
}
|
||||
});
|
||||
}
|
||||
const res = await handleOne(body);
|
||||
if (res === null) {
|
||||
return new Response(null, {
|
||||
status: 202
|
||||
});
|
||||
}
|
||||
return Response.json(res, {
|
||||
headers: {
|
||||
'cache-control': 'no-store'
|
||||
}
|
||||
});
|
||||
}
|
||||
// No server→client SSE stream in this read-only server.
|
||||
async function GET() {
|
||||
return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
|
||||
headers: {
|
||||
allow: 'POST'
|
||||
},
|
||||
status: 405
|
||||
});
|
||||
}
|
||||
return {
|
||||
GET,
|
||||
POST
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=createMcpRoute.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -0,0 +1 @@
|
||||
export { createMcpRoute } from './createMcpRoute.js';
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export { createMcpRoute } from './createMcpRoute.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/mcp/index.ts"],"sourcesContent":["export { createMcpRoute } from './createMcpRoute.js'\n"],"names":["createMcpRoute"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
|
||||
Vendored
+1
@@ -1,2 +1,3 @@
|
||||
export { lexicalToMarkdown } from './lexicalToMarkdown.js';
|
||||
export { RenderRichText } from './RenderRichText.js';
|
||||
export type { RenderRichTextProps } from './RenderRichText.js';
|
||||
|
||||
Vendored
+1
@@ -1,3 +1,4 @@
|
||||
export { lexicalToMarkdown } from './lexicalToMarkdown.js';
|
||||
export { RenderRichText } from './RenderRichText.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/richtext/index.ts"],"sourcesContent":["export { RenderRichText } from './RenderRichText.js'\nexport type { RenderRichTextProps } from './RenderRichText.js'\n"],"names":["RenderRichText"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
|
||||
{"version":3,"sources":["../../../src/modules/richtext/index.ts"],"sourcesContent":["export { lexicalToMarkdown } from './lexicalToMarkdown.js'\nexport { RenderRichText } from './RenderRichText.js'\nexport type { RenderRichTextProps } from './RenderRichText.js'\n"],"names":["lexicalToMarkdown","RenderRichText"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,cAAc,QAAQ,sBAAqB"}
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical';
|
||||
export declare function lexicalToMarkdown(data: null | SerializedEditorState | undefined): string;
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// Lexical text format bitflags.
|
||||
const IS_BOLD = 1;
|
||||
const IS_ITALIC = 1 << 1;
|
||||
const IS_STRIKETHROUGH = 1 << 2;
|
||||
const IS_CODE = 1 << 4;
|
||||
function isNodeArray(value) {
|
||||
return Array.isArray(value);
|
||||
}
|
||||
function wrapText(text, format) {
|
||||
if (!text) {
|
||||
return text;
|
||||
}
|
||||
// Don't wrap pure whitespace — would produce "** **".
|
||||
if (!text.trim()) {
|
||||
return text;
|
||||
}
|
||||
let out = text;
|
||||
if (format & IS_CODE) {
|
||||
out = `\`${out}\``;
|
||||
}
|
||||
if (format & IS_BOLD) {
|
||||
out = `**${out}**`;
|
||||
}
|
||||
if (format & IS_ITALIC) {
|
||||
out = `_${out}_`;
|
||||
}
|
||||
if (format & IS_STRIKETHROUGH) {
|
||||
out = `~~${out}~~`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
/** Render inline children (text, links, line breaks) to a single string. */ function inline(nodes) {
|
||||
if (!isNodeArray(nodes)) {
|
||||
return '';
|
||||
}
|
||||
let out = '';
|
||||
for (const node of nodes){
|
||||
if (!node || typeof node !== 'object') {
|
||||
continue;
|
||||
}
|
||||
const type = node.type;
|
||||
if (type === 'text') {
|
||||
const text = typeof node.text === 'string' ? node.text : '';
|
||||
const format = typeof node.format === 'number' ? node.format : 0;
|
||||
out += wrapText(text, format);
|
||||
} else if (type === 'linebreak') {
|
||||
out += '\n';
|
||||
} else if (type === 'link') {
|
||||
const fields = node.fields ?? {};
|
||||
const url = typeof fields.url === 'string' ? fields.url : typeof fields.doc?.value === 'string' ? fields.doc.value : '';
|
||||
const label = inline(node.children);
|
||||
out += url ? `[${label}](${url})` : label;
|
||||
} else if (node.children) {
|
||||
out += inline(node.children);
|
||||
} else if (typeof node.text === 'string') {
|
||||
out += node.text;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
/** Render a list (ordered/unordered), handling nesting via indentation. */ function renderList(node, depth) {
|
||||
const ordered = node.listType === 'number';
|
||||
const items = isNodeArray(node.children) ? node.children : [];
|
||||
const indent = ' '.repeat(depth);
|
||||
const lines = [];
|
||||
let i = 1;
|
||||
for (const item of items){
|
||||
if (!item || typeof item !== 'object') {
|
||||
continue;
|
||||
}
|
||||
const marker = ordered ? `${i}.` : '-';
|
||||
// A listitem may contain inline content and/or a nested list.
|
||||
const kids = isNodeArray(item.children) ? item.children : [];
|
||||
const nested = kids.filter((k)=>k && typeof k === 'object' && k.type === 'list');
|
||||
const inlineKids = kids.filter((k)=>!(k && typeof k === 'object' && k.type === 'list'));
|
||||
const text = inline(inlineKids);
|
||||
if (text.trim()) {
|
||||
lines.push(`${indent}${marker} ${text}`);
|
||||
i++;
|
||||
}
|
||||
for (const n of nested){
|
||||
lines.push(renderList(n, depth + 1));
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
/** Render a block-level node to Markdown. */ function block(node) {
|
||||
const type = node.type;
|
||||
switch(type){
|
||||
case 'heading':
|
||||
{
|
||||
const level = typeof node.tag === 'string' ? Number(node.tag.replace('h', '')) || 2 : 2;
|
||||
return `${'#'.repeat(Math.min(level, 6))} ${inline(node.children)}`;
|
||||
}
|
||||
case 'horizontalrule':
|
||||
return '---';
|
||||
case 'list':
|
||||
return renderList(node, 0);
|
||||
case 'paragraph':
|
||||
{
|
||||
const text = inline(node.children);
|
||||
return text.trim() ? text : '';
|
||||
}
|
||||
case 'quote':
|
||||
return inline(node.children).split('\n').map((l)=>`> ${l}`).join('\n');
|
||||
case 'upload':
|
||||
{
|
||||
const value = node.value ?? {};
|
||||
const url = typeof value.url === 'string' ? value.url : '';
|
||||
const alt = typeof value.alt === 'string' ? value.alt : '';
|
||||
return url ? `` : '';
|
||||
}
|
||||
default:
|
||||
// Unknown block-level node: emit its inline content if any.
|
||||
return node.children ? inline(node.children) : '';
|
||||
}
|
||||
}
|
||||
export function lexicalToMarkdown(data) {
|
||||
const root = data?.root;
|
||||
if (!root || !isNodeArray(root.children)) {
|
||||
return '';
|
||||
}
|
||||
const blocks = [];
|
||||
for (const node of root.children){
|
||||
if (!node || typeof node !== 'object') {
|
||||
continue;
|
||||
}
|
||||
const md = block(node);
|
||||
if (md.trim()) {
|
||||
blocks.push(md);
|
||||
}
|
||||
}
|
||||
// Blank line between block-level elements — standard Markdown separation.
|
||||
return blocks.join('\n\n').trim();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=lexicalToMarkdown.js.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
+15
-1
@@ -4,6 +4,15 @@ type BuildLlmsTxtArgs = {
|
||||
/** Absolute site URL (https://…). */
|
||||
baseUrl: string;
|
||||
config: I18nConfig;
|
||||
/**
|
||||
* Full-content mode (llms-full.txt). When true, each page's full body is
|
||||
* inlined as Markdown (via blocksToMarkdown) under its heading, so an agent
|
||||
* gets the whole site in one request — the llmstxt.org "llms-full.txt"
|
||||
* convention. Default false = the compact index (links + descriptions).
|
||||
*/
|
||||
full?: boolean;
|
||||
/** Field holding the block layout (full mode only). Default 'layout'. */
|
||||
layoutField?: string;
|
||||
/** Locale for names/descriptions. Defaults to config.defaultLocale. */
|
||||
locale?: string;
|
||||
/** Pages collection slug. Defaults to 'pages'. */
|
||||
@@ -11,6 +20,11 @@ type BuildLlmsTxtArgs = {
|
||||
payload: BasePayload;
|
||||
/** Site settings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
/**
|
||||
* Field holding a richer AI summary (buildSummaryField). When set and present,
|
||||
* it's used as the page description instead of meta.description.
|
||||
*/
|
||||
summaryField?: string;
|
||||
};
|
||||
/**
|
||||
* Builds the body of /llms.txt — a Markdown file describing the site for AI
|
||||
@@ -41,5 +55,5 @@ type BuildLlmsTxtArgs = {
|
||||
* Data comes from the panel (siteName, siteDescription, pages) — nothing
|
||||
* hardcoded. Skips drafts and noindex pages (same as the sitemap).
|
||||
*/
|
||||
export declare function buildLlmsTxt({ baseUrl, config, locale, pagesSlug, payload, settingsSlug, }: BuildLlmsTxtArgs): Promise<string>;
|
||||
export declare function buildLlmsTxt({ baseUrl, config, full, layoutField, locale, pagesSlug, payload, settingsSlug, summaryField, }: BuildLlmsTxtArgs): Promise<string>;
|
||||
export {};
|
||||
|
||||
Vendored
+55
-3
@@ -1,3 +1,4 @@
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js';
|
||||
import { buildLocalizedPath } from '../i18n/index.js';
|
||||
/**
|
||||
* Builds the body of /llms.txt — a Markdown file describing the site for AI
|
||||
@@ -27,7 +28,13 @@ import { buildLocalizedPath } from '../i18n/index.js';
|
||||
*
|
||||
* Data comes from the panel (siteName, siteDescription, pages) — nothing
|
||||
* hardcoded. Skips drafts and noindex pages (same as the sitemap).
|
||||
*/ export async function buildLlmsTxt({ baseUrl, config, locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings' }) {
|
||||
*/ export async function buildLlmsTxt({ baseUrl, config, full = false, layoutField = 'layout', locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings', summaryField }) {
|
||||
const pickDescription = (raw)=>{
|
||||
if (summaryField && typeof raw[summaryField] === 'string' && raw[summaryField].trim()) {
|
||||
return raw[summaryField].trim();
|
||||
}
|
||||
return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined;
|
||||
};
|
||||
const loc = locale ?? config.defaultLocale;
|
||||
const origin = baseUrl.replace(/\/$/, '');
|
||||
const settings = await payload.findGlobal({
|
||||
@@ -42,9 +49,10 @@ import { buildLocalizedPath } from '../i18n/index.js';
|
||||
// "path cannot be queried: _status" (a real bug report). Draft filtering
|
||||
// happens in memory below, which is safe for every collection. Same as
|
||||
// buildSitemapEntries and generateStaticParams.
|
||||
// Full mode needs depth:1 so block images/relations populate for the Markdown.
|
||||
const result = await payload.find({
|
||||
collection: pagesSlug,
|
||||
depth: 0,
|
||||
depth: full ? 1 : 0,
|
||||
limit: 1000,
|
||||
locale: loc
|
||||
});
|
||||
@@ -55,6 +63,49 @@ import { buildLocalizedPath } from '../i18n/index.js';
|
||||
if (description) {
|
||||
lines.push(`> ${description}`, '');
|
||||
}
|
||||
if (full) {
|
||||
// Full-content: each published page inlined as Markdown under its heading.
|
||||
const sections = [];
|
||||
for (const raw of result.docs){
|
||||
if (raw._status && raw._status !== 'published') {
|
||||
continue;
|
||||
}
|
||||
if (raw.meta?.noindex) {
|
||||
continue;
|
||||
}
|
||||
const title = typeof raw.title === 'string' ? raw.title : undefined;
|
||||
const slug = typeof raw.slug === 'string' ? raw.slug : undefined;
|
||||
if (!title || !slug) {
|
||||
continue;
|
||||
}
|
||||
const path = buildLocalizedPath({
|
||||
config,
|
||||
locale: loc,
|
||||
slugs: {
|
||||
[loc]: slug
|
||||
}
|
||||
});
|
||||
const body = blocksToMarkdown(raw[layoutField]);
|
||||
const desc = pickDescription(raw);
|
||||
const parts = [
|
||||
`## ${title}`
|
||||
];
|
||||
if (path) {
|
||||
parts.push(`${origin}${path}`);
|
||||
}
|
||||
if (desc) {
|
||||
parts.push(`_${desc}_`);
|
||||
}
|
||||
if (body) {
|
||||
parts.push(body);
|
||||
}
|
||||
sections.push(parts.join('\n\n'));
|
||||
}
|
||||
if (sections.length > 0) {
|
||||
lines.push(sections.join('\n\n---\n\n'), '');
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
const pageLinks = [];
|
||||
for (const raw of result.docs){
|
||||
if (raw._status && raw._status !== 'published') {
|
||||
@@ -78,7 +129,8 @@ import { buildLocalizedPath } from '../i18n/index.js';
|
||||
if (!path) {
|
||||
continue;
|
||||
}
|
||||
const pageDesc = typeof raw.meta?.description === 'string' ? ` — ${raw.meta.description}` : '';
|
||||
const desc = pickDescription(raw);
|
||||
const pageDesc = desc ? ` — ${desc}` : '';
|
||||
pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`);
|
||||
}
|
||||
if (pageLinks.length > 0) {
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+49
-8
@@ -1,4 +1,36 @@
|
||||
type RobotRule = {
|
||||
allow?: string;
|
||||
disallow?: string[];
|
||||
userAgent: string | string[];
|
||||
};
|
||||
/**
|
||||
* Known AI user agents, split by purpose:
|
||||
* - assistant/search bots fetch a page to answer a user's question live or to
|
||||
* power an AI search index — the ones that make "the chat reads your site"
|
||||
* work, and that most businesses WANT.
|
||||
* - training crawlers collect pages to train models — some clients prefer to
|
||||
* opt out of these while keeping assistant/search visibility.
|
||||
*/
|
||||
export declare const AI_ASSISTANT_BOTS: readonly ["ClaudeBot", "Claude-Web", "Claude-SearchBot", "ChatGPT-User", "OAI-SearchBot", "PerplexityBot", "Perplexity-User"];
|
||||
export declare const AI_TRAINING_BOTS: readonly ["GPTBot", "Google-Extended", "CCBot", "anthropic-ai", "Applebot-Extended", "Bytespider", "Meta-ExternalAgent"];
|
||||
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false;
|
||||
type BuildRobotsArgs = {
|
||||
/** Override the assistant/search bot list. */
|
||||
aiAssistantAgents?: readonly string[];
|
||||
/**
|
||||
* How to treat AI crawlers (assistant/search + training). Default 'allow' —
|
||||
* explicitly welcome them so the site stays visible to Claude, ChatGPT,
|
||||
* Perplexity etc. and an accidental future '*' tightening doesn't lock them
|
||||
* out. Options:
|
||||
* - 'allow' (default): explicit allow for assistant AND training bots.
|
||||
* - 'block-training': allow assistant/search bots, disallow training crawlers
|
||||
* — keep AI answers/visibility, opt out of model training.
|
||||
* - 'disallow': block all known AI bots.
|
||||
* - false: emit no AI-specific rules (only the '*' rule).
|
||||
*/
|
||||
aiBots?: AiBotsPolicy;
|
||||
/** Override the training crawler list. */
|
||||
aiTrainingAgents?: readonly string[];
|
||||
/** Absolute origin, e.g. 'https://example.com'. */
|
||||
baseUrl: string;
|
||||
/** Paths to disallow. Defaults to Payload's admin and API. */
|
||||
@@ -7,20 +39,18 @@ type BuildRobotsArgs = {
|
||||
sitemap?: boolean;
|
||||
};
|
||||
/**
|
||||
* Shape for Next's `app/robots.ts`.
|
||||
* Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array
|
||||
* (Next accepts both) — it becomes an array when AI-bot rules are added.
|
||||
*/
|
||||
export type RobotsRules = {
|
||||
host?: string;
|
||||
rules: {
|
||||
allow?: string;
|
||||
disallow?: string[];
|
||||
userAgent: string;
|
||||
};
|
||||
rules: RobotRule | RobotRule[];
|
||||
sitemap?: string;
|
||||
};
|
||||
/**
|
||||
* Builds robots rules that allow crawling everything except the admin panel and
|
||||
* API, and point crawlers at the sitemap.
|
||||
* API, point crawlers at the sitemap, and (by default) explicitly welcome AI
|
||||
* assistant/search/training bots.
|
||||
*
|
||||
* ```ts
|
||||
* // app/robots.ts
|
||||
@@ -31,6 +61,17 @@ export type RobotsRules = {
|
||||
*
|
||||
* The admin and API are disallowed by default — no reason for them in the index,
|
||||
* and it keeps crawl budget on real content.
|
||||
*
|
||||
* AI visibility: the #1 reason "the chat won't read the site" is an AI user
|
||||
* agent being blocked (or not explicitly allowed under a tightened '*' rule).
|
||||
* `aiBots: 'allow'` (default) emits explicit allow rules for ClaudeBot, GPTBot,
|
||||
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
|
||||
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
|
||||
*
|
||||
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
|
||||
* ```ts
|
||||
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
|
||||
* ```
|
||||
*/
|
||||
export declare function buildRobots({ baseUrl, disallow, sitemap, }: BuildRobotsArgs): RobotsRules;
|
||||
export declare function buildRobots({ aiAssistantAgents, aiBots, aiTrainingAgents, baseUrl, disallow, sitemap, }: BuildRobotsArgs): RobotsRules;
|
||||
export {};
|
||||
|
||||
Vendored
+84
-6
@@ -1,6 +1,32 @@
|
||||
/**
|
||||
* Known AI user agents, split by purpose:
|
||||
* - assistant/search bots fetch a page to answer a user's question live or to
|
||||
* power an AI search index — the ones that make "the chat reads your site"
|
||||
* work, and that most businesses WANT.
|
||||
* - training crawlers collect pages to train models — some clients prefer to
|
||||
* opt out of these while keeping assistant/search visibility.
|
||||
*/ export const AI_ASSISTANT_BOTS = [
|
||||
'ClaudeBot',
|
||||
'Claude-Web',
|
||||
'Claude-SearchBot',
|
||||
'ChatGPT-User',
|
||||
'OAI-SearchBot',
|
||||
'PerplexityBot',
|
||||
'Perplexity-User'
|
||||
];
|
||||
export const AI_TRAINING_BOTS = [
|
||||
'GPTBot',
|
||||
'Google-Extended',
|
||||
'CCBot',
|
||||
'anthropic-ai',
|
||||
'Applebot-Extended',
|
||||
'Bytespider',
|
||||
'Meta-ExternalAgent'
|
||||
];
|
||||
/**
|
||||
* Builds robots rules that allow crawling everything except the admin panel and
|
||||
* API, and point crawlers at the sitemap.
|
||||
* API, point crawlers at the sitemap, and (by default) explicitly welcome AI
|
||||
* assistant/search/training bots.
|
||||
*
|
||||
* ```ts
|
||||
* // app/robots.ts
|
||||
@@ -11,17 +37,69 @@
|
||||
*
|
||||
* The admin and API are disallowed by default — no reason for them in the index,
|
||||
* and it keeps crawl budget on real content.
|
||||
*/ export function buildRobots({ baseUrl, disallow = [
|
||||
*
|
||||
* AI visibility: the #1 reason "the chat won't read the site" is an AI user
|
||||
* agent being blocked (or not explicitly allowed under a tightened '*' rule).
|
||||
* `aiBots: 'allow'` (default) emits explicit allow rules for ClaudeBot, GPTBot,
|
||||
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
|
||||
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
|
||||
*
|
||||
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
|
||||
* ```ts
|
||||
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
|
||||
* ```
|
||||
*/ export function buildRobots({ aiAssistantAgents = AI_ASSISTANT_BOTS, aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow = [
|
||||
'/admin',
|
||||
'/api'
|
||||
], sitemap = true }) {
|
||||
const origin = baseUrl.replace(/\/$/, '');
|
||||
return {
|
||||
rules: {
|
||||
const baseRule = {
|
||||
allow: '/',
|
||||
disallow,
|
||||
userAgent: '*'
|
||||
};
|
||||
const aiRules = [];
|
||||
if (aiBots === 'allow') {
|
||||
aiRules.push({
|
||||
allow: '/',
|
||||
disallow,
|
||||
userAgent: '*'
|
||||
},
|
||||
userAgent: [
|
||||
...aiAssistantAgents,
|
||||
...aiTrainingAgents
|
||||
]
|
||||
});
|
||||
} else if (aiBots === 'block-training') {
|
||||
aiRules.push({
|
||||
allow: '/',
|
||||
disallow,
|
||||
userAgent: [
|
||||
...aiAssistantAgents
|
||||
]
|
||||
});
|
||||
aiRules.push({
|
||||
disallow: [
|
||||
'/'
|
||||
],
|
||||
userAgent: [
|
||||
...aiTrainingAgents
|
||||
]
|
||||
});
|
||||
} else if (aiBots === 'disallow') {
|
||||
aiRules.push({
|
||||
disallow: [
|
||||
'/'
|
||||
],
|
||||
userAgent: [
|
||||
...aiAssistantAgents,
|
||||
...aiTrainingAgents
|
||||
]
|
||||
});
|
||||
}
|
||||
return {
|
||||
rules: aiRules.length > 0 ? [
|
||||
baseRule,
|
||||
...aiRules
|
||||
] : baseRule,
|
||||
...sitemap ? {
|
||||
sitemap: `${origin}/sitemap.xml`
|
||||
} : {},
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+39
@@ -0,0 +1,39 @@
|
||||
type SpeakableJsonLdArgs = {
|
||||
/**
|
||||
* CSS selectors marking the parts best suited to be read aloud by voice
|
||||
* assistants / AI (a summary, the lead paragraph, key answer). Default
|
||||
* ['h1', '.speakable']. Keep it to genuinely readable, self-contained text —
|
||||
* not nav or boilerplate.
|
||||
*/
|
||||
cssSelectors?: string[];
|
||||
/** Optional @id to join this node into a @graph (e.g. `${url}#webpage`). */
|
||||
id?: string;
|
||||
/** Canonical URL of the page this describes. */
|
||||
url: string;
|
||||
};
|
||||
/**
|
||||
* Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice
|
||||
* assistants and AI which parts of the page are meant to be read aloud /
|
||||
* quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key
|
||||
* content easy for assistants to lift cleanly.
|
||||
*
|
||||
* Add to the page's @graph via JsonLdGraph (recommended) or emit standalone:
|
||||
*
|
||||
* import { buildSpeakableJsonLd } from '@intecion/ipal-kit'
|
||||
* const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] })
|
||||
*
|
||||
* Mark the matching elements in the project markup (e.g. className="speakable"
|
||||
* or a `.lead` summary). Selectors that match nothing are simply ignored by
|
||||
* consumers — but don't point at nav/boilerplate.
|
||||
*/
|
||||
export declare function buildSpeakableJsonLd({ id, cssSelectors, url, }: SpeakableJsonLdArgs): {
|
||||
speakable: {
|
||||
'@type': string;
|
||||
cssSelector: string[];
|
||||
};
|
||||
url: string;
|
||||
'@id'?: string | undefined;
|
||||
'@context': string;
|
||||
'@type': string;
|
||||
};
|
||||
export {};
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice
|
||||
* assistants and AI which parts of the page are meant to be read aloud /
|
||||
* quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key
|
||||
* content easy for assistants to lift cleanly.
|
||||
*
|
||||
* Add to the page's @graph via JsonLdGraph (recommended) or emit standalone:
|
||||
*
|
||||
* import { buildSpeakableJsonLd } from '@intecion/ipal-kit'
|
||||
* const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] })
|
||||
*
|
||||
* Mark the matching elements in the project markup (e.g. className="speakable"
|
||||
* or a `.lead` summary). Selectors that match nothing are simply ignored by
|
||||
* consumers — but don't point at nav/boilerplate.
|
||||
*/ export function buildSpeakableJsonLd({ id, cssSelectors = [
|
||||
'h1',
|
||||
'.speakable'
|
||||
], url }) {
|
||||
return {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'WebPage',
|
||||
...id ? {
|
||||
'@id': id
|
||||
} : {},
|
||||
speakable: {
|
||||
'@type': 'SpeakableSpecification',
|
||||
cssSelector: cssSelectors
|
||||
},
|
||||
url
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=buildSpeakableJsonLd.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/seo/buildSpeakableJsonLd.ts"],"sourcesContent":["type SpeakableJsonLdArgs = {\n /**\n * CSS selectors marking the parts best suited to be read aloud by voice\n * assistants / AI (a summary, the lead paragraph, key answer). Default\n * ['h1', '.speakable']. Keep it to genuinely readable, self-contained text —\n * not nav or boilerplate.\n */\n cssSelectors?: string[]\n /** Optional @id to join this node into a @graph (e.g. `${url}#webpage`). */\n id?: string\n /** Canonical URL of the page this describes. */\n url: string\n}\n\n/**\n * Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice\n * assistants and AI which parts of the page are meant to be read aloud /\n * quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key\n * content easy for assistants to lift cleanly.\n *\n * Add to the page's @graph via JsonLdGraph (recommended) or emit standalone:\n *\n * import { buildSpeakableJsonLd } from '@intecion/ipal-kit'\n * const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] })\n *\n * Mark the matching elements in the project markup (e.g. className=\"speakable\"\n * or a `.lead` summary). Selectors that match nothing are simply ignored by\n * consumers — but don't point at nav/boilerplate.\n */\nexport function buildSpeakableJsonLd({\n id,\n cssSelectors = ['h1', '.speakable'],\n url,\n}: SpeakableJsonLdArgs) {\n return {\n '@context': 'https://schema.org',\n '@type': 'WebPage',\n ...(id ? { '@id': id } : {}),\n speakable: {\n '@type': 'SpeakableSpecification',\n cssSelector: cssSelectors,\n },\n url,\n }\n}\n"],"names":["buildSpeakableJsonLd","id","cssSelectors","url","speakable","cssSelector"],"mappings":"AAcA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,qBAAqB,EACnCC,EAAE,EACFC,eAAe;IAAC;IAAM;CAAa,EACnCC,GAAG,EACiB;IACpB,OAAO;QACL,YAAY;QACZ,SAAS;QACT,GAAIF,KAAK;YAAE,OAAOA;QAAG,IAAI,CAAC,CAAC;QAC3BG,WAAW;YACT,SAAS;YACTC,aAAaH;QACf;QACAC;IACF;AACF"}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import type { Field, TextareaField } from 'payload';
|
||||
type BuildSummaryFieldArgs = {
|
||||
/** Auto-fill from page content when the editor leaves it empty. Default true. */
|
||||
autoFill?: boolean;
|
||||
/** Help text under the field. */
|
||||
description?: string;
|
||||
/** Sidebar/admin label. */
|
||||
label?: string;
|
||||
/** Block layout field to derive the summary from. Default 'layout'. */
|
||||
layoutField?: string;
|
||||
/** Target length for the auto-generated summary. Default 300. */
|
||||
maxLength?: number;
|
||||
/** Field name. Default 'aiSummary'. */
|
||||
name?: string;
|
||||
/** Extend/override the generated textarea (position, access…). */
|
||||
overrides?: Partial<TextareaField>;
|
||||
};
|
||||
/**
|
||||
* A localized `aiSummary` textarea — a concise, human-written (or auto-derived)
|
||||
* description of the page, richer than the SEO meta description. It's the
|
||||
* preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'`
|
||||
* to buildLlmsTxt and searchContent and they'll use it over meta.description.
|
||||
*
|
||||
* With `autoFill` (default), an empty summary is filled on save from the page's
|
||||
* own content (blocks → plain text, trimmed to ~maxLength). Editors can always
|
||||
* overwrite it — auto-fill only runs when the field is blank, never clobbers a
|
||||
* manual summary. Derived from the page's OWN content, so no hard-coded data.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildSummaryField } from '@intecion/ipal-kit'
|
||||
* fields: [ /* … *\/ buildSummaryField() ]
|
||||
*
|
||||
* // then, richer AI descriptions:
|
||||
* buildLlmsTxt({ …, summaryField: 'aiSummary' })
|
||||
* createSearchRoute({ …, summaryField: 'aiSummary' })
|
||||
*/
|
||||
export declare function buildSummaryField(args?: BuildSummaryFieldArgs): Field;
|
||||
export {};
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js';
|
||||
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */ function mdToPlain(md) {
|
||||
return md.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
|
||||
.replace(/^#{1,6}\s+/gm, '') // heading markers
|
||||
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
|
||||
.replace(/[*_~`]/g, '') // inline emphasis/code marks
|
||||
.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
/** Truncate at a word boundary, adding an ellipsis when cut. */ function truncate(text, max) {
|
||||
if (text.length <= max) {
|
||||
return text;
|
||||
}
|
||||
const slice = text.slice(0, max);
|
||||
const lastSpace = slice.lastIndexOf(' ');
|
||||
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`;
|
||||
}
|
||||
/**
|
||||
* A localized `aiSummary` textarea — a concise, human-written (or auto-derived)
|
||||
* description of the page, richer than the SEO meta description. It's the
|
||||
* preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'`
|
||||
* to buildLlmsTxt and searchContent and they'll use it over meta.description.
|
||||
*
|
||||
* With `autoFill` (default), an empty summary is filled on save from the page's
|
||||
* own content (blocks → plain text, trimmed to ~maxLength). Editors can always
|
||||
* overwrite it — auto-fill only runs when the field is blank, never clobbers a
|
||||
* manual summary. Derived from the page's OWN content, so no hard-coded data.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildSummaryField } from '@intecion/ipal-kit'
|
||||
* fields: [ /* … *\/ buildSummaryField() ]
|
||||
*
|
||||
* // then, richer AI descriptions:
|
||||
* buildLlmsTxt({ …, summaryField: 'aiSummary' })
|
||||
* createSearchRoute({ …, summaryField: 'aiSummary' })
|
||||
*/ export function buildSummaryField(args = {}) {
|
||||
const { name = 'aiSummary', autoFill = true, description = 'Zwięzły opis strony dla agentów AI i llms.txt (bogatszy niż meta description). Puste → generowane automatycznie z treści.', label = 'Streszczenie dla AI', layoutField = 'layout', maxLength = 300, overrides = {} } = args;
|
||||
const autofillHook = ({ data, value })=>{
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value;
|
||||
} // never clobber a manual summary
|
||||
if (!data || typeof data !== 'object') {
|
||||
return value;
|
||||
}
|
||||
const layout = data[layoutField];
|
||||
const md = blocksToMarkdown(layout);
|
||||
if (!md) {
|
||||
return value;
|
||||
}
|
||||
const plain = mdToPlain(md);
|
||||
return plain ? truncate(plain, maxLength) : value;
|
||||
};
|
||||
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides;
|
||||
return {
|
||||
name,
|
||||
type: 'textarea',
|
||||
admin: {
|
||||
description,
|
||||
position: 'sidebar',
|
||||
...adminOverrides
|
||||
},
|
||||
hooks: {
|
||||
...hooksOverrides,
|
||||
...autoFill ? {
|
||||
beforeChange: [
|
||||
autofillHook,
|
||||
...hooksOverrides?.beforeChange ?? []
|
||||
]
|
||||
} : {}
|
||||
},
|
||||
label,
|
||||
localized: true,
|
||||
...restOverrides
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=buildSummaryField.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+3
-1
@@ -11,13 +11,15 @@ export { buildMetadata } from './buildMetadata.js';
|
||||
export type { PageMetadata } from './buildMetadata.js';
|
||||
export { buildNoindexField } from './buildNoindexField.js';
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||
export { buildRobots } from './buildRobots.js';
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js';
|
||||
export type { RobotsRules } from './buildRobots.js';
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
|
||||
export { buildSitemapEntries } from './buildSitemapEntries.js';
|
||||
export type { SitemapEntry } from './buildSitemapEntries.js';
|
||||
export { buildSitemapXml } from './buildSitemapXml.js';
|
||||
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js';
|
||||
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js';
|
||||
export { buildSummaryField } from './buildSummaryField.js';
|
||||
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js';
|
||||
export { composeTitle } from './composeTitle.js';
|
||||
export type { TitleOrder } from './composeTitle.js';
|
||||
|
||||
Vendored
+3
-1
@@ -9,11 +9,13 @@ export { createManifestHandler } from './buildManifest.js';
|
||||
export { buildMetadata } from './buildMetadata.js';
|
||||
export { buildNoindexField } from './buildNoindexField.js';
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||
export { buildRobots } from './buildRobots.js';
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js';
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
|
||||
export { buildSitemapEntries } from './buildSitemapEntries.js';
|
||||
export { buildSitemapXml } from './buildSitemapXml.js';
|
||||
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js';
|
||||
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js';
|
||||
export { buildSummaryField } from './buildSummaryField.js';
|
||||
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js';
|
||||
export { composeTitle } from './composeTitle.js';
|
||||
export { createMetadataGenerator } from './createMetadataGenerator.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,WAAW,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||
Vendored
+10
@@ -13,13 +13,23 @@ import type { SitemapEntry } from './buildSitemapEntries.js';
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
||||
*
|
||||
* For the full-content variant, add a second route with `full: true`:
|
||||
*
|
||||
* // app/llms-full.txt/route.ts
|
||||
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true })
|
||||
*/
|
||||
export declare function createLlmsTxtRoute(opts: {
|
||||
baseUrl: string;
|
||||
config: I18nConfig;
|
||||
/** Inline every page's full Markdown (llms-full.txt). Default false. */
|
||||
full?: boolean;
|
||||
getCachedPayload: () => Promise<BasePayload>;
|
||||
pagesSlug?: string;
|
||||
settingsSlug?: string;
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string;
|
||||
}): () => Promise<Response>;
|
||||
/**
|
||||
* Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.
|
||||
|
||||
Vendored
+9
-1
@@ -12,6 +12,12 @@ import { buildSitemapXml } from './buildSitemapXml.js';
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
||||
*
|
||||
* For the full-content variant, add a second route with `full: true`:
|
||||
*
|
||||
* // app/llms-full.txt/route.ts
|
||||
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true })
|
||||
*/ export function createLlmsTxtRoute(opts) {
|
||||
return async ()=>{
|
||||
try {
|
||||
@@ -19,9 +25,11 @@ import { buildSitemapXml } from './buildSitemapXml.js';
|
||||
const body = await buildLlmsTxt({
|
||||
baseUrl: opts.baseUrl,
|
||||
config: opts.config,
|
||||
full: opts.full,
|
||||
pagesSlug: opts.pagesSlug,
|
||||
payload,
|
||||
settingsSlug: opts.settingsSlug
|
||||
settingsSlug: opts.settingsSlug,
|
||||
summaryField: opts.summaryField
|
||||
});
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user