@coherent.js/forms 1.1.2 → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,6 +8,476 @@ function isEmailShaped(value) {
8
8
  return typeof value === "string" && value.length <= EMAIL_MAX_LENGTH && EMAIL_PATTERN.test(value);
9
9
  }
10
10
 
11
+ // src/rules.js
12
+ var BUILTIN = /* @__PURE__ */ Symbol("coherent.forms.builtin");
13
+ var DESCRIPTORS = /* @__PURE__ */ new WeakMap();
14
+ var HELPER_NAMES = /* @__PURE__ */ new Set(["get", "compose", "debounce", "cancellable", "when", "chain"]);
15
+ var isEmpty = (value) => value === null || value === void 0 || value === "";
16
+ var isOptionsObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof RegExp);
17
+ function argsFromString(params, kind, text) {
18
+ if (text === void 0 || text.trim() === "") return [];
19
+ if (params.length === 0) return [text.trim()];
20
+ if (kind === "list") {
21
+ return [text.split(",").map((part) => part.trim()).filter(Boolean)];
22
+ }
23
+ if (kind === "regexp") {
24
+ try {
25
+ return [new RegExp(text)];
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+ const comma = text.indexOf(",");
31
+ const raw = (comma === -1 ? text : text.slice(0, comma)).trim();
32
+ const message = comma === -1 ? "" : text.slice(comma + 1).trim();
33
+ let arg = raw;
34
+ if (kind === "number") {
35
+ arg = Number(raw);
36
+ if (raw === "" || Number.isNaN(arg)) return null;
37
+ }
38
+ return message ? [arg, message] : [arg];
39
+ }
40
+ function defineRule(name, { params = [], stringArg = "string", valid, message }) {
41
+ const fromOptions = (options = {}) => {
42
+ const config = { message: options.message };
43
+ for (const [key, ...aliases] of params) {
44
+ config[key] = [key, ...aliases].map((alias) => options[alias]).find((v) => v !== void 0);
45
+ }
46
+ return config;
47
+ };
48
+ const check = (value, config, formData) => {
49
+ if (valid(value, config, formData || {})) return null;
50
+ return config.message || builtin.message || message(config);
51
+ };
52
+ const factory = (...args) => {
53
+ const config = { message: args[params.length] };
54
+ params.forEach(([key], index) => {
55
+ config[key] = args[index];
56
+ });
57
+ const rule = (value, formData, _translator, allValues) => check(value, config, allValues ?? formData);
58
+ DESCRIPTORS.set(rule, { name, args });
59
+ return rule;
60
+ };
61
+ const isDirectCall = (args) => {
62
+ if (args.length >= 2) {
63
+ return params.length === 0 || isOptionsObject(args[1]);
64
+ }
65
+ if (args.length === 1 && params.length === 0) {
66
+ const [arg] = args;
67
+ return arg === "" || arg !== void 0 && arg !== null && typeof arg !== "string";
68
+ }
69
+ return false;
70
+ };
71
+ function builtin(...args) {
72
+ if (isDirectCall(args)) {
73
+ const [value, options, , allValues] = args;
74
+ return check(value, fromOptions(isOptionsObject(options) ? options : {}), allValues);
75
+ }
76
+ return factory(...args);
77
+ }
78
+ Object.defineProperty(builtin, "name", { value: name });
79
+ builtin[BUILTIN] = {
80
+ name,
81
+ factory,
82
+ argsFromString: (text) => argsFromString(params, stringArg, text)
83
+ };
84
+ return builtin;
85
+ }
86
+ var toNumber = (value) => typeof value === "number" ? value : Number(value);
87
+ function testRegExp(regex, value) {
88
+ if (!(regex instanceof RegExp)) return true;
89
+ regex.lastIndex = 0;
90
+ return regex.test(String(value));
91
+ }
92
+ function fileMatchesType(file, allowedTypes) {
93
+ const fileType = file.type;
94
+ const fileExt = file.name ? file.name.split(".").pop().toLowerCase() : "";
95
+ return allowedTypes.some((type) => {
96
+ if (type.startsWith(".")) {
97
+ return fileExt === type.slice(1).toLowerCase();
98
+ }
99
+ if (type.includes("/")) {
100
+ if (type.endsWith("/*")) {
101
+ return fileType.startsWith(type.replace("/*", "/"));
102
+ }
103
+ return fileType === type;
104
+ }
105
+ return fileExt === type.toLowerCase();
106
+ });
107
+ }
108
+ var validators = {
109
+ required: defineRule("required", {
110
+ valid: (value) => !isEmpty(value),
111
+ message: () => "This field is required"
112
+ }),
113
+ email: defineRule("email", {
114
+ valid: (value) => isEmpty(value) || isEmailShaped(value),
115
+ message: () => "Invalid email address"
116
+ }),
117
+ url: defineRule("url", {
118
+ valid: (value) => {
119
+ if (isEmpty(value)) return true;
120
+ try {
121
+ new URL(value);
122
+ return true;
123
+ } catch {
124
+ return false;
125
+ }
126
+ },
127
+ message: () => "Invalid URL"
128
+ }),
129
+ minLength: defineRule("minLength", {
130
+ params: [["min", "minLength"]],
131
+ stringArg: "number",
132
+ valid: (value, { min }) => !value || !(value.length < (min ?? 0)),
133
+ message: ({ min }) => `Minimum length is ${min}`
134
+ }),
135
+ maxLength: defineRule("maxLength", {
136
+ params: [["max", "maxLength"]],
137
+ stringArg: "number",
138
+ valid: (value, { max }) => !value || !(value.length > (max ?? Infinity)),
139
+ message: ({ max }) => `Maximum length is ${max}`
140
+ }),
141
+ // Empty values pass (combine with `required`); a non-numeric value fails.
142
+ min: defineRule("min", {
143
+ params: [["min"]],
144
+ stringArg: "number",
145
+ valid: (value, { min }) => {
146
+ if (isEmpty(value)) return true;
147
+ const number = toNumber(value);
148
+ return !Number.isNaN(number) && !(number < (min ?? -Infinity));
149
+ },
150
+ message: ({ min }) => `Minimum value is ${min}`
151
+ }),
152
+ max: defineRule("max", {
153
+ params: [["max"]],
154
+ stringArg: "number",
155
+ valid: (value, { max }) => {
156
+ if (isEmpty(value)) return true;
157
+ const number = toNumber(value);
158
+ return !Number.isNaN(number) && !(number > (max ?? Infinity));
159
+ },
160
+ message: ({ max }) => `Maximum value is ${max}`
161
+ }),
162
+ pattern: defineRule("pattern", {
163
+ params: [["pattern", "regex"]],
164
+ stringArg: "regexp",
165
+ valid: (value, { pattern }) => isEmpty(value) || testRegExp(pattern, value),
166
+ message: () => "Invalid format"
167
+ }),
168
+ /** Equal to another field, even when empty */
169
+ matches: defineRule("matches", {
170
+ params: [["field", "fieldName"]],
171
+ valid: (value, { field }, formData) => value === formData[field],
172
+ message: () => "Fields do not match"
173
+ }),
174
+ /** Equal to another field; an empty value passes */
175
+ match: defineRule("match", {
176
+ params: [["field", "fieldName"]],
177
+ valid: (value, { field }, formData) => !value || value === formData[field],
178
+ message: ({ field }) => `Must match ${field}`
179
+ }),
180
+ oneOf: defineRule("oneOf", {
181
+ params: [["options", "values"]],
182
+ stringArg: "list",
183
+ valid: (value, { options }) => !value || !Array.isArray(options) || options.includes(value),
184
+ message: () => "Invalid option"
185
+ }),
186
+ custom: defineRule("custom", {
187
+ params: [["validator", "fn"]],
188
+ valid: (value, { validator }, formData) => typeof validator !== "function" || Boolean(validator(value, formData)),
189
+ message: () => "Validation failed"
190
+ }),
191
+ number: defineRule("number", {
192
+ valid: (value) => isEmpty(value) || !Number.isNaN(Number(value)),
193
+ message: () => "Must be a valid number"
194
+ }),
195
+ integer: defineRule("integer", {
196
+ valid: (value) => isEmpty(value) || Number.isInteger(Number(value)),
197
+ message: () => "Must be a whole number"
198
+ }),
199
+ phone: defineRule("phone", {
200
+ valid: (value) => !value || /^[\d\s\-+()]+$/.test(value) && value.replace(/\D/g, "").length >= 10,
201
+ message: () => "Please enter a valid phone number"
202
+ }),
203
+ date: defineRule("date", {
204
+ valid: (value) => !value || !Number.isNaN(new Date(value).getTime()),
205
+ message: () => "Please enter a valid date"
206
+ }),
207
+ alpha: defineRule("alpha", {
208
+ valid: (value) => !value || /^[a-zA-Z]+$/.test(value),
209
+ message: () => "Must contain only letters"
210
+ }),
211
+ alphanumeric: defineRule("alphanumeric", {
212
+ valid: (value) => !value || /^[a-zA-Z0-9]+$/.test(value),
213
+ message: () => "Must contain only letters and numbers"
214
+ }),
215
+ uppercase: defineRule("uppercase", {
216
+ valid: (value) => !value || value === String(value).toUpperCase(),
217
+ message: () => "Must be uppercase"
218
+ }),
219
+ fileType: defineRule("fileType", {
220
+ params: [["accept", "types"]],
221
+ stringArg: "list",
222
+ valid: (value, { accept }) => !value || value.type === void 0 || fileMatchesType(value, accept || []),
223
+ message: ({ accept }) => `File type must be one of: ${(accept || []).join(", ")}`
224
+ }),
225
+ fileSize: defineRule("fileSize", {
226
+ params: [["maxSize"]],
227
+ stringArg: "number",
228
+ valid: (value, { maxSize }) => !value || value.size === void 0 || !(value.size > (maxSize ?? Infinity)),
229
+ message: ({ maxSize }) => `File size must be less than ${((maxSize ?? Infinity) / (1024 * 1024)).toFixed(2)}MB`
230
+ }),
231
+ fileExtension: defineRule("fileExtension", {
232
+ params: [["extensions"]],
233
+ stringArg: "list",
234
+ valid: (value, { extensions }) => {
235
+ if (!value) return true;
236
+ const fileName = value.name || value;
237
+ const ext = `.${String(fileName).split(".").pop().toLowerCase()}`;
238
+ return (extensions || []).some((allowed) => ext === allowed.toLowerCase());
239
+ },
240
+ message: ({ extensions }) => `File extension must be one of: ${(extensions || []).join(", ")}`
241
+ }),
242
+ /** A registered validator or built-in by name */
243
+ get: (name) => Object.hasOwn(validators, name) ? validators[name] : void 0,
244
+ /** Combine validators into one returning the first error */
245
+ compose: (validatorList) => {
246
+ const rules = validatorList.map(resolveValidator);
247
+ return (value, options, translator, allValues) => {
248
+ for (const rule of rules) {
249
+ const error = rule ? rule(value, options, translator, allValues) : null;
250
+ if (error) {
251
+ return error;
252
+ }
253
+ }
254
+ return null;
255
+ };
256
+ },
257
+ /** Debounce an async validator */
258
+ debounce: (validator, delay = 300) => {
259
+ let timeoutId;
260
+ return (value) => {
261
+ return new Promise((resolve) => {
262
+ clearTimeout(timeoutId);
263
+ timeoutId = setTimeout(async () => {
264
+ const result = await validator(value);
265
+ resolve(result);
266
+ }, delay);
267
+ });
268
+ };
269
+ },
270
+ /** Cancellable async validator */
271
+ cancellable: (validator) => {
272
+ let abortController;
273
+ const wrapped = async (value) => {
274
+ if (abortController) {
275
+ abortController.abort();
276
+ }
277
+ abortController = typeof AbortController !== "undefined" ? new AbortController() : null;
278
+ try {
279
+ return await validator(value, abortController ? abortController.signal : null);
280
+ } catch (error) {
281
+ if (error.name === "AbortError") {
282
+ return null;
283
+ }
284
+ throw error;
285
+ }
286
+ };
287
+ wrapped.cancel = () => {
288
+ if (abortController) {
289
+ abortController.abort();
290
+ }
291
+ };
292
+ return wrapped;
293
+ },
294
+ /** Run `validator` only when `condition` holds */
295
+ when: (condition, validator) => {
296
+ const rule = resolveValidator(validator);
297
+ return (value, options = {}, translator, allValues = {}) => {
298
+ const context = options.min !== void 0 || options.max !== void 0 ? allValues : options;
299
+ const shouldValidate = typeof condition === "function" ? condition(value, context) : condition;
300
+ if (!shouldValidate) {
301
+ return null;
302
+ }
303
+ return rule ? rule(value, options, translator, allValues) : null;
304
+ };
305
+ },
306
+ /** Validator chain builder */
307
+ chain: (options = {}) => {
308
+ const validatorList = [];
309
+ const stopOnFirstError = options.stopOnFirstError !== false;
310
+ const direct = (name) => (opts) => {
311
+ validatorList.push((v, o, t, a) => validators[name](v, opts || o || {}, t, a));
312
+ return chain;
313
+ };
314
+ const chain = {
315
+ required: direct("required"),
316
+ email: direct("email"),
317
+ minLength: direct("minLength"),
318
+ maxLength: direct("maxLength"),
319
+ custom: (fn, message) => {
320
+ validatorList.push((v, o, t, a) => {
321
+ const result = fn(v, a);
322
+ return result === null || result === true || result === void 0 ? null : message || result;
323
+ });
324
+ return chain;
325
+ },
326
+ validate: (value, opts, translator, allValues) => {
327
+ if (stopOnFirstError) {
328
+ for (const validator of validatorList) {
329
+ const error = validator(value, opts, translator, allValues);
330
+ if (error) {
331
+ return error;
332
+ }
333
+ }
334
+ return null;
335
+ }
336
+ const errors = [];
337
+ for (const validator of validatorList) {
338
+ const error = validator(value, opts, translator, allValues);
339
+ if (error) {
340
+ errors.push(error);
341
+ }
342
+ }
343
+ return errors.length > 0 ? errors : null;
344
+ }
345
+ };
346
+ return chain;
347
+ }
348
+ };
349
+ function lookup(name) {
350
+ const found = Object.hasOwn(validators, name) && !HELPER_NAMES.has(name) ? validators[name] : null;
351
+ return typeof found === "function" ? found : null;
352
+ }
353
+ function resolveString(entry) {
354
+ const exact = lookup(entry);
355
+ const colon = exact ? -1 : entry.indexOf(":");
356
+ const name = colon === -1 ? entry : entry.slice(0, colon).trim();
357
+ const found = exact ?? lookup(name);
358
+ if (!found) return null;
359
+ const text = colon === -1 ? void 0 : entry.slice(colon + 1);
360
+ if (!found[BUILTIN]) {
361
+ return text === void 0 ? { name, args: [], validator: found } : null;
362
+ }
363
+ const args = found[BUILTIN].argsFromString(text);
364
+ if (!args) return null;
365
+ return { name: found[BUILTIN].name, args, validator: found[BUILTIN].factory(...args) };
366
+ }
367
+ function resolveValidator(entry) {
368
+ if (typeof entry === "string") {
369
+ return resolveString(entry)?.validator ?? null;
370
+ }
371
+ if (typeof entry !== "function") return null;
372
+ return entry[BUILTIN] ? entry[BUILTIN].factory() : entry;
373
+ }
374
+ function validateField(value, validatorList, formData = {}) {
375
+ const list = Array.isArray(validatorList) ? validatorList : [validatorList];
376
+ for (const entry of list) {
377
+ const validator = resolveValidator(entry);
378
+ const error = validator ? validator(value, formData) : null;
379
+ if (error) {
380
+ return error;
381
+ }
382
+ }
383
+ return null;
384
+ }
385
+ function validateForm(formData, fieldValidators) {
386
+ const errors = {};
387
+ for (const [fieldName, validatorList] of Object.entries(fieldValidators)) {
388
+ const value = formData[fieldName];
389
+ const error = validateField(value, validatorList, formData);
390
+ if (error) {
391
+ errors[fieldName] = error;
392
+ }
393
+ }
394
+ return Object.keys(errors).length > 0 ? errors : null;
395
+ }
396
+ function wrapValidator(validatorFn, message) {
397
+ return (value, options, translator, allValues) => {
398
+ const result = validatorFn(value, options, translator, allValues);
399
+ if (typeof result === "string") {
400
+ return result;
401
+ }
402
+ if (!result) {
403
+ return null;
404
+ }
405
+ return message || "Validation failed";
406
+ };
407
+ }
408
+ function registerValidator(name, validatorFn) {
409
+ validators[name] = validatorFn;
410
+ if (typeof validatorFn === "function" && !validatorFn[BUILTIN]) {
411
+ DESCRIPTORS.set(validatorFn, { name, args: [] });
412
+ }
413
+ }
414
+ function composeValidators(...validatorFns) {
415
+ return validators.compose(validatorFns);
416
+ }
417
+ function serializeArg(arg) {
418
+ if (arg instanceof RegExp) return { $regexp: [arg.source, arg.flags] };
419
+ return arg;
420
+ }
421
+ function reviveArg(arg) {
422
+ if (isOptionsObject(arg) && Array.isArray(arg.$regexp)) {
423
+ try {
424
+ return new RegExp(arg.$regexp[0], arg.$regexp[1]);
425
+ } catch {
426
+ return void 0;
427
+ }
428
+ }
429
+ return arg;
430
+ }
431
+ function isSerializable(arg) {
432
+ if (arg === void 0 || arg === null) return true;
433
+ if (arg instanceof RegExp) return true;
434
+ if (Array.isArray(arg)) return arg.every(isSerializable);
435
+ return ["string", "number", "boolean"].includes(typeof arg);
436
+ }
437
+ function describeValidator(entry) {
438
+ let descriptor;
439
+ if (typeof entry === "string") {
440
+ descriptor = resolveString(entry);
441
+ } else if (typeof entry === "function") {
442
+ descriptor = entry[BUILTIN] ? { name: entry[BUILTIN].name, args: [] } : DESCRIPTORS.get(entry);
443
+ }
444
+ if (!descriptor || !descriptor.args.every(isSerializable)) return null;
445
+ const args = [...descriptor.args];
446
+ while (args.length > 0 && args[args.length - 1] === void 0) args.pop();
447
+ return { name: descriptor.name, args: args.map(serializeArg) };
448
+ }
449
+ function serializeValidators(validatorList) {
450
+ const specs = (validatorList || []).map(describeValidator).filter(Boolean);
451
+ return specs.length > 0 ? JSON.stringify(specs) : null;
452
+ }
453
+ function parseValidators(attribute) {
454
+ if (!attribute) return [];
455
+ const text = String(attribute).trim();
456
+ let specs;
457
+ if (text.startsWith("[")) {
458
+ try {
459
+ specs = JSON.parse(text);
460
+ } catch {
461
+ return [];
462
+ }
463
+ if (!Array.isArray(specs)) return [];
464
+ } else {
465
+ specs = text.split(",").map((part) => {
466
+ const [name, ...params] = part.trim().split(":");
467
+ return { name, args: params.map((p) => p !== "" && !Number.isNaN(Number(p)) ? Number(p) : p) };
468
+ });
469
+ }
470
+ return specs.map((spec) => {
471
+ if (!spec || typeof spec.name !== "string") return null;
472
+ const { name } = spec;
473
+ if (!Object.hasOwn(validators, name) || HELPER_NAMES.has(name)) return null;
474
+ const entry = validators[name];
475
+ if (typeof entry !== "function") return null;
476
+ const args = Array.isArray(spec.args) ? spec.args.map(reviveArg) : [];
477
+ return entry[BUILTIN] ? entry[BUILTIN].factory(...args) : entry;
478
+ }).filter(Boolean);
479
+ }
480
+
11
481
  // src/form-builder.js
12
482
  var DEFAULT_CLASS_NAMES = {
13
483
  /** Wrapper around label, control and error */
@@ -41,10 +511,11 @@ function safeAttributes(attributes) {
41
511
  }
42
512
  return safe;
43
513
  }
514
+ var DEFAULT_CSRF_FIELD_NAME = "_csrf";
44
515
  function joinClasses(...names) {
45
516
  return names.filter(Boolean).join(" ");
46
517
  }
47
- var FormBuilder = class {
518
+ var FormBuilder = class _FormBuilder {
48
519
  constructor(options = {}) {
49
520
  this.options = {
50
521
  validateOnChange: true,
@@ -255,8 +726,9 @@ var FormBuilder = class {
255
726
  return error;
256
727
  }
257
728
  }
258
- for (const validator of field.validators || []) {
259
- const error = validator(value, this.values);
729
+ for (const entry of field.validators || []) {
730
+ const validator = resolveValidator(entry);
731
+ const error = validator ? validator(value, this.values) : null;
260
732
  if (error) {
261
733
  this.errors[name] = error;
262
734
  return error;
@@ -336,20 +808,59 @@ var FormBuilder = class {
336
808
  touch(name) {
337
809
  this.touched[name] = true;
338
810
  }
811
+ /**
812
+ * A copy of this form's definition — fields, groups, options and handlers —
813
+ * with fresh values, errors and touched state.
814
+ *
815
+ * A FormBuilder holds the state of one submission. On a server, keep the
816
+ * shared definition at module scope and fork it per request, so one user's
817
+ * submitted values and errors never render into another user's page.
818
+ */
819
+ fork() {
820
+ const copy = new _FormBuilder({ ...this.options });
821
+ for (const [name, config] of this.fields) {
822
+ copy.fields.set(name, config);
823
+ }
824
+ for (const [name, group] of this.groups) {
825
+ copy.groups.set(name, group);
826
+ }
827
+ copy.values = { ...this.initialValues };
828
+ copy.initialValues = { ...this.initialValues };
829
+ copy.submitHandler = this.submitHandler;
830
+ copy.errorHandler = this.errorHandler;
831
+ return copy;
832
+ }
833
+ /**
834
+ * The values, errors and touched state a render uses.
835
+ *
836
+ * Passing any of `values`, `errors` or `touched` to buildForm renders from
837
+ * those alone — the instance's own state is neither read nor changed — so a
838
+ * shared builder can render per-request state. Values are merged over the
839
+ * fields' default values, and fields with an error count as touched unless
840
+ * `touched` is given.
841
+ */
842
+ resolveRenderState(options = {}) {
843
+ const { values, errors, touched } = options;
844
+ if (values === void 0 && errors === void 0 && touched === void 0) {
845
+ return { values: this.values, errors: this.errors, touched: this.touched };
846
+ }
847
+ const renderErrors = errors || {};
848
+ return {
849
+ values: { ...this.initialValues, ...values },
850
+ errors: renderErrors,
851
+ touched: touched || Object.fromEntries(Object.keys(renderErrors).map((name) => [name, true]))
852
+ };
853
+ }
339
854
  /**
340
855
  * Build input component with validation metadata for hydration
341
856
  */
342
- buildInput(name, classNames = this.resolveClassNames()) {
857
+ buildInput(name, classNames = this.resolveClassNames(), state = this.resolveRenderState()) {
343
858
  const field = this.fields.get(name);
344
859
  if (!field) return null;
345
- const value = this.values[name] || "";
346
- const error = this.errors[name];
347
- const isTouched = this.touched[name];
348
- const validatorNames = field.validators.map((v) => {
349
- if (typeof v === "function") return v.name || "custom";
350
- if (typeof v === "string") return v;
351
- return null;
352
- }).filter(Boolean).join(",");
860
+ const value = state.values[name] || "";
861
+ const error = state.errors[name];
862
+ const isTouched = state.touched[name];
863
+ const validatorSpec = serializeValidators(field.validators);
353
864
  const controlClass = joinClasses(
354
865
  classNames.control,
355
866
  field.className,
@@ -374,8 +885,8 @@ var FormBuilder = class {
374
885
  inputProps.required = true;
375
886
  inputProps["data-required"] = "true";
376
887
  }
377
- if (validatorNames) {
378
- inputProps["data-validators"] = validatorNames;
888
+ if (validatorSpec) {
889
+ inputProps["data-validators"] = validatorSpec;
379
890
  }
380
891
  if (field.type === "textarea" || field.type === "select") {
381
892
  const { type: _type, value: _value, ...rest } = inputProps;
@@ -417,9 +928,9 @@ var FormBuilder = class {
417
928
  /**
418
929
  * Build error component
419
930
  */
420
- buildError(name, classNames = this.resolveClassNames()) {
421
- const error = this.errors[name];
422
- const isTouched = this.touched[name];
931
+ buildError(name, classNames = this.resolveClassNames(), state = this.resolveRenderState()) {
932
+ const error = state.errors[name];
933
+ const isTouched = state.touched[name];
423
934
  if (!error || !isTouched) return null;
424
935
  const props = { id: `${name}-error`, role: "alert", text: error };
425
936
  if (classNames.error) props.className = classNames.error;
@@ -434,14 +945,14 @@ var FormBuilder = class {
434
945
  /**
435
946
  * Build complete field component
436
947
  */
437
- buildField(name, classNames = this.resolveClassNames()) {
948
+ buildField(name, classNames = this.resolveClassNames(), state = this.resolveRenderState()) {
438
949
  const field = this.fields.get(name);
439
950
  if (!field) return null;
440
951
  const children = [
441
952
  this.buildLabel(name, classNames),
442
- this.buildInput(name, classNames)
953
+ this.buildInput(name, classNames, state)
443
954
  ];
444
- const error = this.buildError(name, classNames);
955
+ const error = this.buildError(name, classNames, state);
445
956
  if (error) {
446
957
  children.push(error);
447
958
  }
@@ -451,14 +962,31 @@ var FormBuilder = class {
451
962
  }
452
963
  /**
453
964
  * Build entire form
965
+ *
966
+ * `options.values`, `options.errors` and `options.touched` render
967
+ * per-request state without touching the builder's own (see
968
+ * resolveRenderState). `options.csrfToken` adds a hidden `_csrf` input (the
969
+ * name is `options.csrfFieldName`); create the token with
970
+ * `@coherent.js/forms/csrf`.
454
971
  */
455
972
  buildForm(options = {}) {
456
- const settings = { ...this.options, ...options };
973
+ const { values: _values, errors: _errors, touched: _touched, ...formOptions } = options;
974
+ const settings = { ...this.options, ...formOptions };
457
975
  const classNames = this.resolveClassNames(options.classNames);
976
+ const state = this.resolveRenderState(options);
458
977
  const fields = [];
978
+ if (settings.csrfToken !== void 0 && settings.csrfToken !== null && settings.csrfToken !== "") {
979
+ fields.push({
980
+ input: {
981
+ type: "hidden",
982
+ name: settings.csrfFieldName || DEFAULT_CSRF_FIELD_NAME,
983
+ value: String(settings.csrfToken)
984
+ }
985
+ });
986
+ }
459
987
  for (const [name] of this.fields) {
460
- if (!this.isFieldVisible(name)) continue;
461
- fields.push(this.buildField(name, classNames));
988
+ if (!this.isFieldVisible(name, state.values)) continue;
989
+ fields.push(this.buildField(name, classNames, state));
462
990
  }
463
991
  if (settings.submitButton !== false) {
464
992
  const button = { type: "submit", text: settings.submitText || "Submit" };
@@ -520,13 +1048,13 @@ var FormBuilder = class {
520
1048
  /**
521
1049
  * Check if a field is visible
522
1050
  */
523
- isFieldVisible(name) {
1051
+ isFieldVisible(name, values = this.values) {
524
1052
  const field = this.fields.get(name);
525
1053
  if (!field) return false;
526
1054
  if (field.visible === false) return false;
527
1055
  const showCondition = field.showWhen || field.showIf;
528
1056
  if (showCondition) {
529
- return showCondition(this.values);
1057
+ return showCondition(values);
530
1058
  }
531
1059
  return true;
532
1060
  }
@@ -572,524 +1100,15 @@ function buildForm(config = {}) {
572
1100
  return builder.buildForm(options);
573
1101
  }
574
1102
 
575
- // src/validation.js
576
- var validators = {
577
- required: (message = "This field is required") => (value) => {
578
- if (value === null || value === void 0 || value === "") {
579
- return message;
580
- }
581
- return null;
582
- },
583
- minLength: (min, message = `Minimum length is ${min}`) => (value) => {
584
- if (value && value.length < min) {
585
- return message;
586
- }
587
- return null;
588
- },
589
- maxLength: (max, message = `Maximum length is ${max}`) => (value) => {
590
- if (value && value.length > max) {
591
- return message;
592
- }
593
- return null;
594
- },
595
- min: (min, message = `Minimum value is ${min}`) => (value) => {
596
- if (value !== null && value !== void 0 && Number(value) < min) {
597
- return message;
598
- }
599
- return null;
600
- },
601
- max: (max, message = `Maximum value is ${max}`) => (value) => {
602
- if (value !== null && value !== void 0 && Number(value) > max) {
603
- return message;
604
- }
605
- return null;
606
- },
607
- email: (message = "Invalid email address") => (value) => {
608
- if (value && !isEmailShaped(value)) {
609
- return message;
610
- }
611
- return null;
612
- },
613
- url: (message = "Invalid URL") => (value) => {
614
- if (value) {
615
- try {
616
- new URL(value);
617
- } catch {
618
- return message;
619
- }
620
- }
621
- return null;
622
- },
623
- pattern: (regex, message = "Invalid format") => (value) => {
624
- if (value && !regex.test(value)) {
625
- return message;
626
- }
627
- return null;
628
- },
629
- matches: (fieldName, message = "Fields do not match") => (value, formData) => {
630
- if (value !== formData[fieldName]) {
631
- return message;
632
- }
633
- return null;
634
- },
635
- oneOf: (options, message = "Invalid option") => (value) => {
636
- if (value && !options.includes(value)) {
637
- return message;
638
- }
639
- return null;
640
- },
641
- custom: (fn, message = "Validation failed") => (value, formData) => {
642
- if (!fn(value, formData)) {
643
- return message;
644
- }
1103
+ // src/form-hydration.js
1104
+ function hydrateForm(formSelector, options = {}) {
1105
+ if (typeof document === "undefined") {
1106
+ console.warn("hydrateForm can only run in browser environment");
645
1107
  return null;
646
1108
  }
647
- };
648
- var FormValidator = class {
649
- constructor(schema = {}) {
650
- this.schema = schema;
651
- this.errors = {};
652
- this.touched = {};
653
- }
654
- /**
655
- * Validate a single field
656
- */
657
- validateField(name, value, formData = {}) {
658
- const fieldValidators = this.schema[name];
659
- if (!fieldValidators) {
660
- return null;
661
- }
662
- const validatorArray = Array.isArray(fieldValidators) ? fieldValidators : [fieldValidators];
663
- for (const validator of validatorArray) {
664
- const error = validator(value, formData);
665
- if (error) {
666
- return error;
667
- }
668
- }
669
- return null;
670
- }
671
- /**
672
- * Validate entire form
673
- */
674
- validate(formData) {
675
- const errors = {};
676
- let isValid = true;
677
- for (const [name, value] of Object.entries(formData)) {
678
- const error = this.validateField(name, value, formData);
679
- if (error) {
680
- errors[name] = error;
681
- isValid = false;
682
- }
683
- }
684
- for (const name of Object.keys(this.schema)) {
685
- if (!(name in formData)) {
686
- const error = this.validateField(name, void 0, formData);
687
- if (error) {
688
- errors[name] = error;
689
- isValid = false;
690
- }
691
- }
692
- }
693
- this.errors = errors;
694
- return { isValid, errors };
695
- }
696
- /**
697
- * Mark field as touched
698
- */
699
- touch(name) {
700
- this.touched[name] = true;
701
- }
702
- /**
703
- * Check if field is touched
704
- */
705
- isTouched(name) {
706
- return this.touched[name] || false;
707
- }
708
- /**
709
- * Get error for field
710
- */
711
- getError(name) {
712
- return this.errors[name] || null;
713
- }
714
- /**
715
- * Check if field has error
716
- */
717
- hasError(name) {
718
- return !!this.errors[name];
719
- }
720
- /**
721
- * Clear errors
722
- */
723
- clearErrors() {
724
- this.errors = {};
725
- }
726
- /**
727
- * Clear touched state
728
- */
729
- clearTouched() {
730
- this.touched = {};
731
- }
732
- /**
733
- * Reset validator
734
- */
735
- reset() {
736
- this.clearErrors();
737
- this.clearTouched();
738
- }
739
- };
740
- function createValidator(schema) {
741
- return new FormValidator(schema);
742
- }
743
- function validate(formData, schema) {
744
- const validator = new FormValidator(schema);
745
- return validator.validate(formData);
746
- }
747
-
748
- // src/validators.js
749
- var validators2 = {
750
- required: (value, options = {}) => {
751
- if (value === null || value === void 0 || value === "") {
752
- return options.message || validators2.required.message || "This field is required";
753
- }
754
- return null;
755
- },
756
- email: (value) => {
757
- if (!value) return null;
758
- if (!isEmailShaped(value)) {
759
- return "Please enter a valid email address";
760
- }
761
- return null;
762
- },
763
- minLength: (value, options = {}) => {
764
- if (!value) return null;
765
- const min = options.min || 0;
766
- if (value.length < min) {
767
- return options.message || `Must be at least ${min} characters`;
768
- }
769
- return null;
770
- },
771
- maxLength: (value, options = {}) => {
772
- if (!value) return null;
773
- const max = options.max || Infinity;
774
- if (value.length > max) {
775
- return options.message || `Must be no more than ${max} characters`;
776
- }
777
- return null;
778
- },
779
- min: (value, options = {}) => {
780
- if (value === null || value === void 0 || value === "") return null;
781
- const num = Number(value);
782
- const minValue = options.min || 0;
783
- if (isNaN(num) || num < minValue) {
784
- return options.message || `Must be at least ${minValue}`;
785
- }
786
- return null;
787
- },
788
- max: (value, options = {}) => {
789
- if (value === null || value === void 0 || value === "") return null;
790
- const num = Number(value);
791
- const maxValue = options.max || Infinity;
792
- if (isNaN(num) || num > maxValue) {
793
- return options.message || `Must be no more than ${maxValue}`;
794
- }
795
- return null;
796
- },
797
- pattern: (value, options = {}) => {
798
- if (!value) return null;
799
- const regex = options.pattern || options.regex;
800
- if (regex && !regex.test(value)) {
801
- return options.message || "Invalid format";
802
- }
803
- return null;
804
- },
805
- url: (value) => {
806
- if (!value) return null;
807
- try {
808
- new URL(value);
809
- return null;
810
- } catch {
811
- return "Please enter a valid URL";
812
- }
813
- },
814
- number: (value) => {
815
- if (value === null || value === void 0 || value === "") return null;
816
- if (isNaN(Number(value))) {
817
- return "Must be a valid number";
818
- }
819
- return null;
820
- },
821
- integer: (value) => {
822
- if (value === null || value === void 0 || value === "") return null;
823
- const num = Number(value);
824
- if (isNaN(num) || !Number.isInteger(num)) {
825
- return "Must be a whole number";
826
- }
827
- return null;
828
- },
829
- phone: (value) => {
830
- if (!value) return null;
831
- const phoneRegex = /^[\d\s\-\+\(\)]+$/;
832
- if (!phoneRegex.test(value) || value.replace(/\D/g, "").length < 10) {
833
- return "Please enter a valid phone number";
834
- }
835
- return null;
836
- },
837
- date: (value) => {
838
- if (!value) return null;
839
- const date = new Date(value);
840
- if (isNaN(date.getTime())) {
841
- return "Please enter a valid date";
842
- }
843
- return null;
844
- },
845
- match: (value, options = {}, translator, allValues = {}) => {
846
- if (!value) return null;
847
- const fieldName = options.field || options.fieldName;
848
- if (value !== allValues[fieldName]) {
849
- return options.message || `Must match ${fieldName}`;
850
- }
851
- return null;
852
- },
853
- custom: (value, options = {}, translator, allValues) => {
854
- const validatorFn = options.validator || options.fn;
855
- if (!validatorFn) return null;
856
- const isValid = validatorFn(value, allValues);
857
- return isValid ? null : options.message || "Validation failed";
858
- },
859
- fileType: (value, options = {}) => {
860
- if (!value) return null;
861
- const allowedTypes = options.accept || options.types || [];
862
- if (value.type !== void 0) {
863
- const fileType = value.type;
864
- const fileExt = value.name ? value.name.split(".").pop().toLowerCase() : "";
865
- const isValid = allowedTypes.some((type) => {
866
- if (type.startsWith(".")) {
867
- return fileExt === type.slice(1).toLowerCase();
868
- }
869
- if (type.includes("/")) {
870
- if (type.endsWith("/*")) {
871
- return fileType.startsWith(type.replace("/*", "/"));
872
- }
873
- return fileType === type;
874
- }
875
- return fileExt === type.toLowerCase();
876
- });
877
- if (!isValid) {
878
- return options.message || `File type must be one of: ${allowedTypes.join(", ")}`;
879
- }
880
- return null;
881
- }
882
- return null;
883
- },
884
- fileSize: (value, options = {}) => {
885
- if (!value) return null;
886
- const maxSize = options.maxSize || Infinity;
887
- if (value.size !== void 0) {
888
- if (value.size > maxSize) {
889
- const maxSizeMB = (maxSize / (1024 * 1024)).toFixed(2);
890
- return options.message || `File size must be less than ${maxSizeMB}MB`;
891
- }
892
- return null;
893
- }
894
- return null;
895
- },
896
- fileExtension: (value, options = {}) => {
897
- if (!value) return null;
898
- const allowedExtensions = options.extensions || [];
899
- const fileName = value.name || value;
900
- const ext = `.${fileName.split(".").pop().toLowerCase()}`;
901
- const isValid = allowedExtensions.some((allowed) => {
902
- return ext === allowed.toLowerCase();
903
- });
904
- if (!isValid) {
905
- return options.message || `File extension must be one of: ${allowedExtensions.join(", ")}`;
906
- }
907
- return null;
908
- },
909
- alpha: (value) => {
910
- if (!value) return null;
911
- const alphaRegex = /^[a-zA-Z]+$/;
912
- if (!alphaRegex.test(value)) {
913
- return "Must contain only letters";
914
- }
915
- return null;
916
- },
917
- alphanumeric: (value) => {
918
- if (!value) return null;
919
- const alphanumericRegex = /^[a-zA-Z0-9]+$/;
920
- if (!alphanumericRegex.test(value)) {
921
- return "Must contain only letters and numbers";
922
- }
923
- return null;
924
- },
925
- uppercase: (value) => {
926
- if (!value) return null;
927
- if (value !== value.toUpperCase()) {
928
- return "Must be uppercase";
929
- }
930
- return null;
931
- },
932
- // Get a registered validator
933
- get: (name) => {
934
- return validators2[name];
935
- },
936
- // Compose multiple validators
937
- compose: (validatorList) => {
938
- return (value, options, translator, allValues) => {
939
- for (const validator of validatorList) {
940
- const error = typeof validator === "function" ? validator(value, options, translator, allValues) : null;
941
- if (error) {
942
- return error;
943
- }
944
- }
945
- return null;
946
- };
947
- },
948
- // Debounce async validator
949
- debounce: (validator, delay = 300) => {
950
- let timeoutId;
951
- return (value) => {
952
- return new Promise((resolve) => {
953
- clearTimeout(timeoutId);
954
- timeoutId = setTimeout(async () => {
955
- const result = await validator(value);
956
- resolve(result);
957
- }, delay);
958
- });
959
- };
960
- },
961
- // Cancellable async validator
962
- cancellable: (validator) => {
963
- let abortController;
964
- const wrapped = async (value) => {
965
- if (abortController) {
966
- abortController.abort();
967
- }
968
- abortController = typeof AbortController !== "undefined" ? new AbortController() : null;
969
- try {
970
- return await validator(value, abortController ? abortController.signal : null);
971
- } catch (error) {
972
- if (error.name === "AbortError") {
973
- return null;
974
- }
975
- throw error;
976
- }
977
- };
978
- wrapped.cancel = () => {
979
- if (abortController) {
980
- abortController.abort();
981
- }
982
- };
983
- return wrapped;
984
- },
985
- // Conditional validator
986
- when: (condition, validator) => {
987
- return (value, options = {}, translator, allValues = {}) => {
988
- const context = options.min !== void 0 || options.max !== void 0 ? allValues : options;
989
- const shouldValidate = typeof condition === "function" ? condition(value, context) : condition;
990
- if (!shouldValidate) {
991
- return null;
992
- }
993
- return typeof validator === "function" ? validator(value, options, translator, allValues) : null;
994
- };
995
- },
996
- // Validator chain builder
997
- chain: (options = {}) => {
998
- const validatorList = [];
999
- const stopOnFirstError = options.stopOnFirstError !== false;
1000
- const chain = {
1001
- required: (opts) => {
1002
- validatorList.push((v, o, t, a) => validators2.required(v, opts || o, t, a));
1003
- return chain;
1004
- },
1005
- email: (opts) => {
1006
- validatorList.push((v, o, t, a) => validators2.email(v, opts || o, t, a));
1007
- return chain;
1008
- },
1009
- minLength: (opts) => {
1010
- validatorList.push((v, o, t, a) => validators2.minLength(v, opts || o, t, a));
1011
- return chain;
1012
- },
1013
- maxLength: (opts) => {
1014
- validatorList.push((v, o, t, a) => validators2.maxLength(v, opts || o, t, a));
1015
- return chain;
1016
- },
1017
- custom: (fn, message) => {
1018
- validatorList.push((v, o, t, a) => {
1019
- const result = fn(v, a);
1020
- return result === null || result === true || result === void 0 ? null : message || result;
1021
- });
1022
- return chain;
1023
- },
1024
- validate: (value, opts, translator, allValues) => {
1025
- if (stopOnFirstError) {
1026
- for (const validator of validatorList) {
1027
- const error = validator(value, opts, translator, allValues);
1028
- if (error) {
1029
- return error;
1030
- }
1031
- }
1032
- return null;
1033
- } else {
1034
- const errors = [];
1035
- for (const validator of validatorList) {
1036
- const error = validator(value, opts, translator, allValues);
1037
- if (error) {
1038
- errors.push(error);
1039
- }
1040
- }
1041
- return errors.length > 0 ? errors : null;
1042
- }
1043
- }
1044
- };
1045
- return chain;
1046
- }
1047
- };
1048
- function validateField(value, validatorList, formData = {}) {
1049
- for (const validator of validatorList) {
1050
- const error = validator(value, formData);
1051
- if (error) {
1052
- return error;
1053
- }
1054
- }
1055
- return null;
1056
- }
1057
- function validateForm(formData, fieldValidators) {
1058
- const errors = {};
1059
- for (const [fieldName, validatorList] of Object.entries(fieldValidators)) {
1060
- const value = formData[fieldName];
1061
- const error = validateField(value, validatorList, formData);
1062
- if (error) {
1063
- errors[fieldName] = error;
1064
- }
1065
- }
1066
- return Object.keys(errors).length > 0 ? errors : null;
1067
- }
1068
- function registerValidator(name, validatorFn) {
1069
- validators2[name] = validatorFn;
1070
- validators[name] = validatorFn;
1071
- }
1072
- function composeValidators(...validatorFns) {
1073
- return (value, options, translator, allValues) => {
1074
- for (const validator of validatorFns) {
1075
- const error = validator(value, options, translator, allValues);
1076
- if (error) {
1077
- return error;
1078
- }
1079
- }
1080
- return null;
1081
- };
1082
- }
1083
-
1084
- // src/form-hydration.js
1085
- function hydrateForm(formSelector, options = {}) {
1086
- if (typeof document === "undefined") {
1087
- console.warn("hydrateForm can only run in browser environment");
1088
- return null;
1089
- }
1090
- const form = typeof formSelector === "string" ? document.querySelector(formSelector) : formSelector;
1091
- if (!form) {
1092
- console.warn(`Form not found: ${formSelector}`);
1109
+ const form = typeof formSelector === "string" ? document.querySelector(formSelector) : formSelector;
1110
+ if (!form) {
1111
+ console.warn(`Form not found: ${formSelector}`);
1093
1112
  return null;
1094
1113
  }
1095
1114
  const opts = {
@@ -1115,17 +1134,6 @@ function hydrateForm(formSelector, options = {}) {
1115
1134
  fields: /* @__PURE__ */ new Map()
1116
1135
  };
1117
1136
  const debounceTimers = /* @__PURE__ */ new Map();
1118
- function parseValidators(validatorString) {
1119
- if (!validatorString) return [];
1120
- return validatorString.split(",").map((v) => {
1121
- const trimmed = v.trim();
1122
- const [name, ...params] = trimmed.split(":");
1123
- if (validators2[name]) {
1124
- return params.length > 0 ? validators2[name](...params.map((p) => isNaN(p) ? p : Number(p))) : validators2[name];
1125
- }
1126
- return null;
1127
- }).filter(Boolean);
1128
- }
1129
1137
  function discoverFields() {
1130
1138
  const inputs = form.querySelectorAll("[name]");
1131
1139
  inputs.forEach((input) => {
@@ -1348,6 +1356,111 @@ function hydrateForm(formSelector, options = {}) {
1348
1356
  })
1349
1357
  };
1350
1358
  }
1359
+
1360
+ // src/validation.js
1361
+ var FormValidator = class {
1362
+ constructor(schema = {}) {
1363
+ this.schema = schema;
1364
+ this.errors = {};
1365
+ this.touched = {};
1366
+ }
1367
+ /**
1368
+ * Validate a single field
1369
+ */
1370
+ validateField(name, value, formData = {}) {
1371
+ const fieldValidators = this.schema[name];
1372
+ if (!fieldValidators) {
1373
+ return null;
1374
+ }
1375
+ const validatorArray = Array.isArray(fieldValidators) ? fieldValidators : [fieldValidators];
1376
+ for (const entry of validatorArray) {
1377
+ const validator = resolveValidator(entry);
1378
+ const error = validator ? validator(value, formData) : null;
1379
+ if (error) {
1380
+ return error;
1381
+ }
1382
+ }
1383
+ return null;
1384
+ }
1385
+ /**
1386
+ * Validate entire form
1387
+ */
1388
+ validate(formData) {
1389
+ const errors = {};
1390
+ let isValid = true;
1391
+ for (const [name, value] of Object.entries(formData)) {
1392
+ const error = this.validateField(name, value, formData);
1393
+ if (error) {
1394
+ errors[name] = error;
1395
+ isValid = false;
1396
+ }
1397
+ }
1398
+ for (const name of Object.keys(this.schema)) {
1399
+ if (!(name in formData)) {
1400
+ const error = this.validateField(name, void 0, formData);
1401
+ if (error) {
1402
+ errors[name] = error;
1403
+ isValid = false;
1404
+ }
1405
+ }
1406
+ }
1407
+ this.errors = errors;
1408
+ return { isValid, errors };
1409
+ }
1410
+ /**
1411
+ * Mark field as touched
1412
+ */
1413
+ touch(name) {
1414
+ this.touched[name] = true;
1415
+ }
1416
+ /**
1417
+ * Check if field is touched
1418
+ */
1419
+ isTouched(name) {
1420
+ return this.touched[name] || false;
1421
+ }
1422
+ /**
1423
+ * Get error for field
1424
+ */
1425
+ getError(name) {
1426
+ return this.errors[name] || null;
1427
+ }
1428
+ /**
1429
+ * Check if field has error
1430
+ */
1431
+ hasError(name) {
1432
+ return !!this.errors[name];
1433
+ }
1434
+ /**
1435
+ * Clear errors
1436
+ */
1437
+ clearErrors() {
1438
+ this.errors = {};
1439
+ }
1440
+ /**
1441
+ * Clear touched state
1442
+ */
1443
+ clearTouched() {
1444
+ this.touched = {};
1445
+ }
1446
+ /**
1447
+ * Reset validator
1448
+ */
1449
+ reset() {
1450
+ this.clearErrors();
1451
+ this.clearTouched();
1452
+ }
1453
+ };
1454
+ function createValidator(schemaOrFn, message) {
1455
+ if (typeof schemaOrFn === "function") {
1456
+ return wrapValidator(schemaOrFn, message);
1457
+ }
1458
+ return new FormValidator(schemaOrFn);
1459
+ }
1460
+ function validate(formData, schema) {
1461
+ const validator = new FormValidator(schema);
1462
+ return validator.validate(formData);
1463
+ }
1351
1464
  export {
1352
1465
  DEFAULT_CLASS_NAMES,
1353
1466
  FormBuilder,