Files
ipal-kit/src/modules/forms/formsPluginConfig.ts
T
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

326 lines
16 KiB
TypeScript

import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { Block, Field, Plugin } from 'payload'
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { AdminText } from '../admin-i18n/define.js'
import type { FormsOption } from './types.js'
import { userMeetsRole } from '../access/predicates.js'
import { resolveFormAttachments } from './attachments/config.js'
import { buildFileDeliveryHook, buildFileNoticeHook } from './attachments/delivery.js'
import { buildFormSubmitEndpoint } from './attachments/endpoint.js'
import { buildFileBlock } from './attachments/fileBlock.js'
import { buildFormFilesAfterRead, buildFormFilesBeforeValidate, submissionFileFields } from './attachments/formHooks.js'
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } }
/**
* Panel wording for form-builder's own fields, by its translation key. Its
* labels are functions (`({ t }) => t('plugin-form-builder:name')`); these
* replace them with `{ en, pl }` text — labels only, names and data unchanged.
* Keys not listed keep form-builder's own text.
*/
const FORM_BUILDER_TEXTS: Record<string, AdminText> = {
name: { en: 'Field key', pl: 'Klucz pola' },
bcc: { en: 'BCC', pl: 'UDW' },
cc: { en: 'CC', pl: 'DW' },
checkboxPlural: { en: 'Checkboxes', pl: 'Pola wyboru' },
checkboxSingular: { en: 'Checkbox', pl: 'Pole wyboru' },
checkedByDefault: { en: 'Checked by default', pl: 'Domyślnie zaznaczone' },
chooseConfirmationType: {
en: 'Show a message or go to another page after the form is sent.',
pl: 'Pokaż komunikat lub przejdź na inną stronę po wysłaniu formularza.',
},
confirmationMessage: { en: 'Confirmation message', pl: 'Komunikat potwierdzenia' },
confirmationType: { en: 'After sending', pl: 'Po wysłaniu' },
countryPlural: { en: 'Country fields', pl: 'Pola kraju' },
countrySingular: { en: 'Country', pl: 'Kraj' },
customURL: { en: 'Address (URL)', pl: 'Adres (URL)' },
datePlural: { en: 'Date fields', pl: 'Pola daty' },
dateSingular: { en: 'Date', pl: 'Data' },
defaultValue: { en: 'Default value', pl: 'Wartość domyślna' },
documentToLinkTo: { en: 'Page', pl: 'Strona' },
emailFrom: { en: 'From', pl: 'Od' },
emailPlural: { en: 'E-mail fields', pl: 'Pola e-mail' },
emailsDescription: {
en: 'Sent after each submission; use {{email}} for a field value and {{*:table}} for all values.',
pl: 'Wysyłane po każdym zgłoszeniu; {{email}} wstawia wartość pola, a {{*:table}} wszystkie wartości.',
},
emailSingular: { en: 'E-mail', pl: 'E-mail' },
emailTo: { en: 'To', pl: 'Do' },
field: { en: 'Field', pl: 'Pole' },
fields: { en: 'Fields', pl: 'Pola' },
fieldWidth: { en: 'Width (%)', pl: 'Szerokość (%)' },
internalLink: { en: 'Page', pl: 'Strona' },
label: { en: 'Label', pl: 'Etykieta' },
message: { en: 'Message', pl: 'Wiadomość' },
messageDescription: { en: 'Text of the e-mail.', pl: 'Treść wiadomości e-mail.' },
messagePlural: { en: 'Text blocks', pl: 'Bloki tekstu' },
messageSingular: { en: 'Text block', pl: 'Blok tekstu' },
numberPlural: { en: 'Number fields', pl: 'Pola liczbowe' },
numberSingular: { en: 'Number', pl: 'Liczba' },
optionPlural: { en: 'Options', pl: 'Opcje' },
optionSingular: { en: 'Option', pl: 'Opcja' },
placeholder: { en: 'Placeholder', pl: 'Tekst podpowiedzi' },
radioOptions: { en: 'Options', pl: 'Opcje' },
radioPlural: { en: 'Single choice fields', pl: 'Pola jednokrotnego wyboru' },
radioSingular: { en: 'Single choice', pl: 'Jednokrotny wybór' },
redirect: { en: 'Redirect', pl: 'Przekierowanie' },
replyTo: { en: 'Reply to', pl: 'Odpowiedź do' },
required: { en: 'Required', pl: 'Wymagane' },
selectOptions: { en: 'Options', pl: 'Opcje' },
selectPlural: { en: 'Dropdown fields', pl: 'Listy rozwijane' },
selectSingular: { en: 'Dropdown', pl: 'Lista rozwijana' },
statePlural: { en: 'Region fields', pl: 'Pola regionu' },
stateSingular: { en: 'Region', pl: 'Region' },
subject: { en: 'Subject', pl: 'Temat' },
submitButton: { en: 'Button text', pl: 'Tekst przycisku' },
textareaPlural: { en: 'Long text fields', pl: 'Pola długiego tekstu' },
textareaSingular: { en: 'Long text', pl: 'Długi tekst' },
textPlural: { en: 'Text fields', pl: 'Pola tekstowe' },
textSingular: { en: 'Text', pl: 'Tekst' },
title: { en: 'Title', pl: 'Tytuł' },
urlToRedirectTo: { en: 'Address (URL)', pl: 'Adres (URL)' },
value: { en: 'Value', pl: 'Wartość' },
}
/** `({ t }) => t('plugin-form-builder:<key>')` → our `{ en, pl }`; anything else unchanged. */
function formBuilderText<V>(value: V): AdminText | V {
if (typeof value !== 'function') {return value}
try {
const key = String((value as (args: unknown) => unknown)({ i18n: {}, t: (k: string) => k }))
return FORM_BUILDER_TEXTS[key.replace(/^plugin-form-builder:/, '')] ?? value
} catch {
return value
}
}
/** Replaces form-builder's labels, descriptions and option labels, deep (blocks, arrays, rows, groups). */
function localizeFormBuilder<T>(node: T): T {
if (Array.isArray(node)) {return node.map(localizeFormBuilder) as T}
if (!node || typeof node !== 'object') {return node}
const f = node as Record<string, unknown>
const out: Record<string, unknown> = { ...f }
if ('label' in f) {out.label = formBuilderText(f.label)}
// The text block's rich text has no label of its own.
if (f.type === 'richText' && f.name === 'message' && !f.label) {out.label = { en: 'Text', pl: 'Treść' }}
// The e-mails array has no label (auto "Emails").
if (f.type === 'array' && f.name === 'emails' && !f.label) {
out.label = { en: 'E-mails', pl: 'E-maile' }
out.labels = { plural: { en: 'E-mails', pl: 'E-maile' }, singular: { en: 'E-mail', pl: 'E-mail' } }
}
if (f.labels && typeof f.labels === 'object' && f.name !== 'emails') {
const labels = f.labels as Record<string, unknown>
out.labels = { ...labels, plural: formBuilderText(labels.plural), singular: formBuilderText(labels.singular) }
}
if (f.admin && typeof f.admin === 'object' && 'description' in f.admin) {
const admin = f.admin as Record<string, unknown>
out.admin = { ...admin, description: formBuilderText(admin.description) }
}
if (Array.isArray(f.options)) {out.options = f.options.map((o) => (o && typeof o === 'object' ? { ...o, label: formBuilderText((o as { label?: unknown }).label) } : o))}
for (const key of ['fields', 'blocks', 'tabs'] as const) {
if (Array.isArray(f[key])) {out[key] = localizeFormBuilder(f[key])}
}
return out as T
}
/** Labels for the submission fields form-builder leaves unlabelled. */
const SUBMISSION_LABELS: Record<string, AdminText> = {
form: { en: 'Form', pl: 'Formularz' },
submissionData: { en: 'Answers', pl: 'Odpowiedzi' },
submissionUploads: { en: 'Files', pl: 'Pliki' },
}
const SUBMISSION_ROW_LABELS: Record<string, AdminText> = {
field: { en: 'Field key', pl: 'Klucz pola' },
value: { en: 'Value', pl: 'Wartość' },
}
function labelSubmissionFields(fields: Field[]): Field[] {
return fields.map((field) => {
if (!('name' in field) || !SUBMISSION_LABELS[field.name] || field.label) {return field}
const labelled = { ...field, label: SUBMISSION_LABELS[field.name] } as Field
if (labelled.type === 'array') {
return {
...labelled,
fields: labelled.fields.map((sub) =>
'name' in sub && SUBMISSION_ROW_LABELS[sub.name] && !sub.label ? ({ ...sub, label: SUBMISSION_ROW_LABELS[sub.name] } as Field) : sub,
),
labels: labelled.labels ?? { plural: { en: 'Answers', pl: 'Odpowiedzi' }, singular: { en: 'Answer', pl: 'Odpowiedź' } },
} as Field
}
return labelled
})
}
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
withShowWhen(builtinBlocks[key] as Block)
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
* Submissions are visitors' personal data: editors and admins only. The
* form-builder default lets ANY account of the admin collection read them —
* including a plain 'user' from an open sign-up.
*/
const submissionsReadAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'editor')
const submissionsDeleteAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'admin')
/**
* Forms carry recipient addresses (Emails → To/BCC): a plain 'user' account
* editing a form could BCC every submission to itself. Editors and admins only.
*/
const staffAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'editor')
/**
* Forms stay publicly readable (their fields render the form), but the Emails
* tab — recipient addresses, templates — is for editors and admins only, so
* GET /api/forms doesn't hand out the company's inboxes to spammers. Applied to
* the default fields BEFORE formOverrides.fields sees them, so a project can
* still change the rule there.
*/
function hideEmails(fields: Field[]): Field[] {
return fields.map((field) =>
'name' in field && field.name === 'emails'
? ({
...field,
access: { ...(field as { access?: object }).access, read: staffAccess },
} as Field)
: field,
)
}
/**
* Configures @payloadcms/plugin-form-builder from IAPL's FormsOption.
*
* Provides the forms / form-submissions collections and field types. E-mails
* after a submission are the form-builder's own (Forms → Emails), sent through
* the project's email adapter (mailAdapter()).
*
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
* anyone can POST /api/form-submissions and skip everything submitForm enforces
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
* creation is limited to logged-in users; the site submits through submitForm
* (server action → Local API, which bypasses access by design). A project that
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? { en: 'Forms', pl: 'Formularze' } : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
const formsSlug = forms.formOverrides?.slug ?? 'forms'
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug }) : undefined
// Files (forms.attachments): never stored — attached to the company e-mail by
// the two hooks around the layout, and dropped (attachments/delivery).
const attachments = forms.attachments ? resolveFormAttachments(forms.attachments) : null
const fileNotice = attachments ? buildFileNoticeHook({ formsSlug, notice: attachments.notice }) : undefined
const fileDelivery = attachments ? buildFileDeliveryHook({ formsSlug }) : undefined
const beforeEmail: BeforeEmail | undefined =
layout || forms.beforeEmail || attachments
? async (emails, args) => {
const noticed = fileNotice ? await fileNotice(emails, args) : emails
const laidOut = layout ? await layout(noticed, args) : noticed
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
return fileDelivery ? fileDelivery(changed, args) : changed
}
: undefined
const fileBlockOption = forms.fields?.file
const formHooks = forms.formOverrides?.hooks
const builder = formBuilderPlugin({
...(beforeEmail ? { beforeEmail } : {}),
// Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
fields: {
// every block carries "Show only when" (showWhen) — conditional fields and steps
checkbox: builtin('checkbox'),
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: builtin('date'),
email: withHint('email'),
// File (ipal): only with forms.attachments; `false` hides it, a block object replaces it.
...(attachments && fileBlockOption !== false
? { file: (typeof fileBlockOption === 'object' ? fileBlockOption : buildFileBlock(attachments)) as never }
: {}),
message: builtin('message'),
number: withHint('number'),
payment: false,
radio: builtin('radio'),
select: builtin('select'),
step: forms.fields?.step === false ? false : stepBlock,
text: withHint('text'),
textarea: withHint('textarea'),
time: forms.fields?.time === false ? false : timeBlock,
...Object.fromEntries(
// `true` keeps ipal's block (with "Show only when"); false / an object override it
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'file' && k !== 'step' && k !== 'time' && v !== true),
),
},
...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships }
: {}),
// Client-supplied collection overrides (e.g. a per-form notification
// address). The plugin provides the hook, not the opinion about which
// extra fields a form should carry.
// Tidy panel by default: both collections under one sidebar group with plain
// labels — no per-project overrides needed just to sort the sidebar.
formOverrides: {
labels: { plural: { en: 'Forms', pl: 'Formularze' }, singular: { en: 'Form', pl: 'Formularz' } },
...forms.formOverrides,
access: {
create: staffAccess,
delete: staffAccess,
read: () => true,
update: staffAccess,
...forms.formOverrides?.access,
},
admin: { ...group, ...forms.formOverrides?.admin },
...(attachments
? {
hooks: {
...formHooks,
afterRead: [...(formHooks?.afterRead ?? []), buildFormFilesAfterRead(attachments)],
beforeValidate: [...(formHooks?.beforeValidate ?? []), buildFormFilesBeforeValidate()],
},
}
: {}),
fields: ({ defaultFields }) => {
const protectedFields = hideEmails(localizeFormBuilder(defaultFields))
return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields
},
},
formSubmissionOverrides: {
labels: { plural: { en: 'Submissions', pl: 'Zgłoszenia' }, singular: { en: 'Submission', pl: 'Zgłoszenie' } },
...forms.formSubmissionOverrides,
access: {
create: submissionsCreateAccess,
delete: submissionsDeleteAccess,
read: submissionsReadAccess,
...forms.formSubmissionOverrides?.access,
},
admin: {
...group,
defaultColumns: attachments ? ['form', 'filesDelivery', 'createdAt'] : ['form', 'createdAt'],
...forms.formSubmissionOverrides?.admin,
},
fields: ({ defaultFields }) => {
const labelled = [...labelSubmissionFields(defaultFields), ...(attachments ? submissionFileFields : [])]
return forms.formSubmissionOverrides?.fields ? forms.formSubmissionOverrides.fields({ defaultFields: labelled }) : labelled
},
},
})
if (!attachments) {return builder}
// The submit endpoint for forms with files, and the resolved option where
// submitForm and the endpoint read it (payload.config.custom.ipal.formAttachments).
return (incoming) => {
const config = builder(incoming)
return {
...config,
custom: { ...config.custom, ipal: { ...(config.custom?.ipal as object | undefined), formAttachments: attachments } },
endpoints: [...(config.endpoints ?? []), buildFormSubmitEndpoint(attachments)],
}
}
}