@saastro/forms
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/inputdentro 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 nuevaloadOn: 'mount' | 'interaction'(por defecto'interaction');'mount'restaura el comportamiento anterior. Sin token al enviar, el submit sigue abortando segúnfailMode.
0.28.0
Minor Changes
-
9bb8020: Export the
HookFormMetatype ({ formId }) from the package entry. It is the optional last argument of theonAfterSubmitandonErrorplugin hooks and part of theonStepChangemeta (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(), thelandingPageandfirstReferrerresolvers keep their first-touch value in memory (coherent across form steps, never written), and thecookie,storageandipresolvers return theirfallbackwithout reading cookies / storage or calling the endpoint. Wire your banner once withsetConsent({ get, subscribe }), or declaresetConsent('not-required')on purpose. The hidden fields that depend on consent are resolved again whenever the consent changes (if the provider hassubscribe) 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;submissionIdandtimestampkeep their mount-time value). Granting saves the first-touch the page already knew; withdrawing deletes the twosessionStoragekeys the library wrote and empties the memory copy. Purposes:necessary(never asks),attribution(first-touch, reading cookies and storage) andenrichment(theipcall). New exports:setConsent,hasConsent,getStoredKeys,clearStoredData(for data-subject requests: list and delete everything the library stored) and theConsentCategory/ConsentConfig/ConsentProvider/StoredKey/StoredDataOptionstypes. New optional subpath@saastro/forms/consentwithfromCookie(a banner that keeps its decision in a JSON cookie) andfromGoogleConsentMode; the core never imports it.getStoredKeysandclearStoredDatado not ask for consent: looking at or deleting your own data collects nothing. A purpose is granted only when its checkbox is exactlytrue(cookie) or'granted'(Google); a missing, corrupt or non-object cookie grants nothing.fromGoogleConsentModefails closed onregion: adefaultscoped to regions never grants (the library does not know where the visitor is), one that denies is respected until the visitor’s ownupdate, and a laterdefaultnever overrides what the visitor already decided.Behavior change in 0.x: sites that relied on first-touch attribution, the
cookie/storageresolvers oripmust callsetConsentafter updating. Without consent the first-touch resolvers also delete the twosessionStoragekeys the library wrote, so a withdrawn consent, a provider with onlyget, or keys left by an earlier version do not survive. Internally, every access to storage and cookies now goes throughutils/deviceStorage.ts(the only exception is the opt-inlocalStorageplugin, 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
labelIdaccessibility prop onto DOM controls. The select, file, OTP, phone, rating, text and toggle renderers now spread the newcontrolA11y()helper, so React no longer warns “does not recognize thelabelIdprop”.
0.27.1
Patch Changes
- 304042e:
validateFormConfigrejects an option whoseshortLabelis not a string (option-short-label-invalid), andlintFormConfigwarns on an empty one (short-label-empty): compact channels would silently fall back tolabel. The visual builder can now editshortLabelper option.
0.27.0
Minor Changes
- a5b1ed4:
validateFormConfigvalidatesoptionsSourcedependencies: adependsOnor a{{field}}in the url that points to a nonexistent field (options-source-field-unknown, also thrown bybuild()) 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_submitandform_errornow always carryform_id. The runtime passesformIdin theonStepChangemeta (the plugin’s own only; the user’sonStepChangecallback does not change) and as an optional 3rd argument (HookFormMeta) ofonAfterSubmitandonError; 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.patternis 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. ThesafePatternguard does not change: no new pattern is rejected. - e8faf64: localStoragePlugin:
hiddenfields with aresolver(?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.hiddenfields 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) andBaseFieldProps.ai(evaluate,describe), with the typesAiEvaluateSpec,AiOutputKind,FormAiConfigandFieldAiConfig.validateFormConfigchecks their shape and reportsai-invalid(prompt required and at most 4,000 characters,outputone oftext | json | boolean | number | enum,schemaan object).findClientSecretsreportsai.apiKey(kind'ai.apiKey') andredactClientSecretsremoves it. -
79f5bb8: Nested condition groups with
not.ConditionGroup.conditionsnow accepts other groups (a AND (b OR c)) and a group can setnot: true. Nesting deeper thanMAX_CONDITION_DEPTH(10) makes the whole conditionfalsewithout throwing;validateFormConfigreports it ascondition-too-deep. It applies to step routing,hidden, cross-fieldwhen,$ifexpressions and theconditionof a submit action (nowSubmitActionLeaf | ConditionGroup). Code that readgroup.conditions[i].fielddirectly must now tell leaves from groups (collectConditionFieldsdoes it for you). -
13fd285:
Option.shortLabelandButtonCardOption.shortLabel: a compact form of an option’s label, used by the WhatsApp message (falls back tolabel/textwhen missing or empty). The i18n overlay translates it by optionvaluelike the label; inLocaleOverlayan option entry now takeslabel?andshortLabel?, both optional. -
380557c: Builders:
FormBuilder.step(id, title, s => …)with the new exportedStepBuilder(.fields() .description() .next() .defaultNext() .review() .i18n(locale, {title, description}) .locale(code) .meta(data);Step.metais new and never read by the runtime).FieldBuildergains.matrix(rows, options),.html(content),.visibleWhen(condition)(storeshiddenwithnot),.requiredWhenVisible()(a field hidden by a condition is neither validated nor submitted) and.minDate()/.maxDate(), which take an ISO string, aDateor{ daysFromToday }. The relative form is the new serializable rule pairminDateDaysFromToday/maxDateDaysFromTodayonValidationRules, 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 aFormData/URLSearchParamsinto typed values (checkboxes to boolean, numbers to number, repeated keys anditems[0][name]to arrays,__proto__-style keys ignored);createServerValidate(form)returns an action foruseActionStateor a Server Action, withServerValidateStateandinitialServerValidateState. -
3624e6a: Types only:
InferFormValuesnow works on theaddFieldchain ofFormBuilder.build()returnsTypedFormConfig<F>(aFormConfigwith a type-only'~fields'), andFieldBuildergains 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 infersT | 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).FieldWrappergenerates ids withuseId()and gives the renderersparams.a11y(id,aria-describedby,aria-invalid, pluslabelId). The control’saria-describedbypoints to the description and the error only when they exist;aria-invalidis set only where the role allows it.FieldDescriptionandFieldErrorreceive anid, andFieldLabelreceivesidandhtmlFor(additive optional props inFieldDescriptionProps,FieldErrorPropsandFieldLabelProps). CustomField*primitives must forwardid/htmlForto 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 whenhideLabel); the radiogroup inside is named witharia-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 onlyrequiredor no rules). New i18n messagevalidationTooLong(en/es, optional inFormMessages);compileValidationRulestakes an optional thirdmsgsargument. DeclaremaxLength/maxItemsto set your own limit.signature,hiddenandhtmlfields (long text) are capped at 1,000,000 characters. Contract change:resolveFieldSchemano longer returnsnullfor a field without rules (it returns a limits-only schema), so such fields now appear in thedataofvalidateFormData. Fields with an explicit Zod or Standard Schemaschemaget no default limit. -
c41bff6: New public
registerDateLocales({ fr, de }): register date-fns locales from your app and each form picks its own byconfig.locale(region ignored), without bundling them in the package; an explicitsetDateLocalestill wins. NewformatPlural(locale, count, forms)(and thePluralFormstype) picks the plural form withIntl.PluralRulesfor languages with more than two forms. -
104bf92:
analyticsPluginnow sendsform_step_time(form_id,step_id,duration_ms, when leaving a step or submitting) andform_abandon(form_id,step_id,duration_ms, sent once withtransport_type: 'beacon'when the tab is hidden or the page is unloaded without a submit). No form values are sent; the listeners are removed incleanup.
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 politearia-liveregion (newstepAnnouncemessage in theen/esbundles;FormMessages.stepAnnounceis 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:
FormPropsgainsenctypeandnativeFields(hidden inputs rendered only together withaction, never part of the JS payload), and<HubForm>gainsthanksPath, sent as_redirectwhen the served schema carriesmeta.nativeSubmit.thanksPathmust be a same-site relative path (the Hub worker discards anything else), and<HubForm>never setsmultipart/form-dataon its own because the Hub’s native endpoint only accepts urlencoded today. - c240378: New browser-only submit action
lookup: ononFieldBlur,onFieldChangeoronStepEnterit fetches a JSON endpoint ({{field}}placeholders, URL-encoded;params,timeoutMs,maxBytes,onError) and copies parts of the response into other fields viamapResponse(own properties only, scalars only). While a lookup is in flight Next and Submit aredisabledwitharia-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.validateFormConfigreportslookup-invalid, andfindClientSecretscovers itsendpointandparams.
0.25.0
Minor Changes
-
32021ef: Plugin hardening (P0.8):
- Breaking:
recaptchaPluginnow defaults tofailMode: '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. PassfailMode: 'open'to keep the old behavior. - Breaking: the
ipresolver no longer defaults tohttps://api.ipify.org. Without anendpointit makes no request, logs a warning once and returnsfallback(or''). Setendpointto keep resolving the IP. localStoragePluginnever persists fields of typepassword,otp,fileorsignature, and ignores them when restoring an older saved draft.analyticsPluginsendserror_type(the error class) inform_errorinstead oferror_message, which could carry user input or tokens into Google Analytics.
- Breaking:
-
b23f29f: Breaking: the step UI moves out of the root entry into the new
@saastro/forms/stepssubpath.StepsNavigation,StepsProgress,StepsAccordion,useFormStepsInfo(and itsStepInfo/FormStepsInfo/StepStatustypes) 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/esbyconfig.locale);setDefaultMessages,FormConfig.i18noverrides and the completeen/esfrom@saastro/forms/localeskeep working, and theFormMessageskeys for them become optional.New:
FormConfig.stepsUi({ mode: 'none' | 'progress' | 'sidebar'; navigable?; variant? }) makes<Form>draw a progress bar or step menu, provided you registerstepsUiPlugin()from@saastro/forms/steps(viaPluginManager,FormPlugin.stepsUi/registerStepsUi). Without the plugin it draws nothing and warns once;<Form>never imports the subpath.Step.review: trueis 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’ssuccessMessage(localized to the active locale, sanitized) on the success screen.optionsSourcecan depend on other fields.{{field}}placeholders inurlare 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 (withserverSearch, 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
lintFormConfigto@saastro/forms/validation(P4.4): warnings for configs that are valid but probably not what the author meant (validationinstead ofschema, optional field withformat, required field hidden by a condition,htmlfield with several ofcontent/html/value, step withouttitle, nosuccessMessage, client-side secrets, reserved field names).validateFormConfig(config, { lint: true })from that subpath also returnswarnings. The root entry does not export the linter and itsvalidateFormConfigignoreslint. -
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 paravalidateFormConfig. Solo datos, sin React: el entry raíz no crece. -
a7c4840: Breaking:
generateTestData,generateFieldValue,detectLocaleand theTestDataOptions/TestDataLocaletypes 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>rendersstep.titleas an<h2 tabIndex={-1}>andstep.descriptionas a<p>above the step’s fields (locale overlay applied),StepsNavigationandStepsAccordionshowstep.titleinstead of «Step n» when set,StepInfoexposestitle, andFormBuilder#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 byvalidateFormConfig: Zod ignores that key while parsing, so such a field was silently never validated. validateFormDatano longer throws aTypeErrorwhen an error belongs to a field named like anObject.prototypemember (constructor,toString…). Itserrorsobject now has no prototype: callObject.hasOwn(errors, key)orkey in errorsinstead oferrors.hasOwnProperty(key).- Repeater
itemFieldsnested deeper than 8 levels throw a clear error instead of overflowing the stack. optionsSourcereadspath,labelKeyandvalueKeyfrom own properties only (no__proto__/constructortraversal).
- ReDoS guard: a fixed-count group of three or more repetitions whose atoms overlap (e.g.
-
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 returnsfalsefor an unknown id or the step you are already on;FormRef.getCurrentStep()returns the active id. The jump fires the sameonStepChangehooks as next/prev, and «Back» steps back along the visited path (jumping to an already-visited step trims the history to it).Step.review: truemakes 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 callsgoToStep. New messagesreviewEdit/reviewEmpty(en/es). Put it last, usually withfields: [].<HubForm>now forwardsrefto<Form>(sogoToStepworks through it) and acceptsplugins: FormPlugin[], registered in the samePluginManageras 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
hiddenis a function or a condition group and evaluates totrueused to keep its rules: an optional URL withformatthat 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),triggeronly runs on visible fields, and the payload drops the hidden keys. Server-side,buildFormSchema(form, { values, validateHidden })andvalidateFormData(form, data, { validateHidden })do the same. New helpersisHiddenByCondition,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 withvalidation: { 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;crossFieldRulesthat 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,successMessageand plugin hooks (onFieldChange,onStepChange, autosave) still receive the raw values; hidden-type and literalhidden: truefields can still drive conditions. Circular conditions that never settle validate everything. -
364517e:
onStepChangenow 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 }, withdirection'next' | 'back' | 'jump'(goToStepis'jump'). Plugin hook:onStepChange(stepId, values, meta). Migrate code that read the first argument as «the step just completed» tometa.from. analyticsPluginsendsform_step: { step_id, from_step_id };step_idis now the destination.StepChangeMetais exported.
- Breaking: the first argument is the step being ENTERED (it used to be the step being left). The new second argument is
Patch Changes
- 3a17818: Internal plumbing, no behavior change. The root entry now lists the
./validationexports explicitly instead ofexport *(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).useFormStepsnextStep/prevStepnow return the destination step id ornullinstead of a boolean (internal hook;useFormStatestill exposes booleans). - 194aa76: Fix: an optional text-like field (
required: false) withformat,minLengthorpatternnow accepts an empty string. A blank input is submitted as''and used to failformat: '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 throwingUnknown action typeand failing the submit. - 5134081: Fix: the
commandandcomboboxfields now take their default search placeholder and empty text from the i18n messages (commandSearch,commandEmpty), soconfig.localeandsetDefaultMessagesapply to them. A field’s ownsearchPlaceholder/emptyTextstill wins.COMMON_STRINGS.COMMAND_EMPTYandCOMMAND_SEARCH_PLACEHOLDERare deprecated and no longer used.
0.23.1
Patch Changes
- cdc4da0: Peer
react-day-pickerampliado de^9.11.3a^9.11.3 || ^10.0.0. El paquete solo haceimport 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):
zodpasa de^3.25.0 || ^4.0.0a^4.0.0; Zod 3 deja de estar soportado (GHSA-mrhx-c7xc-m3w5 no tiene parche en 3.x). El CLI instalazod@^4.0.0. Los tipos publicados (.d.ts) no cambian.Fix: con Zod 4, un campo
daterequerido compilado desdeValidationRulesvuelve a mostrar elrequiredMessagedel autor (o «This field is required») en vez de «Invalid input: expected date, received undefined»:required_error/invalid_type_errorno 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 errorunreadable). Acepta el sobre{ version, formConfig }—la versión tiene que existir y su MAJOR ser el deFORM_SCHEMA_VERSION— o un FormConfig desnudo, sin regla de versión. Falla un campo sintype(un tipo que no está en el registro sí vale: los plugins registran los suyos), dos steps con el mismo id efectivo (ido, si no lo lleva, su clave) y las reglas que ya comprobabaFormBuilder.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 tiposFormConfigIssue,FormConfigIssueCodeyFormConfigValidationResult.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 cuyofieldsno es un array, que antes reventaba con unTypeError, ahora lanza unErrorcon mensaje; y un nombre de campo o de step heredado deObject.prototype('constructor','toString') ya no cuenta como existente.
Patch Changes
-
5671e8f:
button-cardconmultiple: truearranca 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: trueyrequired: trueen sus reglas (lo que exporta el builder) sinminItems, el campo exige al menos una opción y pinta elrequiredMessagedel autor, en cliente y en@saastro/forms/validation. ConminItemsexplícito mandaminItems.checkbox-group,switch-groupybutton-checkboxno cambian. -
aa9098a: Los labels por defecto del botón submit/next/back, y el «Submitting…» mientras envía, siguen
config.locale: un formlocale: 'es'sinbuttonspinta «Enviar» y «Enviando…» en vez de «Submit» ('es-ES'también; un idioma sin bundle cae al default). Lo registrado consetDefaultMessagessigue 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 asetDefaultMessagescon un override parcial (sin claves de botón) y renderiza formslocale: 'es': esos botones pasan de «Submit» a «Enviar». Quien registrasetDefaultMessages(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 bundleesviaja con él). -
821b26c: Un campo
date(sinshowTime) viaja en el envío como su fecha de calendarioYYYY-MM-DD, no como el instante UTC de su medianoche local: el 15/06/1990 elegido en Madrid llegaba como1990-06-14T22:00:00.000Zy 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 undaterangey losdatedentro de unrepeater. UndateconshowTimesigue viajando como ISO completo, y untransform: 'dateISO'explícito manda.Quien recibe los valores en código (submit custom,
onSuccess, plugins de submit) sigue recibiendo unDatecon el mismo instante, pero sutoJSON()devuelve ahoraYYYY-MM-DD: un receptor que parseaba un ISO completo de undatesin hora recibe ahora solo el día. Para seguir recibiendo el instante,transform: 'dateISO'en el campo.autosavePlugintambién envíaYYYY-MM-DD(es un POST a un servidor). Fuera, a propósito:localStoragePluginsigue guardando ISO completo, porque su rehidratación hacenew Date(guardado)y unYYYY-MM-DDse leería como medianoche UTC (el día anterior al oeste de Greenwich); y elonSubmitprop de<Form>recibe los valores crudos de react-hook-form. -
777b4f3: El
Calendardel date picker (datesimple y popover, ydaterange) recibe el locale de date-fns del formulario como proplocale: el mismo que ya usa el trigger (config.locale, consetDateLocale()como override global). Un formlocale: 'es'abre el calendario con los meses y los días en español en vez de en inglés, siempre que elCalendarinyectado paselocalea react-day-picker (el del registry de saastro-ui lo hace).CalendarPropsganalocale?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]}aCommandItem, así que{ value: 'next', label: 'Next.js' }aparece al teclear «Next.js» con el@saastro/commanddel registry.CommandItemPropsdeclarakeywords?: string[](aditivo y opcional). -
cc32dfb: Tipos.
CommandPropsdeclarashouldFilter?: booleanyCommandInputPropsdeclaraonValueChange?: (search: string) => void: el renderer de combobox/command ya los pasaba y el contrato delComponentRegistryno los recogía. Aditivo y opcional. -
745d145: Requisitos. El tipo
commanddeclara ahoraPopover,PopoverTrigger,PopoverContentyButtonenfieldTypeComponents, comocombobox: los dos comparten renderer y lo usaban sin declararlo, así quegetRequiredComponents/getInstallCommandde un form solo concommandno pedíanpopover. -
0833b2f:
config.localeelige también el formato de las fechas del date picker (popover y rango): un formulariolocale: 'es'(oes-ES) sinsetDateLocale(es)pinta «30 de septiembre de 2026» en vez de «September 30th, 2026».setDateLocale()sigue mandando como override global sobreconfig.locale, y sinlocalenada cambia (inglés). El localeesde date-fns se importa solo desde el chunk lazy de DateRenderers. -
b906214:
config.localeelige también el resto de textos por defecto, no solo los botones: placeholders (texto, email, tel, select, fecha), el error de requerido, los mensajes decrossFieldRules, el tamaño máximo defile, 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 formulariolocale: 'es'sinsetDefaultMessages(es)ya sale entero en español. Lo registrado consetDefaultMessagessigue mandando clave a clave, y sinlocalenada cambia.getDateLocale()(el formato de las fechas) sigue siendo global. -
241f565: Los props
onSubmityonErrorde<Form>se disparan al pulsar el botón de enviar. Antes solo estaban cableados al submit nativo del<form>(Enter), y el botón estype="button", así que con el botón nunca se llamaban. Ahora los llama el pipeline de submit, por donde pasan las dos rutas:onSubmituna vez por envío correcto, con los valores procesados (los mismos queconfig.onSuccess) y antes de la pantalla de éxito;onErroruna vez por envío fallido, o cuandoonSubmitlanza (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 aonSubmittras un envío fallido. -
0c7886b: Instalación desde el registry
@saastro.getInstallCommand(missing, { registries }),MissingComponentFallback(propregistries) ynpx @saastro/forms install-depspiden@saastro/<nombre>(primitivos Base UI) cuando elcomponents.jsondel consumidor declararegistries['@saastro']; sin él, los nombres pelados de siempre (shadcn upstream). La CLI lo lee del disco; en runtime se pasa el bloqueregistries.MissingComponentFallbackusa ahora el mismo mapa quegetInstallCommand(tenía una copia) y no pinta el comando manual si no hay nada que instalar. Nuevo tipo exportadoInstallCommandOptions. -
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@internalin their JSDoc. They are still exported; nothing is removed. DocumenttoE164,parseE164,DEFAULT_COUNTRIES(Phone page) and the deprecatedcreateShadcnRegistryalias (Components page). -
30957b1:
native-select,combobox/command,button-card,button-radio,checkbox-groupyswitch-group: elegir (o marcar/desmarcar) una opción marca el campo como tocado (field.onBlur), como ya hacíanselectyradio. Convalidation.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 UISelect) yradio(RadioGroup): elegir una opción marca el campo como tocado (field.onBlur). Convalidation.mode: 'onTouched'(u'onBlur'), el error «obligatorio» que pinta Continuar desaparece al elegir, en vez de quedarse hasta el siguiente Continuar.native-select,combobox/commandy 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
.mapconsourcesContent(el código fuente entero) porque tsup solo los quitaba conNODE_ENV=production. AñadeLICENSE(MIT). Se publica desde CI por tagforms-v<versión>connpm stage publish(trusted publisher, sin tokens) y aprobación 2FA. -
9346104: Seguridad.
compileValidationRulesrechaza unpatternvulnerable a ReDoS en vez de compilarlo: lanzaunsafe validation patternal construir el schema, igual que ya lanzabaSyntaxErrorcon 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.validateFormConfiglo reporta comopattern-unsafe, también en lositemFieldsde un repeater. -
6bce012: Seguridad.
pickByPathsignora entero cualquier path con un segmento__proto__,constructoroprototype: un campo llamado__proto__.x(p.ej. desde un schema remoto) escribíaxenObject.prototype. Los paths normales no cambian. -
57494c3: Seguridad.
findClientSecretsdetecta también un token en la query de una URL (?token=,?access_token=,?api_key=,?key=,?sig=…) dehttp.endpoint.url,webhook.urlyoptionsSource.url, conkind: 'url.query',pathterminado en?<parámetro>(nunca el valor) y el nuevo campo opcionalqueryParam;redactClientSecrets(el export TSX del builder) redacta solo el valor del parámetro y deja la URL. Un valor{{campo}}no cuenta, nipageToken/max_tokens; un secreto en el fragmento (#access_token=) no se detecta (FORMS-3-3). Campofile: un fichero que no casa conacceptse rechaza como uno que pasa demaxSize; conuploadAdapterno se sube, y sin él no pasa la validación. Mensaje nuevovalidationFileTypeen los bundles en/es, opcional enFormMessagespara no romper a quien declara el tipo completo (FORMS-UP-2).recaptchaPlugincodifica elsiteKeyen la URL del script (FORMS-3-4). Aditivo: un miembro más en el unionClientSecretKind(unswitchexhaustivo sobre él pide un caso nuevo), un campo opcional enClientSecretHity una clave opcional enFormMessages. -
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). CampofileconuploadAdapter: un fichero por encima demaxSizeya 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.
findClientSecretsdetecta también una credencial en el FRAGMENTO de una URL (#access_token=,#id_token=, un hash-router#/ruta?token=) dehttp.endpoint.url,webhook.urlyoptionsSource.url, con el mismokind: 'url.query',pathterminado en#<parámetro>y el nuevo campo opcionalinFragment: true;redactClientSecretsredacta solo ese valor, en su parte de la URL (FORMS-3-3). Tipos aditivos: un campo opcional más enClientSecretHit. Salida que cambia: un secreto de un hash-router que antes salía como…url?tokensale ahora como…url#token(coninFragment: 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?defno deja cola). -
9b5fe1b:
button-checkbox,checkboxyswitch: elegir o marcar/desmarcar marca el campo como tocado (field.onBlur), como el resto de controles de opción. Convalidation.mode: 'onTouched'(u'onBlur'), el error que pinta Continuar desaparece al elegir. Ybutton-cardde selección única (sinmultiple) compila susValidationRulescomo string, en el cliente y envalidateFormData/resolveFieldSchema:{ required, requiredMessage }pinta su mensaje en vez de «Expected array, received string». Conmultiple: truesigue 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}}enhttp.body.templateywebhook.payloadTemplateya 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. Enemail.customTemplatey en la plantilla por defecto cada valor pasa porescapeHtml. Antes un"cerraba la cadena y"admin":trueentraba en el payload; un<img onerror>llegaba vivo al correo del administrador.Campo
htmlsaneado por defecto (FORMS-6-2). Iba adangerouslySetInnerHTMLsin sanitizar: un autor del workspace ejecutaba JS en el site del cliente. Ahora pasa porsanitizeHtmlsiempre que el config sea datos. El opt-out esFieldBuilder#trustedHtml(), que pone el marcadorTRUSTED_HTML— un objeto que JSON no puede expresar:"trustedHtml": trueen un esquema del Hub o del builder se ignora (con aviso) y se sanea igual.sanitizeHtmlreescrito como allowlist isomorfo. Antes: blocklist sobre el DOM, que sindocument(SSR de<HubForm initialSchema>) degradaba a texto escapado — y React no repara undangerouslySetInnerHTMLdistinto 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 solohttps:(nihttp:ni//host),rel="noopener noreferrer"forzado entarget=_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: unhtmldel Hub constyle=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.apiKeyy las cabeceras de autenticación deoptionsSource/endpoints corren en el navegador y no pueden ser secretos. Nuevo:findClientSecrets(rutas, nunca valores),redactClientSecrets+REDACTED_SECRET, y unconsole.warnuna vez porformIdal 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).
secretqueda deprecado en cliente (no es autenticación; avisa una vez por acción). La cabecera legacyX-Webhook-Signature: sha256=HMAC(payload)no cambia; se añadenX-Webhook-TimestampyX-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 ahttp(s)://absolutas;javascript:,data:y el resto se ignoran con aviso.isSafeRedirectUrlexportado.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, peroHubForm.wrappedSubmitpasa astatus: 'submitted'y esa rama devolvía elsuccessFallbackdel host, desmontando el<Form>entero. Un esquema conwhatsapp.placement: "success"no pintaba nada hiciera lo que hiciera el site: quitar elsuccessFallbacksó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 pasasuccessFallbacky no declarawhatsappen el esquema no cambia en nada.Cambio de comportamiento en
placement: "success": el CTA es ahora un<a href>y no un<Button>conwindow.open. En la pantalla de éxito no hay nada que habilitar (enableWhenno aplica), así que el botón sólo aportaba unwindow.openque 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.classNamese sigue aplicando;cta.variantsó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
resolverya no anula los resolvers de todos los demásuseHiddenFieldResolversresolvía los ocultos con unPromise.allsin red:resolveValue(cfg.resolver)conresolverausente lee.$resolverdeundefined, 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): tieneprecio_mes,viaylocalecomo 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.resolverpasa 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.jsdistintos. 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:// 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óloindex.jscambiaba—. Es el orden de las líneas. Permuta consplitting: truey 16 entries, y no depende del paralelismo:GOMAXPROCS=1sigue dando permutaciones, y quitar la emisión de.d.tstampoco lo estabiliza.Por qué importaba.
size-limitmide brotli, y brotli sí nota el orden: dos permutaciones del mismoindex.jscomprimen 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 buildtermina llamando ascripts/imports-deterministas.mjs, que ordena por nombre de fichero el prefijo contiguo de imports./chunk-*.jsde 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, enindex.jsy en todo el árbol.jsdedist/.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>aceptaactionymethod: mejora progresiva para el envío sin JSDesde 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 conwrangler dev):<form>con 3<input>, 1<textarea>, sus etiquetas y cero «Loading…». Lo que no hace es enviar: el<form>emitido no llevabaaction, 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
FormPropsaceptaactionymethod, y llegan tal cual a través de<HubForm formProps>(que esOmit<FormProps, 'config'>, así que no hizo falta tocarHubForm). Los campos ya llevaban suname, así que el navegador serializa solo.<HubForm siteId="acme" formSlug="contact" initialSchema={schema} formProps={{ components, action: `${hubUrl}/acme/contact/submit`, method: "post", }} />Inerte cuando hay JS.
handleSubmitde react-hook-form llama apreventDefault(), así que una página que funciona sigue enviando por el camino de siempre —fetchconapplication/json, que es el que sabe de adjuntos y captcha. Hay test de eso: se lanza unsubmitcancelable 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íaaction/methoda<Form>sólo si el esquema servido traemeta.nativeSubmit; si no, los tira y el marcado sale byte a byte como antes de que existieran las props. No es burocracia: exigirapplication/jsones 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 unactionque 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
HubFormy no en<Form>a propósito.<Form>recibe unFormConfiggenérico y también sirve formularios que nunca vinieron del Hub (configs de FormBuilder, submits propios);metaes un concepto del Hub, y meterlo en el componente genérico lo ataría a un origen que no conoce.HubFormsí es dueño del esquema — ya leemetapara el captcha.La marca autoriza, no cablea:
HubFormnunca se inventa unaction. 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 mandarapplication/x-www-form-urlencoded, y el endpoint de ingestión del Hub acepta hoy sóloapplication/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
selectpintaba el value crudo en vez de la etiquetaCon
@saastro/[email protected]y primitivos shadcn sobre@base-ui/react, al elegir una opción de un camposelectel trigger enseñabaotroen vez deOtro seguro o consulta. Con Radix no pasaba y por eso no se vio antes:SelectValueheredaba el contenido delSelectItemelegido, así que la etiqueta salía gratis.Base UI no hace eso. La etiqueta del trigger se resuelve desde
itemsen el Root —o desdechildrencomo función enSelect.Value— yrenderSelectFieldno 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:/** 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
itemsconstruido desde las opciones ya resueltas ({ value, label }, con el icono dentro del label comoReactNode, que es lo que se veía con Radix en el trigger).itemsno 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-selectpinta la etiqueta como texto del<option>, ycombobox/commandya resolvían la suya con una búsqueda explícita sobre las opciones. El resto de renderers tampoco dependen de heredar contenido —radio/checkbox-grouppintan{opt.label}, las fechas formatean el valor en el trigger y el slider compone su propio display.
0.20.0
Minor Changes
-
e970323:
computedacepta una expresión serializable, y el servidor la recalculaHasta ahora
computedera{ dependsOn, compute }, ycomputees 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 campohiddenque rellena el NAVEGADOR — es decir, un dato de negocio que cualquiera puede reescribir antes de enviarlo:precio_mes: 0.01y el formulario lo acepta encantado.computedadmite ahora una segunda forma,{ $expr }, que es JSON puro: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,
$fieldreferencia a otro campo,$ophace+ - * /,$roundredondea y$ifbifurca. El test de un$ifes unConditionGroupde los de siempre —los mismos que ya usan la visibilidad condicional y las reglas cross-field— o un$cmpnumérico.Y lo importante: el servidor recalcula y gana.
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`applyComputedFieldssale 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 devalidateFormDataa 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, porque5 + (conductor ? 1.5 : 0)no mencionaconductoren 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 + dtove elmesde ESTA pasada y no el de la anterior. $cmpexiste por un motivo concreto. Las comparaciones numéricas deConditionGroupoperan sobre el valor CRUDO: contra un campo de texto donde el usuario escribió «1.234,56» eso esNaN > 0→ false, y una guarda del tipo «solo si la prima es positiva» se la come el silencio.$cmppasa 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.evaluateExpressionNUNCA devuelveNaNniInfinity. FieldBuilderestrena.computed(), yFormBuilder.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 eldefaultValuey las escrituras siguen siendoshouldDirty: false. Cambian dos comportamientos, los dos a mejor: un campo concomputedahora 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 uncomputelegacy encadenado ve los valores de aguas arriba ya frescos en vez de los de la pasada anterior. - 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
-
e970323: El campo
htmlinterpola{{campo}}con los valores del formularioEl campo
htmlera 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
htmladmite{{tokens}}, resueltos con los valores en vivo y repintados al cambiar:{ 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», noreparto.Sobre la seguridad, que aquí es todo el problema. El campo
htmles 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 undangerouslySetInnerHTML. 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
htmlcuyo contenido contiene{{. Unhtmlestá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, no6,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
htmlsin{{se comporta exactamente igual que en 0.19. - Solo se suscriben a los valores los
0.19.0
Minor Changes
-
36d3650:
HubFormaceptainitialSchema: el formulario se pinta en el primer render, sin esperar al efectoLa descarga del esquema vive en un
useEffect, y unuseEffectno 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: 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
initialSchemapresente no se hace ningún fetch: el primer render ya esready, 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 mismoisRenderableSchemaque la ruta de fetch — un esquema vacío daunconfiguredigual que antes. nullsignifica «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/formSlugdespué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.ioexigecontent-type: application/jsony responde 415 a un POST de formulario nativo. Lo que se arregla aquí es que el formulario exista en el HTML. - El valor es exactamente lo que devuelve
0.18.0
Minor Changes
-
8652204: BREAKING: la librería pasa a hablar la API de Base UI, no la de Radix.
@saastro/formsno 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"encomponents.json, o cualquier estilo sin prefijoradix-/aria-).Para seguir en Radix, fija
@saastro/formsen0.17.x.Cambios en el contrato (
ComponentRegistry):- Accordion — desaparecen
typeycollapsible.value/defaultValueson ahora arrays yonValueChangerecibe un array.multiplesustituye atype="multiple"; el colapso libre es el comportamiento por defecto. - Select —
valueaceptastring | null. Base UI modela “sin selección” comonull, no comoundefinedni''. - Slider —
value/defaultValueaceptannumber | number[]; con un solo thumb Base UI emite un número plano. NuevoonValueCommitted. - PopoverTrigger / TooltipTrigger / DialogTrigger —
asChildse sustituye porrender(el elemento a renderizar) ynativeButton. - PopoverContent — acepta además
side,sideOffsetyalignOffset, que el wrapper de shadcn reenvía alPositionerde 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 dechecked).
Interno: el combobox usaba la variable CSS
--radix-popover-trigger-width, que en Base UI es--anchor-width. - Accordion — desaparecen
0.17.0
Minor Changes
-
856a5a5: CTA de WhatsApp:
onSteps: 'all'para pintarlo en todos los pasosHasta 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 aplacement: '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.enableWhenis 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 inRef: /.onWhatsappClickplugin hook, fired just before the link opens, with{ formId, url, placement }.analyticsPluginimplements it as aform_whatsapp_clickgtag event. Note the hard limit this works around:wa.meis 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 hostedHubForm— turns it on without touching code.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), optionalmessage,enableWhen,label,hint,variant,className. Builder:.whatsapp(config);build()rejects a number under 8 digits and an unknownenableWhen.- Message. With no
messagethe CTA sends an auto-summary —Label: value, one line per filled field, option labels (not values) forselect-likes, comma-joined multi-selects, locale-formatted dates, a localized “Yes” for checked boxes, and one bullet per item for repeaters. Amessagetemplate 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 makeanyFilledtrue before the user typed), themustBeTrueconsent checkbox, empty values,file/signature, buttons andhtml. Per-field opt-out:.whatsapp(false). enableWhen:'anyFilled'(default) or'valid'.'valid'relies on RHF’sformState.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 awhatsappblock 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/whatsappinstead of the root barrel.
Also: raised the
size-limitceiling 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; withoutthen.field→ root error). Enforced identically client-side (composed into the resolver viaz.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 byidvia locale overlays.FormBuilder.crossFieldRule(s)()with reference validation atbuild(). (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/getLiveDirtyFieldsover RHF’sdirtyFieldsmirror (machine writes viashouldDirty: false— computed fields, hidden resolvers — stay excluded).FormRefgainsgetDirtyValues()/getDirtyPaths()/isDirty(). Plugins receive an optional 4thonFieldChangeargumentFieldChangeMeta { formId, getDirtyPaths(), getDirtyValues() }with lazy getters (3-param plugins remain valid).autosavePlugingainspayload: 'dirty'(PATCH-friendly{ formId, dirtyPaths, values }body, skips the POST when clean; default'all'is byte-identical to before).localStoragePluginnow keys writes by the per-eventformId(fixes last-mounted-wins on writes) and skips pristine writes.<Form>mounts a null-rendering formState subscriber so RHF actually computesdirtyFields(headless users: mountuseFormFlags). - 321b21e: Form state flags and granular reset: new
useFormFlags(methods)selector hook (isolated RHFformStatesubscription —isDirty,isValidating,dirtyFields,touchedFieldswithout subscribing the whole form),isSubmittingalias +resetSubmitState()onuseFormState’s return, andFormRef.resetForm(options?)— a granular reset mapping to RHFKeepStateOptionsthat also clears the package’s bespoke submit state (success screen / error / submit-actions result) unlesskeepSubmitState: true. The rawFormRef.resetis 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 fieldtype; 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 requiremoduleResolution: 'bundler' | 'node16' | 'nodenext'(same as the existing/validationsubpath). - 2704f0b: Repeater first-class. Behavioral change: repeater
minItems/maxItemsand item-field rules are now enforced on submit — client AND server (@saastro/forms/validation); opt out per field with an explicitschema: z.any(). New generated array schema (buildRepeaterSchema, exported): per-item validation fromitemFields(passthrough — unvalidated sub-field values survive the parse; nested repeaters recurse),.min()/.max()with i18n messages (validationMinItems/validationMaxItems+ per-fieldminItemsMessage/maxItemsMessage),minItemsdefault pre-population on mount. Opt-in reordering:reorderableprop /.reorderable()builder method renders per-item move up/down buttons (moves values via RHFmove). 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.validationoption ({ mode, revalidateMode, delayError }, mapping 1:1 to react-hook-form’smode/reValidateMode/delayError) plus aFormBuilder.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:revalidateModeonly affects headless flows drivingmethods.handleSubmitthemselves; the standard<Form>submit path validates via per-steptrigger(), which never marks the RHF-levelisSubmitted. The form builder exposes the mode under Form Settings → Validation Timing.
0.14.1
Patch Changes
- ad05590:
createHubFormSubmitnow attaches the SAASTRO Gen visitor id (gen_visitor_id, read fromsessionStorage['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 explicitgen_visitor_idfield 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), andidentityDeclaration(a required must-be-true confirmation). Each ships serializable validators and bundledestranslations (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, andprojectDetails. Each ships serializable validators and bundledestranslations, 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/switchcontrol 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.showTimeanddate.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 +valuedays.showTime: truerenders a time input next to the calendar (single-date types) and folds the chosen hour/minute into theDatevalue; 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 ondaterange. -
429f692: Add
@saastro/forms/library— a curatedFIELD_LIBRARYof 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
./librarysubpath (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
orderactually apply (closes the v1.0 #37 no-op cleanup).Two bugs kept
orderfrom working:getFieldClassearly-returnedcol-span-1when a field had nocolumns, skipping theorderblock entirely — soorder(and evenlayout.order) only took effect whencolumnswas also set.Form.tsxonly fell back to the top-levelcolumnsshortcut, never the top-levelordershortcut (the mirror ofcolumns).
Both are fixed:
ordernow applies on its own, with or withoutcolumns, in manual layout mode (auto-fit grids still ignore per-field span/order by design). Removed the now-emptyNOOP_FIELD_PROPSdev-warning machinery (orderwas 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 oneradiogroupper row for accessibility. Wired through the type union,FIELD_REGISTRY(builder palette), and test-data generation. Additive. -
ad40dae: Add a
phonefield 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’scountriesprop;defaultCountrysets 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 theCountrytype. Additive. -
3336970: Breaking: remove the no-op
gridSpanfield prop. It never had a runtime effect — field column span is driven bycolumns/layout.columns, which is unchanged. Configs that setgridSpanshould usecolumnsinstead (the form-builder already writescolumns).Shipped as a 0.x minor (per semver,
0.xminors may carry breaking changes) to keep the package on 0.x — not promoting to 1.0 yet. -
165bfec: Add a
signaturefield type — free-hand drawing on a native<canvas>, stored as a PNG data URL. Includes a “Clear” control (i18n:signatureClear) and apenColor/heightconfig.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_modulesand aren’t scanned). Following thesignaturefield’s pattern,rating,phone,file,matrixand thedateshow-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:hoveraffordances on a couple of controls are dropped (not expressible inline).
0.12.0
Minor Changes
- 6ab46c5: Add a
ratingfield type — a star rating whose value is an integer1..max(defaultmax5). It’s self-contained (native buttons + a lucideStar, no extra DI component beyond the base wrapper every form already provides), renders withradiogroup/radiosemantics 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:loadOptionsnow receives the search term, andoptionsSourcegains asearchParamthat 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 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. Theschematype and theSchemaTypealias are widened toz.ZodType | ValidationRules | StandardSchemaV1(additive — existing Zod/ValidationRules schemas are unchanged; Zod schemas keep the native path). New exports:isStandardSchema,standardSchemaToZod, and theStandardSchemaV1type. Standard Schemas are code-only, so the isomorphicvalidateFormDataskips them server-side (serializable configs carry ValidationRules). - 7982b93: Add a generic file-upload adapter. A
filefield can take anuploadAdapter: selected files are uploaded on change (with a progress bar) and the field value becomes the adapter’sUploadResult(e.g.{ key }/{ url }) instead of the rawFile.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, theuseFileUploadhook, and theUploadAdapter/UploadResulttypes. Additive — without an adapter the file field keeps its current behaviour (stores rawFiles, uploaded on submit).
0.11.0
Minor Changes
- 353b604: Add a
@saastro/forms/validationsubpath export — a lean, React-free entry exposing the validation API (validateFormData,buildFormSchema,resolveFieldSchema,compileValidationRules, the type guards and presets). Its only runtime dependency iszod, 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, andnative-select. A new optionalloadOptionsfield (and.loadOptions(loader)builder method) accepts an async function that resolves the field’s options; it runs once on mount, shows the staticoptionsarray as a fallback while loading (and disables the control), and keeps the fallback if the loader rejects. Fully additive — existing static-optionsconfigs are unchanged.loadOptionsis 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), andresolveFieldSchema(fieldConfig)validate a submission against a form config anywhere — React-free — reusing the sameValidationRules → Zodcompiler the browser runs, so a form’s rules are enforced identically on the client and on the server (e.g. the submit Worker).validateFormDatareturns{ success, data?, errors? }with per-field error messages; unknown keys (hidden fields, server-injected geo/IP) are stripped, not rejected; files/repeaters resolve toz.any()and plugin validators are client-only.buildRequiredOnlySchemamoved to the React-freevalidation/module (still re-exported, no change for consumers). - 41cf1d7: Add a serializable URL source for async options:
optionsSource(and.optionsSource(src)) onselect/combobox/native-select. UnlikeloadOptions(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), navigatespath, and maps each item vialabelKey/valueKey(defaultlabel/value), reusing the existinguseAsyncOptionsmachinery. If bothloadOptionsandoptionsSourceare set,loadOptionswins. Additive — no behaviour change for existing configs.
Patch Changes
- 7aba454: CLI: replace two mid-function
process.exit(0)calls ininstall-deps(running inside the package itself, and nocomponents.jsonfound) with gracefulreturns. Behaviour is unchanged for the CLI (the script still ends with exit 0), but it no longer hard-kills the process — safer wheninstall-depsruns as a postinstall hook. Completes the CLI cleanup; theaddredirect, English messages, and components.json alias resolution were already in place. - 769c71d: Mark the no-op
gridSpanfield prop as@deprecatedin the types. It has never had a runtime effect (layout is driven bycolumns/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(allutm_*as an object),clickId(first present gclid/fbclid/msclkid…),landingPageandfirstReferrer(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).
resolveValuenow delegates all sync resolvers toresolveValueSync(single source of truth;ip/customstay async).BUILTIN_RESOLVERSlists 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. - Marketing attribution:
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 (
thiswasundefined) andonFormInitreceives the bareFormConfig(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{}) continueOnErroron submit actions is honored (any failure used to abort the submit)submitExecution.globalTimeoutis now implemented (was silently ignored)- reCAPTCHA script polling and token fetch have 10s timeouts (misconfigured keys used to hang the submit forever)
iphidden-field resolver has a 5s fetch timeout;customresolvers are error-bounded- autosave plugin keeps its debounce timer per instance (was on
window, colliding across forms) - databowl
staticFieldsno 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.maxSizeis now enforced client-side via validationFormBuilder.layoutClassName()is applied to the grid (was stored and ignored)FieldBuilder.schema()acceptsValidationRulesobjects in its signature (runtime already did)- Standard layout forms now pass
pluginManagerto fields (plugin custom fields only worked in the inline-buttons layout) StepsNavigationacceptsonBeforeNavigateto 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. Thehtmlfield 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 (
componentsDI registry,shouldDisable/shouldReadOnlyevaluated,renderLabel/renderFieldIcon) —CustomFieldPropsexported FieldWrapperis exported: custom fields get label/error/helper scaffolding for freeFieldBuilder.type()accepts custom type strings; new.prop(key, value)escape hatch;build()doesn’t require a schema for custom typesCustomFieldConfig/AnyFieldConfigtypes;Fieldsaccepts custom configs without castsdefaultValueis honored when seeding form defaults (the builder method existed but was ignored)button-cardsupportscardLayout: 'vertical'(icon above text — logo pickers)@saastro/forms/styles.cssships selected-state styles via CSS variables (no Tailwind compilation of node_modules needed)
Deprecation warnings (dev-only):
date.showTime,date.presets,gridSpan, and top-levelorderare declared in types but not implemented — they now warn once in development and will be implemented or removed in v1.0. - Plugin hooks are now invoked bound to their plugin (
-
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 thecreateHubFormSubmitpipeline (presigned uploads, captcha conventions) as a composable submit action.localeDetectorPlugin()— activatesconfig.localefromnavigator.languagewhen a matching translation overlay exists.
i18n:
- New
useMessages()hook (reactive — re-renders onsetDefaultMessages); the steps UI components use it - Validation fallback messages (“This field is required”, “You must accept this”, file max-size) moved into the
FormMessagescatalog (translated in the bundledeslocale)
Hardening:
recaptchaPlugingainsfailMode('open'default preserves historical behavior;'closed'fails the submit like turnstile)- Plugin
transformValueserrors now ABORT the submit (a throwing captcha plugin no longer ships a tokenless submission);executeHookkeeps per-plugin isolation but propagates errors, restoring theonBeforeSubmitveto contract - localStorage plugin: debounced writes (300ms), pending saves cancelled on submit, ISO date strings rehydrated to
Dateon 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: falseresults (honoringcontinueOnError) instead of crashing the pipeline requiredsingle-selectbutton-cardvalidates correctly; option-less selection fields render safely
Removed / behavior changes:
- The deprecated
useRecaptchahook is removed — userecaptchaPlugin(). The legacyconfig.submit.recaptchapath 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
submitConfirmationno 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-radioand single-selectbutton-cardrenderrole="radiogroup"withrole="radio"/aria-checkedbuttons;button-checkbox, multi-selectbutton-card,checkbox-groupandswitch-grouprenderrole="group"(+aria-pressedwhere 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-digitaria-labels; file inputs setaria-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 singleFormMessagessource — 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):
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
enandeslocales ship via the new@saastro/forms/localessubpath; per-formlocale/i18noverlays 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_REGISTRYexport: 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 gainsfile+repeater) - New
FORM_SCHEMA_VERSIONexport — 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 onshouldHidebefore 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.i18noverlay ({ defaultLocale, locales, translations }) andFormConfig.locale. The base config holds the default-language strings; eachtranslations[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 inuseFormState— whenconfig.localeis set, the overlay is merged before rendering, so no renderer changes are needed.useFormStatenow also returns the locale-resolvedconfig, andFormrenders fields/buttons/steps from it (previously it rendered from the raw prop, so translated labels never showed). HubFormgains alocaleprop (pass the host page’s active language).Steptype gainstitle/description(already written by the builder).
The visual form-builder gains a Translations panel (author per-language strings) and a preview language switcher.
- New
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 theHubForminline 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.
- The widget container is marked
0.6.1
Patch Changes
-
bab9b68: Fix: enforce top-level
requiredon fields without an explicitschema.useFormStateonly built validation fromfield.schema, so a field withrequired: trueat the top level (the flag the builder sets, which drives the asterisk + nativerequiredattribute) but no explicitschemaskipped validation entirely — empty submissions passed. Now a top-levelrequired: trueadds 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 explicitschema/ValidationRules.
0.6.0
Minor Changes
- fa30852: Add Cloudflare Turnstile support.
- New
turnstilePlugin({ siteKey })— mirrorsrecaptchaPlugin, renders the Turnstile widget (explicit +execution: 'execute', interaction-only by default) and attaches the token to submissions as_captchaToken. HubFormnow auto-wires the captcha plugin when the served schema declaresmeta.captchaProvider(turnstileorrecaptcha-v3) +meta.captchaSiteKey. Host apps need no extra setup — captcha just works. Both providers write the token to_captchaToken(the fieldcreateHubFormSubmitforwards ascaptchaToken).
- New
0.5.0
Minor Changes
-
e3c842f: Removed starter templates from the package.
TEMPLATES,TEMPLATE_META,TemplateId,TemplateMeta, and the fivecreate*Templatefactories (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-builderapp, where they belong (visible to standalone users offorms.saastro.iotoo). 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/[email protected].// 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/v1The Saastro Hub Forms public API was split out of the monolithic
hub.saastro.ioworker into a dedicated Cloudflare Worker atsubmit.saastro.io/v1/*. This is the canonical endpoint going forward — independent scaling, latency, and deploy cadence from the dashboard.Bump type
minorinstead ofmajorbecause 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.hubUrlandCreateHubFormSubmitOptions.hubUrlare 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_URLfor callers that need to reference the canonical base. - Captcha token now sent as
captchaToken(canonical, multi-provider). Legacy_turnstilefield name is still accepted by the SDK and forwarded; the worker accepts bothcaptchaTokenandturnstileshapes 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.- <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).- <HubForm hubUrl="https://hub.example.com" ... /> + <HubForm hubUrl="https://submit.example.com/v1" ... /> -
Captcha field name: if you were passing
_turnstileas the hidden field name in form values, it still works. New code should prefer_captchaTokenfor clarity (the schema now supports both Turnstile AND reCAPTCHA v3 viameta.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
TEMPLATESregistry.Importable factories return fresh
FormConfigobjects so callers can safely mutate the result:import { createContactTemplate, TEMPLATES, TEMPLATE_META, } from "@saastro/forms"; const config = createContactTemplate(); // direct factory const config2 = TEMPLATES.newsletter(); // dynamic dispatch const choices = TEMPLATE_META; // for pickersTemplates:
- 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
ValidationRulesAPI so they serialize cleanly to JSON (Hub-storable) and compile to Zod schemas at runtime viacompileValidationRules.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-depsnow 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 appropriateaddcommand for any of these peer deps that are missing from the consumer’spackage.json:zod@^4react-hook-form@^7react-day-picker@^9date-fns@^4
A fresh React or Astro project can now go from zero to a working form with three commands:
npm install @saastro/forms npx @saastro/forms init npx @saastro/forms install-depsreactandreact-domare 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
unconfiguredstate. 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 newunconfiguredFallbackprop. - Adds
onSuccess(values)andonError(error)props, called after the submission either succeeds or fails. Mirrors the existing FormConfig callbacks so existing patterns transfer. - Adds a
successFallbackprop and a built-in “Thanks — we’ll get back to you soon” panel rendered after a successful submission. PasssuccessFallback={null}to render nothing (useful if the host page controls the after-submit UX viaonSuccess).
Non-breaking: existing
<HubForm>callsites keep their behavior. The inner<Form>is still rendered for valid schemas. - Adds an
-
412672a: Allow consumers to use
zod@3orzod@4.The
zodpeerDependency is now^3.25.0 || ^4.0.0(previously only^3.25.76). Sub-dependency@hookform/resolvers@^5imports fromzod/v4/core, which made esbuild crash duringoptimizeDepsin consumer Vite/Astro setups that installedzod@4directly. Both versions are now accepted at the peer-range level.Local builds of
@saastro/formsare pinned againstzod@^3.25until@hookform/resolversloosens its v4 type pin (it currently expects zod4.0.xspecifically). 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 inbuilder.saastro.io(Hub embed mode) and want to submit back to Hub without writing the upload-URL flow by hand.Also extends
SubmitActionTypewith'integration'and adds theIntegrationSubmitActioninterface (declarative reference to asite_integrationsrow 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