# Changelog

URL: https://docs.forms.saastro.io/docs/changelog
> Every released version of @saastro/forms, newest first — what changed, what broke, and what to do about it. Each version has its own anchor.

## 0.29.0

### Minor Changes

- 4458023: `turnstilePlugin`: **cambio de comportamiento** — el script de Cloudflare y el widget ya no se cargan al montar el formulario, sino en la primera interacción del visitante con él (`focusin`/`pointerdown`/`input` dentro del `<form>`, una sola vez) o, a más tardar, al enviar. Montar el form no contacta con terceros (Turnstile pedía Client Hints de alta entropía antes de cualquier uso). Opción nueva `loadOn: 'mount' | 'interaction'` (por defecto `'interaction'`); `'mount'` restaura el comportamiento anterior. Sin token al enviar, el submit sigue abortando según `failMode`.

## 0.28.0

### Minor Changes

- 9bb8020: Export the `HookFormMeta` type (`{ formId }`) from the package entry. It is the optional last argument of the `onAfterSubmit` and `onError` plugin hooks and part of the `onStepChange` meta (`StepChangeMeta & HookFormMeta`), so plugin authors can now type those parameters. Docs updated.
- 78b165a: Consent gate: the library no longer touches the visitor's device by default. Until you call the new `setConsent()`, the `landingPage` and `firstReferrer` resolvers keep their first-touch value in memory (coherent across form steps, never written), and the `cookie`, `storage` and `ip` resolvers return their `fallback` without reading cookies / storage or calling the endpoint. Wire your banner once with `setConsent({ get, subscribe })`, or declare `setConsent('not-required')` on purpose. The hidden fields that depend on consent are resolved again whenever the consent changes (if the provider has `subscribe`) and, as the final word, when the form is submitted, with the consent of that moment (granted after mount and before sending: the data goes out; withdrawn in between: it does not; `submissionId` and `timestamp` keep their mount-time value). Granting saves the first-touch the page already knew; withdrawing deletes the two `sessionStorage` keys the library wrote and empties the memory copy. Purposes: `necessary` (never asks), `attribution` (first-touch, reading cookies and storage) and `enrichment` (the `ip` call). New exports: `setConsent`, `hasConsent`, `getStoredKeys`, `clearStoredData` (for data-subject requests: list and delete everything the library stored) and the `ConsentCategory` / `ConsentConfig` / `ConsentProvider` / `StoredKey` / `StoredDataOptions` types. New optional subpath `@saastro/forms/consent` with `fromCookie` (a banner that keeps its decision in a JSON cookie) and `fromGoogleConsentMode`; the core never imports it. `getStoredKeys` and `clearStoredData` do not ask for consent: looking at or deleting your own data collects nothing. A purpose is granted only when its checkbox is exactly `true` (cookie) or `'granted'` (Google); a missing, corrupt or non-object cookie grants nothing. `fromGoogleConsentMode` fails closed on `region`: a `default` scoped to regions never grants (the library does not know where the visitor is), one that denies is respected until the visitor's own `update`, and a later `default` never overrides what the visitor already decided.

  Behavior change in 0.x: sites that relied on first-touch attribution, the `cookie` / `storage` resolvers or `ip` must call `setConsent` after updating. Without consent the first-touch resolvers also delete the two `sessionStorage` keys the library wrote, so a withdrawn consent, a provider with only `get`, or keys left by an earlier version do not survive. Internally, every access to storage and cookies now goes through `utils/deviceStorage.ts` (the only exception is the opt-in `localStorage` plugin, which saves what the visitor types and is not governed by consent); a test fails if any other file touches them, each built-in resolver declares its device effect (`RESOLVER_EFFECTS`), and a contract test mounts a form with every resolver and asserts zero writes, reads and requests without consent. The docs list every key the library stores.

### Patch Changes

- c427ae1: Stop leaking the internal `labelId` accessibility prop onto DOM controls. The select, file, OTP, phone, rating, text and toggle renderers now spread the new `controlA11y()` helper, so React no longer warns "does not recognize the `labelId` prop".

## 0.27.1

### Patch Changes

- 304042e: `validateFormConfig` rejects an option whose `shortLabel` is not a string (`option-short-label-invalid`), and `lintFormConfig` warns on an empty one (`short-label-empty`): compact channels would silently fall back to `label`. The visual builder can now edit `shortLabel` per option.

## 0.27.0

### Minor Changes

- a5b1ed4: `validateFormConfig` validates `optionsSource` dependencies: a `dependsOn` or a `{{field}}` in the url that points to a nonexistent field (`options-source-field-unknown`, also thrown by `build()`) or to a multi-value one (`options-source-dependency-array`). `build()` now throws on configs that previously passed.

### Patch Changes

- 2080e44: Analytics: `form_step`, `form_submit` and `form_error` now always carry `form_id`. The runtime passes `formId` in the `onStepChange` meta (the plugin's own only; the user's `onStepChange` callback does not change) and as an optional 3rd argument (`HookFormMeta`) of `onAfterSubmit` and `onError`; previously it came from the last initialised session on the page, which was the wrong one with two forms. Backwards compatible: plugins with 1–2 parameters keep working.
- c1a2876: `ValidationRules.pattern` is evaluated with a linear-time engine (Pike automaton) when the pattern fits its subset (no lookarounds or backreferences): `^(\d?\d?\d?\d?\d?){9}$`, `^(\d{1,3}\d{1,3}){9}$` and `^(?:\d{1,3}|\d{1,3}\d{1,3}){9}$`, which the ReDoS heuristic let through and which cost n^k with the native engine, now validate 10,000 characters in milliseconds. The `safePattern` guard does not change: no new pattern is rejected.
- e8faf64: localStoragePlugin: `hidden` fields with a `resolver` (`?ref`, UTM, referrer…) are no longer restored from, nor written to, the saved draft, so the value resolved from the URL always wins over stored progress. `hidden` fields without a resolver keep being saved and restored.

## 0.26.0

### Minor Changes

- 0099cf0: AI metadata (data only, no runtime and no `fetch`): `FormConfig.ai` (`evaluate`, `summarize`, `apiKey`) and `BaseFieldProps.ai` (`evaluate`, `describe`), with the types `AiEvaluateSpec`, `AiOutputKind`, `FormAiConfig` and `FieldAiConfig`. `validateFormConfig` checks their shape and reports `ai-invalid` (prompt required and at most 4,000 characters, `output` one of `text | json | boolean | number | enum`, `schema` an object). `findClientSecrets` reports `ai.apiKey` (kind `'ai.apiKey'`) and `redactClientSecrets` removes it.
- 79f5bb8: Nested condition groups with `not`. `ConditionGroup.conditions` now accepts other groups (`a AND (b OR c)`) and a group can set `not: true`. Nesting deeper than `MAX_CONDITION_DEPTH` (10) makes the whole condition `false` without throwing; `validateFormConfig` reports it as `condition-too-deep`. It applies to step routing, `hidden`, cross-field `when`, `$if` expressions and the `condition` of a submit action (now `SubmitActionLeaf | ConditionGroup`). Code that read `group.conditions[i].field` directly must now tell leaves from groups (`collectConditionFields` does it for you).
- 13fd285: `Option.shortLabel` and `ButtonCardOption.shortLabel`: a compact form of an option's label, used by the WhatsApp message (falls back to `label`/`text` when missing or empty). The i18n overlay translates it by option `value` like the label; in `LocaleOverlay` an option entry now takes `label?` and `shortLabel?`, both optional.
- 380557c: Builders: `FormBuilder.step(id, title, s => …)` with the new exported `StepBuilder` (`.fields() .description() .next() .defaultNext() .review() .i18n(locale, {title, description}) .locale(code) .meta(data)`; `Step.meta` is new and never read by the runtime). `FieldBuilder` gains `.matrix(rows, options)`, `.html(content)`, `.visibleWhen(condition)` (stores `hidden` with `not`), `.requiredWhenVisible()` (a field hidden by a condition is neither validated nor submitted) and `.minDate()` / `.maxDate()`, which take an ISO string, a `Date` or `{ daysFromToday }`. The relative form is the new serializable rule pair `minDateDaysFromToday` / `maxDateDaysFromToday` on `ValidationRules`, resolved when the schema is built (the max day is valid all day).
- b19e86c: New subpath `@saastro/forms/standard-schema` (React-free, separate from `/validation`): `toStandardSchema(form)` exposes a form as a Standard Schema v1 with the same rules the browser runs; `parseFormData(form, formData)` turns a `FormData`/`URLSearchParams` into typed values (checkboxes to boolean, numbers to number, repeated keys and `items[0][name]` to arrays, `__proto__`-style keys ignored); `createServerValidate(form)` returns an action for `useActionState` or a Server Action, with `ServerValidateState` and `initialServerValidateState`.
- 3624e6a: Types only: `InferFormValues` now works on the `addField` chain of `FormBuilder`. `build()` returns `TypedFormConfig<F>` (a `FormConfig` with a type-only `'~fields'`), and `FieldBuilder` gains three defaulted type parameters (field type, Zod schema, hidden by condition) changed only by `.type()`, `.schema()`, `.visibleWhen()` and `.hidden(group | fn)`. A field hidden by a condition infers `T | undefined`, also for literal configs. No runtime change.
- 274c7bd: Accessibility wiring in `FieldWrapper` (5.4). Every built-in field type now passes axe (38 types, at rest and with an error).

  - `FieldWrapper` generates ids with `useId()` and gives the renderers `params.a11y` (`id`, `aria-describedby`, `aria-invalid`, plus `labelId`). The control's `aria-describedby` points to the description and the error only when they exist; `aria-invalid` is set only where the role allows it.
  - `FieldDescription` and `FieldError` receive an `id`, and `FieldLabel` receives `id` and `htmlFor` (additive optional props in `FieldDescriptionProps`, `FieldErrorProps` and `FieldLabelProps`). **Custom `Field*` primitives must forward `id`/`htmlFor` to the DOM node** (the shadcn ones already do via `...props`).
  - Groups (radio, checkbox-group, switch-group, button-card/radio, matrix, repeater) render as `<fieldset>` + `<legend>` (visually hidden when `hideLabel`); the radiogroup inside is named with `aria-labelledby`. Option ids are index-based.
  - Date triggers are named with `aria-labelledby="<label> <trigger>"`, so the selected value stays in the accessible name.
  - New exported types: `FieldA11y`.

- d398470: Default size limits on every field, client and server: a text value over 10,000 characters and a list over 1,000 items are rejected when the field declares no `maxLength` / `maxItems` (also fields with only `required` or no rules). New i18n message `validationTooLong` (en/es, optional in `FormMessages`); `compileValidationRules` takes an optional third `msgs` argument. Declare `maxLength` / `maxItems` to set your own limit. `signature`, `hidden` and `html` fields (long text) are capped at 1,000,000 characters. Contract change: `resolveFieldSchema` no longer returns `null` for a field without rules (it returns a limits-only schema), so such fields now appear in the `data` of `validateFormData`. Fields with an explicit Zod or Standard Schema `schema` get no default limit.
- c41bff6: New public `registerDateLocales({ fr, de })`: register date-fns locales from your app and each form picks its own by `config.locale` (region ignored), without bundling them in the package; an explicit `setDateLocale` still wins. New `formatPlural(locale, count, forms)` (and the `PluralForms` type) picks the plural form with `Intl.PluralRules` for languages with more than two forms.
- 104bf92: `analyticsPlugin` now sends `form_step_time` (`form_id`, `step_id`, `duration_ms`, when leaving a step or submitting) and `form_abandon` (`form_id`, `step_id`, `duration_ms`, sent once with `transport_type: 'beacon'` when the tab is hidden or the page is unloaded without a submit). No form values are sent; the listeners are removed in `cleanup`.

### Patch Changes

- f493c91: Accessibility: when the step changes (next, back, `goToStep`), `<Form>` moves focus to the step's `<h2>` title (or its first control when the step has no title) and announces «Step n of N» in a polite `aria-live` region (new `stepAnnounce` message in the `en`/`es` bundles; `FormMessages.stepAnnounce` is optional, falling back to the English text). It never steals focus on first mount, and single-step forms render no live region.
- a5b345a: Native (no-JS) submit gets its thank-you page and form encoding: `FormProps` gains `enctype` and `nativeFields` (hidden inputs rendered only together with `action`, never part of the JS payload), and `<HubForm>` gains `thanksPath`, sent as `_redirect` when the served schema carries `meta.nativeSubmit`. `thanksPath` must be a same-site relative path (the Hub worker discards anything else), and `<HubForm>` never sets `multipart/form-data` on its own because the Hub's native endpoint only accepts urlencoded today.
- c240378: New browser-only submit action `lookup`: on `onFieldBlur`, `onFieldChange` or `onStepEnter` it fetches a JSON endpoint (`{{field}}` placeholders, URL-encoded; `params`, `timeoutMs`, `maxBytes`, `onError`) and copies parts of the response into other fields via `mapResponse` (own properties only, scalars only). While a lookup is in flight _Next_ and _Submit_ are `disabled` with `aria-busy` (Enter does not submit either); on timeout it is aborted and the form is never left blocked, and the last lookup of an action wins. The submit orchestrator and the Hub never run it. `validateFormConfig` reports `lookup-invalid`, and `findClientSecrets` covers its `endpoint` and `params`.

## 0.25.0

### Minor Changes

