Compare commits

...
16 Commits
Author SHA1 Message Date
radoslaw.smolinski 7ef7927e38 1.8.11 2026-10-14 13:28:12 +02:00
radoslaw.smolinski a7846d9770 mcp and content fix 2026-10-14 13:28:04 +02:00
radoslaw.smolinski 015092e773 1.8.10 2026-10-14 11:32:12 +02:00
radoslaw.smolinski f4d969ad29 Sitemap.xml fixed 2026-10-14 11:32:03 +02:00
radoslaw.smolinski fad5d778e8 1.8.9 2026-10-14 11:06:04 +02:00
radoslaw.smolinski 0f073b963e Added fluid skills support 2026-10-14 11:05:57 +02:00
radoslaw.smolinski 54c2d64cce 1.8.8 2026-10-14 10:41:00 +02:00
radoslaw.smolinski e29c919e5e Fix 2026-10-14 10:40:48 +02:00
radoslaw.smolinski 0f6bbd597b 1.8.7 2026-10-13 23:59:56 +02:00
radoslaw.smolinski 65437a144b Fix for routerhandlers.ts 2026-10-13 23:59:51 +02:00
radoslaw.smolinski e7ad64230a 1.8.6 2026-10-13 23:51:17 +02:00
radoslaw.smolinski 5af5033148 import fix in buildLinkField 2026-10-13 23:51:08 +02:00
radoslaw.smolinski 7572ec0c04 1.8.5 2026-10-13 23:41:13 +02:00
radoslaw.smolinski a24777b915 Sitemap.css is now builded in plugin 2026-10-13 23:41:05 +02:00
radoslaw.smolinski 562e7f2244 1.8.4 2026-10-13 19:07:17 +02:00
radoslaw.smolinski 80d8b7102c Added more agent skills 2026-10-13 19:07:03 +02:00
135 changed files with 3872 additions and 767 deletions
+16 -2
View File
@@ -6,8 +6,8 @@
// Only folders named ipal-* are touched; the project's own skills stay as they are.
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
@@ -45,3 +45,17 @@ for (const name of retired) {
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
}
console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`)
// Skills ship .ts/.tsx templates and scripts. A Next tsconfig ("include": ["**/*.tsx"]) would
// type-check them as project code and break `tsc` / `next build` → they must be excluded.
const tsconfig = join(process.cwd(), 'tsconfig.json')
const top = relative(process.cwd(), dest).split(/[\\/]/)[0]
if (existsSync(tsconfig) && top && !top.startsWith('..')) {
const text = readFileSync(tsconfig, 'utf8')
const exclude = text.match(/"exclude"\s*:\s*\[([^\]]*)\]/)?.[1] ?? ''
if (!exclude.includes(top)) {
console.warn(`\n⚠ tsconfig.json does not exclude "${top}" — skill templates would be type-checked and break the build.`)
console.warn(` Add it: "exclude": ["node_modules", "${top}"]`)
process.exitCode = 1
}
}
+2 -1
View File
@@ -1,7 +1,8 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding). Separate export so Payload's
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/
+2 -1
View File
@@ -1,7 +1,8 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding). Separate export so Payload's
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/ export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"}
{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'\n/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["RowLabel","AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,2CAA0C;AACnE;;;;;;CAMC,GACD,SAASC,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"}
+17
View File
@@ -0,0 +1,17 @@
/**
* Entry point: @intecion/ipal-kit/env
*
* Environment validation ONLY — zero imports beyond this module, no Payload,
* no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next
* also compiles for the Edge runtime: importing the package root there drags in
* Payload / file-type / fs and crashes Turbopack ("Export fileTypeFromFile
* doesn't exist in target module").
*
* // src/instrumentation.ts
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'
* export function register() {
* if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true }))
* }
*/
export { assertEnv, ipalEnvRules } from '../modules/env/index.js';
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js';
+17
View File
@@ -0,0 +1,17 @@
/**
* Entry point: @intecion/ipal-kit/env
*
* Environment validation ONLY — zero imports beyond this module, no Payload,
* no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next
* also compiles for the Edge runtime: importing the package root there drags in
* Payload / file-type / fs and crashes Turbopack ("Export fileTypeFromFile
* doesn't exist in target module").
*
* // src/instrumentation.ts
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'
* export function register() {
* if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true }))
* }
*/ export { assertEnv, ipalEnvRules } from '../modules/env/index.js';
//# sourceMappingURL=env.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/exports/env.ts"],"sourcesContent":["/**\n * Entry point: @intecion/ipal-kit/env\n *\n * Environment validation ONLY — zero imports beyond this module, no Payload,\n * no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next\n * also compiles for the Edge runtime: importing the package root there drags in\n * Payload / file-type / fs and crashes Turbopack (\"Export fileTypeFromFile\n * doesn't exist in target module\").\n *\n * // src/instrumentation.ts\n * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'\n * export function register() {\n * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true }))\n * }\n */\nexport { assertEnv, ipalEnvRules } from '../modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js'\n"],"names":["assertEnv","ipalEnvRules"],"mappings":"AAAA;;;;;;;;;;;;;;CAcC,GACD,SAASA,SAAS,EAAEC,YAAY,QAAQ,0BAAyB"}
+59 -55
View File
@@ -1,70 +1,74 @@
export type { AccessOption, Role } from './modules/access/index.js';
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js';
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y, } from './modules/accessibility/index.js';
export type { A11yState } from './modules/accessibility/index.js';
export type { AnalyticsConfig } from './modules/analytics/index.js';
export { getAnalyticsConfig } from './modules/analytics/index.js';
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent, } from './modules/consent/index.js';
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js';
export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
export type { ArchiveEntries } from './modules/content/index.js';
export type { SearchResult } from './modules/content/index.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js';
export { mailAdapter } from './modules/email/mailAdapter.js';
export type { MailAdapterArgs } from './modules/email/mailAdapter.js';
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js';
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.js';
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './modules/forms/validators.js';
export type { Rule } from './modules/forms/validators.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { createHealthRoute } from './modules/health/index.js';
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
export { ipalKit } from './plugin.js';
export type { IpalOptions } from './types.js';
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath, } from './modules/i18n/index.js';
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkValue, ResolveLinkHrefOptions, } from './modules/links/index.js';
export { createMcpRoute } from './modules/mcp/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js';
export type { PagesOption, SystemPageRole } from './modules/pages/index.js';
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
export type { AccessOption, Role } from './modules/access/index.js';
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js';
export type { GlobalQueryOptions } from './modules/payload/index.js';
export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG, SITE_SETTINGS_SLUG, } from './modules/payload/index.js';
export { getGlobal, getSiteSettings, getSiteIntegrations, SITE_SETTINGS_SLUG, SITE_INTEGRATIONS_SLUG, } from './modules/payload/index.js';
export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js';
export { composeTitle, buildHreflangAlternates, buildMetadata, readSiteMetaConfig, slugsAcrossLocales, } from './modules/seo/index.js';
export type { SiteMetaConfig } from './modules/seo/index.js';
export type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { resolveRoute, resolveRedirect, resolveNotFoundPage, blocksToMarkdown, createMarkdownRenderer, markdownResponse, prefersMarkdown, markdownHref, MARKDOWN_PREFIX, searchContent, createSearchRoute, archiveFieldName, getArchiveEntries, buildArchivePath, buildEntryPath, parsePageParam, } from './modules/content/index.js';
export type { ArchiveEntries } from './modules/content/index.js';
export type { SearchResult } from './modules/content/index.js';
export { lexicalToMarkdown } from './modules/richtext/index.js';
export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js';
export { buildAutoFillMetaHook, injectAutoFillMeta, createMetadataGenerator, createPageMetadata, buildSitemapEntries, buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, } from './modules/seo/index.js';
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER, } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { CONSENT_CATEGORIES, DEFAULT_CONSENT, ACCEPT_ALL_CONSENT, REJECT_ALL_CONSENT, CONSENT_COOKIE, CONSENT_VERSION, CONSENT_MAX_AGE, serializeConsent, parseConsent, setDefaultConsent, updateConsent, getConsentTexts, } from './modules/consent/index.js';
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js';
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
export { mailAdapter } from './modules/email/mailAdapter.js';
export type { MailAdapterArgs } from './modules/email/mailAdapter.js';
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js';
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export type { FormsOption, FormsCollectionOverrides, FormsFieldsOverride, } from './modules/forms/types.js';
export { buildValidator, isEmail, required, email, minLength, maxLength, checked, pattern, custom, } from './modules/forms/validators.js';
export type { Rule } from './modules/forms/validators.js';
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
export { createHealthRoute } from './modules/health/index.js';
export { createMcpRoute } from './modules/mcp/index.js';
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
export type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js';
export type { AnalyticsConfig } from './modules/analytics/index.js';
export { getAnalyticsConfig } from './modules/analytics/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js';
export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/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 { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales, } from './modules/seo/index.js';
export type { SiteMetaConfig } from './modules/seo/index.js';
export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry, } from './modules/seo/index.js';
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, 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, validateFaviconField } from './modules/seo/index.js';
export { buildNoindexField } from './modules/seo/index.js';
export { rowLabel } from './modules/admin-ui/index.js';
export type { RowLabelProps } from './modules/admin-ui/index.js';
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
export type { LinkAppearance, LinkValue, BuildLinkFieldOptions, BuildLinksFieldOptions, ResolveLinkHrefOptions, } from './modules/links/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 { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
export { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js';
export { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
export { buildArticleJsonLd } from './modules/seo/index.js';
export { buildLlmsTxt } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { buildSitemapXml, buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './modules/seo/index.js';
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js';
export { buildR2Storage } from './modules/storage/index.js';
export { ipalKit } from './plugin.js';
export type { IpalOptions } from './types.js';
export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js';
export type { OptimizeUploadOptions } from './modules/media/index.js';
export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js';
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
export type { A11yState } from './modules/accessibility/index.js';
export type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js';
export type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js';
+34 -33
View File
@@ -1,58 +1,59 @@
export { ipalKit } from './plugin.js';
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js';
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY } from './modules/access/index.js';
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
export { getAnalyticsConfig } from './modules/analytics/index.js';
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
export { mailAdapter } from './modules/email/mailAdapter.js';
export { getGlobal, getSiteSettings, getSiteIntegrations, SITE_SETTINGS_SLUG, SITE_INTEGRATIONS_SLUG } from './modules/payload/index.js';
export { composeTitle, buildHreflangAlternates, buildMetadata, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/index.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { resolveRoute, resolveRedirect, resolveNotFoundPage, blocksToMarkdown, createMarkdownRenderer, markdownResponse, prefersMarkdown, markdownHref, MARKDOWN_PREFIX, searchContent, createSearchRoute, archiveFieldName, getArchiveEntries, buildArchivePath, buildEntryPath, parsePageParam } from './modules/content/index.js';
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js';
export { buildAutoFillMetaHook, injectAutoFillMeta, createMetadataGenerator, createPageMetadata, buildSitemapEntries, buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './modules/seo/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { CONSENT_CATEGORIES, DEFAULT_CONSENT, ACCEPT_ALL_CONSENT, REJECT_ALL_CONSENT, CONSENT_COOKIE, CONSENT_VERSION, CONSENT_MAX_AGE, serializeConsent, parseConsent, setDefaultConsent, updateConsent, getConsentTexts } from './modules/consent/index.js';
// Imported straight from the file, NOT from ./modules/email/index.js — that
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
export { mailAdapter } from './modules/email/mailAdapter.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
// Validation rules are pure — exported server-side too, for re-validating a
// submission inside a server action. (useForm/useContactForm are client-only →
// '@intecion/ipal-kit/client'.)
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './modules/forms/validators.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { buildValidator, isEmail, required, email, minLength, maxLength, checked, pattern, custom } from './modules/forms/validators.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js';
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js';
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
export { getGlobal, getSiteIntegrations, getSiteSettings, 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';
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
export { getAnalyticsConfig } from './modules/analytics/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js';
export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js';
export { buildSecurityHeaders } from './modules/security/index.js';
export { buildCsp } from './modules/security/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/index.js';
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, 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 { buildNoindexField } from './modules/seo/index.js';
export { rowLabel } from './modules/admin-ui/index.js';
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/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 { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } 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 { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
export { buildArticleJsonLd } from './modules/seo/index.js';
export { buildLlmsTxt } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { buildSitemapXml, buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './modules/seo/index.js';
export { buildR2Storage } from './modules/storage/index.js';
export { ipalKit } from './plugin.js';
export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js';
export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js';
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
File diff suppressed because one or more lines are too long
+12
View File
@@ -0,0 +1,12 @@
export type RowLabelProps = {
/** Shown with the row number when every path is empty, e.g. "Button" → "Button 02". */
fallback?: string;
/** Dot paths inside the row, tried in order — the first non-empty text wins. */
fields?: string[];
};
/**
* Array row title in the admin panel: shows the row's own content ("Contact us",
* "Fast delivery") instead of "Item 01", so an editor finds the right row
* without expanding every one. Wire it with `rowLabel()`.
*/
export declare function RowLabel({ fallback, fields }: RowLabelProps): import("react/jsx-runtime").JSX.Element;
+54
View File
@@ -0,0 +1,54 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useRowLabel } from '@payloadcms/ui';
const at = (obj, path)=>path.split('.').reduce((o, k)=>o && typeof o === 'object' ? o[k] : undefined, obj);
const toText = (v)=>{
if (typeof v === 'string') {
return v.trim();
}
if (typeof v === 'number') {
return String(v);
}
// populated relationship / upload → its title, name, filename or alt
if (v && typeof v === 'object') {
for (const k of [
'title',
'name',
'label',
'alt',
'filename'
]){
const t = v[k];
if (typeof t === 'string' && t.trim()) {
return t.trim();
}
}
}
return '';
};
/**
* Array row title in the admin panel: shows the row's own content ("Contact us",
* "Fast delivery") instead of "Item 01", so an editor finds the right row
* without expanding every one. Wire it with `rowLabel()`.
*/ export function RowLabel({ fallback = 'Item', fields = [
'heading',
'title',
'label',
'link.label',
'name'
] }) {
const { data, rowNumber } = useRowLabel();
for (const f of fields){
const text = toText(at(data, f));
if (text) {
return /*#__PURE__*/ _jsx("span", {
children: text.length > 60 ? `${text.slice(0, 57)}…` : text
});
}
}
return /*#__PURE__*/ _jsx("span", {
children: `${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`
});
}
//# sourceMappingURL=RowLabelComponent.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/admin-ui/RowLabelComponent.tsx"],"sourcesContent":["'use client'\nimport { useRowLabel } from '@payloadcms/ui'\n\nexport type RowLabelProps = {\n /** Shown with the row number when every path is empty, e.g. \"Button\" → \"Button 02\". */\n fallback?: string\n /** Dot paths inside the row, tried in order — the first non-empty text wins. */\n fields?: string[]\n}\n\nconst at = (obj: unknown, path: string): unknown =>\n path.split('.').reduce<unknown>((o, k) => (o && typeof o === 'object' ? (o as Record<string, unknown>)[k] : undefined), obj)\n\nconst toText = (v: unknown): string => {\n if (typeof v === 'string') {return v.trim()}\n if (typeof v === 'number') {return String(v)}\n // populated relationship / upload → its title, name, filename or alt\n if (v && typeof v === 'object') {\n for (const k of ['title', 'name', 'label', 'alt', 'filename']) {\n const t = (v as Record<string, unknown>)[k]\n if (typeof t === 'string' && t.trim()) {return t.trim()}\n }\n }\n return ''\n}\n\n/**\n * Array row title in the admin panel: shows the row's own content (\"Contact us\",\n * \"Fast delivery\") instead of \"Item 01\", so an editor finds the right row\n * without expanding every one. Wire it with `rowLabel()`.\n */\nexport function RowLabel({ fallback = 'Item', fields = ['heading', 'title', 'label', 'link.label', 'name'] }: RowLabelProps) {\n const { data, rowNumber } = useRowLabel<Record<string, unknown>>()\n for (const f of fields) {\n const text = toText(at(data, f))\n if (text) {return <span>{text.length > 60 ? `${text.slice(0, 57)}…` : text}</span>}\n }\n return <span>{`${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`}</span>\n}\n"],"names":["useRowLabel","at","obj","path","split","reduce","o","k","undefined","toText","v","trim","String","t","RowLabel","fallback","fields","data","rowNumber","f","text","span","length","slice","padStart"],"mappings":"AAAA;;AACA,SAASA,WAAW,QAAQ,iBAAgB;AAS5C,MAAMC,KAAK,CAACC,KAAcC,OACxBA,KAAKC,KAAK,CAAC,KAAKC,MAAM,CAAU,CAACC,GAAGC,IAAOD,KAAK,OAAOA,MAAM,WAAW,AAACA,CAA6B,CAACC,EAAE,GAAGC,WAAYN;AAE1H,MAAMO,SAAS,CAACC;IACd,IAAI,OAAOA,MAAM,UAAU;QAAC,OAAOA,EAAEC,IAAI;IAAE;IAC3C,IAAI,OAAOD,MAAM,UAAU;QAAC,OAAOE,OAAOF;IAAE;IAC5C,qEAAqE;IACrE,IAAIA,KAAK,OAAOA,MAAM,UAAU;QAC9B,KAAK,MAAMH,KAAK;YAAC;YAAS;YAAQ;YAAS;YAAO;SAAW,CAAE;YAC7D,MAAMM,IAAI,AAACH,CAA6B,CAACH,EAAE;YAC3C,IAAI,OAAOM,MAAM,YAAYA,EAAEF,IAAI,IAAI;gBAAC,OAAOE,EAAEF,IAAI;YAAE;QACzD;IACF;IACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASG,SAAS,EAAEC,WAAW,MAAM,EAAEC,SAAS;IAAC;IAAW;IAAS;IAAS;IAAc;CAAO,EAAiB;IACzH,MAAM,EAAEC,IAAI,EAAEC,SAAS,EAAE,GAAGlB;IAC5B,KAAK,MAAMmB,KAAKH,OAAQ;QACtB,MAAMI,OAAOX,OAAOR,GAAGgB,MAAME;QAC7B,IAAIC,MAAM;YAAC,qBAAO,KAACC;0BAAMD,KAAKE,MAAM,GAAG,KAAK,GAAGF,KAAKG,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,GAAGH;;QAAY;IACpF;IACA,qBAAO,KAACC;kBAAM,GAAGN,SAAS,CAAC,EAAEH,OAAO,AAACM,CAAAA,aAAa,CAAA,IAAK,GAAGM,QAAQ,CAAC,GAAG,MAAM;;AAC9E"}
+2
View File
@@ -0,0 +1,2 @@
export { rowLabel } from './rowLabel.js';
export type { RowLabelProps } from './RowLabelComponent.js';
+3
View File
@@ -0,0 +1,3 @@
export { rowLabel } from './rowLabel.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/admin-ui/index.ts"],"sourcesContent":["export { rowLabel } from './rowLabel.js'\nexport type { RowLabelProps } from './RowLabelComponent.js'\n"],"names":["rowLabel"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe"}
+16
View File
@@ -0,0 +1,16 @@
import type { RowLabelProps } from './RowLabelComponent.js';
/**
* Readable array rows in the panel. Spread into an array field's `admin.components`:
*
* { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' },
* admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] }
*
* Rows then read "Fast delivery", "24/7 support"… instead of "Feature 01, Feature 02".
* After adding it to a project: `pnpm payload generate:importmap`.
*/
export declare function rowLabel(fields: string | string[], fallback?: string): {
RowLabel: {
path: string;
clientProps: RowLabelProps;
};
};
+24
View File
@@ -0,0 +1,24 @@
/**
* Readable array rows in the panel. Spread into an array field's `admin.components`:
*
* { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' },
* admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] }
*
* Rows then read "Fast delivery", "24/7 support"… instead of "Feature 01, Feature 02".
* After adding it to a project: `pnpm payload generate:importmap`.
*/ export function rowLabel(fields, fallback = 'Item') {
const clientProps = {
fields: Array.isArray(fields) ? fields : [
fields
],
fallback
};
return {
RowLabel: {
path: '@intecion/ipal-kit/admin#RowLabel',
clientProps
}
};
}
//# sourceMappingURL=rowLabel.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/admin-ui/rowLabel.ts"],"sourcesContent":["import type { RowLabelProps } from './RowLabelComponent.js'\n\n/**\n * Readable array rows in the panel. Spread into an array field's `admin.components`:\n *\n * { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' },\n * admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] }\n *\n * Rows then read \"Fast delivery\", \"24/7 support\"… instead of \"Feature 01, Feature 02\".\n * After adding it to a project: `pnpm payload generate:importmap`.\n */\nexport function rowLabel(fields: string | string[], fallback = 'Item') {\n const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], fallback }\n return { RowLabel: { path: '@intecion/ipal-kit/admin#RowLabel', clientProps } }\n}\n"],"names":["rowLabel","fields","fallback","clientProps","Array","isArray","RowLabel","path"],"mappings":"AAEA;;;;;;;;CAQC,GACD,OAAO,SAASA,SAASC,MAAyB,EAAEC,WAAW,MAAM;IACnE,MAAMC,cAA6B;QAAEF,QAAQG,MAAMC,OAAO,CAACJ,UAAUA,SAAS;YAACA;SAAO;QAAEC;IAAS;IACjG,OAAO;QAAEI,UAAU;YAAEC,MAAM;YAAqCJ;QAAY;IAAE;AAChF"}
+6 -1
View File
@@ -68,7 +68,7 @@ export function CookieBanner({ classNames } = {}) {
const primaryClass = classNames?.primaryButton ?? defaults.primaryButton;
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton;
return /*#__PURE__*/ _jsx("div", {
"aria-label": "Cookie consent",
"aria-label": texts.settingsTitle,
className: rootClass,
"data-ipal": "banner",
role: "dialog",
@@ -107,16 +107,19 @@ export function CookieBanner({ classNames } = {}) {
children: [
/*#__PURE__*/ _jsx("button", {
className: secondaryClass,
"data-ipal": "settings",
onClick: ()=>setShowSettings(true),
children: texts.buttons.settings
}),
/*#__PURE__*/ _jsx("button", {
className: secondaryClass,
"data-ipal": "reject",
onClick: rejectAll,
children: texts.buttons.reject
}),
/*#__PURE__*/ _jsx("button", {
className: primaryClass,
"data-ipal": "accept",
onClick: acceptAll,
children: texts.buttons.acceptAll
})
@@ -168,11 +171,13 @@ export function CookieBanner({ classNames } = {}) {
children: [
/*#__PURE__*/ _jsx("button", {
className: secondaryClass,
"data-ipal": "back",
onClick: ()=>setShowSettings(false),
children: texts.buttons.back
}),
/*#__PURE__*/ _jsx("button", {
className: primaryClass,
"data-ipal": "save",
onClick: ()=>savePreferences(choices),
children: texts.buttons.save
})
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -14,7 +14,7 @@ import { useIsMounted } from './useIsMounted.js';
* replace the styling outright.
*/ export function CookieButton({ className } = {}) {
const isMounted = useIsMounted();
const { decided, reopen } = useConsentContext();
const { decided, reopen, texts } = useConsentContext();
// Render nothing until mounted — prevents hydration mismatch (no project
// ConsentWrapper workaround needed).
if (!isMounted) {
@@ -25,7 +25,8 @@ import { useIsMounted } from './useIsMounted.js';
}
const cls = className ?? 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' + 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' + 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]';
return /*#__PURE__*/ _jsx("button", {
"aria-label": "Cookie settings",
// a11y label per locale: the panel's "settings title" (Cookie Settings global)
"aria-label": texts.settingsTitle,
className: cls,
"data-ipal": "cookie-button",
onClick: reopen,
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/consent/CookieButton.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\n\nimport { useConsentContext } from './ConsentContext.js'\nimport { useIsMounted } from './useIsMounted.js'\n\n/**\n * Floating \"cookie settings\" button — lets visitors reopen the consent panel\n * after deciding (GDPR: withdrawing consent must be as easy as giving it).\n * Hidden while the banner is showing.\n *\n * Colours follow the same CSS custom properties as CookieBanner\n * (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's\n * palette applies to both without touching either component. Pass className to\n * replace the styling outright.\n */\nexport function CookieButton({ className }: { className?: string } = {}) {\n const isMounted = useIsMounted()\n const { decided, reopen } = useConsentContext()\n\n // Render nothing until mounted — prevents hydration mismatch (no project\n // ConsentWrapper workaround needed).\n if (!isMounted) {return null}\n if (!decided) {return null}\n\n const cls =\n className ??\n 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +\n 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +\n 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'\n\n return (\n <button aria-label=\"Cookie settings\" className={cls} data-ipal=\"cookie-button\" onClick={reopen}>\n <Cookie\n aria-hidden=\"true\"\n className=\"h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]\"\n />\n </button>\n )\n}\n"],"names":["Cookie","useConsentContext","useIsMounted","CookieButton","className","isMounted","decided","reopen","cls","button","aria-label","data-ipal","onClick","aria-hidden"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AAErC,SAASC,iBAAiB,QAAQ,sBAAqB;AACvD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD;;;;;;;;;CASC,GACD,OAAO,SAASC,aAAa,EAAEC,SAAS,EAA0B,GAAG,CAAC,CAAC;IACrE,MAAMC,YAAYH;IAClB,MAAM,EAAEI,OAAO,EAAEC,MAAM,EAAE,GAAGN;IAE5B,yEAAyE;IACzE,qCAAqC;IACrC,IAAI,CAACI,WAAW;QAAC,OAAO;IAAI;IAC5B,IAAI,CAACC,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAME,MACJJ,aACA,2HACE,4GACA;IAEJ,qBACE,KAACK;QAAOC,cAAW;QAAkBN,WAAWI;QAAKG,aAAU;QAAgBC,SAASL;kBACtF,cAAA,KAACP;YACCa,eAAY;YACZT,WAAU;;;AAIlB"}
{"version":3,"sources":["../../../src/modules/consent/CookieButton.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\n\nimport { useConsentContext } from './ConsentContext.js'\nimport { useIsMounted } from './useIsMounted.js'\n\n/**\n * Floating \"cookie settings\" button — lets visitors reopen the consent panel\n * after deciding (GDPR: withdrawing consent must be as easy as giving it).\n * Hidden while the banner is showing.\n *\n * Colours follow the same CSS custom properties as CookieBanner\n * (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's\n * palette applies to both without touching either component. Pass className to\n * replace the styling outright.\n */\nexport function CookieButton({ className }: { className?: string } = {}) {\n const isMounted = useIsMounted()\n const { decided, reopen, texts } = useConsentContext()\n\n // Render nothing until mounted — prevents hydration mismatch (no project\n // ConsentWrapper workaround needed).\n if (!isMounted) {return null}\n if (!decided) {return null}\n\n const cls =\n className ??\n 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +\n 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +\n 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'\n\n return (\n <button\n // a11y label per locale: the panel's \"settings title\" (Cookie Settings global)\n aria-label={texts.settingsTitle}\n className={cls}\n data-ipal=\"cookie-button\"\n onClick={reopen}\n >\n <Cookie\n aria-hidden=\"true\"\n className=\"h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]\"\n />\n </button>\n )\n}\n"],"names":["Cookie","useConsentContext","useIsMounted","CookieButton","className","isMounted","decided","reopen","texts","cls","button","aria-label","settingsTitle","data-ipal","onClick","aria-hidden"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AAErC,SAASC,iBAAiB,QAAQ,sBAAqB;AACvD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD;;;;;;;;;CASC,GACD,OAAO,SAASC,aAAa,EAAEC,SAAS,EAA0B,GAAG,CAAC,CAAC;IACrE,MAAMC,YAAYH;IAClB,MAAM,EAAEI,OAAO,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGP;IAEnC,yEAAyE;IACzE,qCAAqC;IACrC,IAAI,CAACI,WAAW;QAAC,OAAO;IAAI;IAC5B,IAAI,CAACC,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAMG,MACJL,aACA,2HACE,4GACA;IAEJ,qBACE,KAACM;QACC,+EAA+E;QAC/EC,cAAYH,MAAMI,aAAa;QAC/BR,WAAWK;QACXI,aAAU;QACVC,SAASP;kBAET,cAAA,KAACP;YACCe,eAAY;YACZX,WAAU;;;AAIlB"}
+8
View File
@@ -11,6 +11,14 @@ type CreateSearchRouteArgs = {
getCachedPayload: () => Promise<BasePayload>;
/** Home slug map/string so the home result collapses to root. */
homeSlug?: Record<string, string> | string;
/**
* Per-IP limit (in memory, per instance). Default { max: 120, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
*/
rateLimit?: {
max?: number;
windowMs?: number;
} | false;
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
summaryField?: string;
};
+22
View File
@@ -1,3 +1,4 @@
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js';
import { searchContent } from './searchContent.js';
/**
* A JSON content-search endpoint. Powers both the site's own search UI and
@@ -18,7 +19,28 @@ import { searchContent } from './searchContent.js';
* Uses the global Request/Response — no next/server import.
*/ export function createSearchRoute(args) {
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args;
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
const rl = args.rateLimit === false ? null : {
max: 120,
windowMs: 60_000,
...args.rateLimit
};
return async (req)=>{
if (rl) {
const ip = clientIp(req);
if (!checkRateLimit({
key: ip,
scope: 'search',
...rl
})) {
return tooManyRequests(ip, 'search', {
count: 0,
error: 'Too many requests',
query: '',
results: []
});
}
}
const url = new URL(req.url);
const query = url.searchParams.get('q')?.trim() ?? '';
const locale = url.searchParams.get('locale') ?? undefined;
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -13,7 +13,7 @@
}
switch(kind){
case 'boolean':
if (!/^(true|false|1|0|yes|no)$/i.test(value)) {
if (!/^(?:true|false|1|0|yes|no)$/i.test(value)) {
return `${name} must be a boolean (true/false/1/0/yes/no, got "${value}")`;
}
break;
+1 -1
View File
File diff suppressed because one or more lines are too long
+13 -2
View File
@@ -59,8 +59,19 @@
kind: 'url'
}, {
name: 'R2_PUBLIC_URL',
description: 'Public base URL media is served from',
kind: 'url'
description: 'Public base URL media is served from (custom domain of the bucket)',
// Production: absolute URL (https://media.example.com). Outside production a
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
validate: (v)=>{
if (/^https?:\/\/[^/\s]+/i.test(v)) {
return true;
}
if (v.startsWith('/') && process.env.NODE_ENV !== 'production') {
return true;
}
return v.startsWith('/') ? `R2_PUBLIC_URL must be an absolute URL in production (got "${v}") — e.g. https://media.example.com` : `R2_PUBLIC_URL must be an absolute URL (https://…) or, outside production, a path starting with "/" (got "${v}")`;
}
});
}
if (emailGraph) {
File diff suppressed because one or more lines are too long
+2 -14
View File
@@ -1,14 +1,2 @@
export type RateLimitArgs = {
/** Identifier to limit on — typically the client IP. */
key: string;
/** Max submissions allowed per window. Defaults to 5. */
max?: number;
/** Window length in ms. Defaults to 60_000 (one minute). */
windowMs?: number;
};
/**
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
*/
export declare function checkRateLimit({ key, max, windowMs }: RateLimitArgs): boolean;
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js';
export type { RateLimitArgs } from '../shared/rateLimit.js';
+2 -49
View File
@@ -1,51 +1,4 @@
/**
* Per-IP sliding window, in memory.
*
* Deliberately simple: no Redis, no dependency. The trade-off is that the
* counter lives in one process — with several instances behind a load balancer
* each keeps its own, so the effective limit is per-instance, not global. For a
* contact form that's fine (it raises the cost of flooding without pretending
* to be airtight); a high-security form should put a real limiter in front.
*
* State is module-level, so it survives between requests but resets on redeploy
* — acceptable for abuse throttling.
*/ const buckets = new Map();
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
const SWEEP_INTERVAL = 60_000;
function sweep(now) {
if (now - lastSweep < SWEEP_INTERVAL) {
return;
}
lastSweep = now;
for (const [key, bucket] of buckets){
if (bucket.resetAt <= now) {
buckets.delete(key);
}
}
}
/**
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
*/ export function checkRateLimit({ key, max = 5, windowMs = 60_000 }) {
if (!key) {
return true;
}
const now = Date.now();
sweep(now);
const bucket = buckets.get(key);
if (!bucket || bucket.resetAt <= now) {
buckets.set(key, {
count: 1,
resetAt: now + windowMs
});
return true;
}
if (bucket.count >= max) {
return false;
}
bucket.count += 1;
return true;
}
// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js';
//# sourceMappingURL=rateLimit.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/rateLimit.ts"],"sourcesContent":["type Bucket = { count: number; resetAt: number }\n\n/**\n * Per-IP sliding window, in memory.\n *\n * Deliberately simple: no Redis, no dependency. The trade-off is that the\n * counter lives in one process — with several instances behind a load balancer\n * each keeps its own, so the effective limit is per-instance, not global. For a\n * contact form that's fine (it raises the cost of flooding without pretending\n * to be airtight); a high-security form should put a real limiter in front.\n *\n * State is module-level, so it survives between requests but resets on redeploy\n * — acceptable for abuse throttling.\n */\nconst buckets = new Map<string, Bucket>()\n\n/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */\nlet lastSweep = Date.now()\nconst SWEEP_INTERVAL = 60_000\n\nfunction sweep(now: number) {\n if (now - lastSweep < SWEEP_INTERVAL) {return}\n lastSweep = now\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) {buckets.delete(key)}\n }\n}\n\nexport type RateLimitArgs = {\n /** Identifier to limit on — typically the client IP. */\n key: string\n /** Max submissions allowed per window. Defaults to 5. */\n max?: number\n /** Window length in ms. Defaults to 60_000 (one minute). */\n windowMs?: number\n}\n\n/**\n * Returns true when the request is within the limit, false when it should be\n * rejected. A missing key (no IP) is allowed through — better to accept a\n * submission than to block everyone behind a proxy that strips the header.\n */\nexport function checkRateLimit({ key, max = 5, windowMs = 60_000 }: RateLimitArgs): boolean {\n if (!key) {return true}\n\n const now = Date.now()\n sweep(now)\n\n const bucket = buckets.get(key)\n\n if (!bucket || bucket.resetAt <= now) {\n buckets.set(key, { count: 1, resetAt: now + windowMs })\n return true\n }\n\n if (bucket.count >= max) {\n return false\n }\n\n bucket.count += 1\n return true\n}\n"],"names":["buckets","Map","lastSweep","Date","now","SWEEP_INTERVAL","sweep","key","bucket","resetAt","delete","checkRateLimit","max","windowMs","get","set","count"],"mappings":"AAEA;;;;;;;;;;;CAWC,GACD,MAAMA,UAAU,IAAIC;AAEpB,0EAA0E,GAC1E,IAAIC,YAAYC,KAAKC,GAAG;AACxB,MAAMC,iBAAiB;AAEvB,SAASC,MAAMF,GAAW;IACxB,IAAIA,MAAMF,YAAYG,gBAAgB;QAAC;IAAM;IAC7CH,YAAYE;IACZ,KAAK,MAAM,CAACG,KAAKC,OAAO,IAAIR,QAAS;QACnC,IAAIQ,OAAOC,OAAO,IAAIL,KAAK;YAACJ,QAAQU,MAAM,CAACH;QAAI;IACjD;AACF;AAWA;;;;CAIC,GACD,OAAO,SAASI,eAAe,EAAEJ,GAAG,EAAEK,MAAM,CAAC,EAAEC,WAAW,MAAM,EAAiB;IAC/E,IAAI,CAACN,KAAK;QAAC,OAAO;IAAI;IAEtB,MAAMH,MAAMD,KAAKC,GAAG;IACpBE,MAAMF;IAEN,MAAMI,SAASR,QAAQc,GAAG,CAACP;IAE3B,IAAI,CAACC,UAAUA,OAAOC,OAAO,IAAIL,KAAK;QACpCJ,QAAQe,GAAG,CAACR,KAAK;YAAES,OAAO;YAAGP,SAASL,MAAMS;QAAS;QACrD,OAAO;IACT;IAEA,IAAIL,OAAOQ,KAAK,IAAIJ,KAAK;QACvB,OAAO;IACT;IAEAJ,OAAOQ,KAAK,IAAI;IAChB,OAAO;AACT"}
{"version":3,"sources":["../../../src/modules/forms/rateLimit.ts"],"sourcesContent":["// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).\nexport { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js'\nexport type { RateLimitArgs } from '../shared/rateLimit.js'\n"],"names":["checkRateLimit","clientIp","retryAfterSeconds","tooManyRequests"],"mappings":"AAAA,4EAA4E;AAC5E,SAASA,cAAc,EAAEC,QAAQ,EAAEC,iBAAiB,EAAEC,eAAe,QAAQ,yBAAwB"}
+1 -1
View File
@@ -76,7 +76,7 @@ export type SubmitFormResult = {
*
* Emails aren't sent here. The form-builder sends whatever an editor configured
* under the form's "Emails" tab (form-submissions hook → payload.sendEmail),
* which goes out over panelSmtpAdapter. Storing the submission is enough.
* which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.
*
* server-only: touches the Turnstile secret.
*/
+1 -1
View File
@@ -11,7 +11,7 @@ import { validateSubmission } from './validateSubmission.js';
*
* Emails aren't sent here. The form-builder sends whatever an editor configured
* under the form's "Emails" tab (form-submissions hook → payload.sendEmail),
* which goes out over panelSmtpAdapter. Storing the submission is enough.
* which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.
*
* server-only: touches the Turnstile secret.
*/ export async function submitForm({ consentFieldName, data, formId, ip, maxPerMinute = 5, payload, turnstileToken }) {
File diff suppressed because one or more lines are too long
+8 -2
View File
@@ -1,7 +1,7 @@
import type { BasePayload, SanitizedConfig } from 'payload';
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js';
import type { I18nConfig } from '../i18n/index.js';
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry } from '../seo/index.js';
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js';
type CreateContentHelpersArgs = {
/**
* Absolute site origin for sitemap/robots URLs. Falls back to
@@ -31,6 +31,11 @@ type CreateContentHelpersArgs = {
robots?: RobotsOptions;
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string;
/**
* Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style,
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
*/
sitemapStyle?: false | SitemapStyleOptions;
};
/**
* Bundles the per-request data helpers a frontend needs — the same cached
@@ -58,7 +63,7 @@ type CreateContentHelpersArgs = {
* a URL is, fetching gets the listing. Metadata generation needs the first and
* not the second, and a page component composes them in two obvious lines.
*/
export declare function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug, robots: robotsOptions, settingsSlug, }: CreateContentHelpersArgs): {
export declare function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug, robots: robotsOptions, settingsSlug, sitemapStyle, }: CreateContentHelpersArgs): {
generatePageMetadata: (locale: string, segments: string[] | undefined, page?: number) => Promise<PageMetadata>;
generateStaticParams: () => Promise<Array<{
locale: string;
@@ -74,5 +79,6 @@ export declare function createContentHelpers({ baseUrl, config, content, i18n, p
resolveRoute: (locale: string, segments: string[] | undefined, page: number) => Promise<null | ResolvedRoute>;
robots: () => RobotsRules;
sitemap: () => Promise<SitemapEntry[]>;
sitemapRoute: (req: Request) => Promise<Response>;
};
export {};
+13 -3
View File
@@ -1,7 +1,7 @@
import { getPayload } from 'payload';
import { cache } from 'react';
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/index.js';
import { buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js';
/**
* Bundles the per-request data helpers a frontend needs — the same cached
* wrappers every project was writing by hand (getPayload, settings, locale
@@ -27,7 +27,7 @@ import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/ind
* `resolveRoute` and `getEntries` are separate on purpose: routing decides what
* a URL is, fetching gets the listing. Metadata generation needs the first and
* not the second, and a page component composes them in two obvious lines.
*/ export function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug = 'pages', robots: robotsOptions, settingsSlug = 'site-settings' }) {
*/ export function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug = 'pages', robots: robotsOptions, settingsSlug = 'site-settings', sitemapStyle }) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '';
const getCachedPayload = cache(async ()=>getPayload({
config: await config
@@ -311,6 +311,15 @@ import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/ind
return [];
}
};
/**
* Route handler for app/sitemap.xml/route.ts — XML for crawlers, styled for
* people (`?style` serves the CSS from the plugin; nothing in /public):
*
* export { sitemapRoute as GET } from '@/lib/content'
* export const dynamic = 'force-dynamic'
*/ const sitemapRoute = createSitemapRouteHandler(sitemap, {
style: sitemapStyle ?? {}
});
return {
generatePageMetadata,
generateStaticParams,
@@ -321,7 +330,8 @@ import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/ind
getSettings,
resolveRoute,
robots,
sitemap
sitemap,
sitemapRoute
};
}
File diff suppressed because one or more lines are too long
+9 -1
View File
@@ -27,6 +27,14 @@ export type BuildLinkFieldOptions = {
*/
export declare function buildLinkField({ name, appearances, disableLabel, relationTo, required, uploadTo, }?: BuildLinkFieldOptions): GroupField;
export type BuildLinksFieldOptions = {
/**
* What one row is called in the panel — the add button reads "Add <singular>".
* Default { singular: 'Button', plural: 'Buttons' }; e.g. { singular: 'Link', plural: 'Links' } for a link list.
*/
labels?: {
plural: string;
singular: string;
};
/** Max number of buttons. Default 2. */
maxRows?: number;
/** Field name. Default 'links'. */
@@ -36,4 +44,4 @@ export type BuildLinksFieldOptions = {
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
*/
export declare function buildLinksField({ name, maxRows, ...linkOptions }?: BuildLinksFieldOptions): ArrayField;
export declare function buildLinksField({ name, labels, maxRows, ...linkOptions }?: BuildLinksFieldOptions): ArrayField;
+14 -3
View File
@@ -1,4 +1,5 @@
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/;
import { rowLabel } from '../admin-ui/rowLabel.js';
const URL_PATTERN = /^(?:https?:\/\/|mailto:|tel:|#)/;
/**
* The ONE link shape for a project: a page, an external URL (also mailto:,
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
@@ -117,16 +118,26 @@ const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/;
/**
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
*/ export function buildLinksField({ name = 'links', maxRows = 2, ...linkOptions } = {}) {
*/ export function buildLinksField({ name = 'links', labels = {
plural: 'Buttons',
singular: 'Button'
}, maxRows = 2, ...linkOptions } = {}) {
return {
name,
type: 'array',
admin: {
initCollapsed: true
initCollapsed: true,
// Rows read "Contact us" / "Download catalogue", not "Button 01". Needs the importMap entry.
components: rowLabel([
'link.label',
'link.url'
], labels.singular)
},
fields: [
buildLinkField(linkOptions)
],
label: labels.plural,
labels,
maxRows
};
}
File diff suppressed because one or more lines are too long
+10
View File
@@ -10,6 +10,16 @@ type CreateMcpRouteArgs = {
/** Archive-backed collections (same as the plugin option) for get_page. */
content?: ContentOption;
getCachedPayload: () => Promise<BasePayload>;
/** Max messages in one JSON-RPC batch. Default 10. */
maxBatch?: number;
/**
* Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory, per instance). Default { max: 60, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
*/
rateLimit?: {
max?: number;
windowMs?: number;
} | false;
/** Server name advertised in `initialize`. Default 'ipal-site'. */
serverName?: string;
/** Server version advertised in `initialize`. Default '1.0.0'. */
+26 -1
View File
@@ -1,5 +1,6 @@
import { createMarkdownRenderer, searchContent } from '../content/index.js';
import { getDefaultLocale, isValidLocale } from '../i18n/index.js';
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js';
/**
* A read-only MCP (Model Context Protocol) server for the client site, as a Next
* route handler. Lets Claude / any MCP client CONNECT to the site and query it
@@ -59,7 +60,12 @@ function toolText(text, isError = false) {
};
}
export function createMcpRoute(args) {
const { baseUrl, collection = 'pages', config, content, getCachedPayload, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args;
const { baseUrl, collection = 'pages', config, content, getCachedPayload, maxBatch = 10, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args;
const rl = args.rateLimit === false ? null : {
max: 60,
windowMs: 60_000,
...args.rateLimit
};
const origin = baseUrl?.replace(/\/$/, '') ?? '';
const renderMarkdown = createMarkdownRenderer({
collection,
@@ -217,6 +223,25 @@ export function createMcpRoute(args) {
status: 400
});
}
// Limits: a batch counts as many requests as it has messages, and is capped —
// otherwise one POST could carry hundreds of tool calls (DB queries).
const messages = Array.isArray(body) ? body.length : 1;
if (Array.isArray(body) && body.length > maxBatch) {
return Response.json(rpcError(null, -32600, `Batch too large (max ${maxBatch})`), {
status: 400
});
}
if (rl) {
const ip = clientIp(req);
if (!checkRateLimit({
cost: messages,
key: ip,
scope: 'mcp',
...rl
})) {
return tooManyRequests(ip, 'mcp', rpcError(null, -32000, 'Too many requests'));
}
}
// Batch or single.
if (Array.isArray(body)) {
const out = (await Promise.all(body.map((m)=>handleOne(m)))).filter((r)=>r !== null);
File diff suppressed because one or more lines are too long
+2
View File
@@ -1 +1,3 @@
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js';
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js';
export type { OptimizeUploadOptions } from './optimizeUpload.js';
+1
View File
@@ -1,3 +1,4 @@
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js';
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/media/index.ts"],"sourcesContent":["export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'\n"],"names":["normalizeFilename","normalizeFilenameHook"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,qBAAqB,QAAQ,yBAAwB"}
{"version":3,"sources":["../../../src/modules/media/index.ts"],"sourcesContent":["export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'\nexport { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'\nexport type { OptimizeUploadOptions } from './optimizeUpload.js'\n"],"names":["normalizeFilename","normalizeFilenameHook","buildOptimizeUploadField","buildOptimizeUploadHook"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,qBAAqB,QAAQ,yBAAwB;AACjF,SAASC,wBAAwB,EAAEC,uBAAuB,QAAQ,sBAAqB"}
+45
View File
@@ -0,0 +1,45 @@
import type { CheckboxField, CollectionBeforeOperationHook } from 'payload';
/**
* Safety net for oversized uploads — NOT an image pipeline. The developer and
* editor are expected to upload prepared files; this only catches the 8 MB
* phone photo or the raw 300 MB video, and asks before touching anything.
*
* - JPG / PNG over the limits → upload is stopped with an explanation; the
* editor ticks "Optimize this upload" and saves again → converted to WebP,
* resized to maxImageWidth, auto-rotated, metadata (EXIF/GPS) removed.
* - Video over maxVideoBytes → stopped with export instructions (never
* transcoded — that needs ffmpeg and minutes of CPU per file).
* - Everything else (GIF, SVG, WebP, AVIF, PDF, animated images) → untouched.
*
* Uses the `sharp` instance passed to buildConfig({ sharp }) — the plugin
* never imports sharp itself.
*/
export type OptimizeUploadOptions = {
/** Name of the consent checkbox (buildOptimizeUploadField). Default 'optimizeOnUpload'. */
consentField?: string;
/** Image size limit in bytes. Default 1.5 MB. */
maxImageBytes?: number;
/** Image width limit in px — also the target width after optimizing. Default 2560. */
maxImageWidth?: number;
/** Video size limit in bytes. Default 20 MB. `false` = no video limit. */
maxVideoBytes?: false | number;
/**
* PNG handling: 'lossless' (default — safe for screenshots, logos, text) or
* 'lossy' (much smaller, may soften fine text).
*/
png?: 'lossless' | 'lossy';
/** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */
quality?: number;
};
/**
* Consent checkbox for the upload collection's sidebar. Unticked by default;
* only read when a file exceeds the limits.
*/
export declare function buildOptimizeUploadField(name?: string): CheckboxField;
/**
* beforeOperation hook for an upload collection (e.g. Media):
*
* hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] },
* fields: [..., buildOptimizeUploadField()],
*/
export declare function buildOptimizeUploadHook(options?: OptimizeUploadOptions): CollectionBeforeOperationHook;
+107
View File
@@ -0,0 +1,107 @@
import { readFile } from 'node:fs/promises';
import { APIError } from 'payload';
const OPTIMIZABLE = new Set([
'image/jpeg',
'image/png'
]);
const MB = 1024 * 1024;
const fmt = (bytes)=>`${(bytes / MB).toFixed(1)} MB`;
/**
* Consent checkbox for the upload collection's sidebar. Unticked by default;
* only read when a file exceeds the limits.
*/ export function buildOptimizeUploadField(name = 'optimizeOnUpload') {
return {
name,
type: 'checkbox',
admin: {
description: 'Only used when an image is too large: converts it to WebP, resizes it and removes metadata (EXIF/GPS). Prepared files are never changed.',
position: 'sidebar'
},
defaultValue: false,
label: 'Optimize this upload'
};
}
/**
* beforeOperation hook for an upload collection (e.g. Media):
*
* hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] },
* fields: [..., buildOptimizeUploadField()],
*/ export function buildOptimizeUploadHook(options = {}) {
const { consentField = 'optimizeOnUpload', maxImageBytes = 1.5 * MB, maxImageWidth = 2560, maxVideoBytes = 20 * MB, png = 'lossless', quality = 82 } = options;
return async ({ args, operation, req })=>{
if (operation !== 'create' && operation !== 'update') {
return;
}
const file = req.file;
if (!file) {
return;
}
const data = args.data;
const consent = Boolean(data?.[consentField]);
const size = file.size || file.data?.length || 0;
// --- Video: limit only, never transcoded ---
if (file.mimetype.startsWith('video/')) {
if (maxVideoBytes !== false && size > maxVideoBytes) {
throw new APIError(`Video is ${fmt(size)} (limit ${fmt(maxVideoBytes)}). Export it before uploading: ` + 'MP4 (H.264), 720p–1080p, about 2–4 Mbit/s, no audio track for background videos, ' + '"web optimized" / fast start enabled (e.g. HandBrake preset "Web").', 400, undefined, true);
}
return;
}
if (!OPTIMIZABLE.has(file.mimetype)) {
return;
} // GIF, SVG, WebP, AVIF, PDF… untouched
const sharp = req.payload.config.sharp;
const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined;
if (!buffer) {
return;
}
let width;
let animated = false;
if (sharp) {
const meta = await sharp(buffer).metadata();
width = meta.width;
animated = (meta.pages ?? 1) > 1;
}
if (animated) {
return;
} // APNG — converting would drop the animation
const tooHeavy = size > maxImageBytes;
const tooWide = width !== undefined && width > maxImageWidth;
if (!tooHeavy && !tooWide) {
return;
}
const problem = [
tooHeavy ? `${fmt(size)} (limit ${fmt(maxImageBytes)})` : null,
tooWide ? `${width} px wide (limit ${maxImageWidth} px)` : null
].filter(Boolean).join(', ');
if (!consent) {
throw new APIError(`Image is ${problem}. Tick "Optimize this upload" in the sidebar and save again to convert it ` + `to WebP (max ${maxImageWidth} px wide, metadata removed), or upload a smaller file.`, 400, undefined, true);
}
if (!sharp) {
throw new APIError('Image optimization needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.', 500, undefined, true);
}
const lossless = file.mimetype === 'image/png' && png === 'lossless';
const output = await sharp(buffer).rotate() // apply EXIF orientation before metadata is dropped
.resize({
width: maxImageWidth,
withoutEnlargement: true
}).webp(lossless ? {
lossless: true
} : {
quality
}).toBuffer();
// Conversion didn't help (rare) and the width was fine → keep the original.
if (output.length >= size && !tooWide) {
return;
}
file.data = output;
file.size = output.length;
file.mimetype = 'image/webp';
file.name = `${file.name.replace(/\.[^.]+$/, '')}.webp`;
delete file.tempFilePath; // Payload must read the new buffer, not the temp file
if (data) {
data[consentField] = false;
} // next oversized upload asks again
};
}
//# sourceMappingURL=optimizeUpload.js.map
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -68,7 +68,8 @@
"'none'"
]
};
if (r2Url) {
// Site-relative R2_PUBLIC_URL ('/media', dev) is same-origin — already covered by 'self'.
if (r2Url && /^https?:\/\//i.test(r2Url)) {
src['img-src'].push(r2Url);
}
if (turnstile) {
File diff suppressed because one or more lines are too long
+33 -30
View File
@@ -1,38 +1,41 @@
export { buildAutoFillMetaHook } from './autoFillMeta.js';
export type { AutoFillMapping } from './autoFillMeta.js';
export { buildArticleJsonLd } from './buildArticleJsonLd.js';
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js';
export { buildFaqJsonLd } from './buildFaqJsonLd.js';
export { buildIconsMetadata } from './buildIconsMetadata.js';
export { buildLlmsTxt } from './buildLlmsTxt.js';
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
export { createManifestHandler } from './buildManifest.js';
export type { SeoOption, SeoMeta } from './types.js';
export { composeTitle } from './composeTitle.js';
export type { TitleOrder } from './composeTitle.js';
export { buildHreflangAlternates } from './hreflang.js';
export { buildMetadata } from './buildMetadata.js';
export type { PageMetadata } from './buildMetadata.js';
export { buildNoindexField } from './buildNoindexField.js';
export { buildOrganizationJsonLd } 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 { buildSeoPlugin } from './seoPluginConfig.js';
export { buildAutoFillMetaHook } from './autoFillMeta.js';
export { injectAutoFillMeta } from './injectAutoFillMeta.js';
export { injectSeoTabs } from './injectSeoTabs.js';
export type { AutoFillMapping } from './autoFillMeta.js';
export { createMetadataGenerator } from './createMetadataGenerator.js';
export { createPageMetadata } from './createPageMetadata.js';
export { readSiteMetaConfig } from './readSiteMetaConfig.js';
export type { SiteMetaConfig } from './readSiteMetaConfig.js';
export { slugsAcrossLocales } from './slugsAcrossLocales.js';
export { buildSitemapEntries } from './buildSitemapEntries.js';
export type { SitemapEntry } from './buildSitemapEntries.js';
export { buildSitemapXml } from './buildSitemapXml.js';
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js';
export type { SitemapEntry } from './buildSitemapEntries.js';
export { buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './buildRobots.js';
export type { RobotsRules, RobotsOptions } from './buildRobots.js';
export { buildIconsMetadata } from './buildIconsMetadata.js';
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
export { validateFaviconField } from './validateFavicon.js';
export { buildNoindexField } from './buildNoindexField.js';
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js';
export { buildSummaryField } from './buildSummaryField.js';
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js';
export { composeTitle } from './composeTitle.js';
export type { TitleOrder } from './composeTitle.js';
export { createMetadataGenerator } from './createMetadataGenerator.js';
export { createPageMetadata } from './createPageMetadata.js';
export { buildHreflangAlternates } from './hreflang.js';
export { injectAutoFillMeta } from './injectAutoFillMeta.js';
export { injectSeoTabs } from './injectSeoTabs.js';
export { JsonLdGraph } from './JsonLdGraph.js';
export { readSiteMetaConfig } from './readSiteMetaConfig.js';
export type { SiteMetaConfig } from './readSiteMetaConfig.js';
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js';
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js';
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
export { buildFaqJsonLd } from './buildFaqJsonLd.js';
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
export { buildArticleJsonLd } from './buildArticleJsonLd.js';
export { buildLlmsTxt } from './buildLlmsTxt.js';
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js';
export { buildSeoPlugin } from './seoPluginConfig.js';
export { slugsAcrossLocales } from './slugsAcrossLocales.js';
export type { SeoMeta, SeoOption } from './types.js';
export { validateFaviconField } from './validateFavicon.js';
export type { SitemapRouteOptions } from './routeHandlers.js';
export { buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './sitemapStyle.js';
export type { SitemapStyleOptions } from './sitemapStyle.js';
export { createManifestHandler } from './buildManifest.js';
export { JsonLdGraph } from './JsonLdGraph.js';
+25 -24
View File
@@ -1,33 +1,34 @@
export { buildAutoFillMetaHook } from './autoFillMeta.js';
export { buildArticleJsonLd } from './buildArticleJsonLd.js';
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js';
export { buildFaqJsonLd } from './buildFaqJsonLd.js';
export { buildIconsMetadata } from './buildIconsMetadata.js';
export { buildLlmsTxt } from './buildLlmsTxt.js';
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
export { createManifestHandler } from './buildManifest.js';
export { composeTitle } from './composeTitle.js';
export { buildHreflangAlternates } from './hreflang.js';
export { buildMetadata } from './buildMetadata.js';
export { buildNoindexField } from './buildNoindexField.js';
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js';
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
export { buildSeoPlugin } from './seoPluginConfig.js';
export { buildAutoFillMetaHook } from './autoFillMeta.js';
export { injectAutoFillMeta } from './injectAutoFillMeta.js';
export { injectSeoTabs } from './injectSeoTabs.js';
export { createMetadataGenerator } from './createMetadataGenerator.js';
export { createPageMetadata } from './createPageMetadata.js';
export { readSiteMetaConfig } from './readSiteMetaConfig.js';
export { slugsAcrossLocales } from './slugsAcrossLocales.js';
export { buildSitemapEntries } from './buildSitemapEntries.js';
export { buildSitemapXml } from './buildSitemapXml.js';
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js';
export { buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './buildRobots.js';
export { buildIconsMetadata } from './buildIconsMetadata.js';
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
export { validateFaviconField } from './validateFavicon.js';
export { buildNoindexField } from './buildNoindexField.js';
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js';
export { buildSummaryField } from './buildSummaryField.js';
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js';
export { composeTitle } from './composeTitle.js';
export { createMetadataGenerator } from './createMetadataGenerator.js';
export { createPageMetadata } from './createPageMetadata.js';
export { buildHreflangAlternates } from './hreflang.js';
export { injectAutoFillMeta } from './injectAutoFillMeta.js';
export { injectSeoTabs } from './injectSeoTabs.js';
export { JsonLdGraph } from './JsonLdGraph.js';
export { readSiteMetaConfig } from './readSiteMetaConfig.js';
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js';
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js';
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
export { buildFaqJsonLd } from './buildFaqJsonLd.js';
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
export { buildArticleJsonLd } from './buildArticleJsonLd.js';
export { buildLlmsTxt } from './buildLlmsTxt.js';
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js';
export { buildSeoPlugin } from './seoPluginConfig.js';
export { slugsAcrossLocales } from './slugsAcrossLocales.js';
export { validateFaviconField } from './validateFavicon.js';
export { buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './sitemapStyle.js';
export { createManifestHandler } from './buildManifest.js';
export { JsonLdGraph } from './JsonLdGraph.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsOptions, RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,WAAW,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export type { SeoOption, SeoMeta } from './types.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './buildRobots.js'\nexport type { RobotsRules, RobotsOptions } from './buildRobots.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { validateFaviconField } from './validateFavicon.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport type { SitemapRouteOptions } from './routeHandlers.js'\nexport { buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './sitemapStyle.js'\nexport type { SitemapStyleOptions } from './sitemapStyle.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\n"],"names":["composeTitle","buildHreflangAlternates","buildMetadata","buildSeoPlugin","buildAutoFillMetaHook","injectAutoFillMeta","injectSeoTabs","createMetadataGenerator","createPageMetadata","readSiteMetaConfig","slugsAcrossLocales","buildSitemapEntries","buildSitemapXml","buildRobots","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildLocalBusinessJsonLd","buildFaqJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","createLlmsTxtRoute","createSitemapRouteHandler","buildSitemapCss","SITEMAP_STYLE_PARAM","DEFAULT_SITEMAP_CREDIT","createManifestHandler","JsonLdGraph"],"mappings":"AACA,SAASA,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,qBAAqB,QAAQ,oBAAmB;AACzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AAEtD,SAASC,WAAW,EAAEC,iBAAiB,EAAEC,gBAAgB,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,oBAAoB,QAAQ,uBAAsB;AAC3D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAElF,SAASC,eAAe,EAAEC,mBAAmB,EAAEC,sBAAsB,QAAQ,oBAAmB;AAEhG,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,WAAW,QAAQ,mBAAkB"}
+25 -16
View File
@@ -1,6 +1,7 @@
import type { BasePayload } from 'payload';
import type { I18nConfig } from '../i18n/index.js';
import type { SitemapEntry } from './buildSitemapEntries.js';
import { type SitemapStyleOptions } from './sitemapStyle.js';
/**
* Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch
* every project was copying. buildLlmsTxt already handles collections without
@@ -31,20 +32,28 @@ export declare function createLlmsTxtRoute(opts: {
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
summaryField?: string;
}): () => Promise<Response>;
/**
* Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.
* Replaces the hand-written route in every project. Pass the project's `sitemap`
* helper (from createContentHelpers) and optionally a cssUrl.
*
* // app/sitemap.xml/route.ts
* import { createSitemapRouteHandler } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })
*
* Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps
* confuse crawlers).
*/
export declare function createSitemapRouteHandler(sitemap: () => Promise<SitemapEntry[]>, opts?: {
export type SitemapRouteOptions = {
/** Legacy: your own stylesheet URL (e.g. '/sitemap.css'). Overrides `style`. */
cssUrl?: string;
}): () => Promise<Response>;
/**
* Built-in browser look (default ON): the XML points at `<this route>?style`
* and the same handler serves the CSS — nothing to copy into /public.
* `false` = raw XML. Object = header/credit/accent (SitemapStyleOptions);
* `title` may be async (sitemapRoute passes the Site Settings name).
*/
style?: ({
title?: (() => Promise<string | undefined>) | string;
} & Omit<SitemapStyleOptions, 'title'>) | false;
};
/**
* Ready-made Next route handler for /sitemap.xml, styled for humans out of the box.
* Usually you don't call this — `createContentHelpers` returns `sitemapRoute`:
*
* // app/sitemap.xml/route.ts — the whole file
* export { sitemapRoute as GET } from '@/lib/content'
* export const dynamic = 'force-dynamic'
*
* `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS.
* Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers.
*/
export declare function createSitemapRouteHandler(sitemap: () => Promise<SitemapEntry[]>, opts?: SitemapRouteOptions): (req: Request) => Promise<Response>;
+32 -11
View File
@@ -1,5 +1,6 @@
import { buildLlmsTxt } from './buildLlmsTxt.js';
import { buildSitemapXml } from './buildSitemapXml.js';
import { buildSitemapCss, SITEMAP_STYLE_PARAM } from './sitemapStyle.js';
/**
* Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch
* every project was copying. buildLlmsTxt already handles collections without
@@ -49,24 +50,44 @@ import { buildSitemapXml } from './buildSitemapXml.js';
};
}
/**
* Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.
* Replaces the hand-written route in every project. Pass the project's `sitemap`
* helper (from createContentHelpers) and optionally a cssUrl.
* Ready-made Next route handler for /sitemap.xml, styled for humans out of the box.
* Usually you don't call this — `createContentHelpers` returns `sitemapRoute`:
*
* // app/sitemap.xml/route.ts
* import { createSitemapRouteHandler } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content'
* // app/sitemap.xml/route.ts — the whole file
* export { sitemapRoute as GET } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })
*
* Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps
* confuse crawlers).
* `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS.
* Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers.
*/ export function createSitemapRouteHandler(sitemap, opts = {}) {
return async ()=>{
const style = opts.cssUrl ? false : opts.style === false ? false : opts.style ?? {};
// `req` is required: Next 16 type-checks the first argument of a route handler
// (`Request | undefined` fails the build). A zero-argument call is not supported.
return async (req)=>{
const url = new URL(req.url);
if (style && url.searchParams.has(SITEMAP_STYLE_PARAM)) {
let title;
try {
title = typeof style.title === 'function' ? await style.title() : style.title;
} catch {
title = undefined; // DB down → generic heading, never a broken stylesheet
}
return new Response(buildSitemapCss({
...style,
title
}), {
headers: {
'Cache-Control': 'public, max-age=3600',
'Content-Type': 'text/css; charset=utf-8',
'X-Robots-Tag': 'noindex'
}
});
}
const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined);
try {
const entries = await sitemap();
const xml = buildSitemapXml(entries, {
cssUrl: opts.cssUrl
cssUrl
});
return new Response(xml, {
headers: {
File diff suppressed because one or more lines are too long
+21
View File
@@ -0,0 +1,21 @@
/**
* Built-in look of /sitemap.xml in a browser — served by the sitemap route itself
* (`/sitemap.xml?style`), so projects ship NO sitemap.css and copy nothing.
* Plain CSS on XML (W3C "Associating Style Sheets with XML", type="text/css") —
* not XSLT, which browsers are removing. Crawlers ignore it.
*/
export type SitemapStyleOptions = {
/** Accent colour (card hover). Default '#027bd0'. Any plain CSS colour. */
accent?: string;
/**
* Line under the header — the technology provider. Default
* "Technology by Intecion.com". `false` hides it.
*/
credit?: false | string;
/** Header line. Default "XML Sitemap". */
title?: string;
};
/** Query parameter on the sitemap URL that returns the stylesheet instead of XML. */
export declare const SITEMAP_STYLE_PARAM = "style";
export declare const DEFAULT_SITEMAP_CREDIT = "Technology by Intecion.com";
export declare function buildSitemapCss({ accent, credit, title }?: SitemapStyleOptions): string;
+70
View File
@@ -0,0 +1,70 @@
/**
* Built-in look of /sitemap.xml in a browser — served by the sitemap route itself
* (`/sitemap.xml?style`), so projects ship NO sitemap.css and copy nothing.
* Plain CSS on XML (W3C "Associating Style Sheets with XML", type="text/css") —
* not XSLT, which browsers are removing. Crawlers ignore it.
*/ /** Query parameter on the sitemap URL that returns the stylesheet instead of XML. */ export const SITEMAP_STYLE_PARAM = 'style';
export const DEFAULT_SITEMAP_CREDIT = 'Technology by Intecion.com';
/** CSS `content: "…"` value — escapes backslashes, quotes and newlines. */ const cssString = (s)=>`"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/[\r\n]+/g, ' ')}"`;
/** Only plain colour values — the option ends up inside a stylesheet. */ const safeColor = (c, fallback)=>c && /^(?:#[0-9a-f]{3,8}|[a-z]+|(?:rgb|hsl|oklch)a?\([\d\s.,%/-]+\))$/i.test(c.trim()) ? c.trim() : fallback;
export function buildSitemapCss({ accent, credit, title } = {}) {
const heading = title?.trim() || 'XML Sitemap';
const note = credit === false ? '' : (credit ?? DEFAULT_SITEMAP_CREDIT).trim();
const acc = safeColor(accent, '#027bd0');
const divider = 'padding-bottom: 1.25rem; margin-bottom: 1.5rem; border-bottom: 1px solid var(--border);';
return `:root {
--bg: #fafafa; --card: #ffffff; --border: #e5e7eb; --border-hover: #d1d5db;
--text-main: #111827; --text-secondary: #4b5563; --text-muted: #9ca3af; --url-color: #1e293b;
--badge-bg: #f3f4f6; --badge-border: #e5e7eb; --badge-text: #4b5563; --accent: ${acc};
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #090a0f; --card: #12131a; --border: #1e202e; --border-hover: #2e3247;
--text-main: #f9fafb; --text-secondary: #9ca3af; --text-muted: #6b7280; --url-color: #f3f4f6;
--badge-bg: #1a1c26; --badge-border: #282b3d; --badge-text: #9ca3af;
}
}
urlset {
display: flex; flex-direction: column; box-sizing: border-box; min-height: 100vh;
max-width: 1040px; margin: 0 auto; padding: 3rem 1.5rem; line-height: 1.5;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, Helvetica, Arial, sans-serif;
background-color: var(--bg); color: var(--text-main);
}
urlset::before {
content: ${cssString(heading)};
display: block; order: -2; font-size: 1.35rem; font-weight: 600; letter-spacing: -0.02em;
color: var(--text-main); ${note ? 'padding-bottom: 0.4rem;' : divider}
}
${note ? `urlset::after {
content: ${cssString(note)};
display: block; order: -1; font-size: 0.8rem; color: var(--text-muted); ${divider}
}
` : ''}url {
display: block; width: 100%; order: 0; box-sizing: border-box;
background-color: var(--card); border: 1px solid var(--border); border-radius: 8px;
padding: 1rem 1.25rem; margin-bottom: 0.65rem;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
url:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); }
loc {
display: block; margin-bottom: 0.45rem; word-break: break-all; line-height: 1.45;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
font-size: 0.875rem; font-weight: 500; color: var(--url-color);
}
lastmod, changefreq, priority {
display: inline-block; font-size: 0.775rem; color: var(--text-secondary);
margin-right: 1.25rem; margin-top: 0.15rem;
}
lastmod::before { content: "Updated: "; color: var(--text-muted); }
changefreq::before { content: "Frequency: "; color: var(--text-muted); }
priority::before { content: "Priority: "; color: var(--text-muted); }
link {
display: inline-block; font-size: 0.7rem; font-weight: 600; text-transform: uppercase;
background-color: var(--badge-bg); border: 1px solid var(--badge-border); color: var(--badge-text);
padding: 0.1rem 0.45rem; border-radius: 4px; margin-right: 0.3rem; margin-top: 0.35rem;
}
link::before { content: attr(hreflang); }
`;
}
//# sourceMappingURL=sitemapStyle.js.map
File diff suppressed because one or more lines are too long
+28
View File
@@ -0,0 +1,28 @@
export type RateLimitArgs = {
/** Identifier to limit on — typically the client IP. */
key: string;
/** Max submissions allowed per window. Defaults to 5. */
max?: number;
/** Separate counter space per feature, e.g. 'form', 'search', 'mcp'. Default 'form'. */
scope?: string;
/** Window length in ms. Defaults to 60_000 (one minute). */
windowMs?: number;
};
/**
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
*/
export declare function checkRateLimit({ cost, key, max, scope, windowMs }: {
cost?: number;
} & RateLimitArgs): boolean;
/** Seconds until the key's window resets — for a Retry-After header. */
export declare function retryAfterSeconds(key: string, scope?: string): number;
/**
* Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the
* edge, the real visitor), then the first `x-forwarded-for` hop, then
* `x-real-ip`. Empty string when none — the limiter then lets the request through.
*/
export declare function clientIp(req: Request): string;
/** Standard 429 for route handlers. */
export declare function tooManyRequests(key: string, scope: string, body: unknown): Response;
+78
View File
@@ -0,0 +1,78 @@
/**
* Per-key fixed window, in memory. Shared by submitForm, createSearchRoute and
* createMcpRoute — each uses its own `scope`, so a busy search box never eats
* into the contact form's budget.
*
* Deliberately simple: no Redis, no dependency. The trade-off is that the
* counter lives in one process — with several instances behind a load balancer
* each keeps its own, so the effective limit is per-instance, not global. For a
* contact form that's fine (it raises the cost of flooding without pretending
* to be airtight); a high-security form should put a real limiter in front.
*
* State is module-level, so it survives between requests but resets on redeploy
* — acceptable for abuse throttling.
*/ const buckets = new Map();
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
const SWEEP_INTERVAL = 60_000;
function sweep(now) {
if (now - lastSweep < SWEEP_INTERVAL) {
return;
}
lastSweep = now;
for (const [key, bucket] of buckets){
if (bucket.resetAt <= now) {
buckets.delete(key);
}
}
}
/**
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
*/ export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }) {
if (!key) {
return true;
}
const now = Date.now();
sweep(now);
const id = `${scope}:${key}`;
const bucket = buckets.get(id);
if (!bucket || bucket.resetAt <= now) {
if (cost > max) {
return false;
}
buckets.set(id, {
count: cost,
resetAt: now + windowMs
});
return true;
}
if (bucket.count + cost > max) {
return false;
}
bucket.count += cost;
return true;
}
/** Seconds until the key's window resets — for a Retry-After header. */ export function retryAfterSeconds(key, scope = 'form') {
const bucket = buckets.get(`${scope}:${key}`);
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1;
}
/**
* Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the
* edge, the real visitor), then the first `x-forwarded-for` hop, then
* `x-real-ip`. Empty string when none — the limiter then lets the request through.
*/ export function clientIp(req) {
const h = req.headers;
return h.get('cf-connecting-ip')?.trim() || h.get('x-forwarded-for')?.split(',')[0]?.trim() || h.get('x-real-ip')?.trim() || '';
}
/** Standard 429 for route handlers. */ export function tooManyRequests(key, scope, body) {
return Response.json(body, {
headers: {
'cache-control': 'no-store',
'retry-after': String(retryAfterSeconds(key, scope))
},
status: 429
});
}
//# sourceMappingURL=rateLimit.js.map
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -45,8 +45,12 @@
// (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs
// pointing there. Without it, uploads work but images don't display publicly.
// See docs/storage.md.
const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash
// Site-relative value ('/media', dev only — ipalEnvRules rejects it in production)
// → prefixed with NEXT_PUBLIC_SERVER_URL so Payload still stores absolute URLs.
const rawPublicUrl = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '') // strip trailing slash
;
const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL?.trim().replace(/\/$/, '');
const publicUrl = rawPublicUrl?.startsWith('/') && serverUrl ? `${serverUrl}${rawPublicUrl}` : rawPublicUrl;
// generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a
// top-level one) — R2 needs it to point served URLs at the custom domain
// instead of the private S3 endpoint. Each collection gets either `true`
File diff suppressed because one or more lines are too long
+34
View File
@@ -0,0 +1,34 @@
/*
* @intecion/ipal-kit/fluid.css — fluid type & spacing scale (variables only, no classes).
* Scales smoothly from a 360px to a 1280px viewport; rem-based, so browser zoom and
* user font size still work (WCAG 1.4.4). Opt-in:
*
* @import "tailwindcss";
* @import "@intecion/ipal-kit/fluid.css";
* @theme inline {
* --text-display: var(--ipal-fs-display);
* --text-h1: var(--ipal-fs-h1);
* --text-h2: var(--ipal-fs-h2);
* --text-h3: var(--ipal-fs-h3);
* --text-lead: var(--ipal-fs-lg);
* --spacing-section: var(--ipal-space-section);
* --spacing-gutter: var(--ipal-space-gutter);
* --spacing-gap: var(--ipal-space-gap);
* }
* → text-h1, text-display, py-section, px-gutter, gap-gap
*
* The design (DESIGN.md) decides the numbers: override any variable in the project's
* :root — the plugin only removes the clamp() maths from every project.
*/
:root {
--ipal-fs-sm: clamp(0.875rem, 0.8505rem + 0.1087vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */
--ipal-fs-base: clamp(1rem, 0.9511rem + 0.2174vw, 1.125rem); /* 1→1.125rem · body text */
--ipal-fs-lg: clamp(1.125rem, 1.0272rem + 0.4348vw, 1.375rem); /* 1.125→1.375rem · lead / intro */
--ipal-fs-h3: clamp(1.25rem, 1.0543rem + 0.8696vw, 1.75rem); /* 1.25→1.75rem · h3 */
--ipal-fs-h2: clamp(1.5rem, 1.1087rem + 1.7391vw, 2.5rem); /* 1.5→2.5rem · h2 — section headings */
--ipal-fs-h1: clamp(2rem, 1.413rem + 2.6087vw, 3.5rem); /* 2→3.5rem · h1 — page heading */
--ipal-fs-display: clamp(2.5rem, 1.7174rem + 3.4783vw, 4.5rem); /* 2.5→4.5rem · hero / display */
--ipal-space-gap: clamp(1rem, 0.6087rem + 1.7391vw, 2rem); /* 1→2rem · gap between items in a section */
--ipal-space-gutter: clamp(1rem, 0.413rem + 2.6087vw, 2.5rem); /* 1→2.5rem · container side padding */
--ipal-space-section: clamp(3rem, 1.2391rem + 7.8261vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */
}
+3 -3
View File
@@ -3,9 +3,9 @@
| Kim jesteś | Czytaj |
|---|---|
| **Agent AI** pracujący w projekcie | [AGENT.md](./agent/AGENT.md) — reguły, struktura, budowa sekcji, kontrole przed „gotowe” |
| **Agent AI — skille** | [agent/skills/](./agent/skills) — 7 skilli `ipal-*` dla Antigravity/Claude Code (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) |
| **Agent AI — skille** | [agent/skills/](./agent/skills) — 14 skilli `ipal-*` dla Antigravity/Claude Code, w tym `ipal-site` (strona od briefu do raportu) i skrypty kontrolne (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) |
| **Programista** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — instalacja, nowy projekt, env, wdrożenie, aktualizacja, publikacja pluginu, Gitea |
| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — gotowe polecenia do wklejenia, krok po kroku, moduł po module |
| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — tryb autonomiczny (`/ipal-site`) i gotowe polecenia krok po kroku |
Szczegóły API — jeden plik na moduł:
@@ -22,7 +22,7 @@ Szczegóły API — jeden plik na moduł:
| Formularze, useForm, honeypot | [forms.md](./forms.md) |
| Hooki | [hooks.md](./hooks.md) |
| i18n, proxy, przełącznik języka | [i18n.md](./i18n.md) |
| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref | [links.md](./links.md) |
| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref, rowLabel | [links.md](./links.md) |
| Serwer MCP strony | [mcp.md](./mcp.md) |
| Komunikaty formularzy | [notifications.md](./notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
+157 -19
View File
@@ -17,7 +17,7 @@
## 0. KOMPAS (jeśli zapamiętasz tylko to)
1. **ipal-kit jest obowiązkowy.** Funkcja, którą plugin ma, idzie przez plugin.
Brakuje czegoś → zgłoś (§1.3), nie łataj w projekcie.
Brakuje czegoś → raport (§1.3, ipal-plugin-gap) + oznaczone obejście, nie cicha łata.
2. **Nic na sztywno.** Tekst, obraz, link, plik, dane firmy → panel. Domeny,
klucze → `.env`. Także w fallbacku `||` i w `catch`.
3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`.
@@ -27,6 +27,8 @@
FAQ/hero to bloki.
6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload +
`<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`.
**Panel przejrzysty** (§6.5a): powtarzalne = tablica „+ Add …” z `rowLabel`, nigdy
`cta1`/`cta2`; etykiety EN, krótkie; zero pustych pól „na zapas”.
7. **Renderery z pluginu:** `RenderBlocks` (nie `switch`), `RenderRichText` (nie
własny parser Lexical), `useForm` (nie ręczna hydraulika formularza).
8. **Zero `any` i `@ts-ignore`.** Typy z `@/payload-types`, `unknown` + guard.
@@ -35,6 +37,66 @@
---
## 0a. JAK PRACUJESZ — samodzielnie, jak doświadczony pracownik
Budujesz stronę od briefu do oddania. Człowiek dostarcza **decyzje biznesowe i
treści**, nie prowadzi Cię za rękę. Myślisz, przewidujesz problemy, sam je
rozwiązujesz i sam sprawdzasz swoją pracę. Do pełnej budowy użyj skilla
**ipal-site** — prowadzi przez wszystkie etapy.
### Decydujesz sam (i zapisujesz decyzję w `AGENTS.md` → „Ustalenia projektu”)
- wybory techniczne w ramach tych reguł: podział na bloki, warianty, nazwy,
podkomponenty, kolejność pracy, refaktor własnego kodu,
- naprawę wszystkiego, co znajdą build, `ipal-audit`, `ipal-seo-check`, `ipal-consent-check`,
- wartości domyślne pluginu (limity mediów, ISR, robots) — chyba że brief mówi inaczej.
### Pytasz tylko o to (zbierz pytania w **jedną listę**, nie po jednym)
- **dane, których nie ma** w briefie ani w panelu: języki, rynek, domena, dane firmy,
ID analityki i klucze integracji, adresy e-mail powiadomień;
- **decyzje nieodwracalne**: usuwanie treści, migracja bazy z treścią, zmiana slugów
opublikowanych stron, publikacja na produkcję;
- **sprzeczność** briefu z regułami (np. „ten tekst ma być na sztywno”) — od razu
z propozycją zgodnego rozwiązania;
- koszty i konta w usługach zewnętrznych.
Brakuje treści? **Nie czekaj** — buduj strukturę, wpisz do panelu treść z briefu.
Nie wymyślaj danych firmy, cen, opinii ani liczb — wpisz w panelu wyraźny
placeholder `[DO UZUPEŁNIENIA: …]` i wypisz go w raporcie końcowym.
### Przewidujesz — przed każdym zadaniem przejdź tę listę
| Pytanie | Typowa wpadka, której unikasz |
|---|---|
| Działa w **każdym języku**? (slug, treść, 404, przełącznik) | `/en/...` → 404, bo pusty slug EN |
| Strona zostaje **statyczna**? | `headers()`, `searchParams`, `cookies()` w drzewie stron (§4) |
| Zmiana schematu **gubi dane**? | zmiana nazwy pola bez migracji → **ipal-migrate-fields** |
| Build w kontenerze **bez bazy** przejdzie? | trasa czytająca bazę bez `force-dynamic` |
| Nowy skrypt / piksel / iframe **za zgodą**? | YouTube, mapa, czat ładowane przed zgodą (RODO) |
| Redaktor zmieni to **bez kodu**? | tekst, link albo obraz w JSX (§2) |
| **Wydajność**? | obraz poza `<Media>`, wideo bez `preload`, zapytania poza cache helperów |
| **Bezpieczeństwo**? | sekret w kliencie, brak `server-only`, Local API bez `overrideAccess: false` |
| Plugin **już to ma**? | własna wersja funkcji z ipal-kit (§1.1) |
### Sprawdzasz sam, zanim powiesz „gotowe”
Pełny `ipal-audit`, `ipal-seo-check` i `ipal-consent-check` na zbudowanej
aplikacji (`pnpm build && pnpm start`), test redaktora (§11). Wyniki dołączasz
do raportu — bez nich zadanie nie jest skończone.
### Gdy coś nie działa
Diagnozujesz (**ipal-debug**: objaw → przyczyna → poprawka), naprawiasz u źródła,
sprawdzasz ponownie. Nie zgłaszasz problemów, które możesz rozwiązać.
### Raportujesz tylko gdy
- **ipal-kit ma błąd albo brakuje w nim funkcji** → **ipal-plugin-gap** (raport +
minimalne, oznaczone obejście — praca idzie dalej, nie czekasz),
- widzisz **usprawnienie ipal-kit** przydatne w wielu projektach → **ipal-plugin-gap**
(typ: usprawnienie),
- **zadanie jest skończone** → raport końcowy (format w **ipal-site**).
Nie raportujesz postępu krok po kroku ani rzeczy, które sam naprawiłeś — te
trafiają jedną listą do raportu końcowego.
---
## 1. ipal-kit JEST OBOWIĄZKOWY
### 1.1 Zanim napiszesz cokolwiek
@@ -54,9 +116,10 @@ Reguła: **identyczne w każdym projekcie → plugin. Zależy od klienta → pro
| hooki (revalidate, slugHistory, cross-locale), strony systemowe, storage R2 | wygląd (Tailwind, DESIGN.md) |
### 1.3 Gdy w pluginie czegoś brakuje albo nie działa
**Zatrzymaj się. Nie łataj w projekcie** (hook z zaszytą wartością, własny
helper, `as any`). To prawie zawsze znak, że plugin już to ma (sprawdź docs) albo
pluginowi tego brakuje. Przygotuj raport:
**Nie łataj po cichu** (hook z zaszytą wartością, własny helper, `as any`). To
prawie zawsze znak, że plugin już to ma (sprawdź docs) albo pluginowi tego brakuje.
Skill **ipal-plugin-gap**: raport + minimalne, oznaczone obejście
(`// WORKAROUND ipal-kit <wersja>: …`), praca idzie dalej. Raport zawiera:
- opis problemu / brakującej funkcji,
- proponowane API (sygnatura funkcji / opcji),
- dlaczego to uniwersalne (przyda się w innych projektach).
@@ -102,9 +165,10 @@ src/
[[...slug]]/page.tsx # PODWÓJNE nawiasy; RenderBlocks
(payload)/ # panel (generowany)
manifest.ts # createManifestHandler + force-dynamic
sitemap.ts, robots.ts # z lib/content (+ force-dynamic na sitemap)
sitemap.xml/route.ts # sitemapRoute z lib/content + force-dynamic (wygląd z pluginu)
robots.ts # z lib/content
api/health/route.ts # createHealthRoute
instrumentation.ts # assertEnv(ipalEnvRules({...}))
instrumentation.ts # assertEnv(ipalEnvRules({...})) z '@intecion/ipal-kit/env'
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
components/
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
@@ -155,9 +219,9 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) →
wersja na każdy język + `<LocaleView>` (pages.md).
7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę:
`manifest.ts`, `sitemap.ts`/`sitemap.xml`, `llms.txt`, `api/health`. Handlery
`manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery
pluginu mają try/catch, ale `dynamic` musi być w pliku trasy.
8. **`instrumentation.ts`** z `assertEnv(ipalEnvRules({...}))` (env.md).
8. **`instrumentation.ts`** z `assertEnv(ipalEnvRules({...}))` importowanym z **`@intecion/ipal-kit/env`** (root ciągnie Payload → crash Edge/Turbopack), w `if (process.env.NEXT_RUNTIME === 'nodejs')` (env.md).
9. **RSC domyślnie.** `'use client'` tylko dla stanu/interakcji, w osobnym pliku;
sekcja zostaje serwerowa i podaje mu dane. Sekrety: `import 'server-only'`.
10. **Bloki nie importują `lib/*`** (cykl). Dane server-side → `enhanceProps`.
@@ -244,7 +308,9 @@ Typ linku: strona / URL (też mailto, tel, #anchor) / **plik** (upload). Plik do
pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink`.
**Obraz / wideo:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. Kolekcja
`media` dopuszcza PDF, ma `alt` (required, localized) i `normalizeFilenameHook`.
`media` dopuszcza PDF, ma `alt` (required, localized), `normalizeFilenameHook` i siatkę na za duże
pliki `buildOptimizeUploadHook` + `buildOptimizeUploadField` (storage.md). Pliki przygotowujesz
przed wgraniem — hook tylko łapie wpadki i pyta o zgodę.
**W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md):
- `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
@@ -266,10 +332,7 @@ Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma
**`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach):
```tsx
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
})
const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w layoucie, nie props
```
### 6.4 Warstwa 3 — sekcja = kompozycja
@@ -327,6 +390,66 @@ Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/c
Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
(`media` + `backgroundMedia`); rdzeń nazwy zostaje.
### 6.5a Panel redaktora — przejrzystość (każdy blok, kolekcja, global)
Redaktor ma otworzyć blok i od razu wiedzieć, co gdzie jest — bez dziesiątek
pustych pól, bez zgadywania, bez numerowanych slotów. Schemat projektujesz dla
**redaktora**, nie dla komponentu.
1. **Powtarzalne = jedna tablica z „+ Add …”**, nigdy numerowane pola.
`cta1Label`/`cta2Url`, `feature1Title`…`feature6Title`, `image2`, `phone2` → tablica:
przyciski `buildLinksField()` (panel: **„Add Button”**), elementy `items` z
`labels: { singular: 'Feature', plural: 'Features' }` (panel: **„Add Feature”**).
`maxRows` = ile mieści design, `minRows` tylko gdy bez elementu layout się sypie.
2. **Wiersz pokazuje swoją treść**: `admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }`
→ zwinięte wiersze „Fast delivery”, „24/7 support” zamiast „Feature 01”.
`buildLinksField` ma to wbudowane (wiersz = etykieta przycisku).
3. **Panel po angielsku, krótko.** `label` 1–3 słowa, Sentence case („Heading”,
„Background”); `admin.description` tylko gdy etykieta nie wystarcza — jedno
zdanie ≤ 80 znaków: co to robi / gdzie to widać, z przykładem formatu
(`'Section id for #links, e.g. "pricing".'`), nigdy jak działa kod. Opcje selectów
z czytelnym `label` („Inverted (dark)”), nie surową wartością.
4. **Żadnych pól „na zapas”.** Każde pole jest wyświetlane przez komponent; puste
opcjonalne pole = element się nie renderuje (komponent to obsługuje). Pola
zależne ukryj: `admin.condition` (pola wideo tylko przy `mediaType: 'video'`,
pola wariantu tylko przy tym `variant`). Wariant wyglądu = `variant` (select) w
jednym bloku, nie drugi blok z kopią pól.
5. **Kolejność = kolejność na stronie**: `header` → treść → `media` → `items` → `links`.
Ustawienia techniczne (`settings`: anchor, tło, wariant) w **sidebarze**.
Blok z > ~10 polami → `tabs` (`Content`, `Media`, `Settings`); krótkie pary
(`type` + `newTab`, `width` + `height`) w `row` z `admin.width: '50%'`.
6. **Linki tylko przez pola linku.** Każdy przycisk/odnośnik to `buildLinkField` /
`buildLinksField` (strona z listy, URL, plik) — nigdy tekstowe pole URL do
własnej strony, nigdy link wpisany w JSX.
7. **Nazwy dla ludzi.** Blok: `labels: { singular: 'Feature grid', plural: 'Feature grids' }`
— nazwa tego, co redaktor widzi na stronie. Kolekcja: `admin.useAsTitle`,
`defaultColumns` (3–4), `admin.group` (`Content`, `Settings`, `Forms`).
8. **`required` oszczędnie** — tylko gdy bez wartości sekcja jest zepsuta (np.
`heading` elementu listy, `alt` obrazu). Selecty i checkboxy z `defaultValue`.
```ts
// ŹLE — 14 pól, połowa zawsze pusta, numerowane sloty, link jako tekst
{ name: 'title', type: 'text' }, { name: 'subtitle', type: 'text' },
{ name: 'cta1Label', type: 'text' }, { name: 'cta1Url', type: 'text' },
{ name: 'cta2Label', type: 'text' }, { name: 'cta2Url', type: 'text' },
{ name: 'feature1Title', type: 'text' }, { name: 'feature1Text', type: 'text' }, // …feature3
{ name: 'bgColor', type: 'text', admin: { description: 'Kolor tła sekcji w hex, używany w className komponentu' } },
// DOBRZE — 4 pozycje w panelu, rośnie przyciskiem „+ Add …”
sectionHeaderField(), // Eyebrow / Heading / Intro
{ name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, maxRows: 6,
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') },
fields: [{ name: 'heading', type: 'text', localized: true, required: true }, { name: 'text', type: 'textarea', localized: true }] },
buildLinksField(), // „+ Add Button”
sectionSettingsField(), // sidebar: anchor, background
```
**Test pustego bloku** (po każdym nowym bloku, w panelu): dodaj blok na stronie →
na starcie widać ≤ 6 pozycji, wszystko po angielsku, przyciski i elementy dodaje
się „+ Add …”, zwinięte wiersze mają czytelne nazwy, nic nie wymaga wiedzy o kodzie.
Kontrole automatyczne: `ipal-audit` (sekcja „panel:”). Po dodaniu `rowLabel` w
projekcie: `pnpm payload generate:importmap`.
### 6.6 Antywzorce → poprawka
```ts
@@ -412,6 +535,10 @@ bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resource
ze źródła `DESIGN.md`. W komponentach tylko tokeny (`bg-primary`), **nigdy**
`bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na projekt: `--ipal-primary: var(--color-primary)`.
- Płynna typografia i odstępy: `@import "@intecion/ipal-kit/fluid.css"` + mapowanie w
`@theme` (`text-h1`, `py-section`, `px-gutter` — PROGRAMISTA §2.5). Nie pisz `clamp()`
w komponentach; inne wartości z `DESIGN.md` → nadpisz zmienne `--ipal-*` w `:root`.
- JSON-LD tylko przez `<JsonLdGraph>` z `/rsc` — nigdy własny `<script dangerouslySetInnerHTML>`.
- Fonty przez `next/font`, podpięte zmienną CSS do `@theme`.
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
- Warianty → `Record<Variant, string>`, nie łańcuchy ternary.
@@ -456,9 +583,9 @@ Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sek
| Metadata, sitemap, JSON-LD, llms.txt | `generatePageMetadata` (z `createContentHelpers`), `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md |
| Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md |
| Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md |
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `MediaPreconnect` | storage.md |
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField`, `MediaPreconnect` | storage.md |
| Email | `email: mailAdapter()` | email.md |
| Walidacja env | `assertEnv(ipalEnvRules({...}))` | env.md |
| Walidacja env | `assertEnv(ipalEnvRules({...}))` z `@intecion/ipal-kit/env` | env.md |
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
@@ -646,13 +773,24 @@ zadanie pasuje — ręcznie: `/<nazwa>`.
| Skill | Kiedy |
|---|---|
| `ipal-setup` | nowy projekt od zera |
| `ipal-block` | nowa albo poprawiana sekcja (blok) |
| `ipal-site` | **cała strona od briefu do raportu** — prowadzi przez pozostałe skille (§0a) |
| `ipal-setup` | nowy projekt od zera (fundament) |
| `ipal-block` | nowa albo poprawiana sekcja (blok) — schemat, panel (§6.5a), komponent |
| `ipal-collection` | „potrzebny blog / produkty / …” — zanim powstanie plik w `src/collections` |
| `ipal-nav` | nagłówek, menu, stopka, dane firmy |
| `ipal-form` | formularz z panelu: renderer, akcja `submitForm`, Turnstile, maile, GTM |
| `ipal-locale-add` | nowy język — konfiguracja, treść, skrypt `locale-coverage` |
| `ipal-migrate-fields` | zmiana pól, w których jest już treść — 3 fazy, skrypt z dry-run |
| `ipal-upgrade` | aktualizacja ipal-kit w istniejącym projekcie |
| `ipal-audit` | przed każdym „gotowe” — skrypt z kontrolami §11 + tsc + build |
| `ipal-plugin-gap` | pluginowi czegoś brakuje albo nie działa — raport zamiast łatki |
| `ipal-debug` | cokolwiek nie działa — procedura + tabela objaw → przyczyna → naprawa |
| `ipal-audit` | przed każdym „gotowe” — kontrole §11 + panel (§6.5a) + hardkody w JSX + tsc + build |
| `ipal-seo-check` | działająca strona oczami Googlebota (head, canonical, hreflang, sitemap, 404) |
| `ipal-consent-check` | przeglądarka: zero pikseli i cookies śledzących przed zgodą |
| `ipal-plugin-gap` | ipal-kit ma błąd albo brakuje funkcji — raport + oznaczone obejście, praca idzie dalej |
Skrypty w skillach uruchamiasz, nie czytasz (wynik wystarcza): `ipal-audit/scripts/audit.sh`,
`ipal-seo-check/scripts/seo-check.mjs`, `ipal-consent-check/scripts/consent-check.mjs`,
`ipal-locale-add/scripts/locale-coverage.ts`; szablony do skopiowania w `resources/`.
**Instalacja w projekcie** (raz i po każdej aktualizacji ipal-kit) — skrypt w
`package.json` projektu:
+41 -1
View File
@@ -49,6 +49,21 @@ UI=$(dirs src/blocks src/components)
echo "ipal-audit — $(pwd)"
# --- Skill templates must not be compiled as project code ---
if [ -d .agents ] && [ -f tsconfig.json ]; then
report ERROR "tsconfig.json does not exclude .agents" "skill templates (.ts/.tsx) break tsc / next build — \"exclude\": [\"node_modules\", \".agents\"]" \
"$(grep -qE '"exclude"[^]]*\.agents' tsconfig.json || echo tsconfig.json)"
fi
# --- Sitemap: one route, look from the plugin (seo.md) ---
SM_TS=$(ls src/app/sitemap.ts 2>/dev/null)
SM_ROUTE=$(ls src/app/sitemap.xml/route.ts 2>/dev/null)
if [ -n "$SM_TS" ] && [ -n "$SM_ROUTE" ]; then
report ERROR "two sitemaps" "seo.md — keep src/app/sitemap.xml/route.ts (sitemapRoute), delete src/app/sitemap.ts" "$(printf '%s\n%s' "$SM_TS" "$SM_ROUTE")"
fi
report WARNING "project copy of the sitemap stylesheet" "seo.md — sitemapRoute serves the look from the plugin; delete it (and cssUrl)" \
"$(ls public/sitemap.css 2>/dev/null)"
# --- Architecture (AGENT.md §4) ---
report ERROR "middleware.ts exists" "§4.1 Next 16 uses proxy.ts only" \
"$(ls src/middleware.ts middleware.ts 2>/dev/null)"
@@ -93,6 +108,9 @@ if [ -n "$BLOCKS" ]; then
report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \
"$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)"
report ERROR "hardcoded text in blocks" "§2 every visible text comes from the panel (localized field)" \
"$(node "$(dirname "$0")/jsx-text.mjs" $BLOCKS 2>/dev/null)"
report WARNING "inline <svg> in blocks" "§6.10 icons via media upload or Icon map" \
"$(g '<svg[ >]' $BLOCKS --include=*.tsx)"
@@ -103,6 +121,11 @@ if [ -n "$BLOCKS" ]; then
"$(g "from '\./Component'|/Component'" $BLOCKS --include=config.ts)"
fi
if [ -d src/components ]; then
report WARNING "hardcoded text in components/layout" "§2 texts and a11y labels from the panel — keep only symbols/numbers in code" \
"$(node "$(dirname "$0")/jsx-text.mjs" src/components 2>/dev/null)"
fi
if [ -n "$UI" ]; then
report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \
"$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)"
@@ -125,6 +148,17 @@ if [ -d src/collections ]; then
"$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
fi
# --- Editor panel clarity (§6.5a) ---
SCHEMA=$(dirs src/blocks src/collections src/globals src/fields)
if [ -n "$SCHEMA" ]; then
PANEL=$(node "$(dirname "$0")/panel-check.mjs" $SCHEMA)
while IFS= read -r rule; do
[ -z "$rule" ] && continue
level=${rule%%|*}; rest=${rule#*|}
report "$level" "panel: ${rest%%|*}" "§6.5a editor panel" "$(printf '%s\n' "$PANEL" | grep -F "$level|${rest%%|*}|" | cut -d'|' -f3-)"
done <<< "$(printf '%s\n' "$PANEL" | cut -d'|' -f1-2 | sort -u)"
fi
# --- Plugin duplicates (§1, §7) ---
report ERROR "own block renderer switch" "§7 use RenderBlocks + registry" \
"$(g 'switch *\(.*blockType' src --include=*.tsx --include=*.ts)"
@@ -133,7 +167,13 @@ report WARNING "files that usually duplicate the plugin" "§3 plugin has resolve
report ERROR "project copy of link fields" "links.md — use buildLinkField / buildLinksField / resolveLinkHref from the plugin" \
"$(ls src/fields/link.ts src/lib/links.ts 2>/dev/null; g "from '@/fields/link'|from '@/lib/links'" src --include=*.ts --include=*.tsx)"
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
"$(g 'node\.type *===|dangerouslySetInnerHTML' src --include=*.tsx)"
"$(g 'node\.type *===' src --include=*.tsx | nc 'node')"
HTML=$(node "$(dirname "$0")/html-check.mjs" src)
while IFS= read -r rule; do
[ -z "$rule" ] && continue
level=${rule%%|*}; title=${rule#*|}
report "$level" "$title" "§7 / seo.md" "$(printf '%s\n' "$HTML" | grep -F "$rule|" | cut -d'|' -f3-)"
done <<< "$(printf '%s\n' "$HTML" | cut -d'|' -f1-2 | sort -u)"
# --- Compile & build ---
if [ "$QUICK" -eq 0 ]; then
@@ -0,0 +1,38 @@
#!/usr/bin/env node
// Raw HTML in JSX (dangerouslySetInnerHTML), classified — prints "LEVEL|rule|file:line", exit 0.
// node html-check.mjs src
// - inline JSON-LD (<script type="application/ld+json">) without '<' escaping → ERROR (XSS:
// a "</script>" typed in the panel breaks out of the tag) → JsonLdGraph from /rsc
// - inline JSON-LD with escaping → WARNING (works; JsonLdGraph is the shared version)
// - anything else → WARNING (rich text → RenderRichText; other HTML must be sanitized)
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) { if (!/node_modules|\.next/.test(p)) for (const n of readdirSync(p)) walk(join(p, n)) }
else if (/\.(tsx|jsx)$/.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
for (const file of files) {
// blank out comments (keeps offsets/line numbers)
const src = readFileSync(file, 'utf8')
.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' '))
.replace(/(^|[^:'"`])\/\/.*$/gm, (c, p) => p + ' '.repeat(c.length - p.length))
for (const m of src.matchAll(/dangerouslySetInnerHTML/g)) {
// the element this prop belongs to: from its opening "<tag" to the end of the prop's {{ … }}
const open = src.lastIndexOf('<', m.index)
const close = src.indexOf('}}', m.index)
const el = src.slice(open, close < 0 ? m.index + 400 : close + 2)
const at = `${file}:${src.slice(0, m.index).split('\n').length}`
if (/^<script\b/.test(el) && /application\/ld\+json/.test(el)) {
if (/u003c|replace\(\/</.test(el)) console.log(`WARNING|inline JSON-LD — use <JsonLdGraph schemas={[…]}/> from @intecion/ipal-kit/rsc (seo.md)|${at}`)
else console.log(`ERROR|unescaped JSON-LD in <script> — XSS via "</script>" in panel text; use <JsonLdGraph/> from @intecion/ipal-kit/rsc|${at}`)
} else {
console.log(`WARNING|raw HTML (dangerouslySetInnerHTML) — rich text → RenderRichText; other HTML must be sanitized|${at}`)
}
}
}
@@ -0,0 +1,56 @@
#!/usr/bin/env node
// Finds user-visible text hardcoded in JSX (AGENT.md §2: everything visible comes from the panel).
// node jsx-text.mjs <dir> [<dir> …] → prints "file:line: text" per finding, exit 0
// Detects:
// - text between HTML text tags: <h2>Nasze usługi</h2>, <p>\n Lorem…\n</p>, </strong> więcej <
// - text attributes with words: alt="Logo firmy", placeholder="Twój e-mail", aria-label="Zamknij"
// Ignores comments, {expressions}, digits/punctuation/symbols only (404, →, ☰, ·).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
const TEXT_TAGS =
'h1|h2|h3|h4|h5|h6|p|span|a|button|li|label|strong|em|b|i|small|div|section|article|header|footer|main|nav|td|th|dt|dd|figcaption|blockquote|option|legend|summary|caption|q|cite|time|mark'
// Opening tags: HTML text tags or Capitalized components (<Link …>), never preceded by an
// identifier char — that excludes TS generics like useState<Boolean>( … ).
const OPEN_OR_CLOSE = new RegExp(
`(?:(?<![\\w.$])<(?:${TEXT_TAGS}|[A-Z][\\w.]*)(?:\\s[^<>]*)?>|</[A-Za-z][\\w.]*>)([^<>{}]*)(?=<|\\{)`,
'g',
)
const ATTR = /\b(alt|title|placeholder|aria-label|label)=("([^"]*)"|'([^']*)')/g
const WORD = /\p{L}{2,}/u
// Text right after a closing/self-closing tag may be the JS that follows the JSX
// expression (`<X /> : null`, `</div>) }`, `</p>\n const id = …`) — not visible text.
const JS_CODE = /(^|\s)(return|const|let|var|if|else|export|import|await|typeof)\b|=>|[=;`]|^\s*[:?)\]}]|&&|\|\|/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (p.endsWith('.tsx')) files.push(p)
}
process.argv.slice(2).forEach(walk)
// Blank out comments but keep line numbers.
const stripComments = (src) =>
src
.replace(/\{\/\*[\s\S]*?\*\/\}/g, (m) => m.replace(/[^\n]/g, ' '))
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
.replace(/(^|[^:"'`])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length))
const lineOf = (src, idx) => src.slice(0, idx).split('\n').length
for (const file of files) {
const src = stripComments(readFileSync(file, 'utf8'))
for (const m of src.matchAll(OPEN_OR_CLOSE)) {
const text = m[1].replace(/\s+/g, ' ').trim()
if (!text || !WORD.test(text) || JS_CODE.test(text)) continue
if (/&[a-z]+;/.test(text) && !WORD.test(text.replace(/&[a-z]+;/g, ''))) continue
console.log(`${file}:${lineOf(src, m.index + m[0].length - m[1].length)}: ${text.slice(0, 80)}`)
}
for (const m of src.matchAll(ATTR)) {
const value = m[3] ?? m[4] ?? ''
if (!WORD.test(value)) continue
console.log(`${file}:${lineOf(src, m.index)}: ${m[1]}="${value.slice(0, 60)}"`)
}
}
@@ -0,0 +1,54 @@
#!/usr/bin/env node
// Editor-panel clarity checks (AGENT.md §6.5a): prints "LEVEL|rule|file:line: detail", exit 0.
// node panel-check.mjs src/blocks src/collections src/globals src/fields
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.ts$/.test(p) && !/Component|\.d\.ts$/.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const lineOf = (src, i) => src.slice(0, i).split('\n').length
const out = (level, rule, file, src, i, detail) => console.log(`${level}|${rule}|${file}:${lineOf(src, i)}: ${detail}`)
const strip = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length))
for (const file of files) {
const src = strip(readFileSync(file, 'utf8'))
// numbered slots: cta1Label, feature2Title, image3, phone2 → array with "+ Add …"
for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+[a-zA-Z0-9]*)['"]/g)) {
if (/^(h[1-6]|x[0-9]|[a-z]?2fa)$/i.test(m[1])) continue
out('ERROR', 'numbered fields → one array field with labels {singular, plural} ("+ Add …")', file, src, m.index, m[1])
}
// panel text must be English and short
for (const m of src.matchAll(/\b(label|description|singular|plural|placeholder)\s*:\s*(['"`])((?:(?!\2).)*)\2/g)) {
const text = m[3]
if (POLISH.test(text)) out('WARNING', 'panel is English — labels/descriptions in English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`)
else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`)
}
// arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows)
for (const m of src.matchAll(/type:\s*['"]array['"]/g)) {
const before = src.slice(0, m.index)
const start = Math.max(before.lastIndexOf('name:'), before.lastIndexOf('{'))
const fieldsAt = src.indexOf('fields:', m.index)
const head = src.slice(start < 0 ? m.index : start, fieldsAt < 0 ? m.index + 400 : fieldsAt)
const name = head.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?'
if (!/\blabels\s*:/.test(head)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name)
if (!/rowLabel|RowLabel/.test(head)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name)
}
// too many fields in one block config → tabs / condition / arrays / variant
if (/\/blocks\/[^/]+\/config\.ts$/.test(file)) {
const n = (src.match(/name:\s*['"]/g) ?? []).length
const hasTabs = /type:\s*['"]tabs['"]/.test(src)
if (n > 14 && !hasTabs) out('WARNING', 'block has many fields and no tabs — tabs Content/Media/Settings, admin.condition, arrays', file, src, 0, `${n} fields`)
}
}
+11 -3
View File
@@ -1,6 +1,6 @@
---
name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
---
# ipal-block
@@ -15,7 +15,7 @@ Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
## 1. Plan (pokaż i czekaj na OK)
## 1. Plan (zapisz w 3–5 punktach, potem od razu kod — AGENT.md §0a)
- slug bloku (camelCase), nazwa folderu (PascalCase),
- lista pól **tylko** ze słownika AGENT.md §6.5:
`header`, `media`, `links`, `link`, `items` (+ `heading`, `text`, `content`), `settings`,
@@ -28,7 +28,12 @@ Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
Plik do pobrania = link typu `file`. Etykiety i opisy pól po angielsku.
Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:**
- powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '<Singular>') }`, `maxRows` z designu;
- zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”;
- etykiety EN 1–3 słowa, `description` tylko gdy potrzebny (≤ 80 znaków, co/gdzie, przykład);
- pola zależne `admin.condition`, wariant = `variant` select, > ~10 pól → `tabs`;
- blok: `labels: { singular: 'Feature grid', plural: 'Feature grids' }`.
2. `src/blocks/<Nazwa>/Component.tsx` — nazwany eksport, typ z `@/payload-types`
(`<Nazwa>Block & { locale: string }`), struktura:
`<Section settings>` → `<SectionHeader header>` → treść z `<Media>`, `<CMSLink>`,
@@ -40,6 +45,9 @@ Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
## 3. Weryfikacja
- `Component.tsx` ≤ ~80 linii JSX.
- **Test pustego bloku** w panelu: ≤ 6 pozycji na starcie, wszystko po angielsku,
„+ Add Button / Add Feature”, zwinięte wiersze z treścią, każde pole coś wyświetla.
Pierwszy `rowLabel` w projekcie → `pnpm payload generate:importmap`.
- Uruchom skill **ipal-audit** (`--quick`), napraw wszystkie `[ERROR]`.
- Refaktor istniejącego bloku ze zmianą nazw pól: **najpierw migracja danych**
(stare pole → nowe), dopiero potem usunięcie starych pól (AGENT.md §6.7).
@@ -40,9 +40,9 @@ export function sectionHeaderField(name = 'header'): GroupField {
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true },
{ name: 'eyebrow', type: 'text', localized: true, admin: { description: 'Small line above the heading. Optional.' } },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true },
{ name: 'intro', type: 'textarea', localized: true, admin: { rows: 3 } },
],
}
}
@@ -51,6 +51,7 @@ export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
label: 'Section settings',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
@@ -63,7 +64,11 @@ export function sectionSettingsField(): GroupField {
name: 'background',
type: 'select',
defaultValue: 'default',
options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })),
options: [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
],
},
],
}
@@ -143,14 +148,19 @@ type Props = {
sizes?: string
priority?: boolean
className?: string
/** Poster image URL for videos (shown before playback). */
poster?: string
}
export function Media({ resource, sizes = '100vw', priority = false, className }: Props) {
export function Media({ resource, sizes = '100vw', priority = false, className, poster }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null
const { url, alt, width, height, mimeType } = resource
if (mimeType?.startsWith('video/')) {
return <video src={url} className={className} autoPlay muted loop playsInline />
// preload="metadata": the browser fetches only headers until playback, not the whole file
return (
<video src={url} className={className} poster={poster} preload="metadata" autoPlay muted loop playsInline />
)
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
@@ -205,10 +215,7 @@ export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeader
**`locale` dla każdego bloku — raz, w trasie strony:**
```tsx
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
})
const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w layoucie, nie props
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
```
@@ -264,12 +271,16 @@ export function Hero({ header, media, links, settings, locale }: HeroBlock & { l
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields)
// src/blocks/FeatureGrid/config.ts (fields) — import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
sectionHeaderField(),
{
name: 'items',
type: 'array',
interfaceName: 'FeatureItem',
labels: { singular: 'Feature', plural: 'Features' }, // panel: "+ Add Feature"
minRows: 1,
maxRows: 6, // ile mieści design
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }, // wiersz = nagłówek
fields: [
{ name: 'media', type: 'upload', relationTo: 'media' },
{ name: 'heading', type: 'text', localized: true, required: true },
+5 -1
View File
@@ -23,14 +23,18 @@ Którekolwiek NIE → to nie kolekcja:
Wyjątek: lista bez własnych URL-i zarządzana osobno (np. opinie używane w wielu
blokach) — kolekcja **bez** wpięcia w `content`. Uzasadnij to w planie.
## 2. Plan (pokaż i czekaj na OK)
## 2. Plan (zapisz, potem od razu kod — AGENT.md §0a)
slug (camelCase, l.mn.), pola, relacje, czy ma URL-e (archiwum), JSON-LD.
Decyzję „kolekcja vs global vs blok” zapisz w `AGENTS.md` → „Ustalenia projektu”.
Pytasz tylko, gdy brief nie rozstrzyga czegoś biznesowego (np. „czy wpisy mają autorów?”).
## 3. Kod
1. `src/collections/<Nazwa>.ts`: `title` (localized), `buildSlugField({ from: 'title' })`,
tab SEO (plugin-seo), `buildNoindexField()`, `trackSlugHistoryHook`,
`buildRevalidateHook`, `setPublishedAtHook` (wpisy z datą), upload przez
`media`, linki przez `buildLinkField()`. Nazwy pól wg AGENT.md §6.5.
Panel (AGENT.md §6.5a): `admin.useAsTitle`, `defaultColumns` (3–4), `admin.group: 'Content'`,
`labels` po angielsku, tablice z `labels` + `rowLabel()`, ustawienia w sidebarze.
2. Z URL-ami: dopisz do `content.config.ts` → `{ slug, perPage }`.
**Prefiks URL nie w kodzie** — redaktor przypisuje stronę-archiwum w
Site Settings (`<slug>Archive`). Plugin robi routing, sitemap,
@@ -0,0 +1,39 @@
---
name: ipal-consent-check
description: Proves in a real browser (Playwright) that an ipal-kit site respects cookie consent — no Meta/Clarity/LinkedIn/TikTok/Ads requests and no tracking cookies before a decision or after "reject", Google only with Consent Mode "denied" signals, tags starting after "accept". Use after adding analytics, pixels, embeds (YouTube, maps, chat) or third-party scripts, before handing a site over, and whenever GDPR/RODO or cookie banner behaviour is in question.
---
# ipal-consent-check
RODO: tagi nie-Google ładują się **dopiero po zgodzie**; Google (GA4/GTM) może
się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ciasteczek.
## Kroki
1. Jednorazowo w projekcie:
```bash
pnpm add -D playwright && pnpm exec playwright install chromium
```
2. Uruchom aplikację (`pnpm build && pnpm start`) i sprawdź **stronę z tagami**
(najlepiej stronę główną i stronę z formularzem/wideo):
```bash
node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl
```
`--wait 6000` gdy tagi startują wolno (tryb `defer` w Analytics).
3. Wynik: trzy przebiegi w czystych profilach — brak decyzji, „Akceptuj”,
„Odrzuć” + przeładowanie. Każde `[ERROR]` to naruszenie — napraw:
| Naruszenie | Przyczyna → poprawka |
|---|---|
| piksel loaded without consent | skrypt wpięty ręcznie / skopiowany `Analytics` → ID w Site Integrations, `<Analytics>` z pluginu (analytics.md) |
| tracking cookie set without consent | to samo; albo GTM odpala tag bez warunku `ad_storage` (analytics.md → GTM) |
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` |
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` albo „kliknij, aby załadować” |
4. Sekcja „after accept” mówi, co startuje po zgodzie — porównaj z ID w Site
Integrations (np. czy Meta Pixel jest, jeśli klient go ma). Nic nie startuje,
a ID są wpisane → zgłoś to jako problem do diagnozy (**ipal-debug**).
5. Banner nie znaleziony (`data-ipal="banner"`) → `<CookieBanner/>` nie jest
renderowany albo starsza wersja ipal-kit bez atrybutów `data-ipal` na przyciskach → **ipal-upgrade**.
Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je
`CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7.
@@ -0,0 +1,134 @@
#!/usr/bin/env node
// ipal-consent-check — proves in a real browser that tracking waits for consent (GDPR).
// node consent-check.mjs <pageUrl> [--wait 4000]
// Three runs, each in a fresh browser profile:
// 1. no decision → no third-party pixels, no tracking cookies, Google only with "denied" signals
// 2. accept all → configured tags start (reported, so you can confirm they're the right ones)
// 3. reject all → same as 1, also after a reload
// Needs Playwright: pnpm add -D playwright && pnpm exec playwright install chromium
// Exit code: 0 = compliant, 1 = violations, 2 = setup problem.
const args = process.argv.slice(2)
if (!args[0] || args.includes('--help') || args.includes('-h')) {
console.log('Usage: consent-check.mjs <pageUrl> [--wait ms]')
process.exit(args[0] ? 0 : 2)
}
const url = args[0]
const waitIdx = args.indexOf('--wait')
const WAIT = waitIdx >= 0 ? Number(args[waitIdx + 1]) || 4000 : 4000
let pw
for (const mod of ['playwright', 'playwright-core', '@playwright/test']) {
try { pw = await import(mod); break } catch { /* next */ }
}
if (!pw) {
console.error('ipal-consent-check: Playwright not found. Install: pnpm add -D playwright && pnpm exec playwright install chromium')
process.exit(2)
}
const { chromium } = pw.default ?? pw
// Non-Google vendors have no Consent Mode → ANY request before consent is a violation.
const PIXELS = [
['Meta Pixel', /connect\.facebook\.net|facebook\.com\/tr/],
['Microsoft Clarity', /clarity\.ms/],
['LinkedIn Insight', /snap\.licdn\.com|px\.ads\.linkedin\.com/],
['TikTok Pixel', /analytics\.tiktok\.com/],
['DoubleClick / Google Ads', /doubleclick\.net|googleadservices\.com/],
['Hotjar', /hotjar\.com/],
]
// Embeds that set cookies — should wait for consent or use a privacy mode.
const EMBEDS = [
['YouTube (cookie mode)', /youtube\.com\/embed/],
['Google Maps embed', /google\.com\/maps\/embed/],
]
const GOOGLE_COLLECT = /google-analytics\.com\/(g\/)?collect|analytics\.google\.com\/g\/collect/
const GOOGLE_TAG = /googletagmanager\.com\/(gtm|gtag)/
const TRACKING_COOKIES = /^(_ga|_gid|_gat|_gcl_|_fbp|_fbc|_clck|_clsk|_ttp|li_|lidc|bcookie|_hj)/
// gcs=G1{ad}{analytics}: '1' = granted. Before consent both must not be '1'.
const consentGranted = (u) => {
const gcs = new URL(u).searchParams.get('gcs')
return gcs ? /^G1.?1|^G11/.test(gcs) : null
}
const browser = await chromium.launch()
const run = async (label, action) => {
const ctx = await browser.newContext()
const page = await ctx.newPage()
const requests = []
page.on('request', (r) => requests.push(r.url()))
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
} catch (e) {
console.error(`ipal-consent-check: cannot open ${url} (${e.message.split('\n')[0]})`)
await browser.close()
process.exit(2)
}
await page.waitForTimeout(WAIT)
await page.mouse.wheel(0, 2000) // some tags wait for interaction (Analytics defer)
await page.waitForTimeout(500)
const banner = (await page.locator('[data-ipal="banner"]').count()) > 0
let clicked = null
if (action) {
const btn = page.locator(`[data-ipal="${action}"]`)
if ((await btn.count()) > 0) {
const before = requests.length
await btn.first().click()
await page.waitForTimeout(WAIT)
clicked = before
if (action === 'reject') {
await page.reload({ waitUntil: 'domcontentloaded' })
await page.waitForTimeout(WAIT)
}
} else clicked = -1
}
const cookies = (await ctx.cookies()).map((c) => c.name)
await ctx.close()
return { label, requests, cookies, banner, clicked }
}
const violations = []
const warnings = []
const info = []
const inspect = (r, mustBeQuiet) => {
const pixelHits = PIXELS.filter(([, re]) => r.requests.some((u) => re.test(u))).map(([n]) => n)
const embedHits = EMBEDS.filter(([, re]) => r.requests.some((u) => re.test(u))).map(([n]) => n)
const trackingCookies = r.cookies.filter((c) => TRACKING_COOKIES.test(c))
const collects = r.requests.filter((u) => GOOGLE_COLLECT.test(u))
const grantedCollects = collects.filter((u) => consentGranted(u) === true)
if (mustBeQuiet) {
for (const p of pixelHits) violations.push(`${r.label}: ${p} loaded without consent`)
for (const c of trackingCookies) violations.push(`${r.label}: tracking cookie "${c}" set without consent`)
if (grantedCollects.length) violations.push(`${r.label}: Google Analytics hit with consent GRANTED (gcs) before a decision`)
const noSignal = collects.filter((u) => consentGranted(u) === null)
if (noSignal.length) warnings.push(`${r.label}: Google Analytics hit without Consent Mode signal (gcs) — setDefaultConsent must run before the tag`)
for (const e of embedHits) warnings.push(`${r.label}: ${e} loaded before consent — gate it (ConsentScript) or use youtube-nocookie / click-to-load`)
}
return { pixelHits, trackingCookies, google: r.requests.some((u) => GOOGLE_TAG.test(u) || GOOGLE_COLLECT.test(u)) }
}
const first = await run('1. no decision')
if (!first.banner) warnings.push('1. no decision: cookie banner [data-ipal="banner"] not found — is <CookieBanner/> rendered? Older ipal-kit versions lack data-ipal attributes on buttons.')
const s1 = inspect(first, true)
const accepted = await run('2. accept all', 'accept')
if (accepted.clicked === -1) warnings.push('2. accept: button [data-ipal="accept"] not found — skipped')
const afterAccept = { ...accepted, requests: accepted.clicked > 0 ? accepted.requests.slice(accepted.clicked) : accepted.requests }
const s2 = inspect(afterAccept, false)
if (!accepted.cookies.includes('cookie-consent') && accepted.clicked >= 0) warnings.push('2. accept: consent cookie "cookie-consent" not stored')
const rejected = await run('3. reject all (+ reload)', 'reject')
if (rejected.clicked === -1) warnings.push('3. reject: button [data-ipal="reject"] not found — skipped')
else inspect({ ...rejected, requests: rejected.requests.slice(rejected.clicked ?? 0) }, true)
await browser.close()
info.push(`before consent: Google tag ${s1.google ? 'loaded (Consent Mode, OK if gcs denied)' : 'not loaded'}`)
info.push(`after accept: ${s2.pixelHits.length ? s2.pixelHits.join(', ') : 'no third-party pixels'}${s2.google ? ' + Google' : ''}; cookies: ${accepted.cookies.filter((c) => TRACKING_COOKIES.test(c)).join(', ') || 'none'}`)
console.log(`ipal-consent-check — ${url}`)
for (const v of violations) console.log(`[ERROR] ${v}`)
for (const w of warnings) console.log(`[WARNING] ${w}`)
for (const i of info) console.log(` · ${i}`)
console.log(`ipal-consent-check: ${violations.length} violation(s), ${warnings.length} warning(s)`)
process.exit(violations.length ? 1 : 0)
+96
View File
@@ -0,0 +1,96 @@
---
name: ipal-debug
description: Systematic diagnosis for ipal-kit / Payload 3 / Next 16 projects — reproduce, classify (project code, configuration, panel data, environment, or an ipal-kit bug), fix the cause, prove it. Includes a symptom → cause → fix table of every failure seen so far (TS2307, static→dynamic, metadata in body, 404 per locale, importMap, duplicate @payloadcms/ui, emails, R2, Turnstile, hydration). Use whenever something fails — build, type check, runtime error, wrong behaviour, "it worked yesterday" — before asking the user anything.
---
# ipal-debug
Nie zgaduj, nie przepisuj na ślepo, nie pytaj użytkownika, zanim nie przejdziesz
tej procedury. Pytasz tylko, gdy brakuje czegoś, czego nie możesz uzyskać sam
(sekret, dostęp do panelu produkcji, decyzja biznesowa).
## Procedura
1. **Odtwórz** — dokładna komenda / URL / klik, pełny komunikat (pierwszy błąd w
logu, nie ostatni). Dev i build zachowują się inaczej — sprawdź oba, jeśli dotyczy renderingu/SEO.
2. **Zawęź warstwę**:
| Pytanie | Jak sprawdzić |
|---|---|
| kod projektu? | `git diff`/`git stash` → czy błąd znika |
| konfiguracja? | `payload.config.ts`, `next.config.ts`, `proxy.ts`, `.env` vs `docs/env.md` |
| dane w panelu? | ta sama strona w innym języku / inny dokument działa? `Save` kliknięty? |
| środowisko? | `rm -rf .next`, restart dev, `pnpm install`, wersje: `pnpm why @payloadcms/ui` |
| ipal-kit? | błąd w `node_modules/@intecion/ipal-kit/dist/…`, zachowanie niezgodne z `docs/<moduł>.md` |
3. **Tabela niżej** — większość błędów już się zdarzyła.
4. **Napraw przyczynę**, nie objaw (`as any`, `try/catch` połykający błąd,
`force-dynamic` „żeby działało”, kopia kodu pluginu do projektu = **nie**).
5. **Udowodnij**: ta sama komenda z kroku 1 przechodzi + `ipal-audit --quick` +
(rendering/SEO) `ipal-seo-check` na buildzie.
6. Błąd po stronie ipal-kit → obejście w projekcie **tylko jeśli jest czyste i
oznaczone** (`// WORKAROUND ipal-kit <wersja>: <opis>`) + raport **ipal-plugin-gap**.
Zapisz przypadek w `AGENTS.md` → „Ustalenia projektu”, jeśli wróci.
## Objaw → przyczyna → naprawa
### Build / TypeScript
| Objaw | Przyczyna | Naprawa |
|---|---|---|
| `TS2307 next/navigation` w `dist` pluginu | import bez `.js` w kliencie pluginu (NodeNext) | **bug ipal-kit** → plugin-gap; plugin importuje `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | brak pakietu przy `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol nie wyeksportowany z entry pointu albo zły subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → właściwy import; brak w każdym entry → **bug ipal-kit** (eksport) |
| `Cannot find module '@clocklimited/payload-2fa'` | brak wstrzyknięcia | `twoFactor: { plugin: payloadTotp }` |
| `Page changed from static to dynamic at runtime` | `headers()`, `cookies()`, `searchParams` w drzewie strony (często `not-found.tsx`) | locale z `params`; `not-found` → `LocaleView` (pages.md); `headers()` tylko w server actions / route handlers |
| trasy `ƒ` mimo `generateStaticParams` | build nie widzi bazy | `DATABASE_URI` w buildzie (PROGRAMISTA §4.3) |
| build pada `ENOTFOUND` / Mongoose | trasa czyta bazę w buildzie bez bazy | sitemap/robots/llms: `export const dynamic = 'force-dynamic'` (tylko one) |
| `slug.join is not a function` | `[slug]` zamiast `[[...slug]]` | zmień nazwę folderu |
| `Missing <html> and <body>` | layout `[locale]` bez `<html>` po usunięciu root layoutu | `<html lang>` i `<body>` w `[locale]/layout.tsx` |
| `Export fileTypeFromFile doesn't exist in target module` (Turbopack, start dev) | `instrumentation.ts` importuje z roota pakietu → Payload w bundlu Edge | import z `@intecion/ipal-kit/env` + `NEXT_RUNTIME === 'nodejs'` (env.md) |
| `R2_PUBLIC_URL must be a valid URL (got "/media")` | stara wersja reguły / produkcja ze ścieżką względną | dev: `/media` dozwolone od nowej wersji; produkcja: pełny URL domeny bucketu |
| `server-only` w kliencie | import z `@intecion/ipal-kit/server` w `'use client'` | wywołuj przez server action |
### Panel (`/admin`)
| Objaw | Przyczyna | Naprawa |
|---|---|---|
| `PayloadComponent not found in importMap` (np. `@intecion/ipal-kit/admin#RowLabel`) | importMap nieaktualny po aktualizacji pluginu / dodaniu `rowLabel` | `pnpm payload generate:importmap`, restart |
| `Cannot destructure property 'config'` / hooki UI bez kontekstu | dwie kopie `@payloadcms/ui` | `pnpm why @payloadcms/ui`; jedna wersja + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = pusto |
| pusty tab SEO, brak Forms | rozjazd wersji `@payloadcms/*` | wszystkie `@payloadcms/*` = wersja `payload` |
| upload odrzucony „Image is … Tick Optimize” | `buildOptimizeUploadHook` (zamierzone) | zaznacz checkbox albo przygotuj plik; limit w opcjach hooka |
| upload wideo odrzucony | limit `maxVideoBytes` | eksport wg komunikatu (H.264, 720–1080p, fast start) |
| zmiana w panelu niewidoczna | brak Save / ISR bez rewalidacji | `buildRevalidateHook` na kolekcji/globalu |
### Front / routing / SEO
| Objaw | Przyczyna | Naprawa |
|---|---|---|
| `/pl` → 404 | Homepage nieprzypisany w System Pages | ustaw w panelu |
| `/en/*` → 404, `/pl/*` działa | brak sluga/tytułu w EN | `ipal-locale-add` → `locale-coverage` |
| przełącznik języka → 404 | podmiana prefiksu zamiast `AlternateLinksUpdater` | i18n.md → AlternateLinks |
| metadata w `<body>` (seo-check) | streaming: brak `htmlLimitedBots`, jawny `<head>`, dynamiczna strona | AGENT §4; `generatePageMetadata` |
| canonical / sitemap z localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie | ustaw w env buildu (nie tylko runtime) |
| `/admin`, `/_next` → 500 lub pętla | matcher proxy nie jest literałem | matcher inline w `proxy.ts` |
| hydration mismatch przy banerze | odczyt cookie/`window` w renderze | consent tylko przez `CookieBanner`/`useConsentContext`; `Date`, `Math.random` poza renderem |
| obrazy nie ładują się (R2) | brak domeny w `images.remotePatterns` / zły `R2_PUBLIC_URL` | `next.config.ts` + env (storage.md) |
| 404 strona bez stylów/nav | `not-found.tsx` poza `[locale]` bez layoutu | pages.md — przykład `not-found` |
### Zgoda / analityka / formularze / mail
| Objaw | Przyczyna | Naprawa |
|---|---|---|
| piksel przed zgodą (consent-check) | skrypt wpięty ręcznie (`<Script>`) | wyłącznie przez panel → `<Analytics>` (GA/GTM/piksele) albo `<ConsentScript>` (analytics.md, consent.md) |
| baner bez stylów | Tailwind nie skanuje pluginu | `@source` na `node_modules/@intecion/ipal-kit/dist/**/*.js` (ścieżka względem pliku CSS, PROGRAMISTA §2.5) |
| maile nie wychodzą | brak `email: mailAdapter()` / pusty transport / pusta zakładka Emails | email.md; Send test w panelu |
| nadawca maila stary | cache klienta poczty | sprawdź surowe nagłówki |
| formularz: `unknown_fields` | pole spoza definicji (honeypot nieusunięty) | `ipal-form` → actions.ts |
| Turnstile zawsze odrzuca | token użyty drugi raz / zła domena w Cloudflare | reset tokenu po każdej próbie; domena w CF |
### Środowisko
| Objaw | Przyczyna | Naprawa |
|---|---|---|
| zmiana w pluginie niewidoczna | stara wersja w `node_modules` / `.next` | `pnpm add @intecion/ipal-kit@<wersja>`, `grep -c <symbol> node_modules/@intecion/ipal-kit/dist/...`, `rm -rf .next`, restart |
| skille nieaktualne po aktualizacji | nie odświeżone | `pnpm exec ipal-skills` |
| „Kod dobry, zachowanie złe” | — | po kolei: restart dev → Save w panelu → dublet zależności → importmap → cache |
## Kiedy to bug ipal-kit (raport, nie łatka w node_modules)
- błąd wskazuje plik w `dist` pluginu i nie wynika z błędnego użycia API z dokumentacji;
- zachowanie niezgodne z `docs/<moduł>.md`;
- dokumentacja każe importować coś, czego entry point nie eksportuje;
- ten sam boilerplate piszesz w drugim projekcie z rzędu (kandydat na moduł).
Wtedy **ipal-plugin-gap**: objaw, minimalne odtworzenie, wersja, proponowana
zmiana w pluginie, obejście użyte w projekcie. **Nigdy** nie edytuj `node_modules`.
+106
View File
@@ -0,0 +1,106 @@
---
name: ipal-form
description: Wires forms the ipal-kit way — forms built by the editor in the panel (form-builder Forms collection), one generic renderer, one server action with submitForm (rate limit, Turnstile, schema validation, GDPR consent), honeypot, panel texts from Notifications, emails from Forms → Emails over mailAdapter, GTM events from the panel. Use for any contact/lead/newsletter/quote form, a form block, "the form doesn't send", "no email arrives", spam, or Turnstile problems.
---
# ipal-form
**Formularz buduje redaktor w panelu. Ty piszesz raz: renderer + akcję.** Każdy
kolejny formularz to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
(ipal-audit to złapie). Szczegóły API: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`.
## 1. Config (raz na projekt)
```ts
// payload.config.ts
import { ipalKit, mailAdapter, buildFormAnalyticsFields } from '@intecion/ipal-kit'
export default buildConfig({
email: mailAdapter(), // bez tego maile z Forms → Emails nie wyjdą
plugins: [ipalKit({
i18n: i18nConfig,
forms: {
redirectRelationships: ['pages'],
formOverrides: { fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()] },
},
})],
})
```
`@payloadcms/plugin-form-builder` w `dependencies` projektu **w tej samej wersji co
`payload`** (rozjazd = brak kolekcji Forms). Po zmianie: `generate:types`,
`generate:importmap`, restart.
## 2. Layout — Turnstile raz
`<TurnstileProvider siteKey={turnstileSiteKey}>` w `[locale]/layout.tsx`, siteKey z
`getSiteIntegrations(payload)` (turnstile.md). Brak klucza = widget wyłączony,
formularz działa (dev) — **nie** warunkuj providera.
## 3. Kod (skopiuj z `resources/`, dostosuj tylko klasy)
| Plik | Do projektu | Rola |
|---|---|---|
| `actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | jedna akcja `sendForm`: honeypot → IP → `submitForm` → tekst z Notifications |
| `FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | serwer: RichText (potwierdzenie, pola „message”), bind akcji |
| `FormRenderer.tsx` | `src/components/forms/FormRenderer.tsx` | klient: dowolny formularz z panelu przez `useForm` |
Renderer obsługuje typy buildera `text, email, textarea, number, select, checkbox,
message` (`country/state` jako tekst), `width` ≤ 50 → pół szerokości, `required`,
potwierdzenie albo redirect, a11y (`label for`, `aria-invalid`, `role="alert"`),
honeypot, Turnstile, zdarzenie GTM z panelu. Nie dopisuj własnej walidacji
„na sztywno” — reguły wynikają z definicji pola.
## 4. Strona — dane do bloku przez enhanceProps (bloki nie importują `lib/*`)
```tsx
// [locale]/[[...slug]]/page.tsx
import { getNotificationTexts } from '@intecion/ipal-kit'
import { sendForm } from '../actions'
const formTexts = doc.layout?.some((b) => b.blockType === 'formBlock')
? (await getNotificationTexts({ payload: await getCachedPayload(), locale })).form
: undefined
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { formTexts, sendForm } : {}),
})
```
Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam
`FormRenderer` z formularzem pobranym po ID z globalu (relacja w Footer), nigdy kopia.
## 5. Panel (zrób sam albo seedem, potem opisz w raporcie)
1. **Forms → nowy formularz**: pola z briefu, `name` po angielsku, małe litery
(`name`, `email`, `phone`, `message`, `consent`); etykiety per język.
2. **Zgoda RODO**: checkbox `consent`, etykieta z linkiem do polityki, **nie**
zaznaczony domyślnie (plugin i tak wymusza server-side → `reason: 'consent'`).
3. **Confirmation**: komunikat (per język) albo redirect na stronę „Dziękujemy”
(wtedy ta strona `noindex`).
4. **Emails**: powiadomienie do firmy (`emailTo` z globalu firmy/panelu, `replyTo: {{email}}`,
treść `{{*:table}}`) + opcjonalne potwierdzenie do wysyłającego (`emailTo: {{email}}`).
5. **Analytics (GTM / dataLayer)**: Event name `generate_lead` / `form_submit`, parametry `form_name`.
6. **Site Integrations**: transport maila (SMTP/Graph) + **Send test**; klucze Turnstile.
7. **Notifications → form.\***: teksty w każdym języku.
## 6. Sprawdź sam, zanim powiesz „gotowe”
- [ ] wysyłka z pustymi wymaganymi polami → błędy przy polach, bez requestu;
- [ ] poprawna wysyłka → potwierdzenie, rekord w **Form Submissions**, mail doszedł
(Send test w panelu działa = transport OK; brak maila mimo to → zakładka Emails formularza);
- [ ] niezaznaczona zgoda → komunikat z Notifications (nie angielski fallback);
- [ ] 6 szybkich wysyłek → `rate_limited`;
- [ ] Turnstile z kluczami → widget widoczny, wysyłka bez tokenu odrzucona;
- [ ] drugi język → etykiety i komunikaty w tym języku;
- [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie;
- [ ] `ipal-audit --quick` → zero hardkodów w FormRenderer/FormBlock;
- [ ] `ipal-consent-check` → nadal 0 naruszeń (Turnstile to niezbędny, nie śledzący).
## Diagnostyka
| Objaw | Przyczyna → naprawa |
|---|---|
| brak kolekcji Forms w panelu | rozjazd wersji form-buildera vs payload → ta sama wersja, `pnpm.overrides` |
| blok renderuje nic | `form` to ID (za małe `depth`) albo brak `formTexts`/`sendForm` w enhanceProps |
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (honeypot nieusunięty w akcji, literówka w `name`) |
| `reason: 'not_found'` | `formId` z innej bazy (seed na dev, prod inny ID) — relacja z panelu, nie stałe ID w kodzie |
| zgłoszenie jest, maila brak | brak `email: mailAdapter()`, pusta zakładka Emails, transport w panelu; logi serwera |
| zawsze `turnstile` | token jednorazowy — `ts.reset()` po błędzie (jest w rendererze); zła para kluczy / domena w Cloudflare |
| strona stała się dynamiczna (`ƒ`) | `headers()` w komponencie zamiast w akcji |
| komunikaty po angielsku | puste Notifications w tym języku |
## Znane ograniczenie pluginu
`useForm` trzyma własny stan tokenu, `useTurnstile` swój — renderer synchronizuje je
`useEffect`em. Jeśli w kolejnym projekcie to przeszkadza, zgłoś przez **ipal-plugin-gap**
(propozycja: `useForm` czyta token z `TurnstileProvider`, gdy jest w drzewie).
@@ -0,0 +1,39 @@
// src/blocks/FormBlock/Component.tsx — SERVER part: rich text from the panel + bound action.
// Block config (src/blocks/FormBlock/config.ts): slug 'formBlock', fields
// { name: 'form', type: 'relationship', relationTo: 'forms', required: true } + the
// shared section fields (eyebrow/heading/intro, anchor, background) — ipal-block.
// Page query depth ≥ 1, otherwise `form` is just an ID. Wrap the output in the
// project's <Section>/<SectionHeader> like every other block.
// Blocks never import lib/* or app/* (AGENT.md §4.10) — texts and the server action
// come in through enhanceProps from the page route (SKILL.md, step 4).
import type { ReactNode } from 'react'
import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RichText } from '@/components/RichText'
import { FormRenderer, type BuilderForm, type FormAction } from '@/components/forms/FormRenderer'
type Props = {
form?: BuilderForm | string | number | null
locale: string
formTexts?: FormNotificationTexts
sendForm?: (formId: string, locale: string, values: Record<string, unknown>, token?: string) => ReturnType<FormAction>
}
export function FormBlock({ form, locale, formTexts, sendForm }: Props) {
if (!form || typeof form !== 'object' || !formTexts || !sendForm) return null // never a fake/hardcoded form
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((f, i) => {
if (f.blockType === 'message' && f.message) messages[i] = <RichText data={f.message as never} />
})
const confirmation = form.confirmationMessage ? <RichText data={form.confirmationMessage as never} /> : null
return (
<FormRenderer
form={form}
messages={messages}
confirmation={confirmation}
validationText={formTexts.validation}
action={sendForm.bind(null, String(form.id), locale)}
/>
)
}
@@ -0,0 +1,138 @@
// src/components/forms/FormRenderer.tsx — CLIENT part: renders ANY form built in the panel.
// Logic from ipal-kit, markup + classes are the project's (restyle freely, keep the wiring).
'use client'
import { useEffect, useMemo, type ReactNode } from 'react'
import { useRouter } from 'next/navigation'
import {
useForm, buildValidator, required, email, checked, honeypotInputProps,
useTurnstile, formAnalyticsOnSuccess, type FormAnalyticsConfig,
} from '@intecion/ipal-kit/client'
type Option = { label?: string | null; value: string }
export type BuilderField = {
blockType: 'text' | 'textarea' | 'email' | 'number' | 'select' | 'checkbox' | 'country' | 'state' | 'message' | string
name?: string | null
label?: string | null
required?: boolean | null
width?: number | null
defaultValue?: unknown
options?: Option[] | null
message?: unknown
}
export type BuilderForm = {
id: string | number
fields?: BuilderField[] | null
submitButtonLabel?: string | null
confirmationType?: 'message' | 'redirect' | null
confirmationMessage?: unknown
redirect?: { url?: string | null } | null
analytics?: FormAnalyticsConfig
}
export type FormAction = (values: Record<string, unknown>, turnstileToken?: string) => Promise<{ success: boolean; message?: string }>
type Props = {
form: BuilderForm
action: FormAction
messages: Record<number, ReactNode>
confirmation: ReactNode
/** Notifications → form.validation, may contain {field}. */
validationText: string
}
export function FormRenderer({ form, action, messages, confirmation, validationText }: Props) {
const router = useRouter()
const ts = useTurnstile() // needs <TurnstileProvider> in the layout (siteKey may be empty → disabled)
const fields = (form.fields ?? []).filter((f) => f.blockType !== 'message' && f.name)
const msg = (f: BuilderField) => validationText.replace('{field}', f.label || f.name || '')
const initialValues = useMemo(
() => Object.fromEntries(fields.map((f) => [f.name as string, f.blockType === 'checkbox' ? Boolean(f.defaultValue) : (f.defaultValue as string) ?? ''])),
// eslint-disable-next-line react-hooks/exhaustive-deps
[form.id],
)
const validate = useMemo(
() =>
buildValidator<Record<string, unknown>>(
Object.fromEntries(
fields.map((f) => {
const rules = []
if (f.required) rules.push(f.blockType === 'checkbox' ? checked(msg(f)) : required(msg(f)))
if (f.blockType === 'email') rules.push(email(msg(f)))
return [f.name as string, rules]
}),
),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[form.id, validationText],
)
const f = useForm({
initialValues,
validate,
submitAction: action,
requireTurnstile: ts.enabled,
onSuccess: (result, values) => {
formAnalyticsOnSuccess(form.analytics)(result, values)
if (form.confirmationType === 'redirect' && form.redirect?.url) router.push(form.redirect.url)
},
})
// Turnstile token lives in the provider; the form engine needs it too.
useEffect(() => f.setTurnstileToken(ts.token), [ts.token]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { if (f.errorMessage) ts.reset() }, [f.errorMessage]) // eslint-disable-line react-hooks/exhaustive-deps
if (f.isSuccess && form.confirmationType !== 'redirect') return <div role="status">{confirmation}</div>
return (
<form onSubmit={f.handleSubmit} noValidate className="grid grid-cols-12 gap-4">
<input {...honeypotInputProps()} />
{(form.fields ?? []).map((field, i) => {
if (field.blockType === 'message') return <div key={i} className="col-span-12">{messages[i]}</div>
const name = field.name as string
const id = `f-${String(form.id)}-${name}`
const error = f.errors[name]
const span = field.width && field.width <= 50 ? 'col-span-12 md:col-span-6' : 'col-span-12'
const common = {
id, name, required: Boolean(field.required),
'aria-invalid': Boolean(error) || undefined,
'aria-describedby': error ? `${id}-err` : undefined,
}
const value = f.values[name]
return (
<div key={name} className={span}>
{field.blockType === 'checkbox' ? (
<label htmlFor={id} className="flex items-start gap-2">
<input type="checkbox" {...common} checked={Boolean(value)} onChange={(e) => f.setField(name, e.target.checked)} />
<span>{field.label}</span>
</label>
) : (
<>
<label htmlFor={id} className="mb-1 block">{field.label}</label>
{field.blockType === 'textarea' ? (
<textarea {...common} rows={5} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)} />
) : field.blockType === 'select' ? (
<select {...common} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)}>
<option value="" />
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
) : (
<input
{...common}
type={field.blockType === 'email' ? 'email' : field.blockType === 'number' ? 'number' : 'text'}
autoComplete={field.blockType === 'email' ? 'email' : undefined}
value={String(value ?? '')}
onChange={(e) => f.setField(name, e.target.value)}
/>
)}
</>
)}
{error && <p id={`${id}-err`} className="mt-1 text-sm text-red-600">{error}</p>}
</div>
)
})}
<div className="col-span-12"><ts.TurnstileWidget /></div>
{f.errorMessage && <p role="alert" className="col-span-12 text-red-600">{f.errorMessage}</p>}
<div className="col-span-12">
<button type="submit" disabled={f.isSubmitting}>{form.submitButtonLabel}</button>
</div>
</form>
)
}
@@ -0,0 +1,22 @@
// src/app/(frontend)/[locale]/actions.ts — ONE server action for every builder form.
'use server'
import { headers } from 'next/headers'
import { submitForm } from '@intecion/ipal-kit/server'
import { isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
export async function sendForm(
formId: string,
locale: string,
values: Record<string, unknown>,
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 h = await headers() // fine in a server action — never in the page tree (breaks SSG)
const ip = h.get('cf-connecting-ip') ?? h.get('x-forwarded-for')?.split(',')[0]?.trim() ?? undefined
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
return { success: result.success, message: resolveFormMessage(result, texts) }
}
@@ -0,0 +1,82 @@
---
name: ipal-locale-add
description: Adds a new language to an ipal-kit site (or turns a single-language site into a multilingual one) end to end — i18n.config, routing, Postgres migration, slugs and titles per page, globals (Header, Footer, Site Settings, Cookie Settings, Notifications), forms, SEO (hreflang, sitemap), language switcher — and proves completeness with a coverage script and ipal-seo-check. Use when the user asks for a new language/locale/translation version of the site.
---
# ipal-locale-add
Nowy język to **konfiguracja + treść**. Kod frontu prawie się nie zmienia —
routing, hreflang, sitemap, przełącznik i consent czytają locale z jednego źródła.
Typowa porażka to nie kod, tylko **brak sluga/tytułu w nowym języku → 404** i
puste teksty globali (baner cookies po angielsku z fallbacku).
## 0. Ustal (zbierz w jedną listę pytań, jeśli brief nie mówi)
- kod języka (`de`, `en`, `uk`…) i etykieta w przełączniku (`Deutsch`);
- **kto tłumaczy treść**: klient w panelu / Ty robisz wersję roboczą do akceptacji /
zostają placeholdery. Bez odpowiedzi → wersja robocza oznaczona w raporcie
„do weryfikacji przez klienta”, nigdy publikacja jako finalna;
- czy wszystkie strony mają istnieć w nowym języku (domyślnie: tak).
- RTL (arabski, hebrajski) → `rtl: true` w locale + sprawdzenie stylów (`dir`, `ms-/me-` zamiast `ml-/mr-`).
## 1. Projekt jednojęzyczny → wielojęzyczny (tylko jeśli był 1 locale)
To przebudowa struktury (i18n.md → „Przejście jedno- → wielojęzyczny”):
- `app/(frontend)/[[...slug]]` → `app/(frontend)/[locale]/[[...slug]]`, layout czyta `locale` z `params`;
- `generateStaticParams` zwraca pary `{ locale, slug }` dla `getConfiguredLocales()`;
- `proxy.ts` z `createProxy(i18nConfig, { NextResponse })` (redirect `/` → `/pl`);
- stare adresy bez prefiksu → przekierowania 301 na `/pl/...` (redirects w panelu albo `next.config`);
- `LanguageSwitcher` w Header + `AlternateLinksProvider` w layoucie + `AlternateLinksUpdater` na stronach.
## 2. Konfiguracja (projekt wielojęzyczny)
1. `src/i18n.config.ts` — dopisz `{ code: 'de', label: 'Deutsch' }`. To jedyne
miejsce; `ipalKit({ i18n: i18nConfig })`, proxy, switcher i sitemap biorą stąd.
**Nie** zmieniaj `defaultLocale` przy okazji (zmienia wszystkie kanoniczne URL-e).
2. Postgres: `pnpm payload migrate:create add-locale-de` → przejrzyj (enum `_locales`,
tabele `_locales`) → `pnpm payload migrate`. Mongo: nic.
3. `pnpm payload generate:types` · restart dev (Payload buduje localization przy starcie).
4. `grep -rn "'pl'\|'en'\|\[\"pl\"" src/ --include=*.ts*` — każdy hardkod listy języków
w kodzie projektu (mapy etykiet, `if (locale === 'en')`) to błąd: przenieś do panelu
albo do `i18n.config`.
## 3. Treść — co MUSI mieć wartość w nowym języku
Uruchom raport braków (tylko odczyt):
```bash
pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
LOCALE=de pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
```
Wypisuje: dokumenty bez `slug`/tytułu w danym języku (= 404, brak w sitemapie i
hreflang) oraz puste pola lokalizowane globali, które są wypełnione w defaultLocale.
Uzupełnij w tej kolejności (panel albo skrypt Local API z `locale: 'de'`):
| Co | Gdzie | Skutek braku |
|---|---|---|
| slug + tytuł każdej strony | Pages (i inne kolekcje z URL) | 404 w nowym języku |
| Homepage/404/polityka | System Pages (relacje wspólne) + ich slug w `de` | `/de` → 404, link polityki pusty |
| Header / Footer — etykiety linków | globale nawigacji | puste pozycje menu |
| Site Settings — nazwa, opis, OG | Site Settings | tytuł/OG z fallbacku |
| Cookie Settings — wszystkie teksty + `privacyLinkLabel` | Cookie Settings | baner w innym języku (RODO: zgoda musi być zrozumiała) |
| Notifications — `form.*` | Notifications | komunikaty formularza z angielskiego fallbacku |
| Forms — etykiety pól, potwierdzenie, Emails | Forms (każdy formularz) | formularz w złym języku |
| SEO tab — meta title/description | każda strona | duplikaty/braki w seo-check |
| Media — `alt` (jeśli localized) | Media | a11y |
Slugi w nowym języku: słowa w tym języku, małe litery, bez znaków diakrytycznych
(`ueber-uns`, nie `über-uns`); home = ten sam `homeSlug` co w innych językach.
Pisząc przez Local API: `payload.update({ collection, id, locale: 'de', fallbackLocale: false, data })`:
- **`fallbackLocale: false` obowiązkowo** — bez tego (przy `fallback: true`) Payload
zapisze polski tekst jako tłumaczenie niemieckie we wszystkich polach, których nie podałeś;
- **bloki/tablice: zachowaj `id` wierszy z odczytu w defaultLocale**, inaczej powstaną
nowe wiersze. Gotowy mechanizm: `ipal-site/resources/seed-content.template.ts`
(wartości `{ pl, en, de }` obok siebie, `SEED_UPDATE=1` dla istniejących stron).
## 4. Sprawdzenie
1. `locale-coverage` → `0 gap(s)` (albo lista świadomie pustych pól w raporcie).
2. `pnpm build && pnpm start` → `ipal-seo-check http://localhost:3000`:
hreflang `de` na stronach PL/EN, x-default, `/de/...` w sitemapie, brak 404.
3. `ipal-consent-check http://localhost:3000/de` — baner po niemiecku, zgoda działa.
4. Ręcznie: przełącznik języka z podstrony (nie z home) trafia na odpowiednik, nie na `/de`.
5. `ipal-audit --quick` — zero nowych hardkodów.
## Raport
Nowy język: kod, liczba stron przetłumaczonych / pustych, kto tłumaczył (wersja
robocza = „do akceptacji klienta”), wynik coverage + seo-check, lista pól do
uzupełnienia przez klienta.
@@ -0,0 +1,74 @@
/**
* ipal-locale-add — what is still untranslated, per locale.
*
* pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
* LOCALE=de pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts # one locale
*
* Reports (read-only, never writes):
* - collections with a localized `slug`: documents missing slug/title in a locale
* → that URL returns 404 in that language and is left out of sitemap/hreflang
* - globals: top-level localized text fields (also inside group/tabs/row/collapsible)
* that are empty in a locale while filled in the default locale
* Exit code: 0 = complete, 1 = gaps found.
*/
import { getPayload } from 'payload'
import config from '@payload-config'
type AnyField = { type: string; name?: string; localized?: boolean; fields?: AnyField[]; tabs?: AnyField[] }
const TEXT = new Set(['text', 'textarea', 'richText', 'email'])
const payload = await getPayload({ config })
const loc = payload.config.localization
if (!loc) {
console.log('locale-coverage: localization is off (single-language project) — nothing to check.')
process.exit(0)
}
const def = loc.defaultLocale
const targets = process.env.LOCALE ? [process.env.LOCALE] : loc.localeCodes.filter((c) => c !== def)
const empty = (v: unknown) =>
v == null || (typeof v === 'string' && v.trim() === '') || (typeof v === 'object' && v !== null && 'root' in v &&
!JSON.stringify(v).includes('"text":"'))
/** Paths of localized text fields, descending into non-data containers and named groups. */
const localizedPaths = (fields: AnyField[], prefix: string[] = []): string[][] =>
fields.flatMap((f) => {
if (f.type === 'tabs') return (f.tabs ?? []).flatMap((t) => localizedPaths(t.fields ?? [], t.name ? [...prefix, t.name] : prefix))
if (f.type === 'row' || f.type === 'collapsible') return localizedPaths(f.fields ?? [], prefix)
if (f.type === 'group') return localizedPaths(f.fields ?? [], f.name ? [...prefix, f.name] : prefix)
return f.localized && f.name && TEXT.has(f.type) ? [[...prefix, f.name]] : []
})
const at = (obj: unknown, path: string[]) => path.reduce<unknown>((o, k) => (o && typeof o === 'object' ? (o as Record<string, unknown>)[k] : undefined), obj)
const gaps: string[] = []
for (const col of payload.config.collections) {
const slugField = (col.fields as AnyField[]).find((f) => f.name === 'slug')
if (!slugField?.localized) continue
const titleField = col.admin?.useAsTitle ?? 'title'
const { docs } = await payload.find({ collection: col.slug as never, locale: 'all' as never, depth: 0, limit: 0, pagination: false })
for (const doc of docs as Record<string, unknown>[]) {
const slug = doc.slug as Record<string, unknown> | undefined
const title = doc[titleField] as Record<string, unknown> | string | undefined
const label = (typeof title === 'object' ? title?.[def] : title) ?? slug?.[def] ?? doc.id
for (const l of targets) {
const missing = [empty(slug?.[l]) && 'slug', typeof title === 'object' && empty(title?.[l]) && titleField].filter(Boolean)
if (missing.length) gaps.push(`[${l}] ${col.slug}/${String(doc.id)} "${String(label)}" — missing ${missing.join(', ')}`)
}
}
}
for (const g of payload.config.globals) {
const paths = localizedPaths(g.fields as AnyField[])
if (!paths.length) continue
const byLocale = Object.fromEntries(
await Promise.all([def, ...targets].map(async (l) => [l, await payload.findGlobal({ slug: g.slug as never, locale: l as never, fallbackLocale: false as never, depth: 0 })])),
)
for (const p of paths) {
if (empty(at(byLocale[def], p))) continue
for (const l of targets) if (empty(at(byLocale[l], p))) gaps.push(`[${l}] global ${g.slug} → ${p.join('.')} empty`)
}
}
for (const line of gaps) console.log(line)
console.log(`\nlocale-coverage (${targets.join(', ')} vs ${def}): ${gaps.length} gap(s)`)
process.exit(gaps.length ? 1 : 0)
@@ -0,0 +1,103 @@
---
name: ipal-migrate-fields
description: Safely changes the shape of fields that already hold content in an ipal-kit / Payload 3 project — renaming a field, replacing old CTA fields with buildLinkField/buildLinksField, moving fields into a group, splitting or merging blocks, changing a field's type, making a field localized. Three phases (add new → copy data with a dry-run script → remove old), all locales, no content loss. Use whenever a schema change touches fields that may already have data in the database, including refactors suggested by ipal-audit.
---
# ipal-migrate-fields
Payload **nie migruje danych za Ciebie**. Zmiana nazwy pola albo jego typu w kodzie
= stare dane zostają w bazie pod starym kluczem, panel pokazuje puste pole, front
renderuje pustkę. Na Postgresie dochodzi migracja schematu, która może **usunąć
kolumnę z danymi**. Dlatego zawsze trzy fazy, nigdy „zmień i zobacz”.
## Kiedy NIE potrzebujesz tego skilla
- Projekt bez treści (świeży, seed od zera) → zmień schemat, przeseeduj.
- Dodajesz **nowe** pole (bez zastępowania starego) → zwykła zmiana.
- Zmieniasz tylko `label`, `admin.*`, `validate`, `defaultValue` → bez wpływu na dane.
Wszystko inne (rename, typ, przeniesienie do grupy/tablicy, `localized: true/false`,
zamiana pól CTA na `buildLinkField`, podział bloku) → ten skill.
## Przed startem (sam, bez pytania)
1. **Kopia bazy** — Mongo: `mongodump --uri "$DATABASE_URI" --out backup/$(date +%F)`;
Postgres: `pg_dump "$DATABASE_URI" > backup/$(date +%F).sql`. Bez kopii nie zaczynaj.
2. Ustal adapter bazy (`payload.config.ts` → `mongooseAdapter` / `postgresAdapter`).
3. Spisz: kolekcja/global, typ bloku, STARE pola → NOWE pola, które są `localized`.
4. Znajdź wszystkie miejsca czytające stare pola: `grep -rn "<staraNazwa>" src/`.
## Faza 1 — dodaj NOWE pola obok STARYCH
- Dodaj nowe pola do schematu; stare **zostają**, oznacz je w panelu:
`admin: { description: 'DEPRECATED — migrowane do <nowe>', readOnly: true }`.
- Front: czytaj NOWE z fallbackiem na STARE (na czas przejścia):
`const links = block.links?.length ? block.links : legacyToLinks(block)`.
- `pnpm payload generate:types` · Postgres: `pnpm payload migrate:create add-<nazwa>` +
`pnpm payload migrate` (migracja tylko DODAJE kolumny — przejrzyj plik, zanim uruchomisz).
- `tsc --noEmit` czysto.
## Faza 2 — przenieś dane skryptem
1. Skopiuj szablon: `resources/migrate-block-fields.template.ts` →
`scripts/migrate-<nazwa>.ts`. Zmieniasz tylko sekcję `CONFIG` i `migrateBlock()`.
Szablon: wszystkie dokumenty × wszystkie locale, idempotentny, `context: { ipalMigration: true }`.
2. Zasady w `migrateBlock()`:
- **Pierwszy przebieg (defaultLocale) tworzy strukturę** (wiersze tablic, bloki).
- **Kolejne locale tylko wypełniają pola `localized`** w istniejących wierszach —
używaj `id` wierszy z odczytu (nowe `id` = Payload tworzy nowe wiersze, w innych
językach znika treść).
- Relacje przy `depth: 0` to ID — przepisuj ID, nie obiekty.
- Pola nielokalizowane zapisuj tylko w defaultLocale.
- Zapis w innym języku zawsze z `fallbackLocale: false` (jest w szablonie) — inaczej
Payload zapisze tekst z defaultLocale jako tłumaczenie.
3. Dry run: `pnpm payload run scripts/migrate-<nazwa>.ts` → przeczytaj listę zmian,
sprawdź 2–3 dokumenty ręcznie (zwłaszcza drugi język). Gdy migracja tworzy nowe
wiersze, dry run pokazuje tylko przebieg defaultLocale (wierszy jeszcze nie ma) —
pozostałe języki zobaczysz w wyniku APPLY.
4. Zapis: `APPLY=1 pnpm payload run scripts/migrate-<nazwa>.ts`.
5. Weryfikacja: ponowny dry run → `0 block change(s)`; w panelu otwórz dokument w
każdym języku; na froncie `pnpm build && pnpm start` + `ipal-seo-check`.
Globale (Header, Footer): zamiast `find` → `findGlobal`/`updateGlobal({ slug, data, locale })`
— ta sama pętla po locale. Kolekcja z `versions.drafts`: skrypt aktualizuje
wersję główną; jeśli dokument ma nowszy szkic, dodaj `draft: true` w odczycie i
zapisie albo opublikuj szkice przed migracją (zapytaj, tylko jeśli są szkice klienta).
Hooki, które wysyłają maile/rewalidują/wołają webhooki: przy `context.ipalMigration`
mają nic nie robić (`if (context?.ipalMigration) return`). Sprawdź przed APPLY.
## Faza 3 — usuń STARE pola
- **Produkcja z treścią klienta → zapytaj użytkownika przed fazą 3** (jedyne pytanie
w tym skillu). Lokalnie / staging → rób sam.
- Usuń stare pola ze schematu, fallback z frontu, `grep` → zero trafień.
- `generate:types`; Postgres: `migrate:create remove-<nazwa>` — ta migracja
**USUWA kolumny**; uruchom dopiero po fazie 2 na tej samej bazie.
- Mongo: stare klucze zostają w dokumentach (nieszkodliwe). Sprzątanie opcjonalne:
`$unset` w osobnym skrypcie.
- `ipal-audit --quick` → 0 błędów.
## Typowe przypadki → co w migrateBlock
| Zmiana | Pierwszy przebieg | Kolejne locale |
|---|---|---|
| rename `title` → `heading` | `{ heading: block.title }` | to samo, jeśli localized |
| CTA (`ctaLabel`, `ctaUrl`) → `buildLinkField` | `{ link: { type: 'custom', url, label, appearance } }` | tylko `link.label` |
| CTA z relacją → `buildLinksField` | wiersz `{ link: { type: 'internal', page: id, … } }` (szablon) | `links[i].link.label` z zachowaniem `id` |
| pola → `group` | `{ grupa: { a: block.a, b: block.b } }` | pola localized w grupie |
| `text` → `richText` | `{ body: textToLexical(block.text) }` (akapity → `paragraph` nodes) | to samo |
| nielokalizowane → `localized` | skopiuj wartość do defaultLocale | (opcjonalnie) ta sama wartość jako start tłumaczenia — zapytaj |
| podział bloku A → A + B | dodaj nowy blok za A (`blockType: 'b'`, bez `id`) | uzupełnij pola localized po `id` nowego bloku |
Lexical z tekstu:
```ts
const textToLexical = (t: string) => ({ root: { type: 'root', format: '', indent: 0, version: 1, direction: 'ltr',
children: t.split(/\n{2,}/).map((p) => ({ type: 'paragraph', format: '', indent: 0, version: 1, direction: 'ltr', textFormat: 0,
children: [{ type: 'text', text: p, format: 0, style: '', mode: 'normal', detail: 0, version: 1 }] })) } })
```
## Gdy coś pójdzie źle
- Wiersze zdublowane w drugim języku → nie użyto `id` wierszy; przywróć kopię, popraw, powtórz.
- `ValidationError` przy APPLY → nowe pole `required` bez wartości w starych danych;
uzupełnij wartość domyślną w `migrateBlock` albo tymczasowo zdejmij `required`.
- Skrypt nie startuje (`Cannot find module '@payload-config'`) → alias w `tsconfig.json`
(`"@payload-config": ["./src/payload.config.ts"]`) — standard w szablonie Payload.
Raport końcowy: ile dokumentów / bloków / locale zmieniono, gdzie jest kopia bazy,
czy faza 3 wykonana (albo czeka na zgodę).
@@ -0,0 +1,118 @@
/**
* Field migration — PHASE 2 of 3 (skill ipal-migrate-fields).
* Copies data from OLD fields to NEW fields inside one block type, in every locale.
*
* pnpm payload run scripts/migrate-<name>.ts # dry run — prints what would change
* APPLY=1 pnpm payload run scripts/migrate-<name>.ts # writes
*
* Idempotent: every branch of migrateBlock() returns null once its target is
* filled, so a re-run after a crash is safe — and a dry run after APPLY must
* print "0 block change(s)". Note: a dry run BEFORE the first APPLY shows only
* the default-locale pass when the structure (rows) doesn't exist yet.
*
* Example below: Hero `ctaLabel` + `ctaTarget` (relationship → pages) → `links`
* (buildLinksField). Adapt CONFIG + migrateBlock() — nothing else.
*/
import { getPayload } from 'payload'
import config from '@payload-config'
// ---------------------------------------------------------------- CONFIG --
const COLLECTION = 'pages'
const LAYOUT_FIELD = 'layout'
const BLOCK_TYPE = 'hero'
const APPLY = process.env.APPLY === '1'
type Row = { id?: string; [key: string]: unknown }
type Block = Row & { blockType: string }
/**
* OLD → NEW for one block in ONE locale. Return null = nothing to change.
* `isDefaultLocale` = first pass: create structure (rows). Other locales only
* fill LOCALIZED sub-fields of the rows created in the first pass — reuse the
* row ids from `block` (read in that locale), otherwise Payload creates new rows.
*/
function migrateBlock(block: Block, isDefaultLocale: boolean): Partial<Block> | null {
const label = typeof block.ctaLabel === 'string' ? block.ctaLabel.trim() : ''
const target = block.ctaTarget as Row | string | number | null | undefined
const pageId = target && typeof target === 'object' ? target.id : target
const rows = Array.isArray(block.links) ? (block.links as Row[]) : []
if (isDefaultLocale) {
if (rows.length > 0) return null // already migrated
if (!label && !pageId) return null
return {
links: [
{
link: {
type: 'internal',
page: pageId ?? null,
label: label || null,
newTab: false,
appearance: 'primary',
},
},
],
}
}
// Other locales: only the localized label, on the existing row (same id).
if (rows.length === 0 || !label) return null
const first = rows[0] as Row & { link?: Row }
if (first.link?.label === label) return null // already migrated in this locale
return { links: [{ ...first, link: { ...(first.link ?? {}), label } }, ...rows.slice(1)] }
}
// ------------------------------------------------------------ /CONFIG --
const payload = await getPayload({ config })
const localization = payload.config.localization
const defaultLocale = localization ? localization.defaultLocale : undefined
const locales = localization
? [defaultLocale, ...localization.localeCodes.filter((l) => l !== defaultLocale)]
: [undefined]
const { docs } = await payload.find({
collection: COLLECTION as never,
depth: 0,
limit: 0,
pagination: false,
...(defaultLocale ? { locale: defaultLocale as never } : {}),
})
let changes = 0
for (const { id } of docs as Row[]) {
for (const locale of locales) {
const doc = (await payload.findByID({
collection: COLLECTION as never,
id: id as string,
depth: 0,
...(locale ? { locale: locale as never, fallbackLocale: false as never } : {}),
})) as Row
const layout = (Array.isArray(doc[LAYOUT_FIELD]) ? doc[LAYOUT_FIELD] : []) as Block[]
let dirty = false
const next = layout.map((block) => {
if (block.blockType !== BLOCK_TYPE) return block
const patch = migrateBlock(block, locale === defaultLocale)
if (!patch) return block
dirty = true
changes++
console.log(`${APPLY ? 'UPDATE' : 'would update'} ${COLLECTION}/${String(id)} [${locale ?? '-'}] block ${block.id}:`, JSON.stringify(patch))
return { ...block, ...patch }
})
if (dirty && APPLY) {
await payload.update({
collection: COLLECTION as never,
id: id as string,
data: { [LAYOUT_FIELD]: next } as never,
depth: 0,
// fallbackLocale: false — otherwise Payload saves default-locale text as this locale's value
...(locale ? { locale: locale as never, fallbackLocale: false as never } : {}),
context: { ipalMigration: true }, // hooks can skip side effects on this flag
})
}
}
}
console.log(`\n${changes} block change(s) ${APPLY ? 'written' : 'planned (dry run — set APPLY=1 to write)'}.`)
process.exit(0)
+1 -1
View File
@@ -8,7 +8,7 @@ description: Builds the site header, footer, mobile menu and company data in an
Gotowy kod: `resources/kod-nawigacji.md` (ten skill). Reguły: AGENT.md §6.8.
Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-block, krok 0).
## Plan (pokaż i czekaj na OK)
## Plan (zapisz, potem od razu kod — AGENT.md §0a)
- pozycje menu (jeden poziom podmenu, nie głębiej), CTA w nagłówku (`links`),
- kolumny stopki, notka,
- model `Company` dla rynku z AGENTS.md (PL: NIP/REGON, AU: ABN, US: EIN…),
@@ -12,7 +12,7 @@ Site Settings — nie duplikuj ich w Header.
```ts
// src/globals/Header.ts
import type { GlobalConfig } from 'payload'
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
export const Header: GlobalConfig = {
slug: 'header',
@@ -21,13 +21,17 @@ export const Header: GlobalConfig = {
{
name: 'navItems',
type: 'array',
labels: { singular: 'Menu item', plural: 'Menu items' },
maxRows: 8,
admin: { initCollapsed: true, components: rowLabel('link.label', 'Menu item') },
fields: [
buildLinkField({ appearances: false }),
{
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
type: 'array',
labels: { singular: 'Submenu item', plural: 'Submenu' },
maxRows: 10,
admin: { initCollapsed: true, components: rowLabel('link.label', 'Submenu item') },
fields: [buildLinkField({ appearances: false })],
},
],
@@ -46,7 +50,7 @@ export const Header: GlobalConfig = {
```ts
// src/globals/Footer.ts
import type { GlobalConfig } from 'payload'
import { buildLinkField } from '@intecion/ipal-kit'
import { buildLinkField, rowLabel } from '@intecion/ipal-kit'
export const Footer: GlobalConfig = {
slug: 'footer',
@@ -55,10 +59,18 @@ export const Footer: GlobalConfig = {
{
name: 'columns',
type: 'array',
labels: { singular: 'Column', plural: 'Columns' },
maxRows: 4,
admin: { initCollapsed: true, components: rowLabel('heading', 'Column') },
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'items', type: 'array', fields: [buildLinkField({ appearances: false })] },
{
name: 'items',
type: 'array',
labels: { singular: 'Link', plural: 'Links' },
admin: { initCollapsed: true, components: rowLabel('link.label', 'Link') },
fields: [buildLinkField({ appearances: false })],
},
],
},
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
+9 -4
View File
@@ -5,7 +5,10 @@ description: Handles the moment when @intecion/ipal-kit seems to lack a feature
# ipal-plugin-gap
Reguła: AGENT.md §1.3 — **nie łataj w projekcie**.
Reguła: AGENT.md §1.3 — **nie łataj po cichu**. Raport + minimalne, oznaczone
obejście (jeśli praca tego wymaga) — i pracujesz dalej, nie czekasz na odpowiedź.
Typ raportu: **błąd** (plugin działa niezgodnie z docs) albo **usprawnienie**
(ten sam kod pisany w kolejnym projekcie; brak opcji, która by go usunęła).
## 1. Sprawdź, czy plugin tego nie ma
- `ls node_modules/@intecion/ipal-kit/docs/` — przeczytaj plik modułu,
@@ -16,11 +19,13 @@ Reguła: AGENT.md §1.3 — **nie łataj w projekcie**.
Plugin to ma → użyj go i powiedz użytkownikowi, gdzie to było.
## 2. Raport (gdy naprawdę brakuje albo nie działa)
Zapisz w `docs/plugin-requests/<data>-<temat>.md` projektu i pokaż użytkownikowi:
Zapisz w `docs/plugin-requests/<data>-<temat>.md` projektu. Użytkownikowi pokazujesz
od razu tylko **blokujący błąd** (bez obejścia nie da się iść dalej); resztę zbiera
raport końcowy (ipal-site, sekcja „Dla ipal-kit”).
```markdown
# <temat>
**Projekt:** <nazwa> · **ipal-kit:** <wersja>
**Typ:** błąd / usprawnienie · **Projekt:** <nazwa> · **ipal-kit:** <wersja>
## Problem
<co nie działa / czego brakuje; komunikat błędu; kroki odtworzenia>
## Dlaczego to do pluginu
@@ -28,7 +33,7 @@ Zapisz w `docs/plugin-requests/<data>-<temat>.md` projektu i pokaż użytkowniko
## Proponowane API
<sygnatura funkcji / opcja ipalKit / pole w panelu; przykład użycia w projekcie>
## Obejście tymczasowe (jeśli konieczne)
<minimalne, w jednym pliku, z komentarzem TODO odsyłającym do tego raportu>
<minimalne, w jednym pliku, z komentarzem `// WORKAROUND ipal-kit <wersja>: docs/plugin-requests/<plik>`>
```
## 3. Czego nie robić
+38
View File
@@ -0,0 +1,38 @@
---
name: ipal-seo-check
description: Checks a running ipal-kit site the way Googlebot sees it — metadata inside <head> (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, robots.txt, soft 404s, favicon, llms.txt. Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up.
---
# ipal-seo-check
Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Googlebot.
## Kroki
1. Uruchom wersję produkcyjną (dev streamuje inaczej niż build):
```bash
pnpm build && pnpm start # w drugim terminalu / w tle
node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000
```
Produkcja: `node …/seo-check.mjs https://domena.pl --max 40`.
`--max N` = ile stron z sitemapy sprawdzić (równo z każdego języka). Nie czytaj
źródła skryptu — wynik wystarczy.
2. Pokaż pełny wynik. Każde `[ERROR]` napraw — przy każdym jest wskazówka i
sekcja dokumentacji. Typowe przyczyny:
| Błąd | Przyczyna → poprawka |
|---|---|
| metadata rendered in `<body>` | brak `htmlLimitedBots`, jawny `<head>` w layoucie, brak ISR/`generateStaticParams`, `headers()`/`searchParams` w drzewie stron |
| canonical not pointing to itself | `NEXT_PUBLIC_SERVER_URL` = localhost / inna domena; zły `homeSlug` |
| noindex pages listed in the sitemap | stary build; pole noindex nie z `buildNoindexField` |
| missing / non-self hreflang | strona bez sluga w innym języku; metadata nie z `generatePageMetadata` |
| unknown URL returns 200 | brak `notFound()` w catch-all |
| sitemap URLs not 200 | w sitemapie adresy z przekierowaniem (stare slugi) |
| robots.txt points to localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie |
3. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** —
uzupełnij z briefu albo wypisz w raporcie dla klienta.
4. Uruchom ponownie aż `0 error(s)`.
## Czego skrypt nie sprawdzi
Search Console (indeksacja, ręczne działania), Core Web Vitals, dane
strukturalne JSON-LD (sprawdź w Rich Results Test), treść merytoryczną.
@@ -0,0 +1,172 @@
#!/usr/bin/env node
// ipal-seo-check — what Googlebot actually sees on a running site (Node 18+, no dependencies).
// node seo-check.mjs <baseUrl> [--max 20]
// node seo-check.mjs http://localhost:3000 # after `pnpm build && pnpm start`
// node seo-check.mjs https://klient.pl --max 40 # production
// Exit code: 0 = no errors (warnings allowed), 1 = errors, 2 = site unreachable.
const args = process.argv.slice(2)
if (!args[0] || args.includes('--help') || args.includes('-h')) {
console.log('Usage: seo-check.mjs <baseUrl> [--max N] (N = pages sampled from the sitemap, default 20)')
process.exit(args[0] ? 0 : 2)
}
const origin = args[0].replace(/\/$/, '')
const maxIdx = args.indexOf('--max')
const MAX = maxIdx >= 0 ? Number(args[maxIdx + 1]) || 20 : 20
const UA = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
let errors = 0
let warnings = 0
const findings = []
const report = (level, title, rule, items = []) => {
if (level === 'ERROR') errors += Math.max(items.length, 1)
else warnings += Math.max(items.length, 1)
findings.push({ level, title, rule, items })
}
const get = async (path, opts = {}) => {
const url = path.startsWith('http') ? path : origin + path
const res = await fetch(url, { redirect: opts.redirect ?? 'follow', headers: { 'user-agent': UA } })
return { res, text: opts.body === false ? '' : await res.text(), url }
}
const attr = (tag, name) => tag.match(new RegExp(`${name}\\s*=\\s*"([^"]*)"`, 'i'))?.[1]
const tags = (html, re) => [...html.matchAll(re)].map((m) => m[0])
const norm = (u) => (u || '').replace(/\/$/, '') || '/'
// --- 0. reachable ---------------------------------------------------------
let home
try {
home = await get('/', { redirect: 'manual', body: false })
} catch (e) {
console.error(`ipal-seo-check: ${origin} unreachable (${e.cause?.code ?? e.message}). Start the app first.`)
process.exit(2)
}
console.log(`ipal-seo-check — ${origin} (Googlebot UA)`)
// --- 1. root ----------------------------------------------------------------
const rootStatus = home.res.status
const rootLocation = home.res.headers.get('location')
if (![200, 301, 302, 307, 308].includes(rootStatus)) report('ERROR', `/ returns ${rootStatus}`, 'root must serve the home or redirect to /{locale}')
// --- 2. robots.txt --------------------------------------------------------
const robots = await get('/robots.txt')
if (robots.res.status !== 200) report('ERROR', `robots.txt → ${robots.res.status}`, 'export robots from lib/content (seo.md)')
else {
const txt = robots.text
const sm = txt.match(/^sitemap:\s*(\S+)/im)?.[1]
if (!sm) report('ERROR', 'robots.txt has no Sitemap line', 'buildRobots sitemap: true')
else if (!sm.startsWith('http')) report('ERROR', `Sitemap URL is relative: ${sm}`, 'set NEXT_PUBLIC_SERVER_URL / baseUrl')
const star = txt.split(/user-agent:\s*\*/i)[1]?.split(/user-agent:/i)[0] ?? ''
if (/^disallow:\s*\/\s*$/im.test(star)) report('ERROR', 'robots.txt blocks everything for *', 'Disallow: / — the site is invisible to search engines')
if (/localhost|127\.0\.0\.1/.test(txt) && !/localhost|127\.0\.0\.1/.test(origin)) report('ERROR', 'robots.txt points to localhost', 'NEXT_PUBLIC_SERVER_URL is not the production URL')
}
// --- 3. sitemap -----------------------------------------------------------
const sitemap = await get('/sitemap.xml')
let urls = []
let hasAlternates = false
if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemap from lib/content + force-dynamic')
else {
urls = [...new Set([...sitemap.text.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1]))]
hasAlternates = /hreflang=/.test(sitemap.text)
if (urls.length === 0) report('ERROR', 'sitemap.xml is empty', 'DB unreachable at build without force-dynamic, or no published pages')
const foreign = urls.filter((u) => !u.startsWith('http') || /localhost|127\.0\.0\.1/.test(u) !== /localhost|127\.0\.0\.1/.test(origin))
if (foreign.length) report('ERROR', 'sitemap URLs relative or on another host', 'NEXT_PUBLIC_SERVER_URL / baseUrl', foreign.slice(0, 5))
if (/(\/404|\/500|not-found)(\/|<|$)/.test(sitemap.text)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID')
}
// --- 4. sampled pages -----------------------------------------------------
const localeOf = (u) => new URL(u).pathname.split('/').filter(Boolean)[0] ?? ''
const byLocale = new Map()
for (const u of urls) {
const l = localeOf(u)
if (!byLocale.has(l)) byLocale.set(l, [])
byLocale.get(l).push(u)
}
const sample = []
for (let i = 0; sample.length < Math.min(MAX, urls.length); i++) {
for (const list of byLocale.values()) if (list[i] && sample.length < MAX) sample.push(list[i])
}
const multiLocale = hasAlternates || byLocale.size > 1
const urlSet = new Set(urls.map(norm))
const titles = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [] }
for (const url of sample) {
let page
try { page = await get(url, { redirect: 'manual' }) } catch { issues.status.push(`${url} → unreachable`); continue }
if (page.res.status !== 200) { issues.status.push(`${url} → ${page.res.status}`); continue }
const html = page.text
const cut = html.search(/<\/head>/i)
if (cut < 0) { issues.noHead.push(url); continue }
const head = html.slice(0, cut)
const body = html.slice(cut)
// Next 16 streaming: metadata emitted into <body> is invisible to many crawlers
if (/<link[^>]+rel="canonical"/i.test(body) || /<title>/i.test(body)) issues.body.push(url)
const title = head.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim()
if (!title) issues.title.push(url)
else {
if (title.length > 65) issues.longTitle.push(`${url} (${title.length} chars)`)
titles.set(title, [...(titles.get(title) ?? []), url])
}
if (!/<meta[^>]+name="description"[^>]+content="[^"]+"/i.test(head)) issues.desc.push(url)
const canonTag = tags(head, /<link[^>]+rel="canonical"[^>]*>/gi)[0]
const canon = canonTag && attr(canonTag, 'href')
if (!canon) issues.canonical.push(url)
else if (norm(canon) !== norm(url)) issues.canonSelf.push(`${url} → canonical ${canon}`)
const robotsMeta = tags(head, /<meta[^>]+name="robots"[^>]*>/gi).map((t) => attr(t, 'content') ?? '').join(' ')
if (/noindex/i.test(robotsMeta)) issues.noindex.push(url)
if (!/<link[^>]+rel="(?:shortcut )?icon"/i.test(head)) issues.favicon.push(url)
if (multiLocale) {
const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }))
if (alts.length === 0) issues.hreflang.push(url)
else {
if (!alts.some((a) => a.lang === 'x-default')) issues.xdefault.push(url)
if (!alts.some((a) => norm(a.href) === norm(url))) issues.hreflang.push(`${url} (no self-reference)`)
for (const a of alts) if (a.lang !== 'x-default' && a.href && !urlSet.has(norm(a.href))) issues.reciprocal.push(`${url} → ${a.lang}: ${a.href}`)
}
}
}
const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([t, us]) => `"${t}" × ${us.length}`)
if (issues.status.length) report('ERROR', 'sitemap URLs not 200 (redirect / error)', 'sitemap must list final, live URLs', issues.status)
if (issues.noHead.length) report('ERROR', 'no </head> in HTML', 'broken document', issues.noHead)
if (issues.body.length) report('ERROR', 'metadata rendered in <body>', 'htmlLimitedBots, no explicit <head>, ISR + generateStaticParams (AGENT.md §4)', issues.body)
if (issues.title.length) report('ERROR', 'missing <title> in head', 'generatePageMetadata', issues.title)
if (issues.canonical.length) report('ERROR', 'missing canonical', 'generatePageMetadata + NEXT_PUBLIC_SERVER_URL', issues.canonical)
if (issues.canonSelf.length) report('ERROR', 'canonical not pointing to itself', 'canonical must be the page URL (or remove the page from the sitemap)', issues.canonSelf)
if (issues.noindex.length) report('ERROR', 'noindex pages listed in the sitemap', 'sitemap filters noindex — check buildNoindexField / stale build', issues.noindex)
if (issues.hreflang.length) report('ERROR', 'missing / non-self hreflang', 'createPageMetadata builds alternates from locale:"all" slugs', issues.hreflang)
if (issues.xdefault.length) report('WARNING', 'no x-default hreflang', 'buildHreflangAlternates adds x-default → defaultLocale', issues.xdefault)
if (issues.reciprocal.length) report('WARNING', 'hreflang alternates not in the sitemap', 'translation missing/unpublished or noindex in that locale', issues.reciprocal.slice(0, 15))
if (issues.desc.length) report('WARNING', 'missing meta description', 'fill SEO tab in the panel (or site description fallback)', issues.desc)
if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles)
if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle)
if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3))
// --- 5. 404 ---------------------------------------------------------------
const firstLocale = [...byLocale.keys()].find((l) => l && l.length <= 5) ?? ''
for (const path of [`/${firstLocale ? firstLocale + '/' : ''}ipal-seo-check-${Date.now()}`]) {
const r = await get(path.replace('//', '/'), { redirect: 'manual' })
if (r.res.status === 200) report('ERROR', `unknown URL returns 200 (soft 404): ${path}`, 'notFound() in the catch-all, not-found.tsx (pages.md)')
else if (r.res.status !== 404 && !(r.res.status >= 300 && r.res.status < 400)) report('WARNING', `unknown URL returns ${r.res.status}`, 'expected 404')
}
// --- 6. llms.txt (info-level) -------------------------------------------------
const llms = await get('/llms.txt', { body: false }).catch(() => null)
if (!llms || llms.res.status !== 200) report('WARNING', 'no /llms.txt', 'createLlmsTxtRoute (seo.md) — AI-readable site summary')
// --- output -------------------------------------------------------------
for (const f of findings) {
console.log(`\n[${f.level}] ${f.title}${f.items.length ? ` (${f.items.length})` : ''} — ${f.rule}`)
for (const i of f.items.slice(0, 10)) console.log(` ${i}`)
if (f.items.length > 10) console.log(` … and ${f.items.length - 10} more`)
}
console.log(`\nroot: ${rootStatus}${rootLocation ? ' → ' + rootLocation : ''} · sitemap: ${urls.length} URL(s), ${byLocale.size} locale group(s) · checked: ${sample.length} page(s)`)
console.log(`ipal-seo-check: ${errors} error(s), ${warnings} warning(s)`)
process.exit(errors ? 1 : 0)
+7 -5
View File
@@ -9,28 +9,30 @@ Kod i szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §1
(przed instalacją pakietu: poproś użytkownika o ten plik albo działaj wg kroków
poniżej i doczytaj po `pnpm add`). Reguły: `docs/agent/AGENT.md`.
**Jeden etap = jeden commit. Po każdym etapie pokaż wynik i czekaj na OK.**
**Jeden etap = jeden commit.** Nie czekasz na OK między etapami (AGENT.md §0a) —
pytania o brakujące dane zbierasz w jedną listę na początku; tryb „krok po kroku”
tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
1. **Instalacja** — `.npmrc` (`@intecion:registry=…`, `legacy-peer-deps=true`),
`pnpm add @intecion/ipal-kit` + zależności z PROGRAMISTA §1, `pnpm.overrides`
na wersję `payload` dla wszystkich `@payloadcms/*`, build z `--webpack`.
Nigdy instalacja z gita. Nie twórz `middleware.ts`.
2. **Skille i AGENTS.md** — skopiuj skille (AGENT.md §14), utwórz `AGENTS.md`
2. **Skille i AGENTS.md** — skopiuj skille (AGENT.md §14), w `tsconfig.json` `"exclude": ["node_modules", ".agents"]`, utwórz `AGENTS.md`
wg AGENT.md §13 z danymi od użytkownika (zapytaj o: klient, domena, rynek,
języki, R2/lokalnie, SMTP/Graph).
3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`),
`payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym**
`payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`.
4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages`, `Media`
(PROGRAMISTA §2.4). Żadnych innych kolekcji.
z `normalizeFilenameHook` + `buildOptimizeUploadHook`/`buildOptimizeUploadField` (PROGRAMISTA §2.4, storage.md). Żadnych innych kolekcji.
5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
6. **Routing** — `proxy.ts` (`createProxy`), `lib/content.ts`, layout bez
`<head>`, catch-all z ISR + `generateStaticParams` + `resolveRedirect`,
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md).
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, llms.txt, health
7. **SEO i bezpieczeństwo** — sitemap (`sitemap.xml/route.ts` = `sitemapRoute`, bez CSS w `public/`), robots, manifest, llms.txt, health
(wszystkie z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`,
`instrumentation.ts` z `assertEnv` (PROGRAMISTA §2.8–2.9).
`instrumentation.ts` z `assertEnv` z `@intecion/ipal-kit/env` (PROGRAMISTA §2.8–2.9, env.md).
8. **Nawigacja** — skill **ipal-nav**.
9. `pnpm generate:types`, `pnpm payload generate:importmap`, skill **ipal-audit**
(pełny), lista kroków w panelu dla użytkownika (PROGRAMISTA §2.11).
+118
View File
@@ -0,0 +1,118 @@
---
name: ipal-site
description: Builds a complete client website on ipal-kit from a brief to handover with minimal human involvement — intake and one consolidated question list, foundation, content model, navigation, sections, forms, content seeding in every language, integrations, system pages, design, full self-verification (build, ipal-audit, ipal-seo-check, ipal-consent-check, locale coverage, editor test) and a final report. Orchestrates the other ipal-* skills. Use when asked to build/create/make a website, landing page or new site for a client, or to "finish the site".
---
# ipal-site
Prowadzisz projekt jak samodzielny wykonawca (AGENT.md §0a): decyzje techniczne
podejmujesz sam, pytasz raz o brakujące dane, przewidujesz problemy, sprawdzasz
swoją pracę, a na końcu oddajesz raport. Użytkownik nie powinien musieć Cię
prowadzić ani poprawiać.
**Rytm:** jedna faza = jeden commit (`feat(site): faza N — <co>`). Nie czekasz na OK
między fazami. Przed fazą przejdź tabelę „Przewidujesz” z AGENT.md §0a.
## Faza 0 — Rozpoznanie i jedna lista pytań
1. Przeczytaj: brief (wszystkie załączniki), `AGENTS.md`, `DESIGN.md`/`PRODUCT.md`,
`package.json` (wersja ipal-kit), istniejący kod. Nowy projekt czy dokończenie?
2. Spisz w `AGENTS.md` → „Mapa strony”: strony (z briefu), sekcje na każdej,
formularze, języki, kolekcje (tylko jeśli są listy z URL-ami — ipal-collection).
3. **Jedna lista pytań** — tylko to, czego nie ma w briefie i nie da się ustalić
samemu, każde z **domyślną odpowiedzią**, którą przyjmiesz bez odpowiedzi:
```
Zanim skończę, potrzebuję (jeśli nie odpowiesz, przyjmuję wartość w nawiasie):
1. Języki strony? (pl + en — jak w briefie)
2. Domena produkcyjna? (placeholder w .env, canonical ustawię po wdrożeniu)
3. Dane firmy: NIP, adres, telefon? ([DO UZUPEŁNIENIA] w panelu)
4. Na jaki adres wysyłać zgłoszenia z formularza? ([DO UZUPEŁNIENIA] w Forms → Emails)
5. Analityka: ID GA4/GTM/pikseli? (wyłączona do czasu wpisania ID w panelu)
6. Media: R2 czy lokalnie? (lokalnie w dev, R2 gotowe do włączenia env)
7. Tłumaczenia: robię wersje robocze do akceptacji? (tak, oznaczone w raporcie)
```
Wyślij listę i **pracuj dalej** na wartościach domyślnych. Odpowiedzi wpisujesz,
gdy przyjdą. Zatrzymujesz się tylko przed decyzją nieodwracalną (AGENT §0a).
## Faza 1 — Fundament
- Nowy projekt → **ipal-setup** (całość, z `ipal-skills`, `AGENTS.md`).
- Istniejący na starszym ipal-kit → **ipal-upgrade** przed czymkolwiek innym.
- Wyjście: `pnpm build` przechodzi, `/admin` działa, `ipal-audit --quick` = 0 błędów.
## Faza 2 — Model treści
- Strony = `Pages` + bloki. Kolekcje tylko dla list z URL-ami (**ipal-collection**).
- Globale: Header, Footer, Company (**ipal-nav**), Site Settings, System Pages.
- Każda sekcja z mapy strony → blok istniejący, wariant istniejącego (`variant`)
albo nowy blok. Cel: jak najmniej bloków, maksimum wariantów.
- Zmiana schematu z treścią w bazie → **ipal-migrate-fields**, nigdy „na żywo”.
## Faza 3 — Nawigacja i dane firmy → **ipal-nav**
## Faza 4 — Sekcje → **ipal-block** dla każdego bloku
Kolejność: Hero → sekcje powtarzalne (FeatureGrid, CTA, FAQ…) → specyficzne.
Każdy blok: schemat ze słownika pól, kompozycja prymitywów, zero tekstu w JSX
(`ipal-audit --quick` po każdym bloku — błędy naprawiasz od razu).
## Faza 5 — Formularze → **ipal-form**
Formularze tworzysz w panelu (albo seedem) — kod piszesz raz.
## Faza 6 — Treść w panelu, każdy język
1. Skopiuj `resources/seed-content.template.ts` → `scripts/seed-content.ts`,
wpisz treść z briefu: strony, bloki, linki (`{ $page: 'slug' }`), globale —
wszystkie języki obok siebie (`{ pl, en }`). Brak danych → `[DO UZUPEŁNIENIA: …]`.
Nie wymyślaj danych firmy, cen, opinii, liczb, certyfikatów, nazwisk.
2. `pnpm payload run scripts/seed-content.ts` → lista placeholderów trafia do raportu.
3. System Pages: Homepage, 404, polityka prywatności (strona istnieje; treść
polityki od klienta → placeholder). Cookie Settings, Notifications — teksty w
każdym języku.
4. **ipal-locale-add → `locale-coverage`** = 0 braków (albo świadome w raporcie).
5. Obrazy: zostawiasz puste pola upload (redaktor dodaje) albo wgrywasz pliki z
briefu przez panel — przygotowane (WebP/JPG ≤ 1.5 MB, ≤ 2560 px).
## Faza 7 — Integracje (panel, nie kod)
Site Integrations: transport e-mail + **Send test**, Turnstile, analityka/piksele
(tylko z ID od klienta), consent (kategorie zgodne z użytymi narzędziami).
Site Settings: nazwa, opis, OG image, favicon. SEO tab: meta title/description
każdej strony (≤ 60 / ≤ 155 znaków, unikalne).
## Faza 8 — Wygląd
`DESIGN.md` istnieje → tokeny w `@theme`. Brak → neutralne tokeny + w raporcie
rekomendacja Impeccable. Nie dopieszczaj stylów ad hoc w komponentach.
Responsywność: 360 px, 768 px, 1280 px — bez poziomego scrolla.
## Faza 9 — Weryfikacja (wszystko sam, wyniki do raportu)
```bash
pnpm generate:types && pnpm tsc --noEmit
bash .agents/skills/ipal-audit/scripts/audit.sh # pełny: + tsc + build
pnpm build && pnpm start & # trasy stron ● (SSG), nie ƒ
node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000
node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/<locale>
pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
```
Plus ręcznie: test redaktora (AGENT §11) w każdym języku, formularz (lista w
ipal-form §6), klawiatura (Tab przez menu, baner, formularz; widoczny focus),
404 w każdym języku. Każdy `[ERROR]` naprawiasz (**ipal-debug**) i uruchamiasz
kontrolę ponownie. Nie oddajesz z błędami — wyjątek: blokujący błąd ipal-kit
(raport ipal-plugin-gap + obejście).
## Faza 10 — Raport końcowy (jedyna duża wiadomość do użytkownika)
```markdown
# <Klient> — strona gotowa do przeglądu
## Zrobione
- strony: <lista z URL-ami per język> · bloki: <lista> · formularze: <lista>
- języki: <…> · integracje: <e-mail ✓ Send test, Turnstile ✓, analityka: czeka na ID>
## Kontrole
build ✓ (n tras ●) · ipal-audit 0/0 · seo-check <e>/<w> · consent-check 0 naruszeń · locale-coverage 0
## Do uzupełnienia przez Ciebie / klienta (w panelu)
- [DO UZUPEŁNIENIA: NIP] → Company · … (pełna lista z seeda)
- tłumaczenia robocze do akceptacji: <strony>
## Decyzje, które podjąłem
- <decyzja> — <dlaczego> (pełna lista w AGENTS.md)
## Naprawione po drodze
- <problem → przyczyna → poprawka> (krótko, tylko istotne)
## Dla ipal-kit
- [błąd|usprawnienie] <temat> → docs/plugin-requests/<plik> (obejście: <plik:linia>)
## Następny krok
- <jedna rzecz, np. „podaj domenę → wdrożenie wg PROGRAMISTA §4”>
```
Nie raportujesz postępu w trakcie. Wyjątki: lista pytań z fazy 0, blokujący błąd
ipal-kit, decyzja nieodwracalna.
@@ -0,0 +1,143 @@
/**
* Content seed from the brief — skill ipal-site, phase 6.
*
* pnpm payload run scripts/seed-content.ts # creates what's missing, never overwrites
* SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates existing docs (asks nobody — use before handover only)
*
* Write content ONCE, all languages side by side:
* heading: { pl: 'Nasze usługi', en: 'Our services' } → localized value
* heading: 'Nasze usługi' → same in every locale / non-localized field
* page: { $page: 'kontakt' } → ID of the page whose DEFAULT-locale slug is 'kontakt'
* Missing data: '[DO UZUPEŁNIENIA: NIP]' — never invent company data, prices, reviews, numbers.
*
* The default locale creates the structure (blocks, array rows); other locales are
* written onto the SAME row ids, so nothing is duplicated. Media: leave empty or
* reference existing uploads by ID — the editor adds images.
*
* GOTCHA (Payload, localization.fallback: true): an update in locale X without
* `fallbackLocale: false` merges the FALLBACK values into X — the default-locale
* text gets saved as the X translation. Every non-default write below sets it.
*/
import { getPayload } from 'payload'
import config from '@payload-config'
type Json = string | number | boolean | null | Json[] | { [k: string]: Json }
// ------------------------------------------------------------------ CONTENT --
const PAGES: { [k: string]: Json }[] = [
{
title: { pl: 'Strona główna', en: 'Home' },
slug: { pl: 'home', en: 'home' },
layout: [
{
blockType: 'hero',
heading: { pl: 'Nagłówek z briefu', en: 'Heading from the brief' },
links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' }, appearance: 'primary' } }],
},
],
},
{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' }, layout: [] },
]
const GLOBALS: { slug: string; data: { [k: string]: Json } }[] = [
// { slug: 'header', data: { links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' } } }] } },
]
const COLLECTION = 'pages'
// ----------------------------------------------------------------- /CONTENT --
const UPDATE = process.env.SEED_UPDATE === '1'
const payload = await getPayload({ config })
const loc = payload.config.localization
const def = loc ? loc.defaultLocale : undefined
const codes = loc ? loc.localeCodes : []
const others = codes.filter((c) => c !== def)
const ids = new Map<string, string | number>()
const isLocalized = (v: Json): boolean =>
!!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
/** Value for one locale; arrays keep the ids of rows that already exist. undefined = omit. */
function pick(v: Json, locale: string | undefined, existing: unknown): Json | undefined {
if (isLocalized(v)) { const m = v as { [k: string]: Json }; return locale ? m[locale] : m[def as string] }
if (Array.isArray(v)) {
const ex = Array.isArray(existing) ? existing : []
return v.map((item, i) => {
const out = pick(item, locale, ex[i])
const id = (ex[i] as { id?: string } | undefined)?.id
return out && typeof out === 'object' && !Array.isArray(out) && id ? { ...out, id } : (out ?? null)
})
}
if (v && typeof v === 'object') {
if (typeof v.$page === 'string') {
const id = ids.get(v.$page)
if (id === undefined) throw new Error(`$page "${v.$page}" not found — seed that page earlier in PAGES or create it in the panel`)
return id
}
const ex = (existing && typeof existing === 'object' ? existing : {}) as Record<string, unknown>
const out: { [k: string]: Json } = {}
for (const [k, val] of Object.entries(v) as [string, Json][]) {
const r = pick(val, locale, ex[k])
if (r !== undefined) out[k] = r
}
return out
}
return v
}
const defSlug = (p: { [k: string]: Json }) => String(isLocalized(p.slug) ? (p.slug as { [k: string]: Json })[def as string] : p.slug)
const hasPageRef = (v: Json): boolean =>
Array.isArray(v) ? v.some(hasPageRef) : !!v && typeof v === 'object' ? typeof v.$page === 'string' || Object.values(v).some(hasPageRef) : false
// Existing pages first, so $page works regardless of order.
const { docs: existingPages } = await payload.find({ collection: COLLECTION as never, depth: 0, limit: 0, pagination: false, ...(def ? { locale: def as never } : {}) })
for (const d of existingPages as { id: string | number; slug?: string }[]) if (d.slug) ids.set(d.slug, d.id)
const hasContent = (v: unknown): boolean =>
typeof v === 'string' ? v.trim() !== '' : typeof v === 'number' || v === true ? true
: Array.isArray(v) ? v.some(hasContent) : !!v && typeof v === 'object' ? Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x)) : false
const log: string[] = []
const writeLocales = async (write: (locale: string | undefined, existing: unknown) => Promise<unknown>, read: (l: string) => Promise<unknown>) => {
for (const l of others) await write(l, await read(def as string))
}
// Pass 1: create missing pages without layout links (targets may not exist yet), pass 2: full content.
for (const pass of [1, 2] as const) {
for (const p of PAGES) {
const slug = defSlug(p)
let id = ids.get(slug)
if (pass === 1) {
if (id !== undefined) continue
const data = pick(hasPageRef(p) ? { ...p, layout: [] } : p, def, undefined) as Record<string, unknown>
const created = await payload.create({ collection: COLLECTION as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: { ipalSeed: true } })
id = (created as { id: string | number }).id
ids.set(slug, id)
log.push(`created ${COLLECTION}/${String(id)} "${slug}"`)
continue
}
const fresh = log.includes(`created ${COLLECTION}/${String(id)} "${slug}"`)
if (!fresh && !UPDATE) { log.push(`skipped "${slug}" (exists — SEED_UPDATE=1 to overwrite)`); continue }
const readDoc = (l: string) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, locale: l as never, fallbackLocale: false as never })
await payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, def, undefined) as never, depth: 0, ...(def ? { locale: def as never } : {}), context: { ipalSeed: true } })
await writeLocales(
(l, ex) => payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, l, ex) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: { ipalSeed: true } }),
readDoc,
)
log.push(`${fresh ? 'filled' : 'updated'} "${slug}" [${codes.join(', ') || '-'}]`)
}
}
for (const g of GLOBALS) {
const readG = (l: string) => payload.findGlobal({ slug: g.slug as never, depth: 0, locale: l as never, fallbackLocale: false as never })
if (!UPDATE && def) {
const cur = (await readG(def)) as Record<string, unknown>
const filled = Object.keys(g.data).some((k) => hasContent(cur[k]))
if (filled) { log.push(`skipped global ${g.slug} (has content — SEED_UPDATE=1 to overwrite)`); continue }
}
await payload.updateGlobal({ slug: g.slug as never, data: pick(g.data, def, undefined) as never, depth: 0, ...(def ? { locale: def as never } : {}), context: { ipalSeed: true } })
await writeLocales((l, ex) => payload.updateGlobal({ slug: g.slug as never, data: pick(g.data, l, ex) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: { ipalSeed: true } }), readG)
log.push(`global ${g.slug} [${codes.join(', ') || '-'}]`)
}
for (const line of log) console.log(line)
const todo = JSON.stringify({ PAGES, GLOBALS }).match(/\[DO UZUPEŁNIENIA:[^\]]*\]/g) ?? []
if (todo.length) console.log(`\n${todo.length} placeholder(s) for the final report:\n ${[...new Set(todo)].join('\n ')}`)
process.exit(0)
+5 -2
View File
@@ -11,6 +11,7 @@ Zasada: gdy plugin dostarcza coś, co projekt ma ręcznie — **usuń lokalną w
## 1. Aktualizacja pakietu
```bash
pnpm add @intecion/ipal-kit@latest
pnpm payload generate:importmap # nowe komponenty panelu z pluginu (np. RowLabel)
rm -rf .next
```
Skopiuj skille na nowo (AGENT.md §14) — mogły się zmienić.
@@ -20,13 +21,15 @@ Postgres z migracjami: nowe pola pluginu (np. `privacyLinkLabel`) →
## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
Wynik: lista do zrobienia z priorytetem. Czekaj na OK.
Wynik: lista do zrobienia z priorytetem — realizujesz ją od razu. Zatrzymujesz się
tylko przed zmianą nieodwracalną (migracja danych z treścią → **ipal-migrate-fields**,
zmiana opublikowanych slugów).
## 3. Pozycja po pozycji
Jedna pozycja = jedna zmiana = jeden commit:
1. przeczytaj wskazany plik docs,
2. zastąp lokalny kod funkcją pluginu, usuń stary kod (nie zostawiaj obu),
3. `pnpm build`, pokaż wynik.
3. `pnpm build` — przechodzi, zanim weźmiesz następną pozycję.
Pozycje zmieniające nazwy pól w bazie (np. refaktor `ctaLabel` → `links`)
wymagają **migracji danych przed** usunięciem starych pól — zapytaj
+6 -2
View File
@@ -163,8 +163,12 @@ zmienna po zmiennej. Na większe zmiany są `classNames`:
Sloty: `root`, `primaryButton`, `secondaryButton`. Podany className zastępuje
domyślny (nie dokleja się).
Elementy mają też `data-ipal="banner"` i `data-ipal="cookie-button"` — stabilne
uchwyty do CSS albo testów e2e.
Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich
`ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`,
`accept`, `back`, `save`.
Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings →
settingsTitle** (per język) — bez tekstów na sztywno w komponentach.
## Locale jako cookie functional (wbudowane)
+6 -2
View File
@@ -315,8 +315,12 @@ Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź:
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
```
Brak `q` → 400. Tylko opublikowane, bez `noindex`. Błąd/baza offline → pusty
wynik (200), nie 500. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Błąd/baza
offline → pusty wynik (200), nie 500. **Limit zapytań:** 120/min na IP (w pamięci,
per instancja) → `429` z `Retry-After`; zmiana: `rateLimit: { max, windowMs }`,
wyłączenie (limiter z przodu, np. Cloudflare WAF): `rateLimit: false`.
Kolizja z `@payloadcms/plugin-search` (kolekcja `search` → REST pod `/api/search/...`):
przenieś route, np. `app/api/site-search/route.ts`. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
cache'em CDN.
Sam helper (do własnej wyszukiwarki po stronie serwera):
+39 -9
View File
@@ -87,7 +87,10 @@ layout pod `[locale]` (bo `<html lang>` musi znać język).
}
```
`pnpm ipal:skills` po instalacji i po każdej aktualizacji ipal-kit; `.agents/skills/`
commituj. W roocie `AGENTS.md` wg szablonu z [AGENT.md §13](../agent/AGENT.md).
commituj.
**`tsconfig.json` projektu: `"exclude": ["node_modules", ".agents"]`** — skille mają szablony
`.ts`/`.tsx`; bez wykluczenia `tsc` i `next build` sprawdzają je jak kod projektu i padają
(`ipal-skills` i `ipal-audit` ostrzegają). W roocie `AGENTS.md` wg szablonu z [AGENT.md §13](../agent/AGENT.md).
Lista skilli: AGENT.md §14.
### 2.2 Locale — jedno źródło
@@ -139,7 +142,7 @@ export default buildConfig({
`buildNoindexField()`, `layout` typu `blocks` (min. 1 blok), `trackSlugHistoryHook`,
`buildRevalidateHook`.
- `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized),
`normalizeFilenameHook`; R2 przez `buildR2Storage(['media'], { s3Storage })` —
`normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField` (za duże pliki, za zgodą); R2 przez `buildR2Storage(['media'], { s3Storage })` —
`s3Storage` z `@payloadcms/storage-s3`, wstrzykiwany (storage.md).
- Linki z pluginu (`buildLinkField`, `buildLinksField`, `resolveLinkHref` — links.md),
`src/fields/` (sectionHeader, sectionSettings) i `src/components/ui/`
@@ -155,8 +158,23 @@ export default { plugins: { '@tailwindcss/postcss': {} } }
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@import "@intecion/ipal-kit/fluid.css"; /* opcjonalnie: płynna skala typografii i odstępów */
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
@theme inline {
--text-display: var(--ipal-fs-display);
--text-h1: var(--ipal-fs-h1);
--text-h2: var(--ipal-fs-h2);
--text-h3: var(--ipal-fs-h3);
--text-lead: var(--ipal-fs-lg);
--spacing-section: var(--ipal-space-section);
--spacing-gutter: var(--ipal-space-gutter);
--spacing-gap: var(--ipal-space-gap);
}
```
`fluid.css` to same zmienne `clamp()` (360 → 1280 px, w `rem`) — klasy `text-h1`,
`py-section`, `px-gutter`. Liczby z `DESIGN.md` nadpisujesz w `:root` projektu
(`--ipal-fs-h1: clamp(…)`); formuł nie piszesz od zera.
Bez `@source` komponenty pluginu (baner cookies, Turnstile) są bez stylów.
Kolory komponentów pluginu: `--ipal-primary`, `--ipal-radius` (consent.md).
@@ -276,8 +294,8 @@ Archiwum z paginacją (`?page=`) — osobna trasa albo świadomie dynamiczna (pa
(przykład w pages.md).
```ts
// src/app/sitemap.ts
export { sitemap as default } from '@/lib/content'
// src/app/sitemap.xml/route.ts — XML dla Google, wygląd dla ludzi z pluginu (nic w /public)
export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/robots.ts
@@ -301,8 +319,9 @@ import { createHealthRoute } from '@intecion/ipal-kit'
export const dynamic = 'force-dynamic'
export const GET = createHealthRoute({ getCachedPayload })
```
Albo `sitemap.ts`, albo `sitemap.xml/route.ts` (`createSitemapRouteHandler`) —
nigdy oba.
Jeden sitemap: `sitemap.xml/route.ts` **albo** `sitemap.ts` — nigdy oba. Nagłówek
sitemapy = „XML Sitemap”, pod nim „Technology by Intecion.com”; zmiana
przez `createContentHelpers({ sitemapStyle })` (seo.md).
### 2.9 next.config.ts i instrumentation.ts
```ts
@@ -321,7 +340,7 @@ export default withPayload({
})
```
CSP (`buildCsp`) — najpierw `report-only`, po sprawdzeniu konsoli `enforce`
(security.md). `src/instrumentation.ts`: `assertEnv(ipalEnvRules({...}))` (env.md).
(security.md). `src/instrumentation.ts`: `assertEnv(ipalEnvRules({...}))` z **`@intecion/ipal-kit/env`**, tylko gdy `NEXT_RUNTIME === 'nodejs'` (env.md).
### 2.10 Generowanie i start
```bash
@@ -465,11 +484,17 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 15a | `buildR2Storage(['media'])` bez adaptera (od 1.8.1 błąd przy env R2) | `pnpm add @payloadcms/storage-s3`, `buildR2Storage(['media'], { s3Storage })` | storage.md |
| 15b | `src/fields/link.ts`, `src/lib/links.ts` w projekcie | importy z pluginu, usuń kopie (bez migracji bazy) | links.md |
| 15c | `createPageMetadata(...)` w `page.tsx` | `generatePageMetadata(locale, slug)` z `lib/content` — wspólny cache z komponentem strony, mniej zapytań | seo.md |
| 15d | brak limitów na za duże obrazy / wideo w Media | `buildOptimizeUploadHook()` + `buildOptimizeUploadField()`, migracja pola | storage.md |
| 15e | tablice „Add Row”, wiersze „Item 01”, `cta1`/`cta2`, etykiety PL w panelu | `labels` + `rowLabel()` na tablicach, sloty → tablica (z migracją!), etykiety EN — AGENT.md §6.5a; po aktualizacji pluginu **`pnpm payload generate:importmap`** (buildLinksField używa `RowLabel`) | links.md |
| 15f | `public/sitemap.css` + własna trasa / `app/sitemap.ts` | `app/sitemap.xml/route.ts`: `export { sitemapRoute as GET } from '@/lib/content'` + `force-dynamic`; usuń `public/sitemap.css` i `app/sitemap.ts` | seo.md |
| 15g | `instrumentation.ts` importuje z roota (crash Edge/Turbopack: `fileTypeFromFile`) | `import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'` + `if (process.env.NEXT_RUNTIME !== 'nodejs') return`; usuń dynamiczny `await import` | env.md |
| 15h | `<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(…) }}>` | `<JsonLdGraph schemas={[…]} />` z `@intecion/ipal-kit/rsc` (escapuje `<` — bez tego `</script>` w panelu = XSS) | seo.md |
| 15i | własne formuły `clamp()` w `styles.css` | `@import "@intecion/ipal-kit/fluid.css"` + mapowanie w `@theme` (§2.5) | — |
| 16 | 404 na sztywno | rola 404 w System Pages + `getNotFoundPage` | pages.md |
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` w layoucie | usuń cały parametr; tekst wpisz w Cookie Settings → Privacy link label | consent.md |
| 17 | Opcjonalnie — AI/GEO | Markdown per strona, llms-full, boty AI w robots, MCP, wyszukiwarka, speakable, aiSummary | content.md, seo.md, mcp.md |
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `rm -rf .next`, restart dev, grep nowego symbolu w
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
`node_modules/@intecion/ipal-kit/dist`.
---
@@ -504,6 +529,11 @@ przy starcie) → zapis w panelu → dublet zależności → importmap → cache
## 8. ROZWÓJ I PUBLIKACJA ipal-kit
### 8.1 Łańcuch zmiany
W repo pluginu jest skill **`ipal-release`** (`.agents/skills/ipal-release/`, nie jedzie w
paczce): kontrole `check-exports` (importy w docs ↔ entry pointy, przed i po buildzie) i
`check-deps` (zależności, reguły wstrzykiwania, `next/*.js`), build, publikacja.
**Numer wersji zawsze podaje człowiek.**
Zmiana nie działa w projekcie, dopóki nie przejdzie wszystkich etapów:
```
src → build (dist) → commit → version → publish → pnpm add w projekcie → restart
@@ -515,7 +545,7 @@ grep -c "<symbol>" src/<ścieżka> # >0 — zmiana zapisana
pnpm clean && pnpm build
grep -c "<symbol>" dist/<ścieżka> # >0 — build ją złapał (eksport w index.ts!)
git add -A && git commit -m "opis" # PRZED version
npm version patch # minor = nowe API, major = łamiące
npm version <wersja> # numer podaje człowiek; minor = nowe API, major = łamiące
npm publish
git push && git push --tags

Some files were not shown because too many files have changed in this diff Show More