From c9a50abc33eaf8185423f2e3e3441b3064810002 Mon Sep 17 00:00:00 2001 From: rasm-its Date: Fri, 16 Oct 2026 02:19:08 +0200 Subject: [PATCH] SEO/GEO tools and project requests: site index, IndexNow, page JSON-LD, fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GEO / SEO - collectSiteIndex: one list of public docs per locale (pages + archive entries) on sitemap rules; llms.txt/llms-full and MCP list_pages now include blog/content entries and every language. Fixes hard-coded "## Strony" heading and homepage not collapsing to the locale root in llms.txt. - Markdown frontmatter: canonical url + updated date. - Metadata: X/Twitter card, OG image width/height/alt, og:type article with published/modified times for entries. - Fix: Site Settings "defaultShareImage" was never used — now the OG fallback. - getPageJsonLd (createContentHelpers): WebPage/CollectionPage/BlogPosting, BreadcrumbList from the real route, FAQPage via a project mapper. - IndexNow (opt-in ipalKit({ indexNow: true })): submit published URLs in all languages, key generated in Site Integrations or INDEXNOW_KEY, key route. - sameAs profiles in Site Settings + sameAsUrls(); sitemap . From project reports - Fix: package exports were missing ./env and ./fluid.css although the docs import them (TS2307); regression test checks every documented subpath. - Fix: plugins run before Payload adds its default users collection, so roles and 2FA had nothing to attach to — ipalKit injects an auth collection when the project has none (project's own one wins). Audit no longer errors on it. - createMarkdownRoute, createSubmitAction (/server, headers injected). - formatOpeningHours (PL/EN/DE text → schema.org), used by buildLocalBusinessJsonLd, which also takes a schema.org `type`. - buildNavigationJsonLd straight from the header global. - buildCsp googleMaps: full Maps JS API domain set; values de-duplicated. Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 8 +- docs/agent/skills/ipal-audit/scripts/audit.sh | 6 +- .../skills/ipal-form/resources/actions.ts | 20 +- docs/dev/PROGRAMISTA.md | 2 +- package.json | 8 +- src/exports/server.ts | 2 + src/globals/SiteIntegrations/index.ts | 2 + src/globals/SiteSettings/fields/general.ts | 11 ++ src/index.ts | 21 +- src/modules/content/createMarkdownRenderer.ts | 56 +++++- src/modules/content/index.ts | 2 +- src/modules/forms/createSubmitAction.ts | 92 +++++++++ src/modules/frontend/createContentHelpers.ts | 108 ++++++++++- src/modules/mcp/createMcpRoute.ts | 30 +-- src/modules/security/buildCsp.ts | 15 +- src/modules/seo/buildLlmsTxt.ts | 177 +++++++---------- src/modules/seo/buildLocalBusinessJsonLd.ts | 18 +- src/modules/seo/buildMetadata.ts | 38 +++- src/modules/seo/buildOrganizationJsonLd.ts | 12 ++ src/modules/seo/buildSiteNavigationJsonLd.ts | 64 ++++++ src/modules/seo/buildSitemapEntries.ts | 25 ++- src/modules/seo/buildSitemapXml.ts | 6 +- src/modules/seo/buildWebPageJsonLd.ts | 45 +++++ src/modules/seo/createPageMetadata.ts | 31 ++- src/modules/seo/formatOpeningHours.ts | 112 +++++++++++ src/modules/seo/index.ts | 16 +- src/modules/seo/indexNow.ts | 183 ++++++++++++++++++ src/modules/seo/readSiteMetaConfig.ts | 4 + src/modules/seo/routeHandlers.ts | 4 + src/modules/seo/siteIndex.ts | 167 ++++++++++++++++ src/plugin.ts | 36 ++++ src/types.ts | 10 +- test/exports.test.ts | 37 ++++ test/indexNow.test.ts | 95 +++++++++ test/integration.test.ts | 18 ++ test/openingHours.test.ts | 30 +++ test/plugin.test.ts | 23 +++ test/seo.test.ts | 43 ++++ test/submitAction.test.ts | 40 ++++ 39 files changed, 1449 insertions(+), 168 deletions(-) create mode 100644 src/modules/forms/createSubmitAction.ts create mode 100644 src/modules/seo/buildWebPageJsonLd.ts create mode 100644 src/modules/seo/formatOpeningHours.ts create mode 100644 src/modules/seo/indexNow.ts create mode 100644 src/modules/seo/siteIndex.ts create mode 100644 test/exports.test.ts create mode 100644 test/indexNow.test.ts create mode 100644 test/openingHours.test.ts create mode 100644 test/submitAction.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 40e2564..5852e7d 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -23,7 +23,7 @@ 3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`. 4. **Bez jawnego ``, z ISR i `generateStaticParams`** — inaczej metadata ląduje w `` i SEO pada. -5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale, +5. **Minimum kolekcji.** Users wstrzykuje ipalKit, dane firmy/nawigacja to globale, FAQ/hero to bloki. 6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + ``, upload + ``, `
` + ``. Zero pól `ctaLabel`/`pdfUrl`. @@ -315,7 +315,11 @@ Domyślnie: `pages`, `media` + globale pluginu (`site-settings`, `site-integrations`, Notifications, Cookie Settings) + globale projektu (nawigacja, stopka, firma). Nic więcej, dopóki klient jawnie nie wymaga. -**NIGDY:** `users` (wbudowane w Payload), druga `media`, `daneFirmy`/`settings`/ +**`users`** wstrzykuje `ipalKit` (kolekcja auth z `roles` i 2FA) — nie twórz jej, chyba +że potrzebujesz dodatkowych pól (wtedy własna `Users.ts` ze slugiem z `access.authCollection`; +plugin doda do niej role i 2FA). + +**NIGDY:** druga `media`, `daneFirmy`/`settings`/ `navigation`/`footer` jako kolekcje (to globale), FAQ/hero/features jako kolekcje (to bloki), kolekcja dla jednej rzeczy (to strona albo global). diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/ipal-audit/scripts/audit.sh index 4ed1091..63da3de 100644 --- a/docs/agent/skills/ipal-audit/scripts/audit.sh +++ b/docs/agent/skills/ipal-audit/scripts/audit.sh @@ -142,8 +142,10 @@ fi # --- Collections (§5.3) --- if [ -d src/collections ]; then - report ERROR "forbidden collection" "§5.3 users are built in; settings/nav/footer are globals; FAQ/hero are blocks" \ - "$(ls src/collections | grep -iE '^(users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')" + report ERROR "forbidden collection" "§5.3 settings/nav/footer are globals; FAQ/hero are blocks" \ + "$(ls src/collections | grep -iE '^(settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')" + report WARNING "own users collection" "§5.3 ipalKit injects the auth collection — keep your own only to add fields (roles + 2FA still attach)" \ + "$(ls src/collections | grep -iE '^(users|user)\.ts$')" report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \ "$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')" fi diff --git a/docs/agent/skills/ipal-form/resources/actions.ts b/docs/agent/skills/ipal-form/resources/actions.ts index 6e0f02f..d6d80db 100644 --- a/docs/agent/skills/ipal-form/resources/actions.ts +++ b/docs/agent/skills/ipal-form/resources/actions.ts @@ -1,21 +1,9 @@ // src/app/(frontend)/[locale]/actions.ts — ONE server action for every builder form. +// honeypot → client IP (IPAL_IP_HEADER) → submitForm (rate limit, Turnstile, +// validation, GDPR consent, storage) → visitor message from Notifications. 'use server' import { headers } from 'next/headers' -import { submitForm } from '@intecion/ipal-kit/server' -import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit' +import { createSubmitAction } from '@intecion/ipal-kit/server' import { getCachedPayload } from '@/lib/content' -export async function sendForm( - formId: string, - locale: string, - values: Record, - turnstileToken?: string, -): Promise<{ success: boolean; message: string }> { - const payload = await getCachedPayload() - const texts = (await getNotificationTexts({ payload, locale })).form - if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success, nothing stored - const { [HONEYPOT_FIELD]: _hp, ...data } = values - const ip = clientIp(await headers()) || undefined // headers(): fine in a server action — never in the page tree (breaks SSG) - const result = await submitForm({ payload, formId, data, turnstileToken, ip }) - return { success: result.success, message: resolveFormMessage(result, texts) } -} +export const sendForm = createSubmitAction({ getCachedPayload, headers }) diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 6ecce7e..f74ea43 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -120,7 +120,7 @@ import { Pages } from '@/collections/Pages' import { Media } from '@/collections/Media' export default buildConfig({ - collections: [Pages, Media], // users wbudowane — nie twórz + collections: [Pages, Media], // users wstrzykuje ipalKit (własna tylko dla dodatkowych pól) email: mailAdapter(), // bez tego maile form-buildera nie wyjdą plugins: [ ipalKit({ diff --git a/package.json b/package.json index 8088bb5..6b54de2 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,13 @@ "import": "./dist/exports/admin.js", "types": "./dist/exports/admin.d.ts", "default": "./dist/exports/admin.js" - } + }, + "./env": { + "import": "./dist/exports/env.js", + "types": "./dist/exports/env.d.ts", + "default": "./dist/exports/env.js" + }, + "./fluid.css": "./dist/styles/fluid.css" }, "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/exports/server.ts b/src/exports/server.ts index 1964906..08dc3ed 100644 --- a/src/exports/server.ts +++ b/src/exports/server.ts @@ -1,5 +1,7 @@ export { sendEmail } from '../modules/email/index.js' export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js' +export { createSubmitAction } from '../modules/forms/createSubmitAction.js' +export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js' export { submitForm } from '../modules/forms/index.js' export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js' /** diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index b764a7a..32663f5 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -1,6 +1,7 @@ import type { Field, GlobalConfig } from 'payload' import { isAdmin } from '../../modules/access/index.js' +import { indexNowFields } from '../../modules/seo/indexNow.js' import { analyticsFields } from './fields/analytics.js' import { smtpFields } from './fields/smtp.js' import { turnstileFields } from './fields/turnstile.js' @@ -43,6 +44,7 @@ export function buildSiteIntegrations({ { fields: analyticsFields, label: 'Analytics' }, { fields: turnstileFields, label: 'Turnstile' }, { fields: smtpFields, label: 'SMTP' }, + { fields: indexNowFields, label: 'IndexNow' }, ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []), diff --git a/src/globals/SiteSettings/fields/general.ts b/src/globals/SiteSettings/fields/general.ts index f8515ba..d60f8d3 100644 --- a/src/globals/SiteSettings/fields/general.ts +++ b/src/globals/SiteSettings/fields/general.ts @@ -68,6 +68,17 @@ export const generalFields: Field[] = [ }, relationTo: 'media', }, + { + name: 'sameAs', + type: 'array', + admin: { + description: + 'Official profiles of this business (Google Business Profile, LinkedIn, Facebook, Wikipedia…). Tells search engines and AI which entity the site belongs to.', + initCollapsed: true, + }, + fields: [{ name: 'url', type: 'text', required: true, validate: (v: unknown) => (typeof v === 'string' && /^https?:\/\/\S+$/.test(v)) || 'Full URL, e.g. https://www.linkedin.com/company/acme' }], + labels: { plural: 'Profiles', singular: 'Profile' }, + }, { name: 'favicon', type: 'upload', diff --git a/src/index.ts b/src/index.ts index 74004e3..80d591b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -41,6 +41,7 @@ export { buildArchivePath, buildEntryPath, createMarkdownRenderer, + createMarkdownRoute, createSearchRoute, getArchiveEntries, listContent, @@ -93,6 +94,7 @@ export { required, } from './modules/forms/validators.js' export type { Rule } from './modules/forms/validators.js' +export type { PageJsonLdOptions } from './modules/frontend/createContentHelpers.js' export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js' @@ -143,13 +145,14 @@ export { SITE_INTEGRATIONS_SLUG, SITE_SETTINGS_SLUG, } from './modules/payload/index.js' + // Lexical → Markdown (pure, no React) — for AI-readable output. export { lexicalToMarkdown } from './modules/richtext/index.js' - export { buildSecurityHeaders } from './modules/security/index.js' export { buildCsp } from './modules/security/index.js' export type { BuildCspArgs } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' +export type { OgImage } from './modules/seo/buildMetadata.js' export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' export { buildHreflangAlternates, @@ -159,6 +162,16 @@ export { slugsAcrossLocales, } from './modules/seo/index.js' export type { SiteMetaConfig } from './modules/seo/index.js' +export { collectSiteIndex } from './modules/seo/index.js' +export { + buildIndexNowHook, + createIndexNowKeyRoute, + getIndexNowKey, + INDEXNOW_KEY_ENV, + INDEXNOW_KEY_PATH, + submitToIndexNow, +} from './modules/seo/index.js' +export type { CollectSiteIndexArgs, SiteIndexEntry } from './modules/seo/index.js' export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry } from './modules/seo/index.js' export { AI_ASSISTANT_BOTS, @@ -171,14 +184,14 @@ export { injectAutoFillMeta, } from './modules/seo/index.js' export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js' -export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js' +export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js' export { buildNoindexField } from './modules/seo/index.js' export { buildSpeakableJsonLd } from './modules/seo/index.js' export { buildSummaryField } from './modules/seo/index.js' -export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js' +export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js' // Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage. export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js' -export { buildArticleJsonLd } from './modules/seo/index.js' +export { buildArticleJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js' export { buildLlmsTxt } from './modules/seo/index.js' export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' diff --git a/src/modules/content/createMarkdownRenderer.ts b/src/modules/content/createMarkdownRenderer.ts index 55f762f..c16fc37 100644 --- a/src/modules/content/createMarkdownRenderer.ts +++ b/src/modules/content/createMarkdownRenderer.ts @@ -6,11 +6,21 @@ import { blocksToMarkdown } from './blocksToMarkdown.js' import { resolveRoute } from './resolveRoute.js' type CreateMarkdownRendererArgs = { + /** + * Absolute origin. With it the frontmatter carries `url:` — the canonical page + * address an assistant should cite (instead of the /md/… mirror). + */ + baseUrl?: string /** Pages collection. Default 'pages'. */ collection?: string + /** + * i18n config — only to know a single-locale site has no /{locale} prefix in + * its URLs (for `url:`). Omit on multilingual sites if you like. + */ + config?: { locales: readonly unknown[] } /** Archive-backed collections, same value as the plugin option (optional). */ content?: ContentOption - /** Prepend a YAML frontmatter block (title/description/locale). Default true. */ + /** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */ frontmatter?: boolean /** Field holding the block layout. Default 'layout'. */ layoutField?: string @@ -31,6 +41,7 @@ type DocShape = { [key: string]: unknown meta?: { description?: null | string } | null title?: null | string + updatedAt?: string } function yamlEscape(v: string): string { @@ -62,7 +73,9 @@ function yamlEscape(v: string): string { */ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) { const { + baseUrl, collection = 'pages', + config, content, frontmatter = true, layoutField = 'layout', @@ -92,6 +105,11 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) { const fm = ['---', `locale: ${locale}`] if (title) {fm.push(`title: ${yamlEscape(title)}`)} if (description) {fm.push(`description: ${yamlEscape(description)}`)} + if (baseUrl) { + const segments = config?.locales.length === 1 ? (slug ?? []) : [locale, ...(slug ?? [])] + fm.push(`url: ${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')) + } + if (typeof doc.updatedAt === 'string') {fm.push(`updated: ${doc.updatedAt.slice(0, 10)}`)} fm.push('---') parts.push(fm.join('\n')) } @@ -121,3 +139,39 @@ export function markdownResponse(md: null | string): Response { status: 200, }) } + +type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> } + +/** + * The whole Markdown route in one call — same options as createMarkdownRenderer + * plus `getCachedPayload`: + * + * // src/app/md/[locale]/[[...slug]]/route.ts + * import { createMarkdownRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * import { contentConfig } from '@/content.config' + * import { i18nConfig } from '@/i18n.config' + * export const dynamic = 'force-dynamic' + * export const { GET } = createMarkdownRoute({ getCachedPayload, content: contentConfig, + * config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL }) + * + * 404 for unknown/unpublished pages; a database error returns a generic 503 + * (details only in the server log). + */ +export function createMarkdownRoute( + args: { getCachedPayload: () => Promise } & CreateMarkdownRendererArgs, +): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise } { + const { getCachedPayload, ...rendererArgs } = args + const render = createMarkdownRenderer(rendererArgs) + return { + GET: async (_req, { params }) => { + try { + const { slug, locale } = await params + return markdownResponse(await render({ slug, locale, payload: await getCachedPayload() })) + } catch (err) { + console.warn('[ipal] createMarkdownRoute: render failed:', err) + return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 }) + } + }, + } +} diff --git a/src/modules/content/index.ts b/src/modules/content/index.ts index e25f313..387725d 100644 --- a/src/modules/content/index.ts +++ b/src/modules/content/index.ts @@ -1,6 +1,6 @@ export { buildArchiveFields } from './archiveFields.js' export { blocksToMarkdown } from './blocksToMarkdown.js' -export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js' +export { createMarkdownRenderer, createMarkdownRoute, markdownResponse } from './createMarkdownRenderer.js' export { createSearchRoute } from './createSearchRoute.js' export { getArchiveEntries } from './getArchiveEntries.js' export type { ArchiveEntries } from './getArchiveEntries.js' diff --git a/src/modules/forms/createSubmitAction.ts b/src/modules/forms/createSubmitAction.ts new file mode 100644 index 0000000..aae80ba --- /dev/null +++ b/src/modules/forms/createSubmitAction.ts @@ -0,0 +1,92 @@ +import 'server-only' +import type { BasePayload } from 'payload' + +import type { ClientIpOptions } from '../shared/rateLimit.js' +import type { SubmitFormArgs, SubmitFormResult } from './submitForm.js' + +import { getNotificationTexts } from '../notifications/getNotificationTexts.js' +import { resolveFormMessage } from '../notifications/resolveFormMessage.js' +import { clientIp } from '../shared/rateLimit.js' +import { HONEYPOT_FIELD, isHoneypotTripped } from './honeypot.js' +import { submitForm } from './submitForm.js' + +type CreateSubmitActionArgs = { + /** Optional: IP options (default IPAL_IP_HEADER env / clientIp defaults). */ + clientIp?: ClientIpOptions + getCachedPayload: () => Promise + /** + * `headers` from 'next/headers', INJECTED (the plugin never imports next/*, + * same pattern as NextResponse in createProxy). Called inside the action only. + */ + headers: () => Headers | Promise + /** Honeypot field name. Default HONEYPOT_FIELD. */ + honeypotField?: string +} & Pick + +export type SubmitActionResult = { + field?: string + /** Text for the visitor, from Notifications in this locale. */ + message: string + /** Why it failed — for the renderer to mark a field (`field`) or reset Turnstile. */ + reason?: Exclude['reason'] + success: boolean +} + +/** + * The one server action every panel form posts to — honeypot → client IP → + * submitForm (rate limit, Turnstile, schema validation, GDPR consent, storage) + * → the visitor message from Notifications in the page's locale. + * + * // src/app/(frontend)/[locale]/actions.ts + * 'use server' + * import { headers } from 'next/headers' + * import { createSubmitAction } from '@intecion/ipal-kit/server' + * import { getCachedPayload } from '@/lib/content' + * export const sendForm = createSubmitAction({ getCachedPayload, headers }) + * + * Signature matches the ipal-form FormRenderer: `sendForm(formId, locale, values, + * turnstileToken?)` — bind formId and locale in the block (`sendForm.bind(null, id, locale)`). + * A tripped honeypot gets a fake success and stores nothing. + */ +export function createSubmitAction({ + clientIp: ipOptions, + consentFieldName, + getCachedPayload, + headers, + honeypotField = HONEYPOT_FIELD, + maxPerMinute, + turnstileOnConfigError, +}: CreateSubmitActionArgs) { + return async function sendForm( + formId: string, + locale: string, + values: Record, + turnstileToken?: string, + ): Promise { + const payload = await getCachedPayload() + const texts = (await getNotificationTexts({ locale, payload })).form + const data = values && typeof values === 'object' ? values : {} + if (isHoneypotTripped(data, honeypotField)) {return { message: texts.success, success: true }} + const { [honeypotField]: _honeypot, ...fields } = data + + const ip = clientIp(await headers(), ipOptions) || undefined + const result = await submitForm({ + consentFieldName, + data: fields, + formId: String(formId), + ip, + maxPerMinute, + payload, + turnstileOnConfigError, + turnstileToken: typeof turnstileToken === 'string' ? turnstileToken.trim() || undefined : undefined, + }) + const message = resolveFormMessage(result, texts) + if (result.success) {return { message, success: true }} + return { + message, + reason: result.reason, + success: false, + ...('field' in result && result.field ? { field: result.field } : {}), + } + } +} diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index c83197d..5b04bbe 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -9,7 +9,8 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' -import { buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js' +import { buildWebPageJsonLd } from '../seo/buildWebPageJsonLd.js' +import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js' type CreateContentHelpersArgs = { /** @@ -38,6 +39,8 @@ type CreateContentHelpersArgs = { * (content.md). Indexable pages only. */ markdownAlternate?: boolean | string + /** Defaults for getPageJsonLd — each call can override them. */ + pageJsonLd?: PageJsonLdOptions /** Pages collection slug. Defaults to 'pages'. */ pagesSlug?: string /** @@ -48,6 +51,8 @@ type CreateContentHelpersArgs = { robots?: RobotsOptions /** SiteSettings global slug. Defaults to 'site-settings'. */ settingsSlug?: string + /** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */ + sitemapImages?: (doc: Record) => (null | string | undefined)[] /** * Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style, * header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML. @@ -55,6 +60,20 @@ type CreateContentHelpersArgs = { sitemapStyle?: false | SitemapStyleOptions } +export type PageJsonLdOptions = { + /** BreadcrumbList (home › archive › page) from the real route. Default true. */ + breadcrumbs?: boolean + /** schema.org type of archive entries. Default 'BlogPosting'. */ + entryType?: 'Article' | 'BlogPosting' | 'NewsArticle' + /** + * Q&A visible on this page (e.g. from its FAQ block) → FAQPage. The project + * knows its block shape, so it maps it: `(doc) => doc.layout…map(i => ({ question, answer }))`. + */ + faq?: (doc: Record) => { answer: string; question: string }[] + /** schema.org type of ordinary pages, per document (e.g. 'ContactPage'). Default 'WebPage'. */ + pageType?: (doc: Record) => string | undefined +} + /** * Bundles the per-request data helpers a frontend needs — the same cached * wrappers every project was writing by hand (getPayload, settings, locale @@ -87,9 +106,11 @@ export function createContentHelpers({ content, i18n, markdownAlternate, + pageJsonLd: pageJsonLdDefaults, pagesSlug = 'pages', robots: robotsOptions, settingsSlug = 'site-settings', + sitemapImages, sitemapStyle, }: CreateContentHelpersArgs) { const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '' @@ -175,6 +196,89 @@ export function createContentHelpers({ } } + /** + * Per-page structured data — WebPage (BlogPosting for archive entries) with + * language and dates, BreadcrumbList from the actual route, FAQPage when the + * project maps its FAQ block. Built from the same cached route and metadata + * as the page, so it can't disagree with canonical/title. Returns plain nodes + * — render them with next to the layout's + * WebSite/Organization, add your own, or drop any. + * + * // [[...slug]]/page.tsx + * + */ + const getPageJsonLd = async ( + locale: string, + segments: string[] | undefined, + options: PageJsonLdOptions = {}, + ): Promise[]> => { + const opts = { ...pageJsonLdDefaults, ...options } + const [meta, route, settings] = await Promise.all([ + generatePageMetadata(locale, segments), + resolveRoute(locale, segments ?? [], 1), + getSettings(locale) as Promise>, + ]) + const url = meta.alternates?.canonical + if (!route || !url || meta.robots?.index === false) {return []} + + const doc = route.doc + const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined) + const name = str(doc.title) ?? meta.title + const siteName = str(settings?.siteName) + const root = new URL(url) + const singleLocale = (i18n?.locales.length ?? 0) === 1 + const homeUrl = `${root.origin}${singleLocale ? '' : `/${locale}`}` + const image = meta.openGraph?.images?.[0]?.url + const nodes: (null | Record)[] = [] + + if (route.type === 'entry') { + nodes.push( + buildArticleJsonLd({ + type: opts.entryType ?? 'BlogPosting', + dateModified: str(doc.updatedAt), + datePublished: str(doc.publishedAt) ?? str(doc.createdAt), + description: meta.description, + headline: name, + image: image ? { url: image } : undefined, + publisherName: siteName, + url, + }), + ) + } else { + nodes.push( + buildWebPageJsonLd({ + name, + type: route.type === 'archive' ? 'CollectionPage' : (opts.pageType?.(doc) ?? 'WebPage'), + dateModified: str(doc.updatedAt), + description: meta.description, + image, + inLanguage: locale, + url, + websiteUrl: homeUrl, + }), + ) + } + + if (opts.breadcrumbs !== false && route.type !== 'home') { + const homepage = settings?.homepage as Record | undefined + const crumbs = [{ name: str(homepage?.title) ?? siteName ?? root.host, url: homeUrl }] + if (route.type === 'entry') { + const archiveName = str(route.archive.title) + if (archiveName) {crumbs.push({ name: archiveName, url: url.replace(/\/[^/]+$/, '') })} + } + crumbs.push({ name, url }) + nodes.push(buildBreadcrumbJsonLd(crumbs)) + } + + const faq = opts.faq?.(doc)?.filter((i) => i.question?.trim() && i.answer?.trim()) + if (faq?.length) {nodes.push(buildFaqJsonLd(faq))} + + // JsonLdGraph adds the @context once for the whole @graph. + return nodes + .filter((n): n is Record => Boolean(n)) + .map(({ '@context': _context, ...node }) => node) + } + /** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */ const getNotFoundPageId = cache(async (): Promise => { const payload = await getCachedPayload() @@ -259,6 +363,7 @@ export function createContentHelpers({ baseUrl: origin, config: i18n, content, + images: sitemapImages, pagesSlug, payload: await getCachedPayload(), settingsSlug, @@ -424,6 +529,7 @@ export function createContentHelpers({ getConfiguredLocales, getEntries, getNotFoundPage, + getPageJsonLd, getSettings, resolveRoute, robots, diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index d8e6910..9490e1a 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -4,9 +4,10 @@ import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' -import { createMarkdownRenderer, listContent, searchContent } from '../content/index.js' +import { createMarkdownRenderer, searchContent } from '../content/index.js' import { getDefaultLocale, isValidLocale } from '../i18n/index.js' import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js' +import { collectSiteIndex } from '../seo/siteIndex.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' /** @@ -103,7 +104,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit } const origin = baseUrl?.replace(/\/$/, '') ?? '' - const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug }) + const renderMarkdown = createMarkdownRenderer({ baseUrl: origin || undefined, collection, config, content, settingsSlug }) const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` } @@ -117,7 +118,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { { name: 'list_pages', description: - 'List all published pages of the site with title, URL and description — the table of contents. Fetch one with get_page.', + 'List all published pages and entries (e.g. blog posts) with title, URL and description — the table of contents. Fetch one with get_page.', inputSchema: { type: 'object', properties: { @@ -189,21 +190,26 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { async function runList(params: Record): Promise { const locale = pickLocale(params) - const limit = typeof params.limit === 'number' ? params.limit : 50 + const limit = Math.min(Math.max(Math.trunc(typeof params.limit === 'number' ? params.limit : 50) || 50, 1), 200) const payload = await getCachedPayload() - const meta = await siteMeta(payload, locale) - const results = await listContent({ + // Same index as llms.txt and the sitemap rules: pages AND archive entries (blog…). + const index = await collectSiteIndex({ baseUrl: origin, - collection, config, - homeSlug: meta?.homeSlug, - limit, - locale, + content, + locales: [locale], + pagesSlug: collection, payload, + settingsSlug, summaryField, }) - if (results.length === 0) {return 'No published pages.'} - return formatResults(results) + if (index.length === 0) {return 'No published pages.'} + const shown = index.slice(0, limit) + const lines = shown.map( + (e) => `- ${e.title} (${e.url})${e.description ? ` — ${e.description}` : ''}${e.collection === collection ? '' : ` [${e.collectionLabel}]`}`, + ) + if (index.length > shown.length) {lines.push(`… ${index.length - shown.length} more — raise limit (max 200) or use search_content.`)} + return lines.join('\n') } async function runSearch(params: Record): Promise { diff --git a/src/modules/security/buildCsp.ts b/src/modules/security/buildCsp.ts index bf23fad..c91b414 100644 --- a/src/modules/security/buildCsp.ts +++ b/src/modules/security/buildCsp.ts @@ -3,7 +3,7 @@ export type BuildCspArgs = { analytics?: boolean /** Extra sources per directive, merged with the built-ins. */ extra?: Partial> - /** Google Maps embeds — adds maps.google.com / *.gstatic.com. */ + /** Google Maps — embeds (iframe) and the Maps JavaScript API, full domain set. Google Fonts are allowed by default. */ googleMaps?: boolean /** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */ mode?: 'enforce' | 'report-only' @@ -96,9 +96,14 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } if (googleMaps) { - src['frame-src'].push('https://www.google.com', 'https://maps.google.com') - src['script-src'].push('https://maps.googleapis.com') - src['img-src'].push('https://maps.gstatic.com', 'https://*.googleapis.com') + // Embeds (iframe) and the Maps JavaScript API — the domain set from Google's + // CSP guide for Maps JS (tiles, markers, Street View images, fonts, workers). + const g = ['https://*.googleapis.com', 'https://*.gstatic.com', 'https://*.google.com', 'https://*.ggpht.com', 'https://*.googleusercontent.com'] + src['frame-src'].push('https://www.google.com', 'https://maps.google.com', 'https://*.google.com') + src['script-src'].push(...g) + src['img-src'].push(...g) + src['connect-src'].push('https://*.googleapis.com', 'https://*.google.com', 'https://*.gstatic.com', 'data:', 'blob:') + src['worker-src'].push('blob:') } // Merge caller extras. @@ -108,7 +113,7 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string const value = (Object.entries(src) as Array<[CspDirective, string[]]>) .filter(([, values]) => values.length > 0) - .map(([dir, values]) => `${dir} ${values.join(' ')}`) + .map(([dir, values]) => `${dir} ${[...new Set(values)].join(' ')}`) .join('; ') const key = mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' diff --git a/src/modules/seo/buildLlmsTxt.ts b/src/modules/seo/buildLlmsTxt.ts index 5eb2a12..8f9d647 100644 --- a/src/modules/seo/buildLlmsTxt.ts +++ b/src/modules/seo/buildLlmsTxt.ts @@ -1,14 +1,23 @@ import type { BasePayload } from 'payload' +import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' +import type { SiteIndexEntry } from './siteIndex.js' import { blocksToMarkdown } from '../content/blocksToMarkdown.js' -import { buildLocalizedPath } from '../i18n/index.js' +import { getLocaleDefinition, isValidLocale } from '../i18n/index.js' +import { collectSiteIndex } from './siteIndex.js' type BuildLlmsTxtArgs = { /** Absolute site URL (https://…). */ baseUrl: string config: I18nConfig + /** + * Archive-backed collections (same value as the plugin option). Their entries + * — blog posts, case studies, products — are listed too, grouped under the + * collection's own plural label. Usually the most quotable content on a site. + */ + content?: ContentOption /** * 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 @@ -18,7 +27,10 @@ type BuildLlmsTxtArgs = { full?: boolean /** Field holding the block layout (full mode only). Default 'layout'. */ layoutField?: string - /** Locale for names/descriptions. Defaults to config.defaultLocale. */ + /** + * One locale only. Default: every configured locale, each in its own + * section — an agent learns all language versions exist. + */ locale?: string /** Pages collection slug. Defaults to 'pages'. */ pagesSlug?: string @@ -37,15 +49,7 @@ type SettingsShape = { siteName?: null | string } -type PageRow = { - [key: string]: unknown - _status?: string - id: number | string - meta?: { description?: unknown; noindex?: boolean } | null - noindex?: boolean | null - slug?: unknown - title?: unknown -} +const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined) /** * Builds the body of /llms.txt — a Markdown file describing the site for AI @@ -53,32 +57,22 @@ type PageRow = { * buildSitemapEntries: the plugin already knows the site's name, description, * and pages, so it can generate this automatically. * - * Structure (llmstxt.org): H1 site name, a blockquote/summary, then a list of - * key pages as Markdown links with short descriptions. Agents read this to - * understand the site quickly without crawling everything. + * Structure (llmstxt.org): H1 site name, a blockquote summary, then — per + * language when the site has several — one list per collection (pages first, + * then archive collections such as a blog) of Markdown links with descriptions. + * Section names are the project's own locale and collection labels; the plugin + * adds no text of its own. * - * Wire it as a route that returns text/plain: + * // app/llms.txt/route.ts — use createLlmsTxtRoute (routeHandlers.ts) * - * // app/llms.txt/route.ts - * import { buildLlmsTxt } from '@intecion/ipal-kit' - * import { getCachedPayload } from '@/lib/content' - * import { i18nConfig } from '@/i18n.config' - * export const dynamic = 'force-dynamic' - * export async function GET() { - * const body = await buildLlmsTxt({ - * payload: await getCachedPayload(), - * config: i18nConfig, - * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, - * }) - * return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } }) - * } - * - * Data comes from the panel (siteName, siteDescription, pages) — nothing - * hardcoded. Skips drafts and noindex pages (same as the sitemap). + * Data comes from the panel (siteName, siteDescription, documents) — nothing + * hardcoded. Same rules as the sitemap (collectSiteIndex): drafts, noindex and + * error pages are skipped, the homepage collapses to the language root. */ export async function buildLlmsTxt({ baseUrl, config, + content, full = false, layoutField = 'layout', locale, @@ -87,89 +81,68 @@ export async function buildLlmsTxt({ settingsSlug = 'site-settings', summaryField, }: BuildLlmsTxtArgs): Promise { - const pickDescription = (raw: PageRow): string | undefined => { - 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 locales = locale && isValidLocale(locale, config) ? [locale] : config.locales.map((l) => l.code) + const headerLocale = locales.includes(config.defaultLocale) ? config.defaultLocale : locales[0] - const settings = (await payload.findGlobal({ - slug: settingsSlug as never, - depth: 0, - locale: loc as never, - })) as SettingsShape - - const name = settings.siteName?.trim() || 'Website' + let settings: SettingsShape = {} + try { + settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 0, locale: headerLocale as never })) as SettingsShape + } catch { + // fresh DB — header falls back to the host name + } + const name = settings.siteName?.trim() || new URL(origin || 'http://localhost').host const description = settings.siteDescription?.trim() - // NO where:{_status} filter — collections without drafts enabled don't - // register the _status field, and querying it throws - // "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 as never, + const index = await collectSiteIndex({ + baseUrl: origin, + config, + content, depth: full ? 1 : 0, - limit: 1000, - locale: loc as never, + locales, + pagesSlug, + payload, + settingsSlug, + summaryField, }) const lines: string[] = [`# ${name}`, ''] - if (description) { - lines.push(`> ${description}`, '') - } + if (description) {lines.push(`> ${description}`, '')} - if (full) { - // Full-content: each published page inlined as Markdown under its heading. - const sections: string[] = [] - for (const raw of result.docs as PageRow[]) { - if (raw._status && raw._status !== 'published') {continue} - if (raw.noindex || 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')) + const multi = locales.length > 1 + for (const loc of locales) { + const forLocale = index.filter((e) => e.locale === loc) + if (!forLocale.length) {continue} + if (multi) { + const def = getLocaleDefinition(loc, config) + lines.push(`## ${def?.label ?? loc} (${loc})`, '') } - if (sections.length > 0) {lines.push(sections.join('\n\n---\n\n'), '')} - return lines.join('\n') - } + const level = multi ? '###' : '##' - const pageLinks: string[] = [] - for (const raw of result.docs as PageRow[]) { - if (raw._status && raw._status !== 'published') {continue} - if (raw.noindex || raw.meta?.noindex) {continue} + // Group by collection, pages first (collectSiteIndex already orders them so). + const groups = new Map() + for (const e of forLocale) {groups.set(e.collection, [...(groups.get(e.collection) ?? []), e])} - 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 } }) - if (!path) {continue} - - const desc = pickDescription(raw) - const pageDesc = desc ? ` — ${desc}` : '' - pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`) - } - - if (pageLinks.length > 0) { - lines.push('## Strony', '', ...pageLinks, '') + for (const entries of groups.values()) { + lines.push(`${level} ${entries[0].collectionLabel}`, '') + if (full) { + const sections = entries.map((e) => { + const parts = [`${level}# ${e.title}`, e.url] + const updated = day(e.updatedAt) + if (updated) {parts.push(`Updated: ${updated}`)} + if (e.description) {parts.push(`_${e.description}_`)} + const body = blocksToMarkdown(e.doc[layoutField]) + if (body) {parts.push(body)} + return parts.join('\n\n') + }) + lines.push(sections.join('\n\n---\n\n'), '') + } else { + for (const e of entries) { + lines.push(`- [${e.title}](${e.url})${e.description ? `: ${e.description}` : ''}`) + } + lines.push('') + } + } } return lines.join('\n') diff --git a/src/modules/seo/buildLocalBusinessJsonLd.ts b/src/modules/seo/buildLocalBusinessJsonLd.ts index b608f4f..3851866 100644 --- a/src/modules/seo/buildLocalBusinessJsonLd.ts +++ b/src/modules/seo/buildLocalBusinessJsonLd.ts @@ -1,3 +1,5 @@ +import { formatOpeningHours } from './formatOpeningHours.js' + type MediaLike = { url?: null | string } | null | undefined type Address = { @@ -15,12 +17,18 @@ type LocalBusinessJsonLdArgs = { image?: MediaLike logo?: MediaLike name: string - /** Opening hours, e.g. ['Mo-Fr 08:00-18:00', 'Sa 09:00-14:00']. */ - openingHours?: string[] + /** + * Opening hours — schema.org strings (['Mo-Fr 08:00-18:00']) or the editor's + * own text in Polish/English/German ('Pn-Pt: 8-18, Sob: 9-14'); normalized by + * formatOpeningHours. Unreadable text is omitted, never emitted invalid. + */ + openingHours?: readonly string[] | string priceRange?: string // e.g. '$$' sameAs?: string[] /** Business phone, e.g. '+48 123 456 789'. */ telephone?: string + /** schema.org type for this business, e.g. 'LegalService', 'Dentist', 'HVACBusiness'. Default 'LocalBusiness'. */ + type?: string url: string } @@ -43,6 +51,7 @@ type LocalBusinessJsonLdArgs = { */ export function buildLocalBusinessJsonLd({ name, + type = 'LocalBusiness', address, geo, image, @@ -53,13 +62,14 @@ export function buildLocalBusinessJsonLd({ telephone, url, }: LocalBusinessJsonLdArgs) { + const hours = formatOpeningHours(openingHours) const logoUrl = logo?.url const imageUrl = image?.url ?? logoUrl return { name, '@context': 'https://schema.org', - '@type': 'LocalBusiness', + '@type': type, url, ...(telephone ? { telephone } : {}), ...(imageUrl ? { image: imageUrl.startsWith('http') ? imageUrl : `${url}${imageUrl}` } : {}), @@ -79,7 +89,7 @@ export function buildLocalBusinessJsonLd({ ...(geo ? { geo: { '@type': 'GeoCoordinates', latitude: geo.latitude, longitude: geo.longitude } } : {}), - ...(openingHours && openingHours.length > 0 ? { openingHours } : {}), + ...(hours.length > 0 ? { openingHours: hours } : {}), ...(priceRange ? { priceRange } : {}), ...(sameAs && sameAs.length > 0 ? { sameAs } : {}), } diff --git a/src/modules/seo/buildMetadata.ts b/src/modules/seo/buildMetadata.ts index 78c7900..922ebcb 100644 --- a/src/modules/seo/buildMetadata.ts +++ b/src/modules/seo/buildMetadata.ts @@ -10,6 +10,9 @@ import { buildHreflangAlternates } from './hreflang.js' * Subset of Next.js `Metadata` this helper produces. Kept local so the plugin * doesn't depend on `next` types; the shape is assignable to Next's Metadata. */ +/** Share image with its size and alt — lets X/LinkedIn/Facebook render the card without guessing. */ +export type OgImage = { alt?: string; height?: number; url: string; width?: number } + export type PageMetadata = { alternates?: { canonical?: string @@ -20,8 +23,11 @@ export type PageMetadata = { description?: string openGraph?: { description?: string - images?: { url: string }[] + images?: OgImage[] locale?: string + /** Article entries: ISO dates (og:article:published_time / modified_time). */ + modifiedTime?: string + publishedTime?: string /** Site/brand name for the OG card. */ siteName?: string title: string @@ -45,14 +51,28 @@ export type PageMetadata = { 'max-video-preview'?: number } title: string + /** X (Twitter) card — large image when there is one. */ + twitter?: { + card: 'summary' | 'summary_large_image' + description?: string + images?: string[] + title: string + } } type BuildMetadataArgs = { + /** + * Article dates for archive entries (blog posts…): og:type becomes 'article' + * with published/modified times — a freshness signal for search and AI. + */ + article?: { modifiedTime?: null | string; publishedTime?: null | string } /** Absolute site origin, e.g. 'https://example.com'. */ baseUrl?: string config: I18nConfig /** Home slug that collapses to the locale root. Defaults to 'home'. */ homeSlug?: Record | string + /** Resolved OG image with size/alt (wins over imageUrl). */ + image?: null | OgImage /** Resolved OG image URL (page image or site defaultShareImage). */ imageUrl?: null | string /** Current locale being rendered. */ @@ -113,9 +133,11 @@ type BuildMetadataArgs = { * in — the plugin composes, it doesn't fetch. */ export function buildMetadata({ + article, baseUrl, config, homeSlug = 'home', + image, imageUrl, locale, meta, @@ -152,7 +174,9 @@ export function buildMetadata({ } } - const images = imageUrl ? [{ url: imageUrl }] : undefined + const ogImage: null | OgImage = image?.url ? image : imageUrl ? { url: imageUrl } : null + const images = ogImage ? [ogImage] : undefined + const isArticle = Boolean(article?.publishedTime || article?.modifiedTime) return { title, @@ -165,10 +189,18 @@ export function buildMetadata({ title, ...(description && { description }), ...(images && { images }), - type: 'website', + type: isArticle ? 'article' : 'website', locale, ...(siteName ? { siteName } : {}), ...(canonical ? { url: canonical } : {}), + ...(article?.publishedTime ? { publishedTime: article.publishedTime } : {}), + ...(article?.modifiedTime ? { modifiedTime: article.modifiedTime } : {}), + }, + twitter: { + card: ogImage ? 'summary_large_image' : 'summary', + title, + ...(description && { description }), + ...(ogImage ? { images: [ogImage.url] } : {}), }, // robots: noindex pages are excluded (follow keeps link authority). Indexed // pages get generous snippet/preview limits so Google can show rich results diff --git a/src/modules/seo/buildOrganizationJsonLd.ts b/src/modules/seo/buildOrganizationJsonLd.ts index 7ecefc2..74ee618 100644 --- a/src/modules/seo/buildOrganizationJsonLd.ts +++ b/src/modules/seo/buildOrganizationJsonLd.ts @@ -42,3 +42,15 @@ export function buildOrganizationJsonLd({ name, logo, sameAs, url }: Organizatio ...(sameAs && sameAs.length > 0 ? { sameAs } : {}), } } + +/** + * Profile URLs from Site Settings → sameAs (array of { url }), ready for + * buildOrganizationJsonLd / buildLocalBusinessJsonLd. Empty when none. + */ +export function sameAsUrls(settings: null | Record | undefined): string[] { + const rows = settings?.sameAs + if (!Array.isArray(rows)) {return []} + return rows + .map((r) => (r && typeof r === 'object' ? (r as { url?: unknown }).url : undefined)) + .filter((u): u is string => typeof u === 'string' && /^https?:\/\//.test(u)) +} diff --git a/src/modules/seo/buildSiteNavigationJsonLd.ts b/src/modules/seo/buildSiteNavigationJsonLd.ts index b3b8110..6c68f1e 100644 --- a/src/modules/seo/buildSiteNavigationJsonLd.ts +++ b/src/modules/seo/buildSiteNavigationJsonLd.ts @@ -1,3 +1,8 @@ +import type { I18nConfig } from '../i18n/index.js' +import type { LinkValue } from '../links/resolveLinkHref.js' + +import { resolveLinkHref } from '../links/resolveLinkHref.js' + type NavItem = { /** Visible label (e.g. 'Usługi'). */ name: string @@ -37,3 +42,62 @@ export function buildSiteNavigationJsonLd(items: NavItem[]) { })), } } + +type NavSource = Record + +type BuildNavigationJsonLdArgs = { + /** Absolute origin, e.g. 'https://acme.pl'. */ + baseUrl: string + config: I18nConfig + /** Child items. Default `item.subItems`. Return [] to list top level only. */ + getChildren?: (item: NavSource) => unknown + /** Link of an item. Default `item.link` (ipal-nav template, buildLinkField). */ + getLink?: (item: NavSource) => LinkValue | null | undefined + /** Homepage slug(s) so the home link collapses to /{locale}. */ + homeSlug?: Record | string + /** Menu items straight from the header global (depth ≥ 1, so page links are populated). */ + items: null | readonly unknown[] | undefined + locale: string +} + +/** + * SiteNavigationElement list straight from the project's header global — + * resolves page links per locale (resolveLinkHref), keeps only links on this + * site (external and file links are skipped), de-duplicates, and labels each + * item with the link label from the panel. + * + * const nav = buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config: i18nConfig, homeSlug }) + * + */ +export function buildNavigationJsonLd({ + baseUrl, + config, + getChildren = (item) => item.subItems, + getLink = (item) => item.link as LinkValue | undefined, + homeSlug, + items, + locale, +}: BuildNavigationJsonLdArgs) { + const origin = baseUrl.replace(/\/$/, '') + const out: NavItem[] = [] + const seen = new Set() + const walk = (list: unknown) => { + if (!Array.isArray(list)) {return} + for (const raw of list) { + if (!raw || typeof raw !== 'object') {continue} + const item = raw as NavSource + const link = getLink(item) + if (link && link.type !== 'external' && link.type !== 'file') { + const href = resolveLinkHref(link, { config, homeSlug, locale }) + const name = typeof link.label === 'string' ? link.label.trim() : '' + if (href && name && href.startsWith('/') && !seen.has(href)) { + seen.add(href) + out.push({ name, url: `${origin}${href}` }) + } + } + walk(getChildren(item)) + } + } + walk(items) + return buildSiteNavigationJsonLd(out) +} diff --git a/src/modules/seo/buildSitemapEntries.ts b/src/modules/seo/buildSitemapEntries.ts index 63014dc..b1524f6 100644 --- a/src/modules/seo/buildSitemapEntries.ts +++ b/src/modules/seo/buildSitemapEntries.ts @@ -18,6 +18,8 @@ import { buildHreflangAlternates } from './hreflang.js' export type SitemapEntry = { alternates?: { languages: Record } changeFrequency?: 'always' | 'daily' | 'hourly' | 'monthly' | 'never' | 'weekly' | 'yearly' + /** Absolute image URLs on this page (Google Images). Next renders them as . */ + images?: string[] lastModified?: Date | string priority?: number url: string @@ -41,6 +43,12 @@ type BuildSitemapArgs = { * Read from System Pages when omitted. */ homeSlug?: Record | string + /** + * Images of a document for the sitemap (Google Images). Default: the SEO + * share image (meta.image). Return any URLs your blocks hold — the plugin + * doesn't assume a block shape. Relative URLs are made absolute. + */ + images?: (doc: Record) => (null | string | undefined)[] /** Pages collection slug. Defaults to 'pages'. */ pagesSlug?: string payload: BasePayload @@ -49,6 +57,7 @@ type BuildSitemapArgs = { } type DocRow = { + [key: string]: unknown _status?: string id: number | string meta?: { noindex?: boolean } | null @@ -103,6 +112,7 @@ function entryFor( homeSlug: Record | string | undefined, prefix: Record | undefined, changeFrequency: SitemapEntry['changeFrequency'], + images: string[], ): null | SitemapEntry { const slugs = doc.slug && typeof doc.slug === 'object' @@ -120,9 +130,16 @@ function entryFor( ...(doc.updatedAt ? { lastModified: doc.updatedAt } : {}), ...(changeFrequency ? { changeFrequency } : {}), ...(Object.keys(languages).length ? { alternates: { languages } } : {}), + ...(images.length ? { images } : {}), } } +/** Default image source: the SEO share image (plugin-seo meta.image, populated). */ +function defaultImages(doc: Record): (null | string | undefined)[] { + const image = (doc.meta as { image?: unknown } | null | undefined)?.image + return image && typeof image === 'object' ? [(image as { url?: string }).url] : [] +} + /** * Collects every public URL — pages and archive entries — as sitemap entries * with per-URL hreflang and lastmod. @@ -150,10 +167,14 @@ export async function buildSitemapEntries({ config, content, homeSlug, + images: imagesOf = defaultImages, pagesSlug = 'pages', payload, settingsSlug = 'site-settings', }: BuildSitemapArgs): Promise { + const origin = baseUrl.replace(/\/$/, '') + const absolute = (u: null | string | undefined): string | undefined => + !u ? undefined : /^https?:\/\//.test(u) ? u : `${origin}${u.startsWith('/') ? '' : '/'}${u}` const locales = config.locales.map((l) => l.code) const defaultLocale = config.defaultLocale @@ -194,7 +215,7 @@ export async function buildSitemapEntries({ // alternates without re-querying per locale. const result = await payload.find({ collection: collection.slug as never, - depth: 0, + depth: 1, // populate uploads so image URLs are available limit: 0, // no pagination — sitemap wants everything locale: 'all' as never, pagination: false as never, @@ -202,6 +223,7 @@ export async function buildSitemapEntries({ for (const raw of result.docs as DocRow[]) { if (!isIndexable(raw)) {continue} + const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))] // Emit a separate for EACH locale. Google's sitemap spec for // localized sites requires one per language version (each with its @@ -217,6 +239,7 @@ export async function buildSitemapEntries({ resolvedHomeSlug, collection.prefixSlugs, changeFrequency, + images, ) if (entry) {entries.push(entry)} } diff --git a/src/modules/seo/buildSitemapXml.ts b/src/modules/seo/buildSitemapXml.ts index d1eaaab..f4fa8a8 100644 --- a/src/modules/seo/buildSitemapXml.ts +++ b/src/modules/seo/buildSitemapXml.ts @@ -77,6 +77,9 @@ export function buildSitemapXml( } } } + for (const img of e.images ?? []) { + parts.push(` ${esc(img)}`) + } return ` \n${parts.join('\n')}\n ` }) .join('\n') @@ -87,7 +90,8 @@ export function buildSitemapXml( `\n` + stylesheet + `\n` + + `xmlns:xhtml="http://www.w3.org/1999/xhtml" ` + + `xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n` + urls + `\n` ) diff --git a/src/modules/seo/buildWebPageJsonLd.ts b/src/modules/seo/buildWebPageJsonLd.ts new file mode 100644 index 0000000..72c08fc --- /dev/null +++ b/src/modules/seo/buildWebPageJsonLd.ts @@ -0,0 +1,45 @@ +type WebPageJsonLdArgs = { + /** ISO date of the last change — a freshness signal for search and AI. */ + dateModified?: string + description?: string + /** Absolute URL of a representative image. */ + image?: string + /** BCP 47 language of the page, e.g. 'pl'. */ + inLanguage?: string + name: string + /** 'WebPage' (default), 'CollectionPage' (archive listing), 'AboutPage', 'ContactPage', 'FAQPage'… */ + type?: string + /** Absolute URL of the page (also its @id). */ + url: string + /** Absolute URL of the site root — links the page to the WebSite node. */ + websiteUrl?: string +} + +/** + * schema.org WebPage node for one page: name, description, language, last + * modification and the site it belongs to. Gives search engines and AI + * assistants explicit facts (what, which language, how fresh) instead of + * inferring them from HTML. Render through ; data from the panel. + */ +export function buildWebPageJsonLd({ + name, + type = 'WebPage', + dateModified, + description, + image, + inLanguage, + url, + websiteUrl, +}: WebPageJsonLdArgs) { + return { + name, + '@id': url, + '@type': type, + url, + ...(description ? { description } : {}), + ...(inLanguage ? { inLanguage } : {}), + ...(dateModified ? { dateModified } : {}), + ...(image ? { primaryImageOfPage: { '@type': 'ImageObject', url: image } } : {}), + ...(websiteUrl ? { isPartOf: { '@type': 'WebSite', url: websiteUrl } } : {}), + } +} diff --git a/src/modules/seo/createPageMetadata.ts b/src/modules/seo/createPageMetadata.ts index ab0808f..c11eda2 100644 --- a/src/modules/seo/createPageMetadata.ts +++ b/src/modules/seo/createPageMetadata.ts @@ -2,7 +2,7 @@ import type { BasePayload } from 'payload' import type { ContentOption, ResolvedRoute } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' -import type { PageMetadata } from './buildMetadata.js' +import type { OgImage, PageMetadata } from './buildMetadata.js' import type { SeoMeta } from './types.js' import { resolveRoute } from '../content/index.js' @@ -54,21 +54,33 @@ type PageMetadataContext = { } type DocShape = { + createdAt?: string id: number | string meta?: null | SeoMeta /** Top-level noindex checkbox (buildNoindexField) — the field that persists. */ noindex?: boolean | null + publishedAt?: null | string /** The document's own title (page name), used as the fallback page title. */ title?: null | string + updatedAt?: string } -/** plugin-seo stores the OG image as an upload relationship. */ -function resolveOgImage(doc: DocShape): null | string { - const image = (doc.meta as { image?: unknown } | null | undefined)?.image - if (image && typeof image === 'object' && 'url' in image) { - return (image as { url: string }).url ?? null +/** An upload relationship (populated) → OG image with its size and alt. */ +function toOgImage(image: unknown): null | OgImage { + if (!image || typeof image !== 'object') {return null} + const m = image as { alt?: unknown; height?: unknown; url?: unknown; width?: unknown } + if (typeof m.url !== 'string' || !m.url) {return null} + return { + url: m.url, + ...(typeof m.width === 'number' ? { width: m.width } : {}), + ...(typeof m.height === 'number' ? { height: m.height } : {}), + ...(typeof m.alt === 'string' && m.alt ? { alt: m.alt } : {}), } - return null +} + +/** plugin-seo stores the OG image on the meta group; Site Settings has the fallback. */ +function resolveOgImage(doc: DocShape, fallback: unknown): null | OgImage { + return toOgImage((doc.meta as { image?: unknown } | null | undefined)?.image) ?? toOgImage(fallback) } /** @@ -178,7 +190,10 @@ export function createPageMetadata(args: CreatePageMetadataArgs) { return buildMetadata({ ...base, - imageUrl: resolveOgImage(doc), + ...(route.type === 'entry' + ? { article: { modifiedTime: doc.updatedAt, publishedTime: doc.publishedAt ?? doc.createdAt } } + : {}), + image: resolveOgImage(doc, site.defaultShareImage), meta: doc.meta, noindex: doc.noindex, pageTitle: doc.title, diff --git a/src/modules/seo/formatOpeningHours.ts b/src/modules/seo/formatOpeningHours.ts new file mode 100644 index 0000000..aaf299e --- /dev/null +++ b/src/modules/seo/formatOpeningHours.ts @@ -0,0 +1,112 @@ +/** + * Turns opening hours as an editor types them into schema.org `openingHours` + * strings, so the panel field can stay human text in the site's language: + * + * formatOpeningHours('Pn-Pt: 08:00 - 17:00, Sob: 8-14, Nd: nieczynne') + * // → ['Mo-Fr 08:00-17:00', 'Sa 08:00-14:00'] + * formatOpeningHours('Mon, Wed, Fri 9:30–17') // → ['Mo,We,Fr 09:30-17:00'] + * formatOpeningHours('Mo–Fr 8–16 Uhr; Sa 9–12') // → ['Mo-Fr 08:00-16:00', 'Sa 09:00-12:00'] + * formatOpeningHours('całodobowo') // → ['Mo-Su 00:00-23:59'] + * + * Understands Polish, English and German day names and abbreviations (with or + * without diacritics and dots), ranges (`-`, `–`, `do`, `to`, `bis`), lists, + * `8`, `8:00`, `8.00`, closed days (skipped) and "24/7". Strings already in + * schema.org form pass through. Accepts one string or an array of lines. Anything + * it can't read is dropped rather than emitted invalid — check the result. + */ + +type Day = 'Fr' | 'Mo' | 'Sa' | 'Su' | 'Th' | 'Tu' | 'We' + +// Normalized (lowercase, no diacritics, no dots) day words → schema.org day. +// "so" is German Sonntag; Polish Saturday is "sob"/"sb"/"sobota". +const DAYS: Record = { + // pl + cz: 'Th', czw: 'Th', czwartek: 'Th', nd: 'Su', ndz: 'Su', niedz: 'Su', niedziela: 'Su', piat: 'Fr', piatek: 'Fr', + pn: 'Mo', pon: 'Mo', poniedzialek: 'Mo', pt: 'Fr', sb: 'Sa', sob: 'Sa', sobota: 'Sa', sr: 'We', sro: 'We', + sroda: 'We', wt: 'Tu', wto: 'Tu', wtorek: 'Tu', + // en + fr: 'Fr', fri: 'Fr', friday: 'Fr', mo: 'Mo', mon: 'Mo', monday: 'Mo', sa: 'Sa', sat: 'Sa', saturday: 'Sa', su: 'Su', + sun: 'Su', sunday: 'Su', th: 'Th', thu: 'Th', thur: 'Th', thurs: 'Th', thursday: 'Th', tu: 'Tu', + tue: 'Tu', tues: 'Tu', tuesday: 'Tu', we: 'We', wed: 'We', wednesday: 'We', + // de + di: 'Tu', dienstag: 'Tu', do: 'Th', donnerstag: 'Th', freitag: 'Fr', mi: 'We', mittwoch: 'We', montag: 'Mo', + samstag: 'Sa', so: 'Su', sonntag: 'Su', +} + +const CLOSED = /\b(?:nieczynne|nieczynny|zamkniete|zamkniety|closed|geschlossen|ruhetag)\b/g +const ALWAYS = /\b(?:calodobowo|cala doba|cala dobe|24\s*\/\s*7|24h|non-?stop|rund um die uhr|open 24 hours)\b/ +const TIME = /(?\d{1,2})(?:[:.](?\d{2}))?\s*(?:-|do|to|bis)\s*(?\d{1,2})(?:[:.](?\d{2}))?/g +const SCHEMA = /^(?:Mo|Tu|We|Th|Fr|Sa|Su)(?:[-,](?:Mo|Tu|We|Th|Fr|Sa|Su))*(?:\s+\d{2}:\d{2}-\d{2}:\d{2})?$/ + +function normalize(text: string): string { + return text + .toLowerCase() + .normalize('NFD') + .replace(/\p{M}/gu, '') // drop combining accents (ą → a) + .replace(/ł/g, 'l') + .replace(/[–—−]/g, '-') + .replace(/\./g, (m, i: number, s: string) => (/\d/.test(s[i - 1] ?? '') && /\d/.test(s[i + 1] ?? '') ? m : ' ')) + .replace(/\buhr\b/g, ' ') +} + +function hhmm(h: string, m?: string): null | string { + const hour = Number(h) + const minute = m ? Number(m) : 0 + if (hour > 24 || minute > 59) {return null} + return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` +} + +/** Day words in a fragment → "Mo-Fr" (range) or "Mo,We,Fr" (list). */ +function parseDays(fragment: string): null | string { + const days: Day[] = [] + let range = false + for (const w of fragment.match(/[a-z]+|-/g) ?? []) { + // "do" is both Polish "to" and German Donnerstag: a range word only right after the first day. + const rangeWord = w === '-' || w === 'to' || w === 'bis' || (w === 'do' && days.length === 1) + if (rangeWord) { + if (days.length === 1) {range = true} + continue + } + const day = DAYS[w] + if (day) {days.push(day)} + } + if (days.length === 0) {return null} + if (range && days.length === 2) {return `${days[0]}-${days[1]}`} + return [...new Set(days)].join(',') +} + +export function formatOpeningHours(input: null | readonly string[] | string | undefined): string[] { + if (!input) {return []} + const lines = (Array.isArray(input) ? input : [input as string]).map((l) => l.trim()).filter(Boolean) + if (lines.every((l) => SCHEMA.test(l))) {return [...lines]} + + const out: string[] = [] + for (const raw of lines) { + if (SCHEMA.test(raw)) { + out.push(raw) + continue + } + const text = normalize(raw) + if (ALWAYS.test(text)) { + out.push('Mo-Su 00:00-23:59') + continue + } + let last = 0 + for (const m of text.matchAll(TIME)) { + // The day spec is what precedes this time range — after the previous + // range, the last line break / semicolon, and any "closed" day. + let spec = text.slice(last, m.index) + last = (m.index ?? 0) + m[0].length + spec = spec.split(/[;\n]/).pop() ?? '' + const closedAt = [...spec.matchAll(CLOSED)].pop() + if (closedAt) {spec = spec.slice((closedAt.index ?? 0) + closedAt[0].length)} + const days = parseDays(spec) + const g = m.groups ?? {} + const from = hhmm(g.fromH, g.fromM) + const to = hhmm(g.toH, g.toM) + if (!days || !from || !to) {continue} + out.push(`${days} ${from}-${to === '24:00' ? '23:59' : to}`) + } + } + return out +} diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index 23bb361..f2d51a9 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -10,22 +10,32 @@ export { createManifestHandler } from './buildManifest.js' export { buildMetadata } from './buildMetadata.js' export type { PageMetadata } from './buildMetadata.js' export { buildNoindexField } from './buildNoindexField.js' -export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js' +export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js' export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js' export type { RobotsOptions, 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 { buildNavigationJsonLd, buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js' export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js' export { buildSummaryField } from './buildSummaryField.js' +export { buildWebPageJsonLd } from './buildWebPageJsonLd.js' export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js' export { composeTitle } from './composeTitle.js' export type { TitleOrder } from './composeTitle.js' export { createMetadataGenerator } from './createMetadataGenerator.js' export { createPageMetadata } from './createPageMetadata.js' +export { formatOpeningHours } from './formatOpeningHours.js' export { buildHreflangAlternates } from './hreflang.js' +export { + buildIndexNowHook, + createIndexNowKeyRoute, + getIndexNowKey, + INDEXNOW_KEY_ENV, + INDEXNOW_KEY_PATH, + submitToIndexNow, +} from './indexNow.js' export { injectAutoFillMeta } from './injectAutoFillMeta.js' export { injectSeoTabs } from './injectSeoTabs.js' export { JsonLdGraph } from './JsonLdGraph.js' @@ -34,6 +44,8 @@ export type { SiteMetaConfig } from './readSiteMetaConfig.js' export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js' export type { SitemapRouteOptions } from './routeHandlers.js' export { buildSeoPlugin } from './seoPluginConfig.js' +export { collectSiteIndex } from './siteIndex.js' +export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js' export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js' export type { SitemapStyleOptions } from './sitemapStyle.js' export { slugsAcrossLocales } from './slugsAcrossLocales.js' diff --git a/src/modules/seo/indexNow.ts b/src/modules/seo/indexNow.ts new file mode 100644 index 0000000..156507f --- /dev/null +++ b/src/modules/seo/indexNow.ts @@ -0,0 +1,183 @@ +import type { BasePayload, CollectionAfterChangeHook, Field } from 'payload' + +import type { I18nConfig } from '../i18n/index.js' + +import { archiveFieldName } from '../content/types.js' +import { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs } from '../i18n/index.js' + +/** + * IndexNow — tell search engines a URL changed the moment it's published + * (Bing, Yandex, Seznam, Naver… share submissions). Bing's index feeds ChatGPT + * Search and Copilot, so new content reaches AI answers in minutes instead of + * waiting for a crawl. Google doesn't use IndexNow (it reads the sitemap). + * + * Opt-in: `ipalKit({ indexNow: true })` adds the hook to the pages and content + * collections; or add `buildIndexNowHook(…)` yourself. Needs the key file route + * (createIndexNowKeyRoute) and a key: Site Integrations → IndexNow (generated on + * the first save) or the INDEXNOW_KEY env var. Sends only from production with + * a public NEXT_PUBLIC_SERVER_URL; never blocks or fails a save. + */ + +export const INDEXNOW_KEY_ENV = 'INDEXNOW_KEY' +export const INDEXNOW_KEY_PATH = '/indexnow-key.txt' +const ENDPOINT = 'https://api.indexnow.org/indexnow' +const KEY_FIELD = 'indexNowKey' +const SITE_INTEGRATIONS = 'site-integrations' + +/** Site Integrations field holding the key — generated when empty. */ +export const indexNowFields: Field[] = [ + { + name: KEY_FIELD, + type: 'text', + admin: { + description: + 'Key that proves this site owns its URLs to IndexNow (Bing, ChatGPT Search). Generated automatically — change only to rotate it.', + }, + hooks: { + beforeChange: [ + ({ value }) => (typeof value === 'string' && value.trim() ? value.trim() : randomKey()), + ], + }, + }, +] + +function randomKey(): string { + const bytes = new Uint8Array(16) + globalThis.crypto.getRandomValues(bytes) + return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') +} + +/** The IndexNow key: env first, then Site Integrations. Empty string when none. */ +export async function getIndexNowKey(payload: BasePayload): Promise { + const fromEnv = process.env[INDEXNOW_KEY_ENV]?.trim() + if (fromEnv) {return fromEnv} + try { + const doc = (await payload.findGlobal({ slug: SITE_INTEGRATIONS as never, depth: 0 })) as Record + return typeof doc[KEY_FIELD] === 'string' ? (doc[KEY_FIELD]).trim() : '' + } catch { + return '' + } +} + +/** + * Route serving the key file IndexNow fetches to verify ownership: + * + * // src/app/indexnow-key.txt/route.ts + * import { createIndexNowKeyRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * export const dynamic = 'force-dynamic' + * export const GET = createIndexNowKeyRoute({ getCachedPayload }) + */ +export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: () => Promise }) { + return async (): Promise => { + const key = await getIndexNowKey(await getCachedPayload()) + if (!key) {return new Response('Not found', { status: 404 })} + return new Response(key, { headers: { 'cache-control': 'public, max-age=3600', 'content-type': 'text/plain; charset=utf-8' } }) + } +} + +/** True when submissions may leave this machine: production + a public https origin. */ +function publicOrigin(baseUrl?: string): null | string { + const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '') + if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null} + if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null} + return origin +} + +/** POST a batch of URLs to IndexNow. Never throws; logs a warning on failure. */ +export async function submitToIndexNow({ + baseUrl, + payload, + urls, +}: { + baseUrl?: string + payload: BasePayload + urls: string[] +}): Promise { + const origin = publicOrigin(baseUrl) + if (!origin || urls.length === 0) {return false} + const key = await getIndexNowKey(payload) + if (!key) {return false} + try { + const res = await fetch(ENDPOINT, { + body: JSON.stringify({ host: new URL(origin).host, key, keyLocation: `${origin}${INDEXNOW_KEY_PATH}`, urlList: urls.slice(0, 10_000) }), + headers: { 'content-type': 'application/json; charset=utf-8' }, + method: 'POST', + signal: AbortSignal.timeout(8000), + }) + // 200 = accepted, 202 = accepted, key validation pending. + if (res.status !== 200 && res.status !== 202) { + console.warn(`[ipal] IndexNow: ${res.status} for ${urls.length} URL(s) — check the key file at ${origin}${INDEXNOW_KEY_PATH}`) + return false + } + return true + } catch (err) { + console.warn('[ipal] IndexNow: request failed:', err instanceof Error ? err.message : err) + return false + } +} + +type BuildIndexNowHookArgs = { + /** Absolute origin. Default NEXT_PUBLIC_SERVER_URL. */ + baseUrl?: string + config: I18nConfig + /** + * Set for an archive-backed collection (blog…): its archive page in Site + * Settings gives the URL prefix. Omit for the pages collection. + */ + contentCollection?: string + /** SiteSettings global. Default 'site-settings'. */ + settingsSlug?: string +} + +/** Builds a locale→slug map from a populated relationship read with locale 'all'. */ +function slugsOf(rel: unknown, config: I18nConfig): Record | undefined { + if (!rel || typeof rel !== 'object') {return undefined} + const slug = (rel as { slug?: unknown }).slug + const map = getLocalizedSlugs({ config, slugField: slug && typeof slug === 'object' ? (slug as Record) : undefined }) + return Object.keys(map).length ? map : undefined +} + +/** + * afterChange hook: when a document is published (or a published one changes), + * submits its URL in every language to IndexNow. Drafts, noindex documents and + * non-production environments send nothing. Runs in the background — the save + * never waits for or fails on IndexNow. + */ +export function buildIndexNowHook({ + baseUrl, + config, + contentCollection, + settingsSlug = 'site-settings', +}: BuildIndexNowHookArgs): CollectionAfterChangeHook { + return ({ collection, context, doc, req }) => { + if (context?.ipalSkipIndexNow) {return doc} + const row = doc as { _status?: string; id: number | string; meta?: { noindex?: boolean } | null; noindex?: boolean | null } + if ((row._status && row._status !== 'published') || row.noindex || row.meta?.noindex) {return doc} + if (!publicOrigin(baseUrl)) {return doc} + + const run = async () => { + const all = (await req.payload.findByID({ id: row.id, collection: collection.slug as never, depth: 0, locale: 'all' as never })) as { + slug?: Record | string + } + const slugs = + typeof all.slug === 'string' + ? Object.fromEntries(getLocaleCodes(config).map((l) => [l, all.slug as string])) + : getLocalizedSlugs({ config, slugField: all.slug }) + const settings = (await req.payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })) as Record + const homeSlug = slugsOf(settings.homepage, config) ?? 'home' + const prefix = contentCollection ? slugsOf(settings[archiveFieldName(contentCollection)], config) : undefined + if (contentCollection && !prefix) {return} + + const origin = publicOrigin(baseUrl)! + const urls = getLocaleCodes(config) + .map((locale) => buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })) + .filter((p): p is string => Boolean(p)) + .map((p) => `${origin}${p}`) + await submitToIndexNow({ baseUrl: origin, payload: req.payload, urls }) + } + // Background: never block or fail the save. + void run().catch((err: unknown) => console.warn('[ipal] IndexNow hook failed:', err instanceof Error ? err.message : err)) + return doc + } +} diff --git a/src/modules/seo/readSiteMetaConfig.ts b/src/modules/seo/readSiteMetaConfig.ts index a11148d..2086b25 100644 --- a/src/modules/seo/readSiteMetaConfig.ts +++ b/src/modules/seo/readSiteMetaConfig.ts @@ -10,6 +10,8 @@ type SettingsShape = { } export type SiteMetaConfig = { + /** Site Settings → defaultShareImage (populated upload), used when a page has no OG image. */ + defaultShareImage?: null | Record /** * Home slug per locale, e.g. { pl: 'strona-glowna', de: 'startseite' }. A map * (not a single string) so multilingual homepages collapse to root in EVERY @@ -99,7 +101,9 @@ export async function readSiteMetaConfig({ homeSlug = { [locale]: homepage.slug } } + const share = settings.defaultShareImage return { + defaultShareImage: share && typeof share === 'object' ? (share as Record) : null, siteDescription: (settings.siteDescription as string | undefined) ?? null, siteName: (settings[siteNameField] as string | undefined) ?? null, // The panel stores '|'; titles need it padded. diff --git a/src/modules/seo/routeHandlers.ts b/src/modules/seo/routeHandlers.ts index 7d801da..6b0f86a 100644 --- a/src/modules/seo/routeHandlers.ts +++ b/src/modules/seo/routeHandlers.ts @@ -1,5 +1,6 @@ import type { BasePayload } from 'payload' +import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { SitemapEntry } from './buildSitemapEntries.js' @@ -29,6 +30,8 @@ import { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from ' export function createLlmsTxtRoute(opts: { baseUrl: string config: I18nConfig + /** Archive-backed collections (blog…) — listed too. Same value as the plugin option. */ + content?: ContentOption /** Inline every page's full Markdown (llms-full.txt). Default false. */ full?: boolean getCachedPayload: () => Promise @@ -43,6 +46,7 @@ export function createLlmsTxtRoute(opts: { const body = await buildLlmsTxt({ baseUrl: opts.baseUrl, config: opts.config, + content: opts.content, full: opts.full, pagesSlug: opts.pagesSlug, payload, diff --git a/src/modules/seo/siteIndex.ts b/src/modules/seo/siteIndex.ts new file mode 100644 index 0000000..a724364 --- /dev/null +++ b/src/modules/seo/siteIndex.ts @@ -0,0 +1,167 @@ +import type { BasePayload } from 'payload' + +import type { ContentOption } from '../content/index.js' +import type { I18nConfig } from '../i18n/index.js' + +import { archiveFieldName } from '../content/index.js' +import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js' +import { resolveLocalized } from '../i18n/resolveLocalized.js' + +/** One public, indexable document in one language. */ +export type SiteIndexEntry = { + /** Collection slug, e.g. 'pages', 'posts'. */ + collection: string + /** Plural label of the collection in this locale (from the project's config), e.g. 'Pages'. */ + collectionLabel: string + createdAt?: string + /** Summary field (when configured and filled) or meta.description. */ + description?: string + /** The raw document in this locale — for callers that render content (llms-full). */ + doc: Record + id: number | string + locale: string + /** Locale-aware path, e.g. /pl/blog/moj-wpis. */ + path: string + /** publishedAt when the collection has it (setPublishedAt hook). */ + publishedAt?: string + title: string + updatedAt?: string + /** Absolute URL (path prefixed with baseUrl). */ + url: string +} + +export type CollectSiteIndexArgs = { + /** Absolute origin; omit for relative URLs. */ + baseUrl?: string + config: I18nConfig + /** Archive-backed collections, same value as the plugin option — their entries are included. */ + content?: ContentOption + /** Population depth of `doc`. Default 0 (1 when you render blocks with images). */ + depth?: number + /** Max documents per collection and locale. Default 1000. */ + limit?: number + /** Only these locales. Default: every configured locale. */ + locales?: string[] + /** Pages collection. Default 'pages'. */ + pagesSlug?: string + payload: BasePayload + /** SiteSettings global. Default 'site-settings'. */ + settingsSlug?: string + /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ + summaryField?: string +} + +type Row = { + [key: string]: unknown + _status?: string + createdAt?: string + id: number | string + meta?: { description?: unknown; noindex?: boolean } | null + noindex?: boolean | null + publishedAt?: unknown + slug?: unknown + title?: unknown + updatedAt?: string +} + +/** Same exclusions as the sitemap: error/system pages that exist as documents. */ +const EXCLUDED_SLUGS = new Set(['404', '500', 'error', 'not-found']) + +function slugMap(rel: unknown, locales: string[]): Record | undefined { + if (!rel || typeof rel !== 'object') {return undefined} + const slug = (rel as { slug?: unknown }).slug + if (typeof slug === 'string') {return Object.fromEntries(locales.map((l) => [l, slug]))} + if (!slug || typeof slug !== 'object') {return undefined} + const map: Record = {} + for (const l of locales) { + const v = (slug as Record)[l] + if (typeof v === 'string') {map[l] = v} + } + return Object.keys(map).length ? map : undefined +} + +/** + * Every public page and archive entry, per language, with its URL, title, + * description and dates — ONE source for everything that lists the site to + * machines: llms.txt / llms-full.txt, the MCP server's list_pages, IndexNow. + * Uses the same rules as the sitemap (published only, no noindex, no 404/500 + * pages, archive prefixes and homepage from System Pages), so all of them + * agree with what the site actually serves. + * + * Never throws for a missing field: a collection that can't be read is skipped. + */ +export async function collectSiteIndex({ + baseUrl, + config, + content, + depth = 0, + limit = 1000, + locales, + pagesSlug = 'pages', + payload, + settingsSlug = 'site-settings', + summaryField, +}: CollectSiteIndexArgs): Promise { + const all = getLocaleCodes(config) + const wanted = (locales ?? all).filter((l) => isValidLocale(l, config)) + const origin = baseUrl?.replace(/\/$/, '') ?? '' + + let settings: Record = {} + try { + settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })) as Record + } catch { + // no settings yet (fresh DB) — no homepage/archives, plain paths + } + const homeSlug = slugMap(settings.homepage, all) ?? 'home' + + const collections: { prefix?: Record; slug: string }[] = [{ slug: pagesSlug }] + for (const c of content?.collections ?? []) { + const prefix = slugMap(settings[archiveFieldName(c.slug)], all) + collections.push({ slug: c.slug, prefix }) + } + + const entries: SiteIndexEntry[] = [] + for (const locale of wanted) { + for (const { slug: collection, prefix } of collections) { + // An archive collection without an archive page in this locale has no URLs there. + if (collection !== pagesSlug && !prefix?.[locale]) {continue} + let docs: Row[] = [] + try { + const res = await payload.find({ collection: collection as never, depth, limit, locale: locale as never }) + docs = (res?.docs ?? []) as Row[] + } catch { + continue + } + const labels = payload.collections?.[collection as never]?.config?.labels as { plural?: unknown } | undefined + const collectionLabel = resolveLocalized(labels?.plural, locale, collection) + + for (const doc of docs) { + if (doc._status && doc._status !== 'published') {continue} + if (doc.noindex || doc.meta?.noindex) {continue} + const title = typeof doc.title === 'string' ? doc.title.trim() : '' + const slug = typeof doc.slug === 'string' ? doc.slug : '' + if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue} + const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs: { [locale]: slug } }) + if (!path) {continue} + const summary = summaryField && typeof doc[summaryField] === 'string' ? (doc[summaryField]).trim() : '' + const metaDescription = typeof doc.meta?.description === 'string' ? doc.meta.description.trim() : '' + const description = summary || metaDescription + entries.push({ + id: doc.id, + collection, + collectionLabel, + doc, + locale, + path, + title, + url: `${origin}${path}`, + ...(description ? { description } : {}), + ...(typeof doc.createdAt === 'string' ? { createdAt: doc.createdAt } : {}), + ...(typeof doc.updatedAt === 'string' ? { updatedAt: doc.updatedAt } : {}), + ...(typeof doc.publishedAt === 'string' ? { publishedAt: doc.publishedAt } : {}), + }) + } + } + } + return entries +} diff --git a/src/plugin.ts b/src/plugin.ts index d864580..211759f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -13,6 +13,7 @@ import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' +import { buildIndexNowHook } from './modules/seo/indexNow.js' /** * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3. @@ -49,6 +50,23 @@ export const ipalKit = (options: IpalOptions): Plugin => { let config = { ...incomingConfig } + // --- auth collection: Payload adds its default `users` only AFTER plugins + // run (config sanitize), so roles and 2FA would have nothing to attach to, + // and a project without it crashes ("users is not a valid admin user + // collection"). Inject a plain auth collection when the project defines + // none — a project's own collection with that slug always wins. + const authSlug = + options.access?.authCollection ?? + (options.twoFactor ? options.twoFactor.collectionSlug : undefined) ?? + config.admin?.user ?? + 'users' + if (!(config.collections ?? []).some((c) => c.slug === authSlug)) { + config.collections = [ + ...(config.collections ?? []), + { slug: authSlug, admin: { useAsTitle: 'email' }, auth: true, fields: [] }, + ] + } + // --- custom admin route (e.g. '/its' instead of '/admin') --- // Sets config.routes.admin; the project must move its app/(payload)// // folder to match (plugin can't create files in the project's app/). @@ -202,6 +220,24 @@ export const ipalKit = (options: IpalOptions): Plugin => { config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] + // --- IndexNow: submit published URLs (opt-in) --- + if (options.indexNow) { + const pagesSlug = options.pages?.slug ?? 'pages' + const contentSlugs = new Set((options.content?.collections ?? []).map((c) => c.slug)) + config.collections = (config.collections ?? []).map((collection) => { + const isPages = collection.slug === pagesSlug + if (!isPages && !contentSlugs.has(collection.slug)) {return collection} + const hook = buildIndexNowHook({ + config: options.i18n, + ...(isPages ? {} : { contentCollection: collection.slug }), + }) + return { + ...collection, + hooks: { ...collection.hooks, afterChange: [...(collection.hooks?.afterChange ?? []), hook] }, + } + }) + } + // --- integration alerts on the dashboard (Turnstile status, …) --- // Renders nothing while everything works; never throws. config.admin = { diff --git a/src/types.ts b/src/types.ts index ca6a316..d1eb4c2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -59,9 +59,17 @@ export type IpalOptions = { */ forms?: FormsOption - /** Internationalization — locales, default locale, fallback behavior */ i18n: I18nConfig + /** Internationalization — locales, default locale, fallback behavior */ + /** + * IndexNow (seo/indexNow.ts): on publish, submit the page's URLs in every + * language to Bing & co. (feeds ChatGPT Search / Copilot). Adds the hook to the + * pages collection and every `content` collection. Production only. Needs the + * key file route createIndexNowKeyRoute. Default false. + */ + indexNow?: boolean + /** Additional fields injected into SiteIntegrations global */ integrationsFields?: Field[] diff --git a/test/exports.test.ts b/test/exports.test.ts new file mode 100644 index 0000000..aff4825 --- /dev/null +++ b/test/exports.test.ts @@ -0,0 +1,37 @@ +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +const root = path.resolve(import.meta.dirname, '..') +const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')) as { exports: Record } + +function files(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const p = path.join(dir, name) + return statSync(p).isDirectory() ? files(p) : /\.(?:md|ts|tsx|mjs)$/.test(name) ? [p] : [] + }) +} + +describe('package exports', () => { + test('every @intecion/ipal-kit/ used in docs and src is exported', () => { + const used = new Map() + for (const file of [...files(path.join(root, 'docs')), ...files(path.join(root, 'src'))]) { + for (const m of readFileSync(file, 'utf8').matchAll(/@intecion\/ipal-kit(?\/[a-z0-9./-]+)?(?=['"#\s`)])/g)) { + const sub = m.groups?.sub ? `.${m.groups.sub}` : '.' + // node_modules/@intecion/ipal-kit/dist|docs|package.json — filesystem paths in prose, not imports + if (/^\.\/(?:dist|docs|package\.json)(?:\/|$)/.test(sub)) {continue} + if (!used.has(sub)) {used.set(sub, path.relative(root, file))} + } + } + const missing = [...used].filter(([sub]) => !(sub in pkg.exports)).map(([sub, file]) => `${sub} (e.g. ${file})`) + expect(missing).toEqual([]) + }) + + test('every export points at a file the build produces from src', () => { + for (const [sub, target] of Object.entries(pkg.exports)) { + const out = typeof target === 'string' ? target : (target as { import: string }).import + const src = out.replace('./dist/', 'src/').replace(/\.js$/, '.ts') + expect(existsSync(path.join(root, src)) || existsSync(path.join(root, src.replace(/\.ts$/, '.tsx'))), `${sub} → ${src}`).toBe(true) + } + }) +}) diff --git a/test/indexNow.test.ts b/test/indexNow.test.ts new file mode 100644 index 0000000..ba9def3 --- /dev/null +++ b/test/indexNow.test.ts @@ -0,0 +1,95 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +import type { I18nConfig } from '../src/modules/i18n/types.js' + +import { buildIndexNowHook, createIndexNowKeyRoute, indexNowFields } from '../src/modules/seo/indexNow.js' + +const config: I18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} + +function fakeReq(doc: Record, settings: Record) { + return { + payload: { + findByID: vi.fn(async () => doc), + findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-integrations' ? { indexNowKey: 'k123' } : settings)), + }, + } +} + +const flush = () => new Promise((r) => setTimeout(r, 0)) + +describe('IndexNow hook', () => { + let fetchSpy: ReturnType + beforeEach(() => { + fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 })) + vi.stubEnv('NODE_ENV', 'production') + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl') + }) + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + }) + + const run = async (row: Record, opts = {}, settings: Record = {}) => { + const req = fakeReq({ slug: { en: 'about', pl: 'o-nas' } }, settings) + const hook = buildIndexNowHook({ config, ...opts }) + await hook({ collection: { slug: 'pages' }, context: {}, doc: { id: 1, ...row }, req } as never) + await flush() + await flush() + } + + test('published page → every language submitted with key and keyLocation', async () => { + await run({ _status: 'published' }) + expect(fetchSpy).toHaveBeenCalledOnce() + const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string) + expect(body).toEqual({ + host: 'acme.pl', + key: 'k123', + keyLocation: 'https://acme.pl/indexnow-key.txt', + urlList: ['https://acme.pl/pl/o-nas', 'https://acme.pl/en/about'], + }) + }) + + test('archive entry gets the archive prefix; no archive page → nothing sent', async () => { + await run({}, { contentCollection: 'posts' }, { postsArchive: { slug: { en: 'blog', pl: 'blog-pl' } } }) + const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string) + expect(body.urlList).toEqual(['https://acme.pl/pl/blog-pl/o-nas', 'https://acme.pl/en/blog/about']) + fetchSpy.mockClear() + await run({}, { contentCollection: 'posts' }, {}) + expect(fetchSpy).not.toHaveBeenCalled() + }) + + test('drafts, noindex, dev and localhost send nothing', async () => { + await run({ _status: 'draft' }) + await run({ noindex: true }) + vi.stubEnv('NODE_ENV', 'development') + await run({}) + vi.stubEnv('NODE_ENV', 'production') + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'http://localhost:3000') + await run({}) + expect(fetchSpy).not.toHaveBeenCalled() + }) +}) + +describe('IndexNow key', () => { + afterEach(() => vi.unstubAllEnvs()) + + test('field generates a 32-char key when empty and keeps an existing one', () => { + const hook = (indexNowFields[0] as { hooks: { beforeChange: ((a: { value: unknown }) => string)[] } }).hooks.beforeChange[0] + expect(hook({ value: '' })).toMatch(/^[0-9a-f]{32}$/) + expect(hook({ value: ' mine ' })).toBe('mine') + }) + + test('key route: env wins, 404 without a key', async () => { + const payload = { findGlobal: async () => ({}) } as never + expect((await createIndexNowKeyRoute({ getCachedPayload: async () => payload })()).status).toBe(404) + vi.stubEnv('INDEXNOW_KEY', 'fromenv') + const res = await createIndexNowKeyRoute({ getCachedPayload: async () => payload })() + expect(await res.text()).toBe('fromenv') + }) +}) diff --git a/test/integration.test.ts b/test/integration.test.ts index cffd21f..a6bf889 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -156,3 +156,21 @@ describe('generatePageMetadata — markdownAlternate', () => { expect((await off.generatePageMetadata('pl', ['o-nas'])).alternates?.types).toBeUndefined() }) }) + +describe('getPageJsonLd', () => { + const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const + + test('WebPage + breadcrumbs from the real route, FAQ when mapped, no @context per node', async () => { + await payload.create({ collection: 'pages' as never, data: { slug: 'kontakt', title: 'Kontakt' } as never }) + const h = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) + const nodes = await h.getPageJsonLd('pl', ['kontakt'], { + faq: () => [{ answer: 'Tak.', question: 'Czy dojeżdżacie?' }, { answer: '', question: 'puste' }], + pageType: () => 'ContactPage', + }) + expect(nodes.map((n) => n['@type'])).toEqual(['ContactPage', 'BreadcrumbList', 'FAQPage']) + expect(nodes[0]).toMatchObject({ name: 'Kontakt', '@id': 'https://acme.pl/kontakt', inLanguage: 'pl' }) + expect(nodes.every((n) => !('@context' in n))).toBe(true) + expect((nodes[2] as { mainEntity: unknown[] }).mainEntity).toHaveLength(1) + expect(await h.getPageJsonLd('pl', ['nie-ma'])).toEqual([]) + }) +}) diff --git a/test/openingHours.test.ts b/test/openingHours.test.ts new file mode 100644 index 0000000..1c6180d --- /dev/null +++ b/test/openingHours.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from 'vitest' + +import { formatOpeningHours } from '../src/modules/seo/formatOpeningHours.js' + +describe('formatOpeningHours', () => { + test.each([ + ['Pn-Pt: 08:00 - 17:00, Sob: 08:00 - 14:00', ['Mo-Fr 08:00-17:00', 'Sa 08:00-14:00']], + ['Pn–Pt 8–17, Sob: 8-14, Nd: nieczynne', ['Mo-Fr 08:00-17:00', 'Sa 08:00-14:00']], + ['Poniedziałek - Piątek: 9.30 - 17.30\nSobota: 10-14\nNiedziela: zamknięte', ['Mo-Fr 09:30-17:30', 'Sa 10:00-14:00']], + ['Pn do Pt 8:00 do 16:00', ['Mo-Fr 08:00-16:00']], + ['Sob: nieczynne, Nd 10-14', ['Su 10:00-14:00']], + ['Pn, Śr, Pt 9-17', ['Mo,We,Fr 09:00-17:00']], + ['Mon–Fri 9am... no: 9:00-18:00; Sat 10:00 to 15:00', ['Mo-Fr 09:00-18:00', 'Sa 10:00-15:00']], + ['Mo–Fr 8–16 Uhr; Sa 9–12; So geschlossen', ['Mo-Fr 08:00-16:00', 'Sa 09:00-12:00']], + ['Do 10-18', ['Th 10:00-18:00']], + ['całodobowo', ['Mo-Su 00:00-23:59']], + ['24/7', ['Mo-Su 00:00-23:59']], + ['Pn-Pt 8-24', ['Mo-Fr 08:00-23:59']], + ])('%s', (input, expected) => { + expect(formatOpeningHours(input)).toEqual(expected) + }) + + test('schema.org strings and arrays pass through; junk is dropped', () => { + expect(formatOpeningHours(['Mo-Fr 08:00-17:00', 'Sa 09:00-13:00'])).toEqual(['Mo-Fr 08:00-17:00', 'Sa 09:00-13:00']) + expect(formatOpeningHours(['Pn-Pt 8-16', 'Sa 09:00-13:00'])).toEqual(['Mo-Fr 08:00-16:00', 'Sa 09:00-13:00']) + expect(formatOpeningHours('zadzwoń, umówimy się')).toEqual([]) + expect(formatOpeningHours('Pn-Pt 25-30')).toEqual([]) + expect(formatOpeningHours(undefined)).toEqual([]) + }) +}) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index dd4fd4c..8d9675a 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -54,3 +54,26 @@ describe('ipalKit — config transform', () => { expect(() => ipalKit({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow() }) }) + +describe('ipalKit — auth collection', () => { + test('injects a users auth collection when the project has none, with roles', async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ + collections: [], + secret: 'x', + } as unknown as Config) + const users = config.collections?.find((c) => c.slug === 'users') + expect(users?.auth).toBe(true) + expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true) + }) + + test("keeps the project's own users collection", async () => { + const own = { slug: 'users', auth: true, fields: [{ name: 'fullName', type: 'text' }] } + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ + collections: [own], + secret: 'x', + } as unknown as Config) + const users = config.collections?.filter((c) => c.slug === 'users') + expect(users).toHaveLength(1) + expect(users?.[0].fields.some((f) => 'name' in f && f.name === 'fullName')).toBe(true) + }) +}) diff --git a/test/seo.test.ts b/test/seo.test.ts index 86fdc8b..f741258 100644 --- a/test/seo.test.ts +++ b/test/seo.test.ts @@ -159,3 +159,46 @@ describe('consent cookie', () => { expect(parseConsent(undefined)).toBeNull() }) }) + +describe('buildNavigationJsonLd', () => { + test('resolves page links per locale, keeps own-site links only, dedupes, walks submenus', async () => { + const { buildNavigationJsonLd } = await import('../src/modules/seo/buildSiteNavigationJsonLd.js') + const page = (slug: string) => ({ type: 'internal' as const, page: { slug } }) + const nav = buildNavigationJsonLd({ + baseUrl: 'https://acme.pl/', + config, + homeSlug: { en: 'home', pl: 'start' }, + items: [ + { link: { ...page('start'), label: 'Start' } }, + { link: { ...page('uslugi'), label: 'Usługi' }, subItems: [{ link: { ...page('audyt'), label: 'Audyt' } }] }, + { link: { type: 'external', label: 'Blog firmy X', url: 'https://medium.com/x' } }, + { link: { ...page('uslugi'), label: 'Usługi (dup)' } }, + { link: { ...page('bez-etykiety') } }, + ], + locale: 'pl', + }) + expect(nav?.itemListElement.map((i: { name: string; url: string }) => [i.name, i.url])).toEqual([ + ['Start', 'https://acme.pl/pl'], + ['Usługi', 'https://acme.pl/pl/uslugi'], + ['Audyt', 'https://acme.pl/pl/audyt'], + ]) + }) +}) + +describe('buildCsp — googleMaps', () => { + test('covers Maps JS API domains in every needed directive, no duplicates', () => { + const { value } = buildCsp({ googleMaps: true }) + const dir = (name: string) => value.split('; ').find((d) => d.startsWith(`${name} `)) ?? '' + for (const d of ['script-src', 'img-src', 'connect-src']) { + expect(dir(d)).toContain('https://*.googleapis.com') + expect(dir(d)).toContain('https://*.gstatic.com') + } + expect(dir('frame-src')).toContain('https://*.google.com') + expect(dir('worker-src')).toContain('blob:') + for (const d of value.split('; ')) { + const parts = d.split(' ').slice(1) + expect(new Set(parts).size).toBe(parts.length) + } + expect(buildCsp().value).toContain('https://fonts.gstatic.com') + }) +}) diff --git a/test/submitAction.test.ts b/test/submitAction.test.ts new file mode 100644 index 0000000..86e211f --- /dev/null +++ b/test/submitAction.test.ts @@ -0,0 +1,40 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { createSubmitAction } from '../src/modules/forms/createSubmitAction.js' +import { fakePayload } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const forms = { contact: { fields: [{ name: 'name', blockType: 'text', required: true }] } } + +describe('createSubmitAction', () => { + afterEach(() => vi.restoreAllMocks()) + + const make = (ip: string) => { + const { create, payload } = fakePayload({ forms }) + ;(payload as unknown as { findGlobal: unknown }).findGlobal = vi.fn(async ({ slug }: { slug: string }) => + slug === 'notifications' ? { form: { success: 'Dzięki!', validation: 'Uzupełnij pola' } } : {}, + ) + const sendForm = createSubmitAction({ getCachedPayload: async () => payload, headers: () => new Headers({ 'x-real-ip': ip }) }) + return { create, sendForm } + } + + test('valid submission → stored, message from Notifications', async () => { + const { create, sendForm } = make('10.8.0.1') + expect(await sendForm('contact', 'pl', { name: 'Ala' })).toEqual({ message: 'Dzięki!', success: true }) + expect(create).toHaveBeenCalledOnce() + }) + + test('honeypot → fake success, nothing stored; field is stripped otherwise', async () => { + const { create, sendForm } = make('10.8.0.2') + expect((await sendForm('contact', 'pl', { name: 'x', company_url: 'http://spam' })).success).toBe(true) + expect(create).not.toHaveBeenCalled() + expect((await sendForm('contact', 'pl', { name: 'Ala', company_url: '' })).success).toBe(true) + expect(create).toHaveBeenCalledOnce() + }) + + test('failure carries reason and field for the renderer', async () => { + const { sendForm } = make('10.8.0.3') + expect(await sendForm('contact', 'pl', {})).toMatchObject({ field: 'name', reason: 'validation', success: false }) + }) +})