- 32021ef: Plugin hardening (P0.8):

  - **Breaking:** `recaptchaPlugin` now defaults to `failMode: 'closed'`: if no token can be obtained (script blocked or not loaded, timeout, error) the submit fails with a clear error instead of going through tokenless. Pass `failMode: 'open'` to keep the old behavior.
  - **Breaking:** the `ip` resolver no longer defaults to `https://api.ipify.org`. Without an `endpoint` it makes no request, logs a warning once and returns `fallback` (or `''`). Set `endpoint` to keep resolving the IP.
  - `localStoragePlugin` never persists fields of type `password`, `otp`, `file` or `signature`, and ignores them when restoring an older saved draft.
  - `analyticsPlugin` sends `error_type` (the error class) in `form_error` instead of `error_message`, which could carry user input or tokens into Google Analytics.

- b23f29f: **Breaking:** the step UI moves out of the root entry into the new `@saastro/forms/steps` subpath. `StepsNavigation`, `StepsProgress`, `StepsAccordion`, `useFormStepsInfo` (and its `StepInfo`/`FormStepsInfo`/`StepStatus` types) are no longer exported from `@saastro/forms`: change the import to `@saastro/forms/steps`. The built-in step texts (`stepLabel`, `stepOfTotal`, …) now default from that subpath (`en`/`es` by `config.locale`); `setDefaultMessages`, `FormConfig.i18n` overrides and the complete `en`/`es` from `@saastro/forms/locales` keep working, and the `FormMessages` keys for them become optional.

  New: `FormConfig.stepsUi` (`{ mode: 'none' | 'progress' | 'sidebar'; navigable?; variant? }`) makes `<Form>` draw a progress bar or step menu, provided you register `stepsUiPlugin()` from `@saastro/forms/steps` (via `PluginManager`, `FormPlugin.stepsUi` / `registerStepsUi`). Without the plugin it draws nothing and warns once; `<Form>` never imports the subpath. `Step.review: true` is unaffected and needs no plugin. The root entry is about 1.9 kB (brotli) smaller.

- 980b32e: `<HubForm>` marker and success message, and cascading remote options:

  - `<HubForm>` wraps its output in `<div data-saastro-form="{siteId}/{formSlug}" style="display: contents">` in all five states (loading, error, success, form, empty), so a page can be inspected to find which Hub form it embeds. It also renders the schema's `successMessage` (localized to the active locale, sanitized) on the success screen.
  - `optionsSource` can depend on other fields. `{{field}}` placeholders in `url` are replaced with the current value of that field (URL-encoded, and only allowed after the origin, never in the host); `dependsOn?: string[]` adds dependencies that are not in the URL. While a dependency is empty nothing is requested and the control is disabled. When a dependency changes, the old options are dropped and the request is made again; the field's own value is kept only if it is still one of the new options, and is cleared if the dependency becomes empty or the load fails (with `serverSearch`, a real change of the dependency always clears it). A dependency must be a scalar (text or number): an array value is not resolved and empties the options.

- e8fbfdc: Add `lintFormConfig` to `@saastro/forms/validation` (P4.4): warnings for configs that are valid but probably not what the author meant (`validation` instead of `schema`, optional field with `format`, required field hidden by a condition, `html` field with several of `content`/`html`/`value`, step without `title`, no `successMessage`, client-side secrets, reserved field names). `validateFormConfig(config, { lint: true })` from that subpath also returns `warnings`. The root entry does not export the linter and its `validateFormConfig` ignores `lint`.
- d340e4d: Nuevo subpath `@saastro/forms/presets` (P4.6): `FORM_PRESETS`, cuatro formularios completos en en/es (contacto, presupuesto, reserva y solicitud de empleo con consentimiento RGPD), cada uno válido para `validateFormConfig`. Solo datos, sin React: el entry raíz no crece.
- a7c4840: **Breaking:** `generateTestData`, `generateFieldValue`, `detectLocale` and the `TestDataOptions` / `TestDataLocale` types moved out of the root entry to the new subpath `@saastro/forms/testing` (≈1 kB less in the entry). Migration: `import { generateTestData } from '@saastro/forms/testing'`.

### Patch Changes

- 6773b92: Steps can now carry a visible title and description: `<Form>` renders `step.title` as an `<h2 tabIndex={-1}>` and `step.description` as a `<p>` above the step's fields (locale overlay applied), `StepsNavigation` and `StepsAccordion` show `step.title` instead of «Step n» when set, `StepInfo` exposes `title`, and `FormBuilder#addStep(id, fields, { title?, description? })` accepts both.

## 0.24.0

### Minor Changes

- 4ba013c: Security hardening of config-driven validation (stricter, so a minor):

  - ReDoS guard: a fixed-count group of three or more repetitions whose atoms overlap (e.g. `^(\d+\s?){9}$`) is now rejected like any other catastrophic-backtracking pattern. Delimited ones such as `^(\d{1,3}\.){3}\d{1,3}$` stay valid.
  - A field (or repeater sub-field) named `__proto__` now throws at schema build and is reported by `validateFormConfig`: Zod ignores that key while parsing, so such a field was silently never validated.
  - `validateFormData` no longer throws a `TypeError` when an error belongs to a field named like an `Object.prototype` member (`constructor`, `toString`…). Its `errors` object now has no prototype: call `Object.hasOwn(errors, key)` or `key in errors` instead of `errors.hasOwnProperty(key)`.
  - Repeater `itemFields` nested deeper than 8 levels throw a clear error instead of overflowing the stack.
  - `optionsSource` reads `path`, `labelKey` and `valueKey` from own properties only (no `__proto__` / `constructor` traversal).

- 60eb8f4: Multi-step navigation from the outside, a review step, and plugins in `<HubForm>`:

  - `FormRef.goToStep(stepId)` jumps to any step (no validation of the current one) and returns `false` for an unknown id or the step you are already on; `FormRef.getCurrentStep()` returns the active id. The jump fires the same `onStepChange` hooks as next/prev, and «Back» steps back along the visited path (jumping to an already-visited step trims the history to it).
  - `Step.review: true` makes a step render a summary of the steps the visitor's route has actually gone through (computed from the current values, not from history), one block per step with an «Edit» button that calls `goToStep`. New messages `reviewEdit` / `reviewEmpty` (en/es). Put it last, usually with `fields: []`.
  - `<HubForm>` now forwards `ref` to `<Form>` (so `goToStep` works through it) and accepts `plugins: FormPlugin[]`, registered in the same `PluginManager` as the automatic captcha. Plugins are identified by name; a new array on every render does not rebuild the manager.

- a08414b: Fields hidden by a condition are no longer validated and no longer sent.

  A field whose `hidden` is a function or a condition group and evaluates to `true` used to keep its rules: an optional URL with `format` that the visitor could not even see blocked «Next» (and Enter) with no visible error, and its value travelled in the payload. Now the resolver prunes the schema with the live values (so native Enter submit is covered too), `trigger` only runs on visible fields, and the payload drops the hidden keys. Server-side, `buildFormSchema(form, { values, validateHidden })` and `validateFormData(form, data, { validateHidden })` do the same. New helpers `isHiddenByCondition`, `resolveHiddenFields`, `stripHiddenFields`.

  **Breaking:** the payload loses the keys of fields hidden by a condition. `hidden: true` (literal) and per-breakpoint maps keep validating. Restore the 0.23 behavior with `validation: { validateHidden: true }`.

  Visibility is decided with the values of existing, non-hidden fields only (a hidden field cannot hide another one, an unknown key controls nothing). Known limits: sub-fields of a repeater (`itemFields`) are not covered; `crossFieldRules` that reference a hidden field still evaluate; on the server a visible field with a value outside its options can still hide another one (options are not validated server-side). The WhatsApp summary, `successMessage` and plugin hooks (`onFieldChange`, `onStepChange`, autosave) still receive the raw values; hidden-type and literal `hidden: true` fields can still drive conditions. Circular conditions that never settle validate everything.

- 364517e: `onStepChange` now reports where the visitor goes and how:

  - **Breaking:** the first argument is the step being ENTERED (it used to be the step being left). The new second argument is `{ from, direction }`, with `direction` `'next' | 'back' | 'jump'` (`goToStep` is `'jump'`). Plugin hook: `onStepChange(stepId, values, meta)`. Migrate code that read the first argument as «the step just completed» to `meta.from`.
  - `analyticsPlugin` sends `form_step: { step_id, from_step_id }`; `step_id` is now the destination.
  - `StepChangeMeta` is exported.

### Patch Changes

- 3a17818: Internal plumbing, no behavior change. The root entry now lists the `./validation` exports explicitly instead of `export *` (the public API is the same; a new name can no longer leak in by accident, and a snapshot test pins the root runtime exports). `useFormSteps` `nextStep`/`prevStep` now return the destination step id or `null` instead of a boolean (internal hook; `useFormState` still exposes booleans).
- 194aa76: Fix: an optional text-like field (`required: false`) with `format`, `minLength` or `pattern` now accepts an empty string. A blank input is submitted as `''` and used to fail `format: 'email'`. The rules still apply, with their own messages, to any non-empty value, and `''` is kept as-is in the validated data.
- 7e52ad9: Fix: a submit action of type `integration` (a Saastro Hub reference that the Hub dispatches server-side) is now ignored by the form runtime with a one-time console warning, instead of throwing `Unknown action type` and failing the submit.
- 5134081: Fix: the `command` and `combobox` fields now take their default search placeholder and empty text from the i18n messages (`commandSearch`, `commandEmpty`), so `config.locale` and `setDefaultMessages` apply to them. A field's own `searchPlaceholder` / `emptyText` still wins. `COMMON_STRINGS.COMMAND_EMPTY` and `COMMAND_SEARCH_PLACEHOLDER` are deprecated and no longer used.

## 0.23.1

### Patch Changes

- cdc4da0: Peer `react-day-picker` ampliado de `^9.11.3` a `^9.11.3 || ^10.0.0`. El paquete solo hace `import type { DateRange }` y recibe el `<Calendar>` de la app por el contexto de componentes, así que la major instalada no cambia el runtime; el rango anterior hacía que npm/pnpm marcasen un peer insatisfecho en las apps que ya están en la 10. La suite del paquete corre ahora contra 10.0.2 (devDependency) y un test falla si el peer vuelve a excluir la 10. No cambia ninguna API ni los `.d.ts`; es ampliar un rango, por eso patch.

## 0.23.0

### Minor Changes

- 221640e: Zod 4. **Breaking (peer)**: `zod` pasa de `^3.25.0 || ^4.0.0` a `^4.0.0`; Zod 3 deja de estar soportado (GHSA-mrhx-c7xc-m3w5 no tiene parche en 3.x). El CLI instala `zod@^4.0.0`. Los tipos publicados (`.d.ts`) no cambian.

  Fix: con Zod 4, un campo `date` requerido compilado desde `ValidationRules` vuelve a mostrar el `requiredMessage` del autor (o «This field is required») en vez de «Invalid input: expected date, received undefined»: `required_error`/`invalid_type_error` no existen en Zod 4 y se ignoraban.

## 0.22.0

### Minor Changes

- 6f37b75: Nuevo `validateFormConfig(config)`: valida la FORMA de un FormConfig serializado (lo que exporta el builder y guarda el Hub) y devuelve `{ ok, errors }`, con cada error como `{ code, path, message }`; nunca lanza (si el JSON rompe al propio validador, sale un único error `unreadable`). Acepta el sobre `{ version, formConfig }` —la versión tiene que existir y su MAJOR ser el de `FORM_SCHEMA_VERSION`— o un FormConfig desnudo, sin regla de versión. Falla un campo sin `type` (un tipo que no está en el registro sí vale: los plugins registran los suyos), dos steps con el mismo id efectivo (`id` o, si no lo lleva, su clave) y las reglas que ya comprobaba `FormBuilder.build()` (formId, fields/steps vacíos, campos de un step inexistentes, referencias de cross-field y de computed, ciclos, `initialStep`). Se exporta desde el índice y desde el subpath lean `@saastro/forms/validation` (sin React, apto para un Worker), junto a los tipos `FormConfigIssue`, `FormConfigIssueCode` y `FormConfigValidationResult`.

  `FormBuilder.build()` toma ahora esas reglas del mismo módulo: lanza los mismos errores, con el mismo texto y en el mismo orden, y las reglas nuevas (tipo ausente, id duplicado) no se convierten ahí en un throw. Dos matices: un step que no es un objeto o cuyo `fields` no es un array, que antes reventaba con un `TypeError`, ahora lanza un `Error` con mensaje; y un nombre de campo o de step heredado de `Object.prototype` (`'constructor'`, `'toString'`) ya no cuenta como existente.

### Patch Changes

- 5671e8f: `button-card` con `multiple: true` arranca con `[]` en vez de `''`: con reglas serializables (`minItems`…) el campo sin tocar pintaba «Expected array, received string» en lugar del mensaje del autor. La selección única sigue arrancando con `''`.

  Con `multiple: true` y `required: true` en sus reglas (lo que exporta el builder) sin `minItems`, el campo exige al menos una opción y pinta el `requiredMessage` del autor, en cliente y en `@saastro/forms/validation`. Con `minItems` explícito manda `minItems`. `checkbox-group`, `switch-group` y `button-checkbox` no cambian.

- aa9098a: Los labels por defecto del botón submit/next/back, y el «Submitting...» mientras envía, siguen `config.locale`: un form `locale: 'es'` sin `buttons` pinta «Enviar» y «Enviando...» en vez de «Submit» (`'es-ES'` también; un idioma sin bundle cae al default). Lo registrado con `setDefaultMessages` sigue mandando, clave a clave: sobreescribir un texto que no es de botón no apaga el bundle del locale para los botones. Cambio visible para quien ya llama a `setDefaultMessages` con un override parcial (sin claves de botón) y renderiza forms `locale: 'es'`: esos botones pasan de «Submit» a «Enviar». Quien registra `setDefaultMessages(es)` completo, o las claves de botón, no ve cambio. El resto de textos por defecto (placeholders, validación, pasos, toasts, éxito/error) siguen leyendo el default global, como hasta ahora. Además, `buttons: null` (como llega de un schema JSON) ya no rompe el render de `<Form>`: se trata como ausente. Coste: +0.45 KB brotli en el entry principal (el bundle `es` viaja con él).
- 821b26c: Un campo `date` (sin `showTime`) viaja en el envío como su fecha de calendario `YYYY-MM-DD`, no como el instante UTC de su medianoche local: el 15/06/1990 elegido en Madrid llegaba como `1990-06-14T22:00:00.000Z` y el servidor lo leía como el día 14. Vale para HubForm, el submit por defecto y las submit actions de cualquier disparador (json, form-data, url-encoded y plantillas); también los extremos de un `daterange` y los `date` dentro de un `repeater`. Un `date` con `showTime` sigue viajando como ISO completo, y un `transform: 'dateISO'` explícito manda.

  Quien recibe los valores en código (submit custom, `onSuccess`, plugins de submit) sigue recibiendo un `Date` con el mismo instante, pero su `toJSON()` devuelve ahora `YYYY-MM-DD`: un receptor que parseaba un ISO completo de un `date` sin hora recibe ahora solo el día. Para seguir recibiendo el instante, `transform: 'dateISO'` en el campo.

  `autosavePlugin` también envía `YYYY-MM-DD` (es un POST a un servidor). Fuera, a propósito: `localStoragePlugin` sigue guardando ISO completo, porque su rehidratación hace `new Date(guardado)` y un `YYYY-MM-DD` se leería como medianoche UTC (el día anterior al oeste de Greenwich); y el `onSubmit` prop de `<Form>` recibe los valores crudos de react-hook-form.

- 777b4f3: El `Calendar` del date picker (`date` simple y popover, y `daterange`) recibe el locale de date-fns del formulario como prop `locale`: el mismo que ya usa el trigger (`config.locale`, con `setDateLocale()` como override global). Un form `locale: 'es'` abre el calendario con los meses y los días en español en vez de en inglés, siempre que el `Calendar` inyectado pase `locale` a react-day-picker (el del registry de saastro-ui lo hace). `CalendarProps` gana `locale?` opcional; sin locale nada cambia (inglés).
- dad61a0: combobox/command filtran también por la etiqueta de la opción: el renderer pasa `keywords={[opt.label]}` a `CommandItem`, así que `{ value: 'next', label: 'Next.js' }` aparece al teclear «Next.js» con el `@saastro/command` del registry. `CommandItemProps` declara `keywords?: string[]` (aditivo y opcional).
- cc32dfb: Tipos. `CommandProps` declara `shouldFilter?: boolean` y `CommandInputProps` declara `onValueChange?: (search: string) => void`: el renderer de combobox/command ya los pasaba y el contrato del `ComponentRegistry` no los recogía. Aditivo y opcional.
- 745d145: Requisitos. El tipo `command` declara ahora `Popover`, `PopoverTrigger`, `PopoverContent` y `Button` en `fieldTypeComponents`, como `combobox`: los dos comparten renderer y lo usaban sin declararlo, así que `getRequiredComponents`/`getInstallCommand` de un form solo con `command` no pedían `popover`.
- 0833b2f: `config.locale` elige también el formato de las fechas del date picker (popover y rango): un formulario `locale: 'es'` (o `es-ES`) sin `setDateLocale(es)` pinta «30 de septiembre de 2026» en vez de «September 30th, 2026». `setDateLocale()` sigue mandando como override global sobre `config.locale`, y sin `locale` nada cambia (inglés). El locale `es` de date-fns se importa solo desde el chunk lazy de DateRenderers.
- b906214: `config.locale` elige también el resto de textos por defecto, no solo los botones: placeholders (texto, email, tel, select, fecha), el error de requerido, los mensajes de `crossFieldRules`, el tamaño máximo de `file`, los mínimos/máximos del repeater, los toasts de validación y de error, los mensajes de éxito y error por defecto, los componentes de pasos dentro de un `<Form>`, el botón de limpiar firma y el CTA de WhatsApp. Un formulario `locale: 'es'` sin `setDefaultMessages(es)` ya sale entero en español. Lo registrado con `setDefaultMessages` sigue mandando clave a clave, y sin `locale` nada cambia. `getDateLocale()` (el formato de las fechas) sigue siendo global.
- 241f565: Los props `onSubmit` y `onError` de `<Form>` se disparan al pulsar el botón de enviar. Antes solo estaban cableados al submit nativo del `<form>` (Enter), y el botón es `type="button"`, así que con el botón nunca se llamaban. Ahora los llama el pipeline de submit, por donde pasan las dos rutas: `onSubmit` una vez por envío correcto, con los valores procesados (los mismos que `config.onSuccess`) y antes de la pantalla de éxito; `onError` una vez por envío fallido, o cuando `onSubmit` lanza (en ese caso los datos ya se enviaron y se muestra el éxito igual, para que nadie reenvíe). Por Enter ya no se llama a `onSubmit` tras un envío fallido.
- 0c7886b: Instalación desde el registry `@saastro`. `getInstallCommand(missing, { registries })`, `MissingComponentFallback` (prop `registries`) y `npx @saastro/forms install-deps` piden `@saastro/<nombre>` (primitivos Base UI) cuando el `components.json` del consumidor declara `registries['@saastro']`; sin él, los nombres pelados de siempre (shadcn upstream). La CLI lo lee del disco; en runtime se pasa el bloque `registries`. `MissingComponentFallback` usa ahora el mismo mapa que `getInstallCommand` (tenía una copia) y no pinta el comando manual si no hay nada que instalar. Nuevo tipo exportado `InstallCommandOptions`.
- daded6b: Mark the introspection metadata with no consumer outside the package (`BUILTIN_FIELD_TYPES`, `FIELD_DEFAULTS`, `COMMON_CLASSES`, `COMMON_STRINGS`, `COMMON_METHODS`, `VALIDATION_METHODS`, `BUILD_METHODS`, `getAllKnownMethods`, `FIELD_CATEGORIES`, `getFieldTypesByCategory`, `getFieldTypeMeta`) as `@internal` in their JSDoc. They are still exported; nothing is removed. Document `toE164`, `parseE164`, `DEFAULT_COUNTRIES` (Phone page) and the deprecated `createShadcnRegistry` alias (Components page).
- 30957b1: `native-select`, `combobox`/`command`, `button-card`, `button-radio`, `checkbox-group` y `switch-group`: elegir (o marcar/desmarcar) una opción marca el campo como tocado (`field.onBlur`), como ya hacían `select` y `radio`. Con `validation.mode: 'onTouched'` (u `'onBlur'`), el error «obligatorio» que pinta Continuar desaparece al elegir, en vez de quedarse hasta el siguiente Continuar. En esos modos, desmarcar la última opción de un grupo o deseleccionar el combobox también pinta el error al momento. Sin cambio de API.
- 5683479: `select` (Base UI `Select`) y `radio` (`RadioGroup`): elegir una opción marca el campo como tocado (`field.onBlur`). Con `validation.mode: 'onTouched'` (u `'onBlur'`), el error «obligatorio» que pinta Continuar desaparece al elegir, en vez de quedarse hasta el siguiente Continuar. `native-select`, `combobox`/`command` y las variantes de botón/tarjeta no cambian en esta versión.
- fad1d6e: El paquete publicado deja de llevar sourcemaps: hasta la 0.21.0 viajaban 34 `.map` con `sourcesContent` (el código fuente entero) porque tsup solo los quitaba con `NODE_ENV=production`. Añade `LICENSE` (MIT). Se publica desde CI por tag `forms-v<versión>` con `npm stage publish` (trusted publisher, sin tokens) y aprobación 2FA.
- 9346104: Seguridad. `compileValidationRules` rechaza un `pattern` vulnerable a ReDoS en vez de compilarlo: lanza `unsafe validation pattern` al construir el schema, igual que ya lanzaba `SyntaxError` con un patrón mal escrito. Se rechaza una repetición variable (`*`, `+`, `{n,}`, `{n,m}`) que contiene otra sin un carácter delimitador obligatorio que la separe (`(a+)+$`, `(\w+\s?)+$`, `([a-z0-9]{2,4})+$`) y un grupo repetido cuyas alternativas pueden empezar igual (`(a|aa)+$`). Los presets y los patrones con delimitador (`^[a-z0-9]+(?:-[a-z0-9]+)*$`) no cambian. `validateFormConfig` lo reporta como `pattern-unsafe`, también en los `itemFields` de un repeater.
- 6bce012: Seguridad. `pickByPaths` ignora entero cualquier path con un segmento `__proto__`, `constructor` o `prototype`: un campo llamado `__proto__.x` (p.ej. desde un schema remoto) escribía `x` en `Object.prototype`. Los paths normales no cambian.
- 57494c3: Seguridad. `findClientSecrets` detecta también un token en la query de una URL (`?token=`, `?access_token=`, `?api_key=`, `?key=`, `?sig=`…) de `http.endpoint.url`, `webhook.url` y `optionsSource.url`, con `kind: 'url.query'`, `path` terminado en `?<parámetro>` (nunca el valor) y el nuevo campo opcional `queryParam`; `redactClientSecrets` (el export TSX del builder) redacta solo el valor del parámetro y deja la URL. Un valor `{{campo}}` no cuenta, ni `pageToken`/`max_tokens`; un secreto en el fragmento (`#access_token=`) no se detecta (FORMS-3-3). Campo `file`: un fichero que no casa con `accept` se rechaza como uno que pasa de `maxSize`; con `uploadAdapter` no se sube, y sin él no pasa la validación. Mensaje nuevo `validationFileType` en los bundles en/es, opcional en `FormMessages` para no romper a quien declara el tipo completo (FORMS-UP-2). `recaptchaPlugin` codifica el `siteKey` en la URL del script (FORMS-3-4). Aditivo: un miembro más en el union `ClientSecretKind` (un `switch` exhaustivo sobre él pide un caso nuevo), un campo opcional en `ClientSecretHit` y una clave opcional en `FormMessages`.
- 131f0fc: Seguridad. `redirect`: un tab, salto de línea o retorno de carro dentro de la URL (`/\t/evil.com`) ya no pasa el allowlist; el navegador los borra al navegar y acababa en otro host (FORMS-6-4). Campo `file` con `uploadAdapter`: un fichero por encima de `maxSize` ya no se sube; se muestra el error de tamaño y el adapter no se llama (FORMS-UP-1). Sin cambio de API.
- 109210e: Seguridad. `findClientSecrets` detecta también una credencial en el FRAGMENTO de una URL (`#access_token=`, `#id_token=`, un hash-router `#/ruta?token=`) de `http.endpoint.url`, `webhook.url` y `optionsSource.url`, con el mismo `kind: 'url.query'`, `path` terminado en `#<parámetro>` y el nuevo campo opcional `inFragment: true`; `redactClientSecrets` redacta solo ese valor, en su parte de la URL (FORMS-3-3). Tipos aditivos: un campo opcional más en `ClientSecretHit`. Salida que cambia: un secreto de un hash-router que antes salía como `…url?token` sale ahora como `…url#token` (con `inFragment: true`); en el fragmento cada `?` abre un par candidato (`#/r?a=1?token=` se detecta) y al redactar se sustituye todo lo que sigue a su `=` hasta el `&` (`#token=abc?def` no deja cola).
- 9b5fe1b: `button-checkbox`, `checkbox` y `switch`: elegir o marcar/desmarcar marca el campo como tocado (`field.onBlur`), como el resto de controles de opción. Con `validation.mode: 'onTouched'` (u `'onBlur'`), el error que pinta Continuar desaparece al elegir. Y `button-card` de selección única (sin `multiple`) compila sus `ValidationRules` como string, en el cliente y en `validateFormData`/`resolveFieldSchema`: `{ required, requiredMessage }` pinta su mensaje en vez de «Expected array, received string». Con `multiple: true` sigue siendo array. Sin cambio de API.

## 0.21.0

### Minor Changes

- 44eceb8: Seguridad del pipeline de submit y del campo `html` (auditoría forms-2026-09: FORMS-6-1, 6-2, 3-1, 3-2 y 6-3).

  **Inyección en plantillas (FORMS-6-1).** `{{campo}}` en `http.body.template` y
  `webhook.payloadTemplate` ya no puede cambiar la estructura del JSON: dentro de
  una cadena el valor entra escapado como contenido; fuera, como literal JSON
  (`JSON.stringify`), así que una cadena del visitante siempre sale entre
  comillas. En `email.customTemplate` y en la plantilla por defecto cada valor
  pasa por `escapeHtml`. Antes un `"` cerraba la cadena y `"admin":true` entraba
  en el payload; un `<img onerror>` llegaba vivo al correo del administrador.

  **Campo `html` saneado por defecto (FORMS-6-2).** Iba a `dangerouslySetInnerHTML`
  sin sanitizar: un autor del workspace ejecutaba JS en el site del cliente. Ahora
  pasa por `sanitizeHtml` siempre que el config sea datos. El opt-out es
  `FieldBuilder#trustedHtml()`, que pone el marcador `TRUSTED_HTML` — un objeto
  que JSON no puede expresar: `"trustedHtml": true` en un esquema del Hub o del
  builder se ignora (con aviso) y se sanea igual.

  **`sanitizeHtml` reescrito como allowlist isomorfo.** Antes: blocklist sobre el
  DOM, que sin `document` (SSR de `<HubForm initialSchema>`) degradaba a texto
  escapado — y React no repara un `dangerouslySetInnerHTML` distinto al hidratar.
  Ahora: tokenizador puro que RECONSTRUYE solo lo reconocido (mismo resultado en
  servidor y navegador; lo que no encaja en la gramática se escapa). Endurecido:
  `style=` fuera, `<img src>` externo solo `https:` (ni `http:` ni `//host`),
  `rel="noopener noreferrer"` forzado en `target=_blank`, entidades decodificadas
  antes de mirar el esquema de una URL, comentarios y bogus comments fuera.
  `setHtmlSanitizer(DOMPurify.sanitize)` sigue teniendo la última palabra.
  **Cambio visible**: un `html` del Hub con `style=` inline o con `<iframe>` pierde
  eso — usa clases, o `.trustedHtml()` si el formulario es código tuyo.

  **Secretos en el config (FORMS-3-2).** `http.auth`, `webhook.secret`,
  `email.apiKey` y las cabeceras de autenticación de `optionsSource`/endpoints
  corren en el navegador y no pueden ser secretos. Nuevo: `findClientSecrets`
  (rutas, nunca valores), `redactClientSecrets` + `REDACTED_SECRET`, y un
  `console.warn` una vez por `formId` al montar. El builder avisa junto a cada
  input y redacta esos valores del export TSX (el JSON al Hub no cambia).

  **Firma HMAC del webhook (FORMS-3-1).** `secret` queda deprecado en cliente
  (no es autenticación; avisa una vez por acción). La cabecera legacy
  `X-Webhook-Signature: sha256=HMAC(payload)` no cambia; se añaden
  `X-Webhook-Timestamp` y `X-Webhook-Signature-V2: t=<ts>,sha256=HMAC("<ts>.<payload>")`
  para que el receptor pueda rechazar replays. Documentado como proxy server-side.

  **`redirect` (FORMS-6-3).** Solo navega a rutas que empiezan por `/` (no `//`
  ni `/\`) o a `http(s)://` absolutas; `javascript:`, `data:` y el resto se
  ignoran con aviso. `isSafeRedirectUrl` exportado.

  Presupuesto del entry: 54.5 → 57.5 KB brotli (+3.1 KB medidos módulo a módulo:
  sanitizador 1.6, detector 0.8, plantillas 0.5, resto 0.4).

## 0.20.4

### Patch Changes

- 53c8ba7: `whatsapp.placement: "success"` vuelve a pintarse a través de `<HubForm>`

  Era inalcanzable. `<Form>` pinta el CTA en su pantalla de éxito, pero
  `HubForm.wrappedSubmit` pasa a `status: 'submitted'` y esa rama devolvía el
  `successFallback` del host, desmontando el `<Form>` entero. Un esquema con
  `whatsapp.placement: "success"` no pintaba nada hiciera lo que hiciera el site:
  quitar el `successFallback` sólo cambiaba la tarjeta por el literal en inglés
  por defecto.

  Ahora la pantalla de éxito de `<HubForm>` pinta el CTA JUNTO al fallback del
  host, no dentro. Un site que ya pasa `successFallback` y no declara `whatsapp`
  en el esquema no cambia en nada.

  **Cambio de comportamiento en `placement: "success"`**: el CTA es ahora un
  `<a href>` y no un `<Button>` con `window.open`. En la pantalla de éxito no hay
  nada que habilitar (`enableWhen` no aplica), así que el botón sólo aportaba un
  `window.open` que un bloqueador de pop-ups se puede comer — y es el CTA
  principal de las landings de pago. El enlace no se bloquea, se abre en pestaña
  nueva, se previsualiza y deja el destino a la vista en el DOM. `cta.className`
  se sigue aplicando; `cta.variant` sólo tenía sentido para el `<Button>` y ya no
  se usa en este placement. `placement: "buttons"` no cambia: ahí el CTA convive
  con el submit y sí tiene estados.

## 0.20.3

### Patch Changes

- 70a1638: Un campo oculto sin `resolver` ya no anula los resolvers de todos los demás

  `useHiddenFieldResolvers` resolvía los ocultos con un `Promise.all` sin red:
  `resolveValue(cfg.resolver)` con `resolver` ausente lee `.$resolver` de
  `undefined`, revienta, y el rechazo se lleva el lote entero — ningún oculto se
  rellena y ninguno avisa, porque la promesa no la recogía nadie.

  Bastaba UN oculto sin resolver para que el form entero perdiera su captura de
  datos. Es lo que le pasó al cotizador de patinete de zamesegur (`seguro-patinete`):
  tiene `precio_mes`, `via` y `locale` como ocultos que rellena el propio site, y
  junto a ellos seis con resolver (`landing`, `referrer`, `utm`, `click_id`, `ref`,
  `submitted_at`). Los seis llegaban vacíos. Ninguno de los doce envíos que ese
  formulario lleva registrados desde el 1-ago-2026 ha traído nunca un valor
  producido por un resolver.

  Ahora: un oculto sin resolver se salta (es legítimo — lo rellena el site), y cada
  resolver va aislado, así que uno que falle se lleva su campo y solo el suyo.
  `HiddenFieldProps.resolver` pasa a ser opcional, que es lo que el runtime y el
  Hub ya permitían.

## 0.20.2

### Patch Changes

- ed5929a: El build no era reproducible: dos builds del mismo commit daban bytes distintos

  Tres builds seguidos del mismo árbol daban tres `dist/index.js` distintos. El
  tamaño **en crudo** no se movía —133 637 B siempre—, pero el hash sí: son los
  mismos bytes barajados. Lo que baraja es el bloque de imports que esbuild emite
  al principio del entry:

  ```js
  // build A
  import{a as Zt}from"./chunk-DPCN4RYC.js";import{a as Ie,…}from"./chunk-WPWJC3IG.js";
  // build B, mismo commit
  import{a as Ie,…}from"./chunk-WPWJC3IG.js";import{a as Zt}from"./chunk-DPCN4RYC.js";
  ```

  El contenido de cada chunk y su nombre con hash **sí** son deterministas —de los
  53 ficheros de `dist/`, sólo `index.js` cambiaba—. Es el orden de las líneas.
  Permuta con `splitting: true` y 16 entries, y no depende del paralelismo:
  `GOMAXPROCS=1` sigue dando permutaciones, y quitar la emisión de `.d.ts`
  tampoco lo estabiliza.

  **Por qué importaba.** `size-limit` mide brotli, y brotli sí nota el orden: dos
  permutaciones del mismo `index.js` comprimen a 32 807 B y 32 895 B — 88 B de
  diferencia sin que cambie una línea de código. Con el presupuesto pegado al
  tamaño real, el gate era una moneda al aire: el **#105 pasó con 53.99 kB y el
  #106 falló con 54.01 kB ejecutando el mismo código**. Se mitigó subiendo el
  límite a 55 KB en el #107; esto ataca la causa.

  **El arreglo.** `pnpm build` termina llamando a
  `scripts/imports-deterministas.mjs`, que ordena por nombre de fichero el prefijo
  contiguo de imports `./chunk-*.js` de cada entry. Sólo ese prefijo: los imports
  de dependencias reales (`react`, `react-hook-form`…) vienen después y no se
  tocan. Cuatro builds seguidos dan ahora el mismo hash, en `index.js` y en todo
  el árbol `.js` de `dist/`.

  **Por qué reordenar es seguro.** No se elige un orden frente a otro «bueno»:
  esbuild ya publicaba uno arbitrario en cada build, así que la npm de hoy lleva
  la permutación que le tocó a CI ese día — fijar una es estrictamente más
  controlado que no fijar ninguna. Además el único import de sólo-efecto del
  bloque apunta a un chunk **vacío**, de 0 bytes, así que su posición no ejecuta
  nada; el script lo comprueba en cada build y aborta si algún día deja de estarlo
  en vez de reordenar efectos en silencio. Las 762 pruebas siguen en verde y el
  `dist/` normalizado importa igual (138 exports).

  **El presupuesto baja a 54.5 KB, no a 54.** Medido en orden canónico el paquete
  pesa **54.07 kB**: los 54 KB de antes nunca fueron su tamaño real, sino la
  permutación afortunada que midió el #105. Ahora que la medida no se mueve sola,
  54.5 deja margen para el ruido de una versión de esbuild y ninguno para
  crecimiento silencioso. CI comprueba además que `dist/` va normalizado, para que
  saltarse el paso no devuelva el gate a suertes.

  **Compatibilidad.** Ninguna ruptura: mismo código, mismas exportaciones, mismo
  comportamiento. Cambia el orden de unas líneas dentro del bundle publicado.

- a190250: `<Form>` acepta `action` y `method`: mejora progresiva para el envío sin JS

  Desde la 0.19.0, `<HubForm initialSchema>` deja el formulario **pintado** en el
  HTML que sirve el servidor. Medido en una landing real (build de producción del
  theme servido con `wrangler dev`): `<form>` con 3 `<input>`, 1 `<textarea>`, sus
  etiquetas y cero «Loading…». Lo que no hace es **enviar**: el `<form>` emitido no
  llevaba `action`, así que un submit sin JS recargaba la misma URL y los datos se
  perdían. En una landing de pago eso es un lead perdido.

  Ahora `FormProps` acepta `action` y `method`, y llegan tal cual a través de
  `<HubForm formProps>` (que es `Omit<FormProps, 'config'>`, así que no hizo falta
  tocar `HubForm`). Los campos ya llevaban su `name`, así que el navegador
  serializa solo.

  ```tsx
  <HubForm
    siteId="acme"
    formSlug="contact"
    initialSchema={schema}
    formProps={{
      components,
      action: `${hubUrl}/acme/contact/submit`,
      method: "post",
    }}
  />
  ```

  **Inerte cuando hay JS.** `handleSubmit` de react-hook-form llama a
  `preventDefault()`, así que una página que funciona sigue enviando por el camino
  de siempre — `fetch` con `application/json`, que es el que sabe de adjuntos y
  captcha. Hay test de eso: se lanza un `submit` cancelable y se comprueba que
  alguien lo frena. Y si no se pasan las props, React omite los atributos: el
  `<form>` sale byte a byte como antes, también con test.

  **El envío nativo es opt-in por formulario, y `<HubForm>` lo hace cumplir.**
  Reenvía `action`/`method` a `<Form>` **sólo si el esquema servido trae
  `meta.nativeSubmit`**; si no, los tira y el marcado sale byte a byte como antes
  de que existieran las props. No es burocracia: exigir `application/json` es lo
  que obliga al navegador a hacer preflight en una petición cruzada, o sea lo que
  hoy decide quién puede enviar. Un `<form>` urlencoded es una petición «simple» y
  no lo tiene, así que encenderlo significa que cualquier página puede hacer que
  el navegador de sus visitantes cree leads en ese formulario. Y pintar un
  `action` que el servidor va a rechazar es peor que no pintarlo: para un
  visitante sin JS se ve exactamente igual que un formulario que se come sus
  datos.

  El guard vive en `HubForm` y no en `<Form>` a propósito. `<Form>` recibe un
  `FormConfig` genérico y también sirve formularios que nunca vinieron del Hub
  (configs de FormBuilder, submits propios); `meta` es un concepto del Hub, y
  meterlo en el componente genérico lo ataría a un origen que no conoce.
  `HubForm` sí es dueño del esquema — ya lee `meta` para el captcha.

  La marca autoriza, no cablea: `HubForm` nunca se inventa un `action`. Lo pasa el
  consumidor, que es el único que sabe su endpoint y su página de gracias.

  **Todavía no basta para cerrar el envío sin JS.** Un `<form>` nativo sólo sabe
  mandar `application/x-www-form-urlencoded`, y el endpoint de ingestión del Hub
  acepta hoy sólo `application/json`. Esto es la mitad del paquete, lista y
  esperando a que el endpoint sepa responder; la otra mitad va por saastro-hub.

  **Aviso que no arregla ninguna de las dos mitades:** sin JS no hay captcha.
  Turnstile y reCAPTCHA necesitan ejecutar código para producir su token, así que
  un formulario con captcha encendido rechazará el envío nativo igualmente. Para
  esos formularios esto es una elección, no una suma.

  **Compatibilidad.** Ninguna ruptura: props aditivas, opcionales y ahora además
  cerradas por defecto en el camino del Hub. Quien no las pase no nota nada. Coste
  medido en el bundle: ~20 B en brotli (54.07 → 54.09 kB en orden canónico).

## 0.20.1

### Patch Changes

- 08fad91: El trigger de un `select` pintaba el value crudo en vez de la etiqueta

  Con `@saastro/forms@0.20.0` y primitivos shadcn sobre `@base-ui/react`, al elegir
  una opción de un campo `select` el trigger enseñaba `otro` en vez de
  `Otro seguro o consulta`. Con Radix no pasaba y por eso no se vio antes:
  `SelectValue` heredaba el contenido del `SelectItem` elegido, así que la etiqueta
  salía gratis.

  Base UI no hace eso. La etiqueta del trigger se resuelve desde `items` en el
  Root —o desde `children` como función en `Select.Value`— y `renderSelectField`
  no pasaba ninguna de las dos. Lo llamativo es que el contrato de componentes
  **ya declaraba la prop** desde la 0.20.0, con el comentario de para qué servía:

  ```ts
  /** Base UI: si se pasa, <SelectValue> renderiza la label en vez del valor crudo. */
  items?: Array<{ label: React.ReactNode; value: unknown }> | Record<string, React.ReactNode>;
  ```

  El renderer simplemente nunca la usó. Ahora pasa `items` construido desde las
  opciones ya resueltas (`{ value, label }`, con el icono dentro del label como
  `ReactNode`, que es lo que se veía con Radix en el trigger). `items` no alimenta
  el typeahead de Base UI —eso sale de los items renderizados—, así que un label
  con markup no rompe la búsqueda por teclado.

  **Compatibilidad.** Ninguna ruptura. La prop es aditiva y Radix la ignora, así
  que los consumidores que sigan en Radix se comportan igual que antes. No hace
  falta tocar nada al actualizar: basta con subir la versión.

  Auditados los tres hermanos del mismo fichero, que **no** compartían el fallo y
  quedan cubiertos por tests: `native-select` pinta la etiqueta como texto del
  `<option>`, y `combobox`/`command` ya resolvían la suya con una búsqueda
  explícita sobre las opciones. El resto de renderers tampoco dependen de heredar
  contenido — `radio`/`checkbox-group` pintan `{opt.label}`, las fechas formatean
  el valor en el trigger y el slider compone su propio display.

## 0.20.0

### Minor Changes

- e970323: `computed` acepta una expresión serializable, y el servidor la recalcula

  Hasta ahora `computed` era `{ dependsOn, compute }`, y `compute` es una FUNCIÓN.
  Una función no sobrevive a JSON, así que un FormConfig alojado en el Hub no
  podía expresar un valor derivado. La salida práctica era pintar el precio en un
  campo `hidden` que rellena el NAVEGADOR — es decir, un dato de negocio que
  cualquiera puede reescribir antes de enviarlo: `precio_mes: 0.01` y el
  formulario lo acepta encantado.

  `computed` admite ahora una segunda forma, `{ $expr }`, que es JSON puro:

  ```ts
  computed: { $expr: { $op: '+', args: [
    5,
    { $if: { operator: 'AND', conditions: [{ field: 'conductor', operator: 'isTrue' }] },
      then: 1.5, else: 0 },
  ] } }
  ```

  Nodos: un número suelto es el literal, `$field` referencia a otro campo, `$op`
  hace `+ - * /`, `$round` redondea y `$if` bifurca. El test de un `$if` es un
  `ConditionGroup` de los de siempre —los mismos que ya usan la visibilidad
  condicional y las reglas cross-field— o un `$cmp` numérico.

  Y lo importante: **el servidor recalcula y gana**.

  ```ts
  const raw = await request.json();
  const data = applyComputedFields(form, raw); // ← el servidor manda
  const result = validateFormData(form, data);
  if (!result.success)
    return Response.json({ errors: result.errors }, { status: 422 });
  await persist(data); // ← `data`, nunca `raw`
  ```

  `applyComputedFields` sale por `@saastro/forms/validation` (el subpath lean, sin
  React), es síncrono, no muta lo que le pasas y nunca lanza. Es una función
  APARTE de `validateFormData` a propósito: validar emite un veredicto, recalcular
  devuelve un payload corregido, y un worker que solo observe la validación sin
  bloquear seguiría guardando el cuerpo original.

  Detalles que conviene conocer:
  - **Las dependencias se DERIVAN** de las hojas de la expresión; no se declaran a
    mano. Obligar a repetirlas es una segunda fuente de verdad cuyo fallo es mudo:
    el campo deja de actualizarse y ya. La derivación mira también DENTRO de los
    `ConditionGroup`, porque `5 + (conductor ? 1.5 : 0)` no menciona `conductor`
    en ningún `$field`.
  - **Un campo calculado puede referenciar a otro.** El recálculo va en orden
    topológico y converge en una sola pasada, así que `ahorro = mes + dto` ve el
    `mes` de ESTA pasada y no el de la anterior.
  - **`$cmp` existe por un motivo concreto.** Las comparaciones numéricas de
    `ConditionGroup` operan sobre el valor CRUDO: contra un campo de texto donde
    el usuario escribió «1.234,56» eso es `NaN > 0` → false, y una guarda del tipo
    «solo si la prima es positiva» se la come el silencio. `$cmp` pasa los dos
    lados por la misma coerción.
  - **Coerción numérica explícita**: «1.234,56» y «1,234.56» valen los dos
    1234,56; un separador suelto es SIEMPRE el decimal. Lo que no coerciona cae al
    `fallback` (0 por defecto). Dividir entre cero da 0. `evaluateExpression`
    NUNCA devuelve `NaN` ni `Infinity`.
  - `FieldBuilder` estrena `.computed()`, y `FormBuilder.build()` valida que las
    referencias existan y que no haya autorreferencias ni ciclos, con el mismo
    mensaje «Available fields: …» de las reglas cross-field.

  Compatible hacia atrás: la forma `{ dependsOn, compute }` sigue funcionando
  igual, la pasada de montaje sigue pisando el `defaultValue` y las escrituras
  siguen siendo `shouldDirty: false`. Cambian dos comportamientos, los dos a
  mejor: un campo con `computed` ahora se renderiza **readOnly** de verdad (el
  JSDoc y la doc pública ya lo prometían, y escribir en él siempre fue inútil
  porque el cálculo lo pisaba), y un `compute` legacy encadenado ve los valores de
  aguas arriba ya frescos en vez de los de la pasada anterior.

- e970323: El campo `html` interpola `{{campo}}` con los valores del formulario

  El campo `html` era estático. Para una tarjeta de precio dentro del formulario
  —«tu precio: X €/mes»— no había forma de que el número cambiara al marcar una
  casilla: o montabas el bloque fuera del formulario, o te escribías una isla a
  mano. Que es exactamente lo que acabó pasando en los sitios de cliente.

  Ahora el contenido de un `html` admite `{{tokens}}`, resueltos con los valores en
  vivo y repintados al cambiar:

  ```ts
  { type: 'html', html: '<div class="card">Tu precio: <b>{{precio_mes}}</b> €/mes</div>' }
  ```

  Resuelve la ETIQUETA de la opción, no el value crudo: `{{uso}}` pinta «Reparto o
  uso profesional», no `reparto`.

  **Sobre la seguridad, que aquí es todo el problema.** El campo `html` es el
  escape hatch de contenido CONFIABLE del autor: no pasa por el sanitizador, y eso
  no cambia — tu `<iframe>` sigue siendo tu `<iframe>`. Lo que sí pasa es que cada
  VALOR interpolado se escapa en HTML en el momento de sustituirlo, porque eso sí
  es entrada de usuario y va a parar a un `dangerouslySetInnerHTML`. Sanear la
  cadena entera se habría cargado el markup del autor; escapando solo los valores,
  no. Hay test de regresión con un `<img onerror>` por medio.

  Detalles:
  - **Solo se suscriben a los valores los `html` cuyo contenido contiene `{{`.** Un
    `html` estático recorre exactamente el mismo camino que antes: sin hooks
    nuevos, sin suscripción, sin coste. Los hooks viven en un componente hijo, así
    que el número de hooks del renderer no cambia por esta feature.
  - Un token que no corresponde a nada se sustituye por vacío: al visitante nunca
    se le pintan `{{llaves}}`.
  - El interpolador **no** se comparte con el del CTA de WhatsApp, y no es un
    descuido: WhatsApp es texto plano y QUITA las etiquetas de un label con
    markup; aquí hay que hacer lo contrario, escaparlas. Compartirlo obligaría a
    uno de los dos a hacer algo incorrecto para su medio.
  - Los números se pintan tal cual (`6.5`, no `6,50`). Escribe el símbolo en tu
    markup y redondea con `$round`.
  - Un booleano se resuelve vacío: no tiene texto propio sin i18n, y la forma
    idiomática de reflejar una casilla es la visibilidad condicional.

  Compatible hacia atrás: un `html` sin `{{` se comporta exactamente igual que en
  0.19.

## 0.19.0

### Minor Changes

- 36d3650: `HubForm` acepta `initialSchema`: el formulario se pinta en el primer render, sin esperar al efecto

  La descarga del esquema vive en un `useEffect`, y un `useEffect` **no corre en SSR**. Consecuencia: una página renderizada en servidor manda como HTML el fallback «Loading…», así que un visitante sin JS —o un crawler— no ve formulario ninguno. En landings de campaña eso es un lead perdido.

  Ahora el host puede descargar el esquema por su cuenta y pasarlo:

  ```astro
  ---
  // Astro: el frontmatter corre en el servidor, en cada request
  const res = await fetch(`https://submit.saastro.io/v1/${siteId}/${slug}.json`);
  const initialSchema = res.ok ? await res.json() : null;
  ---
  <HubForm siteId={siteId} formSlug={slug} initialSchema={initialSchema} client:load />
  ```

  Con `initialSchema` presente **no se hace ningún fetch**: el primer render ya es `ready`, el HTML lleva el formulario de verdad y la hidratación solo engancha los handlers. Se acaba también el parpadeo del skeleton.

  Detalles:
  - El valor es exactamente lo que devuelve `{hubUrl}/{siteId}/{formSlug}.json`, y pasa por el mismo `isRenderableSchema` que la ruta de fetch — un esquema vacío da `unconfigured` igual que antes.
  - `null` significa «el host lo intentó y falló» → cae a la descarga en cliente de siempre. `undefined` (por defecto) es «el host ni lo intentó», comportamiento idéntico al actual.
  - Si cambian `siteId`/`formSlug` después del montaje, se descarga como siempre: la semilla solo cubre el primer render.

  Cambio aditivo y compatible: quien no pase la prop no nota nada.

  **Ojo, esto NO hace que el formulario funcione sin JS.** El envío sigue necesitando JavaScript: `submit.saastro.io` exige `content-type: application/json` y responde 415 a un POST de formulario nativo. Lo que se arregla aquí es que el formulario _exista_ en el HTML.

## 0.18.0

### Minor Changes

- 8652204: **BREAKING: la librería pasa a hablar la API de Base UI, no la de Radix.**

  `@saastro/forms` no depende de ninguna librería de primitivas — inyecta las tuyas
  por DI — pero sí las invoca con una forma de props concreta. Esa forma era la de
  Radix y ahora es la de Base UI. A partir de esta versión hay que inyectar
  componentes shadcn/ui construidos sobre Base UI (`"style": "base-nova"` en
  `components.json`, o cualquier estilo sin prefijo `radix-`/`aria-`).

  Para seguir en Radix, fija `@saastro/forms` en `0.17.x`.

  Cambios en el contrato (`ComponentRegistry`):
  - **Accordion** — desaparecen `type` y `collapsible`. `value`/`defaultValue` son
    ahora **arrays** y `onValueChange` recibe un array. `multiple` sustituye a
    `type="multiple"`; el colapso libre es el comportamiento por defecto.
  - **Select** — `value` acepta `string | null`. Base UI modela "sin selección"
    como `null`, no como `undefined` ni `''`.
  - **Slider** — `value`/`defaultValue` aceptan `number | number[]`; con un solo
    thumb Base UI emite un **número plano**. Nuevo `onValueCommitted`.
  - **PopoverTrigger / TooltipTrigger / DialogTrigger** — `asChild` se sustituye
    por `render` (el elemento a renderizar) y `nativeButton`.
  - **PopoverContent** — acepta además `side`, `sideOffset` y `alignOffset`, que el
    wrapper de shadcn reenvía al `Positioner` de Base UI.
  - **Checkbox / Switch / RadioGroup** — los callbacks reciben un 2º argumento
    `eventDetails`. Los handlers existentes que lo ignoran siguen siendo válidos.
  - **Checkbox** — nueva prop booleana `indeterminate` (Base UI la separa de `checked`).

  Interno: el combobox usaba la variable CSS `--radix-popover-trigger-width`, que
  en Base UI es `--anchor-width`.

## 0.17.0

### Minor Changes

- 856a5a5: CTA de WhatsApp: `onSteps: 'all'` para pintarlo en todos los pasos

  Hasta ahora el CTA con `placement: 'buttons'` solo se renderizaba en el ÚLTIMO
  paso, porque nació como la alternativa al submit y ahí es donde vive el submit.

  En un formulario por pasos eso lo vuelve inútil como vía paralela: si WhatsApp
  solo aparece al final, el usuario tiene que recorrer el formulario entero para
  descubrir que podía habérselo ahorrado.

  `onSteps: 'all'` lo pone en todos los pasos. El default sigue siendo `'last'`,
  así que ningún formulario existente cambia de aspecto. No aplica a
  `placement: 'success'`, que se pinta tras enviar y no tiene pasos.

## 0.16.0

### Minor Changes

- 7392ee9: **WhatsApp CTA: placement, attribution and measurement.** Completes the CTA so the channel is a decision you make with data, not a button you bolt on.
  - **`placement: 'buttons' | 'success'`** (default `'buttons'`). The default puts the CTA next to submit, where it _competes_ with the form: whoever clicks leaves no structured lead — no stored submission, no UTM attribution, no consent record. `'success'` renders it on the success screen instead, after a successful submit, so you keep both the structured lead (with its attribution and consent) and the conversation, with the summary already written. `enableWhen` is ignored there: the form was just submitted, so it was filled and valid by definition.
  - **`reference`** — an attribution line appended to the message, with the same `{{field}}` interpolation but able to read hidden fields and resolvers (which the auto-summary deliberately excludes). `reference: 'Ref: {{utm_source}}/{{utm_campaign}}'` lets you reconcile a WhatsApp chat with the campaign that produced it. If none of its tokens resolve — direct traffic — the line is dropped whole, so no message ends in `Ref: /`.
  - **`onWhatsappClick` plugin hook**, fired just before the link opens, with `{ formId, url, placement }`. `analyticsPlugin` implements it as a `form_whatsapp_click` gtag event. Note the hard limit this works around: `wa.me` is a one-way deep link, so the page can never know whether the message was actually sent — the click is "opened WhatsApp", not a conversion, and the docs say so where it matters.

- a84adb0: **"Send via WhatsApp" as a first-class, config-driven CTA.** The pattern was hand-rolled in a client site island (a button that builds a summary of what the user typed and opens `wa.me`); it is now a capability of the library, so any form — including a hosted `HubForm` — turns it on without touching code.

  ```tsx
  FormBuilder.create("contact")
    .addField("name", (f) => f.type("text").label("Name").required())
    .addStep("main", ["name"])
    .whatsapp({ number: "+34 615 74 57 62" })
    .build();
  ```

  **It is not a submit action, on purpose.** This is a 100% client-side channel: it opens the user's own WhatsApp and never issues a request, so it does not go through `submitActions`, the dispatcher or the submit Worker — and there is no endpoint to flood. The lead's name and phone arrive from their WhatsApp account, which is why it works even when the contact fields are left empty. Use it _alongside_ submit, as the fast path.
  - `FormConfig.whatsapp` (`WhatsappCta`): `number` (any format — non-digits are stripped), optional `message`, `enableWhen`, `label`, `hint`, `variant`, `className`. Builder: `.whatsapp(config)`; `build()` rejects a number under 8 digits and an unknown `enableWhen`.
  - **Message.** With no `message` the CTA sends an auto-summary — `Label: value`, one line per filled field, option **labels** (not values) for `select`-likes, comma-joined multi-selects, locale-formatted dates, a localized "Yes" for checked boxes, and one bullet per item for repeaters. A `message` template interpolates `{{field}}` and `{{summary}}`; unknown tokens resolve to empty, so literal `{{braces}}` never reach the user. Labels are stripped of HTML (WhatsApp is plain text).
  - **Exclusions by default**, no config: hidden fields and resolvers (`utm_*`, `clickId`, `timestamp` — they also auto-fill on mount, which would otherwise make `anyFilled` true before the user typed), the `mustBeTrue` consent checkbox, empty values, `file`/`signature`, buttons and `html`. Per-field opt-out: `.whatsapp(false)`.
  - **`enableWhen`**: `'anyFilled'` (default) or `'valid'`. `'valid'` relies on RHF's `formState.isValid`, which needs a validation mode other than `'onSubmit'` — the library warns in dev when it spots that combination.
  - **i18n**: `whatsappButton`, `whatsappHint`, `whatsappHintDisabled`, `whatsappYes` (EN + ES), plus a `whatsapp` block in the locale overlay for per-form copy (`label` / `hint` / `message`; the number is never translated).
  - **Zero cost when unused**: the button renders in the last step's button row and is loaded in its own chunk (same pattern as `DateRenderers`), and the pure message builders ship in a new lean subpath `@saastro/forms/whatsapp` instead of the root barrel.

  Also: raised the `size-limit` ceiling for the index entry 52 → 54 KB. The metric bundles async chunks into the total, so it counts a lazily-loaded, opt-in feature that non-users never download; the ceiling was left with ~50 B of headroom otherwise. Fixed two stale rows in the FormBuilder docs table — `.showTime()` and `.datePresets()` have been implemented since 0.13 but were still documented as no-ops.

## 0.15.0

### Minor Changes

- 6ecf284: Form-level cross-field validation, two layers. (1) **Serializable `crossFieldRules`** (builder/Hub-compatible): `matches` (confirm-email), `requiredIf` (ConditionGroup-driven, 12 operators), `compare` (number/date between two fields), `errorIf` (generic; without `then.field` → root error). Enforced identically client-side (composed into the resolver via `z.intersection` — a field-level error can NOT mask a cross-field error, canary-tested) and server-side (`validateFormData`, rule errors key on the field / `_form`). Root errors render in a new alert slot and block the submit pipeline. Fixing the _source_ field live-revalidates the target (`useCrossFieldRevalidation`). Empty-safe semantics for multi-step. i18n: default messages + per-rule overrides by `id` via locale overlays. `FormBuilder.crossFieldRule(s)()` with reference validation at `build()`. (2) **`formSchema`** — TSX-only whole-form Zod escape hatch (path-aware issue routing; async refinements unsupported — server parses synchronously). Engine exported from `@saastro/forms/validation` (`evaluateCrossFieldRules`, `buildCrossFieldRefinement`).
- bffccb1: Dirty tracking (Formisch-inspired): new pure helpers `getDirtyPaths` / `getDirtyFieldNames` / `getDirtyValues` / `pickByPaths` / `getLiveDirtyFields` over RHF's `dirtyFields` mirror (machine writes via `shouldDirty: false` — computed fields, hidden resolvers — stay excluded). `FormRef` gains `getDirtyValues()` / `getDirtyPaths()` / `isDirty()`. Plugins receive an optional 4th `onFieldChange` argument `FieldChangeMeta { formId, getDirtyPaths(), getDirtyValues() }` with lazy getters (3-param plugins remain valid). `autosavePlugin` gains `payload: 'dirty'` (PATCH-friendly `{ formId, dirtyPaths, values }` body, skips the POST when clean; default `'all'` is byte-identical to before). `localStoragePlugin` now keys writes by the per-event `formId` (fixes last-mounted-wins on writes) and skips pristine writes. `<Form>` mounts a null-rendering formState subscriber so RHF actually computes `dirtyFields` (headless users: mount `useFormFlags`).
- 321b21e: Form state flags and granular reset: new `useFormFlags(methods)` selector hook (isolated RHF `formState` subscription — `isDirty`, `isValidating`, `dirtyFields`, `touchedFields` without subscribing the whole form), `isSubmitting` alias + `resetSubmitState()` on `useFormState`'s return, and `FormRef.resetForm(options?)` — a granular reset mapping to RHF `KeepStateOptions` that also clears the package's bespoke submit state (success screen / error / submit-actions result) unless `keepSubmitState: true`. The raw `FormRef.reset` is unchanged.
- a8ddd25: New type-only helpers `InferFormValues<T>` / `InferFieldValue<F>`: derive the TypeScript type of a form's submitted values from a literal config (`as const satisfies FormConfig`). Zod schemas win (`z.infer`); otherwise the value type derives from the field `type`; action/content fields are omitted. Zero runtime cost. Also enables vitest typecheck mode (`*.test-d.ts`) so type-level contracts are actually enforced by tsc in CI.
- da393a7: Per-plugin subpath exports: every built-in plugin is now importable from `@saastro/forms/plugins/<name>` (plus the barrel `@saastro/forms/plugins`), guaranteeing bundles only carry the plugins they use. Root imports keep working unchanged. Subpath chunks are size-limit-gated and locked by a new contract test (`pluginSubpaths.test.ts`). Subpath types require `moduleResolution: 'bundler' | 'node16' | 'nodenext'` (same as the existing `/validation` subpath).
- 2704f0b: Repeater first-class. **Behavioral change**: repeater `minItems`/`maxItems` and item-field rules are now enforced on submit — client AND server (`@saastro/forms/validation`); opt out per field with an explicit `schema: z.any()`. New generated array schema (`buildRepeaterSchema`, exported): per-item validation from `itemFields` (passthrough — unvalidated sub-field values survive the parse; nested repeaters recurse), `.min()`/`.max()` with i18n messages (`validationMinItems`/`validationMaxItems` + per-field `minItemsMessage`/`maxItemsMessage`), `minItems` default pre-population on mount. Opt-in reordering: `reorderable` prop / `.reorderable()` builder method renders per-item move up/down buttons (moves values via RHF `move`). Add/Remove button labels are now i18n-backed (`repeaterAddItem`/`repeaterRemoveItem`, EN+ES). Builder: Reorderable switch + custom message inputs in the repeater panel.
- 2ef44bf: Configurable validation timing: new serializable `FormConfig.validation` option (`{ mode, revalidateMode, delayError }`, mapping 1:1 to react-hook-form's `mode`/`reValidateMode`/`delayError`) plus a `FormBuilder.validation()` fluent method. Default behavior is unchanged (`onSubmit`/`onChange`, now frozen explicitly). `mode: 'onTouched'` is the recommended UX upgrade — errors from a failed Next/submit clear live as the user fixes them. Note: `revalidateMode` only affects headless flows driving `methods.handleSubmit` themselves; the standard `<Form>` submit path validates via per-step `trigger()`, which never marks the RHF-level `isSubmitted`. The form builder exposes the mode under Form Settings → Validation Timing.

## 0.14.1

### Patch Changes

- ad05590: `createHubFormSubmit` now attaches the SAASTRO Gen visitor id (`gen_visitor_id`, read from `sessionStorage['gen-visitor-id']` where the theme's GenTracking beacon mints it) to the submit payload. react-hook-form only serializes registered fields, so the hidden input GenTracking injects into the `<form>` DOM never reached the payload — this closes the Forms → Gen attribution chain. No-op on sites without GenTracking (SSR-safe, storage errors swallowed). An explicit `gen_visitor_id` field in the form's own values always wins.

## 0.14.0

### Minor Changes

- bc808e0: Add 3 GDPR fields to `FIELD_LIBRARY` (`@saastro/forms/library`): `dsaRequestType` (a select of GDPR rights — access, rectification, erasure, portability, restriction, objection), `requestDetails` (free-text), and `identityDeclaration` (a required must-be-true confirmation). Each ships serializable validators and bundled `es` translations (21 → 24). These back the new "GDPR data request" (DSAR) Quick-start preset in the form-builder. Additive.
- 65609f6: Add 7 form-style fields to `FIELD_LIBRARY` (`@saastro/forms/library`): `marketingConsent`, `eventAttendance`, `guestCount`, `dietaryNotes`, `serviceType`, `budgetRange`, and `projectDetails`. Each ships serializable validators and bundled `es` translations, the same as the existing entries (14 → 21). These are the fields the form-builder's Quick-start presets compose, so a seeded preset is now built entirely from library fields. Additive.

### Patch Changes

- 16fbd22: Top-align the `checkbox`/`switch` control with the first line of its label (`items-start`) so a long consent/terms label no longer vertically centers the box.

## 0.13.0

### Minor Changes

- 8d4017b: Implement `date.showTime` and `date.presets` — until now they were typed (and exposed in the form-builder) but the date renderer ignored them.
  - `presets: [{ label, value }]` renders quick-select chips above the calendar; clicking one sets the date to today + `value` days.
  - `showTime: true` renders a time input next to the calendar (single-date types) and folds the chosen hour/minute into the `Date` value; picking a new day preserves the time. The popover trigger now shows the localized date **and** time.

  Both work with `dateType: 'simple'` and `'popover'`. No effect on `daterange`.

- 429f692: Add `@saastro/forms/library` — a curated `FIELD_LIBRARY` of ready-to-use semantic fields (Full name, Email, Phone, Age, Message, Consent, Company, Website, Address, Country, Date of birth, Postal code…). Each entry is a complete field config with **serializable validators** (`schema: ValidationRules`) and **bundled en/es translations**: define a field once, reuse it everywhere.

  Exposed from the lean `./library` subpath (no React, just data) so it never weighs on the root bundle. The form-builder consumes it as a new "Library" palette section — dragging a field in inserts the whole config and merges its translations into the form's i18n.

- 4dfe00a: Make the field `order` actually apply (closes the v1.0 #37 no-op cleanup).

  Two bugs kept `order` from working:
  1. `getFieldClass` early-returned `col-span-1` when a field had no `columns`, skipping the `order` block entirely — so `order` (and even `layout.order`) only took effect when `columns` was also set.
  2. `Form.tsx` only fell back to the top-level `columns` shortcut, never the top-level `order` shortcut (the mirror of `columns`).

  Both are fixed: `order` now applies on its own, with or without `columns`, in manual layout mode (auto-fit grids still ignore per-field span/order by design). Removed the now-empty `NOOP_FIELD_PROPS` dev-warning machinery (`order` was its last entry).

  **Heads up:** forms that already set a field `order` (e.g. via the form-builder's layout editor, which writes it) were silently ignoring it; they will now respect it and may reorder. This is the intended behavior the editor always implied.

- 180122c: Add a `matrix` (Likert) field type — a grid of single-choice rows that share one set of column options. Config: `{ type: 'matrix', rows: [{ key, label }], options: [{ value, label }] }`; the value is an object keyed by row (`{ q1: 'agree', q2: 'disagree' }`). Self-contained (native table + radios, no extra DI component), with one `radiogroup` per row for accessibility. Wired through the type union, `FIELD_REGISTRY` (builder palette), and test-data generation. Additive.
- ad40dae: Add a `phone` field type — an international phone input (country selector + national number) whose value is an **E.164 string** (e.g. `+34612345678`). Ships a compact built-in country list (`DEFAULT_COUNTRIES`, ~50 common countries) and accepts your own via the field's `countries` prop; `defaultCountry` sets the initial selection. An existing E.164 value is parsed back (best-effort, longest dial-code prefix) to pre-fill the country + number. Self-contained (native `<select>` + `<input type="tel">`, no extra DI component). New exports: `DEFAULT_COUNTRIES`, `toE164`, `parseE164`, and the `Country` type. Additive.
- 3336970: **Breaking:** remove the no-op `gridSpan` field prop. It never had a runtime effect — field column span is driven by `columns` / `layout.columns`, which is unchanged. Configs that set `gridSpan` should use `columns` instead (the form-builder already writes `columns`).

  Shipped as a **0.x minor** (per semver, `0.x` minors may carry breaking changes) to keep the package on 0.x — not promoting to 1.0 yet.

- 165bfec: Add a `signature` field type — free-hand drawing on a native `<canvas>`, stored as a PNG data URL. Includes a "Clear" control (i18n: `signatureClear`) and a `penColor` / `height` config.

  Notably it's **self-styled with inline styles** (no Tailwind utility classes), so it renders correctly even when the consumer's Tailwind build doesn't generate the package's classes — and it needs no injected component (works zero-config). It shows up automatically in the form-builder palette (registry-driven).

### Patch Changes

- d967742: Make the exotic field widgets **self-styled** so they render correctly even when the consumer's Tailwind build doesn't generate the package's utility classes (a known problem — the package's classNames live in `node_modules` and aren't scanned). Following the `signature` field's pattern, `rating`, `phone`, `file`, `matrix` and the `date` show-time/presets controls now use inline styles with shadcn CSS vars + hard fallbacks (e.g. `var(--input, #d4d4d8)`, `var(--primary, …)`) instead of Tailwind utilities on their custom widget parts. Behavior and a11y are unchanged; CSS-only `:hover` affordances on a couple of controls are dropped (not expressible inline).

## 0.12.0

### Minor Changes

- 6ab46c5: Add a `rating` field type — a star rating whose value is an integer `1..max` (default `max` 5). It's self-contained (native buttons + a lucide `Star`, no extra DI component beyond the base wrapper every form already provides), renders with `radiogroup`/`radio` semantics for accessibility, and clears when you click the current value again. Wired through the type union, `FIELD_REGISTRY` (so it shows up in the builder palette), the validation compiler (validated as a number), and test-data generation. Additive — no change to existing fields.
- fe3bee3: Add opt-in server-side search to async-options comboboxes. With `serverSearch: true` (and the `.serverSearch()` builder method), a combobox re-runs its loader (debounced ~300ms) with the typed text instead of filtering loaded options client-side: `loadOptions` now receives the search term, and `optionsSource` gains a `searchParam` that appends `?{searchParam}={term}` to the URL. A request id discards stale out-of-order responses. Off by default — existing combobox behaviour (load-once + client filter) is unchanged.
- 1542aef: Accept any [Standard Schema](https://standardschema.dev) as a field `schema` — not just Zod. Valibot, ArkType, Zod 4, and anything implementing the spec now work: the form detects them (`isStandardSchema`) and runs their `~standard.validate` (sync or async), surfacing issues on the field. The `schema` type and the `SchemaType` alias are widened to `z.ZodType | ValidationRules | StandardSchemaV1` (additive — existing Zod/ValidationRules schemas are unchanged; Zod schemas keep the native path). New exports: `isStandardSchema`, `standardSchemaToZod`, and the `StandardSchemaV1` type. Standard Schemas are code-only, so the isomorphic `validateFormData` skips them server-side (serializable configs carry ValidationRules).
- 7982b93: Add a generic file-upload adapter. A `file` field can take an `uploadAdapter`: selected files are uploaded on change (with a progress bar) and the field value becomes the adapter's `UploadResult` (e.g. `{ key }` / `{ url }`) instead of the raw `File`. `createPresignedUploadAdapter({ getUploadTarget })` generalises the presigned-URL pipeline (R2 / S3 / any backend) — your backend hands out a short-lived URL and the adapter PUTs the binary straight to it with real progress (XHR). New exports: `createPresignedUploadAdapter`, the `useFileUpload` hook, and the `UploadAdapter` / `UploadResult` types. Additive — without an adapter the file field keeps its current behaviour (stores raw `File`s, uploaded on submit).

## 0.11.0

### Minor Changes

- 353b604: Add a `@saastro/forms/validation` subpath export — a lean, React-free entry exposing the validation API (`validateFormData`, `buildFormSchema`, `resolveFieldSchema`, `compileValidationRules`, the type guards and presets). Its only runtime dependency is `zod`, so server consumers (e.g. a Cloudflare Worker validating submissions) can import it without pulling the React / icon graph the main entry carries — importing from the package root bundles ~1.4 MB into a worker; the subpath keeps it to zod + the rule compiler. Same code, just an additional server-friendly import path.

## 0.10.0

### Minor Changes

- e3c21a4: Add async options to `select`, `combobox`, and `native-select`. A new optional `loadOptions` field (and `.loadOptions(loader)` builder method) accepts an async function that resolves the field's options; it runs once on mount, shows the static `options` array as a fallback while loading (and disables the control), and keeps the fallback if the loader rejects. Fully additive — existing static-`options` configs are unchanged. `loadOptions` is a function, so it is not serializable (code-defined forms only); a URL-based source, debounced search-on-type, and dependency-driven reloading are planned follow-ups.
- ccd7c5a: Add isomorphic (server-side) validation. New exports `validateFormData(form, data)`, `buildFormSchema(form)`, and `resolveFieldSchema(fieldConfig)` validate a submission against a form config anywhere — React-free — reusing the same `ValidationRules → Zod` compiler the browser runs, so a form's rules are enforced identically on the client and on the server (e.g. the submit Worker). `validateFormData` returns `{ success, data?, errors? }` with per-field error messages; unknown keys (hidden fields, server-injected geo/IP) are stripped, not rejected; files/repeaters resolve to `z.any()` and plugin validators are client-only. `buildRequiredOnlySchema` moved to the React-free `validation/` module (still re-exported, no change for consumers).
- 41cf1d7: Add a serializable URL source for async options: `optionsSource` (and `.optionsSource(src)`) on `select`/`combobox`/`native-select`. Unlike `loadOptions` (a function), it's plain JSON — `{ url, method?, headers?, path?, labelKey?, valueKey?, timeoutMs? }` — so async options now survive the builder/Hub config. It's compiled into a loader that fetches the URL (with a 10s abort timeout), navigates `path`, and maps each item via `labelKey`/`valueKey` (default `label`/`value`), reusing the existing `useAsyncOptions` machinery. If both `loadOptions` and `optionsSource` are set, `loadOptions` wins. Additive — no behaviour change for existing configs.

### Patch Changes

- 7aba454: CLI: replace two mid-function `process.exit(0)` calls in `install-deps` (running inside the package itself, and no `components.json` found) with graceful `return`s. Behaviour is unchanged for the CLI (the script still ends with exit 0), but it no longer hard-kills the process — safer when `install-deps` runs as a postinstall hook. Completes the CLI cleanup; the `add` redirect, English messages, and components.json alias resolution were already in place.
- 769c71d: Mark the no-op `gridSpan` field prop as `@deprecated` in the types. It has never had a runtime effect (layout is driven by `columns` / `layout.columns`); the JSDoc now says so explicitly and points to its removal in v1.0. No behaviour change — documentation/typings only.

## 0.9.0

### Minor Changes

- 77c3972: Add 12 data-capture resolvers for hidden fields (all client-side, sync):
  - **Marketing attribution**: `utm` (all `utm_*` as an object), `clickId`
    (first present gclid/fbclid/msclkid…), `landingPage` and `firstReferrer`
    (first-touch, persisted to sessionStorage).
  - **Browser / device**: `language`, `timezone`, `screenResolution`,
    `deviceType` (mobile/tablet/desktop), `pageTitle`.
  - **Storage / generated**: `cookie` (by name), `storage`
    (localStorage/sessionStorage by key), `submissionId` (UUID per load).

  `resolveValue` now delegates all sync resolvers to `resolveValueSync` (single
  source of truth; `ip`/`custom` stay async). `BUILTIN_RESOLVERS` lists the new
  ones so the visual builder picks them up automatically. Additive — no breaking
  changes.

  Note: values only the server can trust (real IP, geo) still belong server-side
  (e.g. Cloudflare `CF-Connecting-IP`/`CF-IPCountry`), not these client resolvers.

## 0.8.0

### Minor Changes

- a46a5aa: v0.8 — correctness & security release, plus first-class custom fields.

  **Fixed (correctness):**
  - Plugin hooks are now invoked bound to their plugin (`this` was `undefined`) and `onFormInit` receives the bare `FormConfig` (it received a `{ formConfig }` wrapper) — this repairs the **localStorage plugin**, whose save/restore cycle never worked
  - Async plugin hook rejections no longer abort other plugins' hooks
  - Custom validators now receive the real form values in `context.allValues` (cross-field validation was impossible — it was hardcoded `{}`)
  - `continueOnError` on submit actions is honored (any failure used to abort the submit)
  - `submitExecution.globalTimeout` is now implemented (was silently ignored)
  - reCAPTCHA script polling and token fetch have 10s timeouts (misconfigured keys used to hang the submit forever)
  - `ip` hidden-field resolver has a 5s fetch timeout; `custom` resolvers are error-bounded
  - autosave plugin keeps its debounce timer per instance (was on `window`, colliding across forms)
  - databowl `staticFields` no longer overwrite user-entered values
  - `{{placeholder}}` templates accept hyphens and dots in field names
  - HTTP action timeouts produce a clear "timed out after Xms" error; Mailgun email actions require an explicit endpoint
  - `file.maxSize` is now enforced client-side via validation
  - `FormBuilder.layoutClassName()` is applied to the grid (was stored and ignored)
  - `FieldBuilder.schema()` accepts `ValidationRules` objects in its signature (runtime already did)
  - Standard layout forms now pass `pluginManager` to fields (plugin custom fields only worked in the inline-buttons layout)
  - `StepsNavigation` accepts `onBeforeNavigate` to gate step jumps (e.g. validate before navigating)

  **Security:**
  - HTML in field labels and success/error messages is sanitized (script/iframe removal, `on*` handlers stripped, `javascript:` URLs blocked) — these can come from remote schemas via HubForm. The `html` field type remains the explicit raw escape hatch
  - turnstile plugin fails closed by default: a missing captcha token now fails the submit with a clear message instead of submitting tokenless (configurable via `failMode: 'open'`)

  **Added (custom fields):**
  - Custom field components receive the full renderer context (`components` DI registry, `shouldDisable`/`shouldReadOnly` evaluated, `renderLabel`/`renderFieldIcon`) — `CustomFieldProps` exported
  - `FieldWrapper` is exported: custom fields get label/error/helper scaffolding for free
  - `FieldBuilder.type()` accepts custom type strings; new `.prop(key, value)` escape hatch; `build()` doesn't require a schema for custom types
  - `CustomFieldConfig`/`AnyFieldConfig` types; `Fields` accepts custom configs without casts
  - `defaultValue` is honored when seeding form defaults (the builder method existed but was ignored)
  - `button-card` supports `cardLayout: 'vertical'` (icon above text — logo pickers)
  - `@saastro/forms/styles.css` ships selected-state styles via CSS variables (no Tailwind compilation of node_modules needed)

  **Deprecation warnings (dev-only):** `date.showTime`, `date.presets`, `gridSpan`, and top-level `order` are declared in types but not implemented — they now warn once in development and will be implemented or removed in v1.0.

- a46a5aa: New plugins, reactive i18n, and pre-release polish.

  **New plugins (8 built-in total):**
  - `hubPlugin({ siteId, formSlug })` — hosted Saastro Hub submit for ANY form, including ones built entirely in code. Reuses the `createHubFormSubmit` pipeline (presigned uploads, captcha conventions) as a composable submit action.
  - `localeDetectorPlugin()` — activates `config.locale` from `navigator.language` when a matching translation overlay exists.

  **i18n:**
  - New `useMessages()` hook (reactive — re-renders on `setDefaultMessages`); the steps UI components use it
  - Validation fallback messages ("This field is required", "You must accept this", file max-size) moved into the `FormMessages` catalog (translated in the bundled `es` locale)

  **Hardening:**
  - `recaptchaPlugin` gains `failMode` (`'open'` default preserves historical behavior; `'closed'` fails the submit like turnstile)
  - Plugin `transformValues` errors now ABORT the submit (a throwing captcha plugin no longer ships a tokenless submission); `executeHook` keeps per-plugin isolation but propagates errors, restoring the `onBeforeSubmit` veto contract
  - localStorage plugin: debounced writes (300ms), pending saves cancelled on submit, ISO date strings rehydrated to `Date` on restore
  - Selected-state attribute namespaced to `data-saastro-selected` (no more bleeding into cmdk/react-day-picker)
  - `setHtmlSanitizer()` — plug in DOMPurify in one line
  - Submit orchestrator: throwing field-mapping transforms now produce `success: false` results (honoring `continueOnError`) instead of crashing the pipeline
  - `required` single-select `button-card` validates correctly; option-less selection fields render safely

  **Removed / behavior changes:**
  - The deprecated `useRecaptcha` hook is removed — use `recaptchaPlugin()`. The legacy `config.submit.recaptcha` path no longer auto-injects the script
  - Chaining declarative validators after an explicit Zod schema (`.schema(z).required()`) no longer silently discards the Zod schema — the Zod schema wins and the declarative call is ignored with a dev warning
  - Forms WITHOUT `submitConfirmation` no longer re-render on every keystroke (the confirmation hook only subscribes to values when configured)
  - `factory/variants` (CVA input/textarea/icon variants) are no longer star-exported — they were internal styling helpers

- a46a5aa: Quality wave — renderer test coverage, accessibility, and centralized i18n.

  **Testing:** 52 new tests cover all 34 field types end to end (render matrix with a full DI fake registry + interaction tests writing to react-hook-form) — the rendering pipeline finally has a safety net.

  **Accessibility:**
  - `button-radio` and single-select `button-card` render `role="radiogroup"` with `role="radio"`/`aria-checked` buttons; `button-checkbox`, multi-select `button-card`, `checkbox-group` and `switch-group` render `role="group"` (+`aria-pressed` where applicable)
  - Validation errors render inside `aria-live="polite"` regions (announced by screen readers)
  - Date popover triggers expose `aria-haspopup="dialog"`/`aria-expanded`; OTP slots carry per-digit `aria-label`s; file inputs set `aria-invalid`

  **i18n — ⚠️ DEFAULTS ARE NOW ENGLISH:**
  - ALL package UI strings (placeholders, button labels, toasts, `Submitting...`, step navigation/progress/accordion, aria-labels) now live in a single `FormMessages` source — **and the package defaults flipped from Spanish to English** (`Submit`, `✅ Thank you!`, `Select an option...`, `Step 1 of 3`, ...)
  - **Migration for Spanish apps** (one line in your entry point):
    ```ts
    import { setDefaultMessages, setDateLocale } from "@saastro/forms";
    import { es } from "@saastro/forms/locales";
    import { es as dateEs } from "date-fns/locale";
    setDefaultMessages(es);
    setDateLocale(dateEs); // date picker formatting (was hardcoded Spanish)
    ```
  - Complete `en` and `es` locales ship via the new **`@saastro/forms/locales`** subpath; per-form `locale`/`i18n` overlays still take precedence
  - Date formatting no longer hardcodes the date-fns Spanish locale — English by default, configurable via `setDateLocale()`
  - New `setErrorNotifier()` replaces the default sonner toasts with any notification system

  **Builder contract:**
  - New `FIELD_REGISTRY` export: canonical per-type metadata (title, description, category, lucide icon name, default props, value kind, aliases) for the 34 field types — the visual builder's palette is now derived from it (and gains `file` + `repeater`)
  - New `FORM_SCHEMA_VERSION` export — the export/import contract version lives in the package, not hardcoded in consumers

  **Dev:** lint warnings reduced from 218 to ~138 (import-sort autofix across the package); axe (vitest-axe) runs over representative renderers in CI.

### Patch Changes

- 9fef69f: Fix "Rendered more hooks than during the previous render" (React #310) when a field uses a conditional `hidden` (function or ConditionGroup). FieldRenderer returned early on `shouldHide` before several hooks, so the hook count changed when visibility flipped and React unmounted the whole form. The hidden early-return now runs after all hooks.

## 0.7.0

### Minor Changes

- c9d6177: Add multi-language (i18n) support for forms.
  - New `FormConfig.i18n` overlay (`{ defaultLocale, locales, translations }`) and
    `FormConfig.locale`. The base config holds the default-language strings; each
    `translations[locale]` overlay translates field labels/placeholders/options
    (matched by value), button labels, step titles/descriptions and success/error
    messages. Untranslated strings fall back to the base.
  - New `applyLocale(config, locale)` (pure, exported) + a single injection point
    in `useFormState` — when `config.locale` is set, the overlay is merged before
    rendering, so no renderer changes are needed. `useFormState` now also returns
    the locale-resolved `config`, and `Form` renders fields/buttons/steps from it
    (previously it rendered from the raw prop, so translated labels never showed).
  - `HubForm` gains a `locale` prop (pass the host page's active language).
  - `Step` type gains `title`/`description` (already written by the builder).

  The visual form-builder gains a Translations panel (author per-language strings)
  and a preview language switcher.

## 0.6.2

### Patch Changes

- ba2fb3d: Harden the Turnstile plugin against DOM-rewriting tools (Google Translate).

  Google Translate clones/replaces the widget container's subtree, detaching
  Turnstile's iframe → "Cannot find Widget" and the token never arrives → the
  submit goes out tokenless and the worker rejects it (400). Now:
  - The widget container is marked `translate="no"` / `notranslate` (both the
    `HubForm` inline mount point and the plugin's fallback container) so
    Translate leaves it alone.
  - The plugin re-renders the widget on demand if it detects the container was
    detached or emptied (a re-render or Translate ripped it out), instead of
    reusing a dead `widgetId`.

## 0.6.1

### Patch Changes

- bab9b68: Fix: enforce top-level `required` on fields without an explicit `schema`.

  `useFormState` only built validation from `field.schema`, so a field with
  `required: true` at the top level (the flag the builder sets, which drives the
  asterisk + native `required` attribute) but no explicit `schema` skipped
  validation entirely — empty submissions passed. Now a top-level `required: true`
  adds a value-type-agnostic presence check (non-empty for text/number/select,
  must-be-checked for checkbox/switch, ≥1 selection for multi-selects, a start
  date for date ranges). Rich per-type rules still come from an explicit
  `schema`/`ValidationRules`.

## 0.6.0

### Minor Changes

- fa30852: Add Cloudflare Turnstile support.
  - New `turnstilePlugin({ siteKey })` — mirrors `recaptchaPlugin`, renders the
    Turnstile widget (explicit + `execution: 'execute'`, interaction-only by
    default) and attaches the token to submissions as `_captchaToken`.
  - `HubForm` now auto-wires the captcha plugin when the served schema declares
    `meta.captchaProvider` (`turnstile` or `recaptcha-v3`) + `meta.captchaSiteKey`.
    Host apps need no extra setup — captcha just works. Both providers write the
    token to `_captchaToken` (the field `createHubFormSubmit` forwards as
    `captchaToken`).

## 0.5.0

### Minor Changes

- e3c842f: Removed starter templates from the package.

  `TEMPLATES`, `TEMPLATE_META`, `TemplateId`, `TemplateMeta`, and the five
  `create*Template` factories (`createContactTemplate`, `createNewsletterTemplate`,
  `createLeadGenTemplate`, `createEventRsvpTemplate`, `createQuoteRequestTemplate`)
  are no longer exported.

  **Why:** the package is a runtime/DI library, not a content owner. Bundling 5
  hardcoded form configs forced an npm release for every preset tweak. Presets
  now live in the `@saastro/form-builder` app, where they belong (visible to
  standalone users of `forms.saastro.io` too). Custom per-tenant templates are
  managed by Saastro Hub.

  **Migration:** if you imported any of the above, paste the factory bodies
  verbatim into your own project. They are pure functions over `FormBuilder` —
  no hidden dependencies. The complete sources are preserved in this repository
  under git history at tag `@saastro/forms@0.4.0`.

  ```ts
  // Drop-in replacement for createContactTemplate():
  import { FormBuilder } from "@saastro/forms";
  import type { FormConfig } from "@saastro/forms";

  export function createContactTemplate(): FormConfig {
    return FormBuilder.create("contact")
      .layout("auto")
      .columns(1)
      .gap(4)
      .addField("name", (f) =>
        f.type("text").label("Name").required().minLength(2),
      )
      .addField("email", (f) =>
        f.type("email").label("Email").required().email(),
      )
      .addField("message", (f) =>
        f.type("textarea").label("Message").required().minLength(10),
      )
      .addStep("main", ["name", "email", "message"])
      .initialStep("main")
      .buttons({
        submit: { type: "submit", label: "Send message" },
        align: "end",
      })
      .build();
  }
  ```

  Patterns for the other four (`newsletter`, `lead-gen`, `event-rsvp`,
  `quote-request`) are analogous — see the v0.4.0 sources for verbatim copies.

## 0.4.0

### Minor Changes

- **BREAKING (pre-1.0):** Default ingestion endpoint moved to `https://submit.saastro.io/v1`

  The Saastro Hub Forms public API was split out of the monolithic `hub.saastro.io` worker into a dedicated Cloudflare Worker at `submit.saastro.io/v1/*`. This is the canonical endpoint going forward — independent scaling, latency, and deploy cadence from the dashboard.

  > Bump type `minor` instead of `major` because the package is still pre-1.0. Treat this as a breaking change for upgrade purposes — `hub.saastro.io/api/public/forms/*` returns 410 Gone after the cutover.

  **Changes:**
  - `HubFormProps.hubUrl` and `CreateHubFormSubmitOptions.hubUrl` are now **optional**. Default: `https://submit.saastro.io/v1`.
  - URL builders no longer prepend `/api/public/forms/` — the new endpoint already namespaces with `/v1/`.
  - New export `DEFAULT_HUB_URL` for callers that need to reference the canonical base.
  - Captcha token now sent as `captchaToken` (canonical, multi-provider). Legacy `_turnstile` field name is still accepted by the SDK and forwarded; the worker accepts both `captchaToken` and `turnstile` shapes for backwards-compat with pre-0.4 callers.

  **Migration:**
  - **If you used the default `hubUrl="https://hub.saastro.io"`**: remove the prop entirely. The default works.

    ```diff
    - <HubForm hubUrl="https://hub.saastro.io" siteId="..." formSlug="..." />
    + <HubForm siteId="..." formSlug="..." />
    ```

  - **If you used a custom hub URL**: update the value to point to `https://your-endpoint/v1` (note: the SDK no longer adds `/api/public/forms`, so the path must be the full base).

    ```diff
    - <HubForm hubUrl="https://hub.example.com" ... />
    + <HubForm hubUrl="https://submit.example.com/v1" ... />
    ```

  - **Captcha field name**: if you were passing `_turnstile` as the hidden field name in form values, it still works. New code should prefer `_captchaToken` for clarity (the schema now supports both Turnstile AND reCAPTCHA v3 via `meta.captchaProvider`).

  The old `hub.saastro.io/api/public/forms/*` paths return **410 Gone** with a body pointing at the new endpoint. There is no transparent redirect — consumers MUST upgrade.

  See https://docs.forms.saastro.io/migration/v0.4 for full details.

## 0.3.0

### Minor Changes

- 6ad7e83: Add 5 starter form templates as a top-level `TEMPLATES` registry.

  Importable factories return fresh `FormConfig` objects so callers can
  safely mutate the result:

  ```ts
  import {
    createContactTemplate,
    TEMPLATES,
    TEMPLATE_META,
  } from "@saastro/forms";

  const config = createContactTemplate(); // direct factory
  const config2 = TEMPLATES.newsletter(); // dynamic dispatch
  const choices = TEMPLATE_META; // for pickers
  ```

  Templates:
  - **contact** — name, email, message (3 fields)
  - **newsletter** — email + GDPR-friendly consent (2 fields)
  - **lead-gen** — name, email, phone, company, message (5 fields)
  - **event-rsvp** — name, email, attending radio, guest count, dietary (5 fields)
  - **quote-request** — contact + service select + budget range + details (6 fields)

  All templates use the declarative `ValidationRules` API so they
  serialize cleanly to JSON (Hub-storable) and compile to Zod schemas
  at runtime via `compileValidationRules`.

  Used by `saastro-hub`'s upcoming "New form → Start from" dropdown and
  by the form-builder's template picker (both shipping next).

## 0.2.1

### Patch Changes

- 1a23044: CLI `install-deps` now also installs missing peer dependencies.

  The command previously only installed the shadcn/ui components a consumer
  needed. With this release it also detects the package manager from the
  lockfile (`pnpm` → `bun` → `yarn` → `npm`) and runs the appropriate
  `add` command for any of these peer deps that are missing from the
  consumer's `package.json`:
  - `zod@^4`
  - `react-hook-form@^7`
  - `react-day-picker@^9`
  - `date-fns@^4`

  A fresh React or Astro project can now go from zero to a working form
  with three commands:

  ```bash
  npm install @saastro/forms
  npx @saastro/forms init
  npx @saastro/forms install-deps
  ```

  `react` and `react-dom` are intentionally not auto-installed — projects
  already have them, and choosing between React 18 and 19 is a project
  decision.

- 772cf48: `<HubForm>` is more robust against empty/legacy schemas and exposes
  post-submit hooks.
  - Adds an `unconfigured` state. If Hub returns a schema with no fields
    or no steps, `<HubForm>` now renders a small "form not configured yet"
    banner instead of crashing. Overridable via the new
    `unconfiguredFallback` prop.
  - Adds `onSuccess(values)` and `onError(error)` props, called after the
    submission either succeeds or fails. Mirrors the existing FormConfig
    callbacks so existing patterns transfer.
  - Adds a `successFallback` prop and a built-in "Thanks — we'll get back
    to you soon" panel rendered after a successful submission. Pass
    `successFallback={null}` to render nothing (useful if the host page
    controls the after-submit UX via `onSuccess`).

  Non-breaking: existing `<HubForm>` callsites keep their behavior. The
  inner `<Form>` is still rendered for valid schemas.

- 412672a: Allow consumers to use `zod@3` or `zod@4`.

  The `zod` peerDependency is now `^3.25.0 || ^4.0.0` (previously only
  `^3.25.76`). Sub-dependency `@hookform/resolvers@^5` imports from
  `zod/v4/core`, which made esbuild crash during `optimizeDeps` in
  consumer Vite/Astro setups that installed `zod@4` directly. Both
  versions are now accepted at the peer-range level.

  Local builds of `@saastro/forms` are pinned against `zod@^3.25` until
  `@hookform/resolvers` loosens its v4 type pin (it currently expects
  zod `4.0.x` specifically). Runtime works against both 3.25+ and 4.x.

## 0.2.0

### Minor Changes

- 1c85a10: Add Saastro Hub integration helpers — `createHubFormSubmit()` and the
  `<HubForm>` wrapper — for sites that author their forms in
  `builder.saastro.io` (Hub embed mode) and want to submit back to Hub
  without writing the upload-URL flow by hand.

  Also extends `SubmitActionType` with `'integration'` and adds the
  `IntegrationSubmitAction` interface (declarative reference to a
  `site_integrations` row in Hub). The form runtime ignores this
  action type — Hub's server-side dispatcher executes integrations
  after receiving the submission.

  Non-breaking: existing forms (custom / http / webhook / email submit
  actions) keep working unchanged.

## 0.1.3

### Patch Changes

- 0e6d689: Remove external @saastro/config dependency and replace ButtonPro with DI Button component
