react-f0rm 0.2.2 → 0.4.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.
Files changed (45) hide show
  1. package/README.md +573 -33
  2. package/dist/devtools/index.cjs.js +737 -0
  3. package/dist/devtools/index.cjs.js.map +1 -0
  4. package/dist/devtools/index.d.ts +33 -0
  5. package/dist/devtools/index.mjs +717 -0
  6. package/dist/devtools/index.mjs.map +1 -0
  7. package/dist/form-61297bc0.d.ts +578 -0
  8. package/dist/form-94c70b4b.mjs +378 -0
  9. package/dist/form-94c70b4b.mjs.map +1 -0
  10. package/dist/form-b9441d8c.cjs.js +387 -0
  11. package/dist/form-b9441d8c.cjs.js.map +1 -0
  12. package/dist/index.cjs.js +1265 -157
  13. package/dist/index.cjs.js.map +1 -1
  14. package/dist/index.d.ts +419 -59
  15. package/dist/index.mjs +1684 -0
  16. package/dist/index.mjs.map +1 -0
  17. package/dist/index.umd.js +1265 -157
  18. package/dist/index.umd.js.map +1 -1
  19. package/dist/index.umd.min.js +2 -2
  20. package/dist/index.umd.min.js.map +1 -1
  21. package/dist/resolvers/standard-schema.cjs.js +90 -0
  22. package/dist/resolvers/standard-schema.cjs.js.map +1 -0
  23. package/dist/resolvers/standard-schema.d.ts +66 -0
  24. package/dist/resolvers/standard-schema.mjs +86 -0
  25. package/dist/resolvers/standard-schema.mjs.map +1 -0
  26. package/dist/resolvers/yup.cjs.js +12 -2
  27. package/dist/resolvers/yup.cjs.js.map +1 -1
  28. package/dist/resolvers/yup.d.ts +2 -2
  29. package/dist/resolvers/yup.mjs +23 -0
  30. package/dist/resolvers/yup.mjs.map +1 -0
  31. package/dist/resolvers/zod.cjs.js +14 -1
  32. package/dist/resolvers/zod.cjs.js.map +1 -1
  33. package/dist/resolvers/zod.d.ts +2 -2
  34. package/dist/resolvers/zod.mjs +23 -0
  35. package/dist/resolvers/zod.mjs.map +1 -0
  36. package/dist/validate-148fe167.d.ts +22 -0
  37. package/package.json +34 -8
  38. package/dist/form-d06e6444.d.ts +0 -201
  39. package/dist/index.esm.js +0 -593
  40. package/dist/index.esm.js.map +0 -1
  41. package/dist/resolvers/yup.esm.js +0 -13
  42. package/dist/resolvers/yup.esm.js.map +0 -1
  43. package/dist/resolvers/zod.esm.js +0 -10
  44. package/dist/resolvers/zod.esm.js.map +0 -1
  45. package/dist/validate-0f17f86a.d.ts +0 -8
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../node_modules/.pnpm/@for-fun+event-emitter@1.0.0/node_modules/@for-fun/event-emitter/dist/event-emitter.esm.js","../src/util.ts","../src/path.ts","../src/form.ts","../src/rules.ts","../node_modules/.pnpm/use-sync-external-store@1.6.0_react@18.3.1/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js","../node_modules/.pnpm/use-sync-external-store@1.6.0_react@18.3.1/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js","../node_modules/.pnpm/use-sync-external-store@1.6.0_react@18.3.1/node_modules/use-sync-external-store/shim/index.js","../src/subscribe.ts","../src/hooks/form.tsx","../src/hooks/path.ts","../src/hooks/stage.ts","../src/hooks/validate.ts","../src/hooks/field.tsx","../src/hooks/fieldArray.ts","../src/context.ts","../src/components/Form.tsx","../src/components/Field.tsx"],"sourcesContent":["function getSet(ee, key) {\n var set = ee.get(key);\n if (set) return set;\n var newSet = new Set();\n ee.set(key, newSet);\n return newSet;\n}\nvar errorEvent = Symbol('error');\nfunction create() {\n return new Map();\n}\nfunction emit(ee, key) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n (ee.get(key) || []).forEach(function (h) {\n return h.apply(void 0, args);\n });\n}\nfunction emitError(ee, err) {\n var handlerSet = ee.get(errorEvent);\n if (!handlerSet || !handlerSet.size) throw err;\n handlerSet.forEach(function (h) {\n return h(err);\n });\n}\nfunction on(ee, key, handler) {\n var set = getSet(ee, key);\n set.add(handler);\n return function () {\n return set.delete(handler);\n };\n}\nfunction onError(ee, handler) {\n return on(ee, errorEvent, handler);\n}\nfunction once(ee, key, handler) {\n var off = on(ee, key, function () {\n off();\n handler.apply(void 0, arguments);\n });\n return off;\n}\nfunction onceError(ee, handler) {\n return once(ee, errorEvent, handler);\n}\nfunction bindContext(context) {\n return function (func) {\n return func.bind(null, context);\n };\n}\nfunction createAndBind() {\n var ee = create();\n var bind = bindContext(ee);\n return {\n emit: bind(emit),\n emitError: bind(emitError),\n on: bind(on),\n onError: bind(onError),\n once: bind(once),\n onceError: bind(onceError)\n };\n}\n\nexport { bindContext, create, createAndBind, emit, emitError, errorEvent, on, onError, once, onceError };\n//# sourceMappingURL=event-emitter.esm.js.map\n","import {on} from '@for-fun/event-emitter';\nimport type {EventEmitter} from '@for-fun/event-emitter';\n\nconst pathCache = new Map<string, (string | number)[]>();\n\nexport function normalizePath(\n path: string | (string | number)[]\n): (string | number)[] {\n if (Array.isArray(path)) return path;\n const cached = pathCache.get(path);\n if (cached) return cached;\n const value = parsePath(path);\n pathCache.set(path, value);\n return value;\n}\n\nfunction parsePath(path: string): (string | number)[] {\n const result: (string | number)[] = [];\n let identifier = '';\n const flushIdentifier = () => {\n result.push(identifier);\n identifier = '';\n };\n\n for (let i = 0; i < path.length; i++) {\n const char = path[i];\n if (char === '.') {\n if (identifier !== '') flushIdentifier();\n } else if (char === '[') {\n if (identifier !== '') flushIdentifier();\n const quote = path[i + 1];\n if (quote === '\"' || quote === \"'\") {\n const close = path.indexOf(quote, i + 2);\n if (close === -1) {\n throw new TypeError(`Unterminated quote in path: ${path}`);\n }\n if (path[close + 1] !== ']') {\n throw new TypeError(\n `Expected \"]\" after quoted segment in path: ${path}`\n );\n }\n result.push(path.slice(i + 2, close));\n i = close + 1;\n } else {\n const close = path.indexOf(']', i + 1);\n if (close === -1) {\n throw new TypeError(`Unterminated bracket in path: ${path}`);\n }\n const content = path.slice(i + 1, close);\n result.push(/^-?\\d+$/.test(content) ? Number(content) : content);\n i = close;\n }\n } else {\n identifier += char;\n }\n }\n if (identifier !== '' || result.length === 0) flushIdentifier();\n return result;\n}\n\nexport function get(values: any, path: (string | number)[]): any {\n return path.reduce((current: any, p: string | number) => {\n if (current == null) return undefined;\n return current[p];\n }, values);\n}\n\n/**\n * Immutable counterpart of {@link set}: removes the path from the value\n * tree, copying only along the touched branch (untouched branches stay\n * shared with the source, like set). Deletes the key entirely rather than\n * writing undefined, so the result carries no `a: undefined` entries.\n */\nexport function unset(values: any, path: (string | number)[]): any {\n if (!path.length || values == null) return values;\n const [prop, ...props] = path;\n if (props.length) {\n const next = unset(values[prop], props);\n return next === values[prop] ? values : set(values, path, next);\n }\n if (Array.isArray(values)) {\n if (!(prop in values)) return values;\n const arr = values.slice();\n delete arr[prop as number];\n return arr;\n }\n if (typeof values !== 'object' || !(prop in values)) return values;\n const copy = {...values};\n delete copy[prop as string];\n return copy;\n}\n\nexport function set(values: any, path: (string | number)[], value: any): any {\n if (!path.length) return value;\n\n const [prop, ...props] = path;\n if (typeof prop === 'number') {\n const arr = Array.isArray(values) ? values.slice() : [];\n arr[prop] = set(arr[prop], props, value);\n return arr;\n }\n return {...values, [prop]: set(values && values[prop], props, value)};\n}\n\n/**\n * Ownership-tracked {@link set}: merge many paths into one tree without\n * re-copying containers the merge itself already created.\n *\n * Containers present in `owned` (freshly created by an earlier call of the\n * same merge) are mutated in place; every other container -- nodes borrowed\n * from the seed tree and user leaf values -- is copied first with the exact\n * copy rules `set` applies (numeric prop: array slice, or a fresh array\n * when the node is not one; string prop: object spread). Chaining\n * `setOwned` over a list of paths therefore produces the tree chaining\n * `set` would, in the same insertion order, but allocates each distinct\n * container once (O(distinct path prefixes)) instead of re-copying the\n * whole branch for every path (O(paths x depth)).\n *\n * Use a fresh `owned` set per merge and thread the returned root (a copied\n * replacement when the seed root itself had to be copied) into the next\n * call. Borrowed containers are never mutated.\n */\nexport function setOwned(\n root: any,\n path: (string | number)[],\n value: any,\n owned: Set<object>\n): any {\n if (!path.length) return value;\n let container = root;\n let parent: any = null;\n let parentProp: string | number = '';\n for (let i = 0; i < path.length; i++) {\n const prop = path[i];\n if (!owned.has(container)) {\n let copy: any;\n if (typeof prop === 'number') {\n copy = Array.isArray(container) ? container.slice() : [];\n } else {\n copy = {...container};\n }\n owned.add(copy);\n if (i === 0) root = copy;\n else parent[parentProp] = copy;\n container = copy;\n }\n if (i === path.length - 1) {\n container[prop] = value;\n } else {\n parent = container;\n parentProp = prop;\n container = container[prop];\n }\n }\n return root;\n}\n\nexport function isNil(value: any): value is null | undefined {\n return value == null;\n}\n\nexport function isEmpty(value: any): boolean {\n if (isNil(value)) return true;\n if (typeof value !== 'object') return false;\n\n const values = Object.values(value);\n return values.length === 0 || values.every(isEmpty);\n}\n\nexport function isPromise(value: any): value is Promise<any> {\n return value && typeof value.then === 'function';\n}\n\nexport function waitUntil(\n emitter: EventEmitter<any>,\n event: string,\n isResolve: () => boolean,\n isReject: () => boolean\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (isReject()) return void reject();\n if (isResolve()) return void resolve();\n\n const off = on(emitter, event as any, () => {\n if (isReject()) {\n off();\n reject();\n return;\n }\n // Condition not reached yet — stay subscribed and keep waiting. (The\n // previous `if (isResolve()) return` was inverted: it hung forever\n // once the condition held and resolved prematurely while it didn't.)\n if (!isResolve()) return;\n off();\n resolve();\n });\n });\n}\n","import {normalizePath} from './util';\n\nexport type PathSegments = (string | number)[];\nexport type Name = string | PathSegments;\nexport type Path = {value: PathSegments; key: string};\n\nexport default function create(name: Name): Path {\n const value = normalizePath(name);\n return {value, key: JSON.stringify(value)};\n}\n","import {create as createEmitter, emit as _emit} from '@for-fun/event-emitter';\nimport type {EventEmitter} from '@for-fun/event-emitter';\nimport createPath from './path';\nimport type {Name, Path, PathSegments} from './path';\nimport type {FieldPath, PathValueOf} from './types';\nimport {get, normalizePath, setOwned, unset, waitUntil} from './util';\n\nexport type {Name};\nexport type {FieldPath, PathValue} from './types';\n\nconst emit = _emit as (\n emitter: EventEmitter,\n event: string,\n ...args: any[]\n) => void;\n\n/** A field error: `type` identifies the error kind ('custom' for plain\n * string errors), `message` is the display text. */\nexport interface FieldError {\n type: string;\n message: string;\n}\n\n/** A flattened entry from {@link getErrors}. */\nexport type FieldErrorEntry = {path: string; type: string; message: string};\n\n/** When a field is validated:\n * - `'onSubmit'` (default): only on submit\n * - `'onBlur'`: when the field loses focus\n * - `'onChange'`: on every change\n * - `'onTouched'`: on first blur, then on every change\n * - `'all'`: on both change and blur\n */\nexport type ValidationMode =\n | 'onSubmit'\n | 'onBlur'\n | 'onChange'\n | 'onTouched'\n | 'all';\n\n/** When a field is re-validated after it already has an error:\n * - `'onChange'` (default): on every change\n * - `'onBlur'`: when the field loses focus\n * - `'onSubmit'`: only on submit (no live re-validation)\n */\nexport type ReValidateMode = 'onChange' | 'onBlur' | 'onSubmit';\n\n/** Brand marking a form-level validate result as a structured\n * {@link ValidationOutcome} (parsed values and/or errors) rather than a\n * plain nested error record. Symbols cannot collide with user error\n * records, so detection is an exact `VALIDATION_OUTCOME in result`. */\nexport const VALIDATION_OUTCOME: unique symbol = Symbol('validation-outcome');\n\n/** Structured form-level validate result: `errors` uses the same nested\n * shape a plain error record uses, `values` is the schema's parsed output\n * (coerce/transform results included). Either side may be omitted. */\nexport type ValidationOutcome<T> = {\n [VALIDATION_OUTCOME]: true;\n errors?: Record<string, any>;\n values?: T;\n};\n\n/** What a form-level validate function may return: a plain nested error\n * record (flattened into field errors — the long-standing shape), or a\n * branded {@link ValidationOutcome} whose `values` become the form's\n * parsedValues baseline. */\nexport type ValidateResult<T> =\n | Record<string, any>\n | ValidationOutcome<T>\n | Promise<Record<string, any> | ValidationOutcome<T>>;\n\nexport interface Form<T extends Record<string, any> = any> {\n emitter: EventEmitter;\n mode: ValidationMode;\n reValidateMode: ReValidateMode;\n initialValues: T;\n values: Map<string, any>;\n /** Tombstones of unregistered field paths (JSON path keys): reading or\n * merging values must not fall back to initialValues for these paths. */\n deleted: Set<string>;\n /** Every error registered for a field, as a non-empty array (the\n * write-side {@link setErrorByPath} normalizes to this invariant, so\n * readers never need to guard against an empty list). Readers wanting\n * the display error take the first entry ({@link getError}); readers\n * wanting all of them use {@link getFieldErrors}. */\n errors: Map<string, FieldError[]>;\n touched: Set<string>;\n validators: Map<string, () => void>;\n validating: Set<string>;\n /** Parsed values from the last successful schema validation: the\n * schema's complete output tree (coerced/transformed values included).\n * Sits between initialValues and the values Map in {@link getValues}\n * until `reset`/`setInitialValues` clears it. Never affects dirty\n * state — that compares live edits against initialValues only. */\n parsedValues: T | undefined;\n validate?: (values: T) => ValidateResult<T>;\n isSubmitting: boolean;\n submitCount: number;\n isSubmitSuccessful: boolean | undefined;\n /** Form-level disabled flag, OR-ed into every bound field's `disabled`\n * (form flag || the field's own option). Seeded from\n * {@link Options}.disabled at create time and toggled at runtime with\n * {@link setDisabled}, which emits a payload-less 'disabled' event so\n * subscribed fields re-render. */\n disabled: boolean;\n}\n\nexport type Options<T extends Record<string, any> = any> = {\n initialValues?: T;\n /** When fields are validated. Defaults to `'onSubmit'`. See\n * {@link ValidationMode}. */\n mode?: ValidationMode;\n /** When a field is re-validated after it already has an error — it only\n * takes effect once the field has an error. Defaults to `'onChange'`. See\n * {@link ReValidateMode}. */\n reValidateMode?: ReValidateMode;\n /**\n * Form-level validator. Returns a record of errors keyed by field path;\n * nested objects are flattened ('a.b' style) and array values contribute\n * every non-empty string they hold as separate errors (zod `flatten()`\n * formErrors style). Schema adapters instead return a branded\n * {@link ValidationOutcome}: `errors` flattens the same way, `values`\n * (the schema's parsed output) becomes the form's parsedValues baseline\n * that {@link getValues} layers over initialValues.\n */\n validate?: (values: T) => ValidateResult<T>;\n /** Start the form with every bound field disabled — the flag bound\n * fields OR with their own `disabled` option (a field cannot opt out\n * of a disabled form). Toggle later with {@link setDisabled}.\n * Defaults to `false`. */\n disabled?: boolean;\n};\n\n/**\n * Create form instance\n * @param options\n * @return form instance\n */\nexport default function create<T extends Record<string, any> = any>(\n options?: Options<T>\n): Form<T> {\n const emitter = createEmitter();\n return {\n emitter,\n ...options,\n mode: options?.mode ?? 'onSubmit',\n reValidateMode: options?.reValidateMode ?? 'onChange',\n disabled: options?.disabled ?? false,\n initialValues: (options?.initialValues ?? {}) as T,\n values: new Map(),\n deleted: new Set(),\n errors: new Map(),\n touched: new Set(),\n validators: new Map(),\n validating: new Set(),\n parsedValues: undefined,\n isSubmitting: false,\n submitCount: 0,\n isSubmitSuccessful: undefined\n };\n}\n\n/**\n * Get form values: the values Map layered over parsedValues (when a schema\n * validation produced them) layered over initialValues.\n *\n * Merged with copy-on-write ownership tracking ({@link setOwned}): every\n * distinct container on a written path is allocated once and shared by all\n * paths through it, instead of re-copying the whole branch for every key.\n * One owned set spans the whole merge, so containers borrowed from the\n * parsedValues tree are copied before mutation exactly like initialValues\n * ones. The result is still a freshly merged tree per call, with untouched\n * branches sharing references with the baseline exactly like chained\n * `set` did -- callers may treat it as their own copy.\n *\n * parsedValues is the schema's complete output tree: once validation\n * succeeds it replaces the initialValues baseline (fields the schema\n * dropped disappear), while live edits in the values Map still win over\n * both. It never affects dirty state — {@link isDirty} and\n * {@link getDirtyFields} compare live edits against initialValues only,\n * because parsing is not a user edit.\n *\n * @param form\n */\nexport function getValues<T extends Record<string, any> = any>(\n form: Form<T>\n): T {\n const {initialValues, parsedValues, values, deleted} = form;\n const owned = new Set<object>();\n let merged = parsedValues ?? initialValues;\n for (const [key, value] of values) {\n merged = setOwned(merged, JSON.parse(key), value, owned);\n }\n // Unregistered fields leave a tombstone in `deleted`; remove those paths\n // from the merged result so they don't fall back to initialValues. unset\n // is immutable (set() shares untouched branches with initialValues, so a\n // mutating delete would corrupt them) and deletes the key outright rather\n // than writing undefined, which would leave `a: undefined` entries behind\n // in anything that spreads getValues().\n for (const key of deleted) {\n merged = unset(merged, JSON.parse(key));\n }\n return merged;\n}\n\n/**\n * Get field value\n * @param form\n * @param name\n */\nexport function getValue<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): PathValueOf<T, P> {\n return getValueByPath(form, createPath(name));\n}\n\n/**\n * Get field value by path\n * @param form\n * @param path\n */\nexport function getValueByPath(\n {initialValues, parsedValues, values, deleted}: Form,\n path: Path\n): any {\n if (values.has(path.key)) return values.get(path.key);\n // Unregistered path: the tombstone blocks the initialValues fallback.\n if (deleted.has(path.key)) return undefined;\n // Same layering as getValues: parsed values (when present) are the\n // baseline above initialValues.\n return get(parsedValues ?? initialValues, path.value);\n}\n\n/** Options accepted by {@link setValue} / {@link setValueByPath}. Every flag\n * defaults to `false`; omitting the options object entirely keeps the plain\n * set-value behavior (no validation, no touched marking). */\nexport interface SetFieldOptions {\n /** Run the field's registered validator (if any) after the value lands,\n * same as triggering that single field. Defaults to `false`. */\n shouldValidate?: boolean;\n /** Mark the field as touched. Defaults to `false`. */\n shouldTouch?: boolean;\n /** Reserved for a future manual dirty marker. Dirty state is currently\n * derived from comparing values against initialValues, so this flag is\n * accepted but does nothing. Defaults to `false`. */\n shouldDirty?: boolean;\n}\n\n/**\n * Set field value\n * @param form\n * @param name\n * @param value\n * @param options\n */\nexport function setValue<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(\n form: Form<T>,\n name: P,\n value: PathValueOf<T, P>,\n options?: SetFieldOptions\n): void {\n setValueByPath(form, createPath(name), value, options);\n}\n\n/**\n * Set field value\n * @param form\n * @param path\n * @param value\n * @param options\n */\nexport function setValueByPath(\n form: Form,\n path: Path,\n value: any,\n options?: SetFieldOptions\n): void {\n const {emitter, values, deleted} = form;\n values.set(path.key, value);\n reviveBranch(deleted, path);\n bumpDirtyVersion(form);\n if (options?.shouldTouch) setTouchedByPath(form, path);\n if (options?.shouldValidate) form.validators.get(path.key)?.();\n emit(emitter, 'change', path);\n}\n\n/**\n * Get field error\n * @param form\n * @param name\n * @return FieldError object or undefined\n */\nexport function getError<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldError | undefined {\n return getErrorByPath(form, createPath(name));\n}\n\n/**\n * Get field error by path\n * @param form\n * @param path\n * @return first FieldError of the field, or undefined\n */\nexport function getErrorByPath(\n {errors}: Form,\n path: Path\n): FieldError | undefined {\n return errors.get(path.key)?.[0];\n}\n\n/** Shared empty result for {@link getFieldErrorsByPath}: a fresh `[]` per\n * call would allocate on the hot no-error path, and the stored arrays are\n * handed out by reference too, so callers must treat results as read-only. */\nconst NO_ERRORS: FieldError[] = [];\n\n/**\n * Get all errors of a field\n * @param form\n * @param name\n * @return every error registered for the field (insertion order); an empty\n * array when the field has none\n */\nexport function getFieldErrors<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldError[] {\n return getFieldErrorsByPath(form, createPath(name));\n}\n\n/**\n * Get all errors of a field by path\n * @param form\n * @param path\n * @return every error registered for the field (insertion order); an empty\n * array when the field has none\n */\nexport function getFieldErrorsByPath({errors}: Form, path: Path): FieldError[] {\n return errors.get(path.key) ?? NO_ERRORS;\n}\n\n/**\n * Get all errors\n * @param form\n * @return array of {path, type, message} entries, in insertion order; path\n * is the user-facing dotted field path ('a.b', 'list.0'), and a\n * field holding several errors contributes one entry per error\n */\nexport function getErrors({errors}: Form): FieldErrorEntry[] {\n const entries: FieldErrorEntry[] = [];\n for (const [key, list] of errors) {\n const path = (JSON.parse(key) as PathSegments).join('.');\n for (const {type, message} of list) entries.push({path, type, message});\n }\n return entries;\n}\n\n/**\n * Get first error message\n * @param form\n * @return first error's message string, or undefined when there are no errors\n */\nexport function getFirstError({errors}: Form): string | undefined {\n return errors.values().next().value?.[0]?.message;\n}\n\n/** Snapshot of one field's aggregated state, as {@link getFieldState}\n * returns it. `errors` is the stored array shared with the form — treat it\n * as read-only, like every {@link getFieldErrors} result. */\nexport interface FieldState<T = any> {\n value: T;\n error: FieldError | undefined;\n errors: FieldError[];\n isDirty: boolean;\n isTouched: boolean;\n isValidating: boolean;\n}\n\n/**\n * Get one field's aggregated state: the layered value ({@link getValue}),\n * the first error ({@link getError}) and every error ({@link\n * getFieldErrors}), dirtiness, the touched flag, and whether a validator\n * is in flight. `isDirty` applies the same per-field rule as {@link\n * getDirtyFields}: a live value exists and differs from initialValues at\n * that path (parsedValues never counts — parsing is not an edit).\n *\n * @param form\n * @param name\n */\nexport function getFieldState<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldState<PathValueOf<T, P>> {\n const path = createPath(name);\n const {initialValues, values, touched, validating} = form;\n const live = values.get(path.key);\n return {\n value: getValueByPath(form, path),\n error: getErrorByPath(form, path),\n errors: getFieldErrorsByPath(form, path),\n isDirty: values.has(path.key) && get(initialValues, path.value) !== live,\n isTouched: touched.has(path.key),\n isValidating: validating.has(path.key)\n };\n}\n\nexport function unsetValidatingByPath(\n {emitter, validating}: Form,\n path: Path\n): void {\n validating.delete(path.key);\n // Path payload lets key-scoped subscribers (onKeyEvent) skip unrelated\n // fields; payload-less listeners ignore it.\n emit(emitter, 'validating', path);\n}\n\nexport function setValidatingByPath(\n {emitter, validating}: Form,\n path: Path\n): void {\n validating.add(path.key);\n emit(emitter, 'validating', path);\n}\n\n/**\n * Set field error\n * @param form\n * @param name\n * @param error string is normalized to {type: 'custom', message}; a\n * FieldError object is stored as-is; an array holds several errors\n * (falsy items dropped, strings normalized); undefined clears\n */\nexport function setError<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(\n form: Form<T>,\n name: P,\n error: string | FieldError | (string | FieldError)[] | undefined\n): void {\n setErrorByPath(form, createPath(name), error);\n}\n\n/**\n * Set field error\n * @param form\n * @param path\n * @param error string is normalized to {type: 'custom', message}; a\n * FieldError object is stored as-is; an array holds several errors\n * (falsy items dropped, strings normalized); undefined clears\n */\nexport function setErrorByPath(\n {emitter, errors}: Form,\n path: Path,\n error: string | FieldError | (string | FieldError)[] | undefined\n): void {\n const list = normalizeErrors(error);\n // An empty result (undefined, '', or an array of only falsy items) clears\n // the key: the errors Map never stores an empty list, so hasErrors stays\n // a plain size check and readers can index [0] unguarded.\n if (list) errors.set(path.key, list);\n else errors.delete(path.key);\n // Path payload lets key-scoped subscribers (onKeyEvent) skip unrelated\n // fields; payload-less listeners ignore it.\n emit(emitter, 'errors', path);\n}\n\n/** Normalize any {@link setErrorByPath} input into the stored non-empty\n * FieldError[] shape, or undefined when there is nothing to store. */\nfunction normalizeErrors(\n error: string | FieldError | (string | FieldError)[] | undefined\n): FieldError[] | undefined {\n if (typeof error === 'string') {\n return error ? [{type: 'custom', message: error}] : undefined;\n }\n if (isFieldError(error)) return [error];\n if (!error) return undefined;\n // Falsy items drop out before normalization, so '' never becomes a\n // stored {type: 'custom', message: ''} placeholder.\n const list: FieldError[] = [];\n error.forEach(item => {\n if (typeof item === 'string' && item) {\n list.push({type: 'custom', message: item});\n } else if (isFieldError(item)) {\n list.push(item);\n }\n });\n return list.length ? list : undefined;\n}\n\n/**\n * Clear errors\n * @param form\n * @param name a single path or a list of paths; omit to clear every error\n */\nexport function clearErrors(form: Form, name?: Name | Name[]): void {\n const {emitter, errors} = form;\n if (name === undefined) {\n errors.clear();\n // Payload-less broadcast: every error subscriber re-syncs.\n emit(emitter, 'errors');\n return;\n }\n // Same single-path vs list discrimination as trigger: a segment array\n // holding a number is one path ('a.0' shape), not a list of names.\n const paths =\n typeof name === 'string' || isSegmentsPath(name)\n ? [createPath(name)]\n : name.map(one => createPath(one));\n for (const {key} of paths) errors.delete(key);\n // Path-payload emits — the setErrorByPath scoping — wake exactly the\n // affected fields' subscribers.\n for (const path of paths) emit(emitter, 'errors', path);\n}\n\n/**\n * Set field touched state\n * @param form\n * @param name\n */\nexport function setTouched(form: Form, name: Name): void {\n setTouchedByPath(form, createPath(name));\n}\n\n/**\n * Set field touched state\n * @param form\n * @param path\n */\nexport function setTouchedByPath({emitter, touched}: Form, path: Path): void {\n if (touched.has(path.key)) return;\n touched.add(path.key);\n // Path payload lets key-scoped subscribers (onKeyEvent) skip unrelated\n // fields; payload-less listeners ignore it.\n emit(emitter, 'touched', path);\n}\n\n/**\n * Check if field has been touched\n * @param form\n * @param name\n */\nexport function hasTouched<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): boolean {\n return hasTouchedByPath(form, createPath(name));\n}\n\n/**\n * Check if field has been touched\n * @param form\n * @param path\n */\nexport function hasTouchedByPath({touched}: Form, path: Path): boolean {\n return touched.has(path.key);\n}\n\n/**\n * Is dirty -- any value differs from initialValues\n * @param form\n */\nexport function isDirty(form: Form): boolean {\n let dirty = false;\n forEachDirtyField(form, () => {\n dirty = true;\n });\n return dirty;\n}\n\nfunction forEachDirtyField(\n {initialValues, values}: Form,\n fn: (dottedKey: string) => void\n): void {\n for (const [key, value] of values) {\n const path = JSON.parse(key) as PathSegments;\n if (get(initialValues, path) !== value) fn(path.join('.'));\n }\n}\n\n/** Per-form memoization of {@link getDirtyFields}. `version` counts value\n * mutations since the cached `result` was computed: bump points increment\n * it, reads reset it, so a non-zero version means the cache is stale. */\ninterface DirtyFieldsCache {\n version: number;\n result: Record<string, boolean>;\n}\n\nconst dirtyFieldsCaches = new WeakMap<Form, DirtyFieldsCache>();\n\n/**\n * Invalidate `form`'s cached {@link getDirtyFields} result. Called at every\n * point that can change values or initialValues (setValueByPath,\n * removeFieldByPath, setInitialValues, reset) so repeated reads hand out a\n * stable reference and useWatch's Object.is snapshot check can skip\n * re-renders.\n */\nfunction bumpDirtyVersion(form: Form): void {\n const cache = dirtyFieldsCaches.get(form);\n if (cache) cache.version++;\n}\n\nfunction computeDirtyFields(form: Form): Record<string, boolean> {\n const dirtyFields: Record<string, boolean> = {};\n forEachDirtyField(form, key => {\n dirtyFields[key] = true;\n });\n return dirtyFields;\n}\n\n/** Dirty entries only ever map to `true`, so equal key sets mean shallow\n * equal results. */\nfunction sameDirtyKeys(\n a: Record<string, boolean>,\n b: Record<string, boolean>\n): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n return aKeys.every(key => b[key] === true);\n}\n\n/**\n * Get dirty fields -- fields whose current value differs from initialValues.\n * Keys are user-facing dotted paths ('a.b', 'a.0.c'), unlike the JSON array\n * keys stored in the values Map.\n * @param form\n * @return object mapping each dirty field's dotted path to true; the same\n * reference is returned until the dirty set actually changes\n */\nexport function getDirtyFields(form: Form): Record<string, boolean> {\n let cache = dirtyFieldsCaches.get(form);\n if (!cache) {\n cache = {version: 0, result: computeDirtyFields(form)};\n dirtyFieldsCaches.set(form, cache);\n } else if (cache.version > 0) {\n const result = computeDirtyFields(form);\n // Keep the old reference when the dirty set is unchanged (values always\n // map to true) so subscribers see identity-stable snapshots.\n if (!sameDirtyKeys(cache.result, result)) cache.result = result;\n cache.version = 0;\n }\n return cache.result;\n}\n\n/**\n * Get touched fields as user-facing dotted paths ('a.b', 'a.0.c'), unlike\n * the JSON array keys stored in the touched Set.\n * @param form\n * @return array of touched fields' dotted paths\n */\nexport function getTouchedFields({touched}: Form): string[] {\n return Array.from(touched, key =>\n (JSON.parse(key) as PathSegments).join('.')\n );\n}\n\n/**\n * Is touched -- any field has been touched\n * @param form\n */\nexport function isTouched({touched}: Form): boolean {\n return touched.size > 0;\n}\n\n/**\n * Remove field\n * @param form\n * @param name\n */\nexport function removeField(form: Form, name: Name): void {\n removeFieldByPath(form, createPath(name));\n}\n\n/**\n * Remove field\n * @param form\n * @param path\n */\nexport function removeFieldByPath(\n form: Form,\n {key, value: segments}: Path\n): void {\n const {emitter, values, touched, errors, validating, deleted} = form;\n values.delete(key);\n touched.delete(key);\n errors.delete(key);\n validating.delete(key);\n // Tombstone the unregistered path so later reads do not fall back to\n // initialValues and \"revive\" the field's old initial value. A tombstone\n // never shadows live values: skip it when the branch is already covered\n // by a live ancestor key (e.g. a FieldArray rewrite stored the whole\n // array at the parent path) or a still-mounted descendant key.\n if (!hasLiveBranch(values, segments)) deleted.add(key);\n bumpDirtyVersion(form);\n emit(emitter, 'change');\n emit(emitter, 'touched');\n emit(emitter, 'errors');\n emit(emitter, 'validating');\n}\n\n/**\n * Does a live value cover the branch at `segments` -- either at an ancestor\n * key or below it at a descendant key?\n */\nfunction hasLiveBranch(\n values: Map<string, any>,\n segments: PathSegments\n): boolean {\n for (let i = 1; i < segments.length; i++) {\n if (values.has(JSON.stringify(segments.slice(0, i)))) return true;\n }\n const stem = `${JSON.stringify(segments).slice(0, -1)},`;\n for (const key of values.keys()) {\n if (key.startsWith(stem)) return true;\n }\n return false;\n}\n\n/**\n * Writing a value revives its whole branch: drop any removal tombstone for\n * the path itself, its ancestors, or its descendants (a remounted field\n * overwrites its own tombstone; rewriting a parent array supersedes the\n * tombstones of shifted child paths).\n */\nfunction reviveBranch(deleted: Set<string>, {key}: Path): void {\n if (!deleted.size) return;\n for (const tombstone of deleted) {\n if (\n tombstone === key ||\n tombstone.startsWith(`${key.slice(0, -1)},`) ||\n key.startsWith(`${tombstone.slice(0, -1)},`)\n ) {\n deleted.delete(tombstone);\n }\n }\n}\n\n/**\n * Set form initialValues\n * @param form\n * @param initialValues\n */\nexport function setInitialValues(form: Form, initialValues: any): void {\n if (form.initialValues === initialValues) return;\n form.initialValues = initialValues;\n // A new baseline invalidates the previous schema parse.\n form.parsedValues = undefined;\n form.values.clear();\n form.deleted.clear();\n bumpDirtyVersion(form);\n emit(form.emitter, 'change');\n}\n\n/** Options accepted by {@link reset}. Every flag defaults to `false` —\n * omitting the object (or any flag) keeps the plain full-reset behavior.\n * Names mirror react-hook-form's reset options to ease migration. */\nexport interface ResetOptions {\n /** Keep the current values of fields that are dirty — differ from the\n * pre-reset initialValues (the same rule {@link getDirtyFields} applies).\n * Clean fields fall back to the new initialValues as usual. */\n keepDirtyValues?: boolean;\n /** Keep the touched set instead of clearing it. */\n keepTouched?: boolean;\n /** Keep field errors instead of clearing them. */\n keepErrors?: boolean;\n /** Keep the submitted flag (`isSubmitSuccessful`) instead of clearing\n * it. */\n keepIsSubmitted?: boolean;\n /** Keep `submitCount` instead of resetting it to 0. */\n keepSubmitCount?: boolean;\n /** Keep `isSubmitting` instead of resetting it to false. */\n keepIsSubmitting?: boolean;\n}\n\n/**\n * Reset form\n * @param form\n * @param initialValues\n * @param options keep-flags to preserve slices of state through the reset\n */\nexport function reset(\n form: Form,\n initialValues?: any,\n options?: ResetOptions\n): void {\n // Snapshot dirty fields' live values before the wipe: dirtiness is\n // measured against the pre-reset initialValues, so capture must happen\n // before form.values and form.initialValues are touched.\n const dirtyValues = options?.keepDirtyValues\n ? Object.keys(getDirtyFields(form)).map(key => ({\n key,\n value: getValue(form, key)\n }))\n : [];\n form.initialValues = initialValues;\n // The fresh baseline drops any schema parse from the previous cycle.\n form.parsedValues = undefined;\n if (!options?.keepErrors) clearErrors(form);\n const {emitter, touched, values, deleted, validating} = form;\n values.clear();\n deleted.clear();\n if (!options?.keepTouched) touched.clear();\n validating.clear();\n if (!options?.keepIsSubmitting) form.isSubmitting = false;\n if (!options?.keepSubmitCount) form.submitCount = 0;\n if (!options?.keepIsSubmitted) form.isSubmitSuccessful = undefined;\n bumpDirtyVersion(form);\n // Write the kept dirty values back over the fresh baseline: plain\n // setValueByPath, so no validation fires and nothing is marked touched.\n for (const {key, value} of dirtyValues) {\n setValueByPath(form, createPath(key), value);\n }\n emit(emitter, 'change');\n emit(emitter, 'touched');\n emit(emitter, 'validating');\n emit(emitter, 'submitting');\n emit(emitter, 'submitCount');\n emit(emitter, 'submitSuccessful');\n emit(emitter, 'reset');\n}\n\n/** Options accepted by {@link resetField}. The flags default to `false`;\n * `value` has no default — omitted, the field falls back to initialValues;\n * provided, the explicit value becomes the live value with no fallback at\n * all. Mirrors react-hook-form's resetField options (`value` plays their\n * `defaultValue`'s role) to ease migration. */\nexport interface ResetFieldOptions {\n /** Keep the field's touched flag instead of clearing it. */\n keepTouched?: boolean;\n /** Keep the field's errors instead of clearing them. */\n keepErrors?: boolean;\n /** Explicit post-reset value for the field — never falls back to\n * initialValues. */\n value?: any;\n}\n\n/**\n * Reset a single field: drop its live value (reads fall back to the\n * baseline — initialValues, or the schema's parsed output when one\n * exists, in which case the path is removed from parsedValues and the\n * initial value pinned back so the field reads initialValues again),\n * clear its touched flag and errors, and revive the path's removal\n * tombstones — the inverse of {@link removeFieldByPath}. Other fields\n * and the submission flags are untouched; see {@link reset} for the\n * form-wide counterpart.\n *\n * @param form\n * @param name\n * @param options\n */\nexport function resetField<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P, options?: ResetFieldOptions): void {\n const path = createPath(name);\n const {emitter, values, touched, errors, deleted} = form;\n values.delete(path.key);\n // A parse baseline wholesale-shadows initialValues in reads (see\n // getValues), so unset alone would read the path as undefined. Remove\n // the path from the tree (immutable — parsedValues shares branches with\n // the schema's own output) and pin the initial value back as the live\n // value: equal to initialValues, so the field stays clean.\n if (form.parsedValues !== undefined) {\n form.parsedValues = unset(form.parsedValues, path.value);\n const initial = get(form.initialValues, path.value);\n if (initial !== undefined) values.set(path.key, initial);\n }\n if (options && 'value' in options) {\n values.set(path.key, options.value);\n }\n // A reset re-registers the branch, same as a write: tombstones on the\n // path or around it stop applying.\n reviveBranch(deleted, path);\n // Payload-less like removeFieldByPath: reviveBranch can un-tombstone\n // ancestor or descendant paths, whose readers must re-sync too.\n emit(emitter, 'change');\n if (!options?.keepTouched && touched.delete(path.key)) {\n emit(emitter, 'touched', path);\n }\n if (!options?.keepErrors && errors.delete(path.key)) {\n emit(emitter, 'errors', path);\n }\n bumpDirtyVersion(form);\n}\n\n/**\n * @param form\n */\nexport function hasErrors({errors}: Form): boolean {\n return errors.size > 0;\n}\n\n/**\n * Trigger field validation.\n *\n * Without `name` every registered field validator runs. A single `name` —\n * dotted string or segments array — runs only that field's validator, and\n * an array of names runs each one in order. An empty array is a no-op, as\n * is any name with no registered validator. An array argument counts as\n * one segments path only when it mixes in numbers (`['items', 0]`); pure\n * string arrays are name lists, so `['a', 'b']` triggers fields `a` and\n * `b`, not the nested path `a.b`.\n *\n * The returned promise waits for the triggered validation to settle —\n * async validators included — so their errors have already landed in\n * `form.errors` when it resolves. It never rejects: landing errors is the\n * expected outcome here, not a failure. Resolves `true` when the triggered\n * scope is error-free, `false` otherwise. Without `name` the scope is all\n * fields plus the form-level `validate` result (which runs after field\n * validators settle, same pipeline as {@link ensureValidate}); with `name`\n * only those fields' own errors count and form-level `validate` is\n * skipped (RHF semantics).\n *\n * Fire-and-forget callers may ignore the promise: the validator kicks\n * still happen synchronously, matching the pre-promise behavior.\n *\n * @param form\n * @param name field name(s) to trigger, or all fields when omitted\n * @return whether the triggered scope is error-free once validation settles\n */\nexport async function trigger(\n form: Form,\n name?: Name | Name[]\n): Promise<boolean> {\n // Never reject (an error landing is a normal outcome, not a failure), so\n // waitUntil's isReject is permanently false. Waiting on the whole\n // `validating` set is deliberately conservative: it also rides out\n // unrelated in-flight validators rather than racing them.\n const settle = () =>\n waitUntil(\n form.emitter,\n 'validating',\n () => !form.validating.size,\n () => false\n );\n\n if (name === undefined) {\n form.validators.forEach(validator => validator());\n await settle();\n if (form.validate) {\n const result = await form.validate(getValues(form));\n applyValidateResult(form, result);\n }\n return !hasErrors(form);\n }\n\n const keys: string[] =\n typeof name === 'string' || isSegmentsPath(name)\n ? [createPath(name).key]\n : name.map(one => createPath(one).key);\n keys.forEach(key => form.validators.get(key)?.());\n await settle();\n return keys.every(key => !form.errors.has(key));\n}\n\n/** Numbers only occur inside a segments path (`['a', 0]`), never as\n * standalone names, so a top-level number marks `name` as one single path\n * rather than a list of names. */\nfunction isSegmentsPath(name: PathSegments | Name[]): name is PathSegments {\n return (name as (number | unknown)[]).some(part => typeof part === 'number');\n}\n\nfunction isFieldError(value: any): value is FieldError {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof value.type === 'string' &&\n typeof value.message === 'string'\n );\n}\n\n/**\n * Flatten a form-level validate result and write each leaf error through\n * setError. Nested objects descend into deeper paths ({a: {b: 'msg'}} sets\n * the 'a.b' error), array values contribute every non-empty string they\n * hold as separate errors (zod flatten() formErrors style), and\n * FieldError-shaped objects are stored as-is. Falsy values are skipped.\n */\nfunction setFormErrors(\n form: Form,\n result: Record<string, any>,\n segments: PathSegments = []\n): void {\n Object.entries(result).forEach(([key, value]) => {\n const path: PathSegments = [...segments, ...normalizePath(key)];\n if (typeof value === 'string') {\n if (value) setError(form, path, value);\n } else if (Array.isArray(value)) {\n setError(form, path, value);\n } else if (isFieldError(value)) {\n setError(form, path, value);\n } else if (value && typeof value === 'object') {\n setFormErrors(form, value, path);\n }\n });\n}\n\n/** Store a schema validator's parsed output as the getValues baseline\n * layer above initialValues. Payload-less 'change' notifies value\n * watchers (useValue, useDirtyFields, ...); dirty state is untouched —\n * it only compares live edits against initialValues, and parsing is not\n * an edit. */\nfunction setParsedValues(form: Form, values: any): void {\n if (values === undefined || values === form.parsedValues) return;\n form.parsedValues = values;\n emit(form.emitter, 'change');\n}\n\n/**\n * Land a form-level validate result. A plain record keeps the\n * long-standing behavior — flattened into field errors by\n * {@link setFormErrors}. A branded {@link ValidationOutcome} splits\n * instead: `errors` flattens exactly like a plain record, and `values`\n * (the schema's parsed output — coerced/transformed values included)\n * becomes the form's parsedValues baseline. Falsy results are skipped,\n * branded or not.\n */\nfunction applyValidateResult(\n form: Form,\n result: ValidateResult<any> | undefined\n): void {\n if (!result) return;\n if (typeof result === 'object' && VALIDATION_OUTCOME in result) {\n const outcome = result as ValidationOutcome<any>;\n if (outcome.errors) setFormErrors(form, outcome.errors);\n setParsedValues(form, outcome.values);\n return;\n }\n setFormErrors(form, result as Record<string, any>);\n}\n\n/**\n * Validate and throw if any field error.\n * @param form\n * @return resolve if no error; reject and stop validate if has an error\n */\nexport async function ensureValidate(form: Form): Promise<void> {\n form.validators.forEach(validator => validator());\n\n await waitUntil(\n form.emitter,\n 'validating',\n () => !form.validating.size,\n () => hasErrors(form)\n ).catch(() => {\n throw new Error(getFirstError(form));\n });\n\n if (form.validate) {\n const result = await form.validate(getValues(form));\n applyValidateResult(form, result);\n if (hasErrors(form)) throw new Error(getFirstError(form));\n }\n}\n\n/**\n * Validate and return if any field error.\n * @param form\n * @return error message string or void\n */\nexport async function validate(form: Form): Promise<void | string> {\n return ensureValidate(form).catch(e => e.message);\n}\n\nexport function setIsSubmitting(form: Form, value: boolean): void {\n form.isSubmitting = value;\n emit(form.emitter, 'submitting');\n}\n\nexport function incrementSubmitCount(form: Form): void {\n form.submitCount++;\n emit(form.emitter, 'submitCount');\n}\n\nexport function setSubmitSuccessful(form: Form, value: boolean): void {\n form.isSubmitSuccessful = value;\n emit(form.emitter, 'submitSuccessful');\n}\n\n/**\n * Set the form-level disabled flag and emit a payload-less 'disabled'\n * event — subscribed fields (useField and the components built on it)\n * re-render with the merged disabled state: form flag || their own\n * `disabled` option.\n * @param form\n * @param value\n */\nexport function setDisabled(form: Form, value: boolean): void {\n form.disabled = value;\n emit(form.emitter, 'disabled');\n}\n\n/** Structural slice of a <form>-like element: an elements collection whose\n * controls expose the constraint-validation members we read. Matches the\n * DOM HTMLFormElement shape without coupling the core to DOM types. */\ninterface NativeFormElement {\n elements: ArrayLike<{\n name: string;\n checkValidity: () => boolean;\n validationMessage: string;\n }>;\n}\n\n/**\n * Converts a control's DOM name to the user-visible dotted path. Field\n * components render the path key (JSON.stringify'd segments, '[\"a\",\"0\"]')\n * as the name attribute, so JSON keys are parsed back and joined with\n * dots; any other name value is returned as-is.\n */\nfunction nameToPath(name: string): string {\n if (name.startsWith('[')) {\n try {\n const segments = JSON.parse(name);\n if (Array.isArray(segments)) return segments.join('.');\n } catch {\n // Not a JSON path key — fall through and use the raw name.\n }\n }\n return name;\n}\n\n/**\n * Collects the constraints failing native validation on a <form> as\n * {@link FieldErrorEntry} entries, in DOM order.\n *\n * Design note: native errors are deliberately NOT written into the form's\n * errors Map. That Map tracks custom validator state, while native\n * validity is transient DOM state owned by the browser (surfaced through\n * reportValidity); onInvalidSubmit receives this snapshot directly.\n */\nfunction getNativeErrors(formEl: NativeFormElement): FieldErrorEntry[] {\n const errors: FieldErrorEntry[] = [];\n const {elements} = formEl;\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n if (\n el.name &&\n typeof el.checkValidity === 'function' &&\n !el.checkValidity()\n ) {\n errors.push({\n path: nameToPath(el.name),\n type: 'native',\n message: el.validationMessage\n });\n }\n }\n return errors;\n}\n\n/** Submit callbacks for {@link handleSubmit}. All optional — a missing\n * callback is simply skipped, matching the <Form> component semantics. */\nexport interface HandleSubmitOptions<T extends Record<string, any> = any> {\n /** Called after validation passes, before onValidSubmit. */\n onSubmit?: (values: T, e?: any) => void | Promise<void>;\n /** Called after validation passes, following a successful onSubmit. */\n onValidSubmit?: (values: T, e?: any) => void | Promise<void>;\n /**\n * Called when validation fails.\n * @param errors array of {path, type, message} entries in insertion\n * order; path is the dotted field path ('a.b', 'list.0'), type is\n * the error kind ('custom' for plain string errors, 'native' for\n * failed DOM constraint validation), message is the display text\n * @param values current form values\n */\n onInvalidSubmit?: (errors: FieldErrorEntry[], values: T) => void;\n /**\n * Focus the first error field after a failed submit. Defaults to true —\n * only an explicit `false` disables it. When custom validation fails,\n * a 'focusError' event carrying the first error's path key is emitted\n * on the form (bound fields such as <Field> subscribe and focus their\n * input); when native constraint validation fails, the submitted\n * form's first ':invalid' control is focused directly.\n */\n shouldFocusError?: boolean;\n}\n\n/**\n * Create an async submit handler for `form` — the headless counterpart of\n * the <Form> component's onSubmit wiring.\n *\n * Behavior mirrors <Form> exactly: preventDefault when present, then the\n * submit state machine (isSubmitting/submitCount/isSubmitSuccessful) runs\n * around native constraint validation (via `e.currentTarget.checkValidity`,\n * skipped when the target has no checkValidity — e.g. React Native or\n * toolbar-button submits) and custom validators. Failed validation fires\n * onInvalidSubmit with the flattened error entries; a passing submit runs\n * onSubmit then onValidSubmit. Errors thrown by either are swallowed into\n * isSubmitSuccessful=false rather than rejecting the returned promise.\n * Failed validation also focuses the offending field (see\n * {@link HandleSubmitOptions.shouldFocusError}).\n *\n * @param form form instance\n * @param options submit callbacks\n * @return async event handler, callable without an event object\n */\nexport function handleSubmit<T extends Record<string, any> = any>(\n form: Form<T>,\n options?: HandleSubmitOptions<T>\n): (e?: {preventDefault?: () => void; currentTarget?: any}) => Promise<void> {\n const {\n onSubmit,\n onValidSubmit,\n onInvalidSubmit,\n shouldFocusError = true\n } = options ?? {};\n return async e => {\n if (e && typeof e.preventDefault === 'function') {\n e.preventDefault();\n }\n const formEl = e?.currentTarget;\n setIsSubmitting(form, true);\n incrementSubmitCount(form);\n const values = getValues(form);\n\n if (\n formEl &&\n typeof formEl.checkValidity === 'function' &&\n formEl.checkValidity() === false\n ) {\n formEl.reportValidity();\n // Focus the first natively-invalid control directly off the DOM;\n // native failures never enter the errors Map (see below).\n if (shouldFocusError && typeof formEl.querySelector === 'function') {\n const invalid = formEl.querySelector(':invalid') as HTMLElement | null;\n if (invalid && typeof invalid.focus === 'function') invalid.focus();\n }\n setIsSubmitting(form, false);\n setSubmitSuccessful(form, false);\n // Native constraint failures are read from the DOM (not the errors\n // Map, which only holds custom validation state — see getNativeErrors).\n if (onInvalidSubmit) onInvalidSubmit(getNativeErrors(formEl), values);\n return;\n }\n\n const error = await validate(form);\n\n if (error) {\n setIsSubmitting(form, false);\n setSubmitSuccessful(form, false);\n // Notify bound fields (e.g. <Field>) so the first errored one can\n // focus its input; the payload is the errors Map's first key.\n if (shouldFocusError) {\n const firstKey = form.errors.keys().next().value;\n if (firstKey !== undefined) emit(form.emitter, 'focusError', firstKey);\n }\n if (onInvalidSubmit) onInvalidSubmit(getErrors(form), values);\n return;\n }\n\n try {\n // Re-read after validation: a schema validator's parsed output\n // (ValidationOutcome.values) landed in parsedValues during\n // validate(), and the submit callbacks must see the coerced /\n // transformed values, not the raw pre-validation snapshot.\n const submitted = getValues(form);\n if (onSubmit) await onSubmit(submitted, e);\n if (onValidSubmit) await onValidSubmit(submitted, e);\n setSubmitSuccessful(form, true);\n } catch {\n setSubmitSuccessful(form, false);\n } finally {\n setIsSubmitting(form, false);\n }\n };\n}\n\n/** Options accepted by {@link setFocus}. All flags default to `false`. */\nexport interface SetFocusOptions {\n /** Select the field's text after focusing it. Bound fields call\n * `select()` on their element; elements without one (custom `as`\n * components) just focus. */\n shouldSelect?: boolean;\n}\n\n/**\n * Programmatically focus a bound field's element (e.g. the <Field>'s\n * input).\n *\n * Rides the same 'focusError' event channel a failed handleSubmit uses to\n * focus the first errored field: the payload is the target's path key,\n * with the focus options as a second, backward-compatible argument (older\n * subscribers declared with a single `key` parameter simply ignore it).\n * Being event-driven, it is a silent no-op when the field is unmounted or\n * nothing subscribes — unknown names never throw.\n *\n * @param form form instance\n * @param name field name (dot path or segments path)\n * @param options focus options\n */\nexport function setFocus(\n form: Form,\n name: Name,\n options?: SetFocusOptions\n): void {\n const {key} = createPath(name);\n // Omit the options argument when absent so the payload is exactly the\n // shape handleSubmit emits after a failed submit.\n if (options) emit(form.emitter, 'focusError', key, options);\n else emit(form.emitter, 'focusError', key);\n}\n","import type {FieldError} from './form';\nimport type {Validator} from './hooks/validate';\n\n/** Type tag of a failed rule, as stored on the resulting FieldError. */\nexport type RuleType =\n | 'required'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * Declarative field rules — a subset of react-hook-form's `register` rules.\n *\n * Failed rules land in the form's error state as FieldErrors (`type` is the\n * rule name) instead of only surfacing through the browser's validity\n * bubble, so any design system can render the messages uniformly.\n */\nexport interface FieldRules {\n /**\n * Fails on empty values: `''`, `undefined` or `null` (`0` and `false`\n * count as filled). A string is the error message; `true` uses the\n * default. When it fails, the remaining rules are skipped — an empty\n * value reports only its required error.\n */\n required?: string | true;\n /** Fails when `Number(value)` is below this bound; `NaN` values skip. */\n min?: number;\n /** Fails when `Number(value)` is above this bound; `NaN` values skip. */\n max?: number;\n /** Fails when a string value is shorter than this; non-strings skip. */\n minLength?: number;\n /** Fails when a string value is longer than this; non-strings skip. */\n maxLength?: number;\n /** Fails when the value does not match `pattern.value`. */\n pattern?: {value: RegExp; message: string};\n /**\n * Overrides the message per rule type — `min`, `max`, `minLength`,\n * `maxLength` defaults and pattern's inline `message` alike — e.g. for\n * centralizing or localizing messages.\n */\n messages?: Partial<Record<Exclude<RuleType, 'required'>, string>>;\n}\n\n/** Default English messages, aligned with RHF's default-message style. */\nfunction defaultMessage(type: RuleType, bound?: number): string {\n switch (type) {\n case 'required':\n return 'This field is required';\n case 'min':\n return `Must be at least ${bound}`;\n case 'max':\n return `Must be at most ${bound}`;\n case 'minLength':\n return `Must be at least ${bound} characters`;\n case 'maxLength':\n return `Must be at most ${bound} characters`;\n case 'pattern':\n return 'Invalid format';\n default:\n return 'Invalid value';\n }\n}\n\n/**\n * Compile declarative {@link FieldRules} into a {@link Validator}.\n *\n * `required` is checked first and, when it fails on an empty value,\n * short-circuits the rest. Every other failing rule is collected into one\n * FieldError[] in declaration order (min, max, minLength, maxLength,\n * pattern); a fully passing value yields undefined. Messages resolve to\n * the rule's own string (required), `rules.messages`, or the default.\n *\n * @param rules declarative constraints\n * @return validator producing FieldError[] | undefined\n */\nexport function rulesToValidator(rules: FieldRules): Validator {\n return value => {\n if (rules.required) {\n if (value === '' || value === undefined || value === null) {\n return [\n {\n type: 'required',\n message:\n typeof rules.required === 'string'\n ? rules.required\n : defaultMessage('required')\n }\n ];\n }\n }\n const errors: FieldError[] = [];\n const message = (type: Exclude<RuleType, 'required'>, bound: number) =>\n rules.messages?.[type] ?? defaultMessage(type, bound);\n if (rules.min !== undefined) {\n const n = Number(value);\n if (!Number.isNaN(n) && n < rules.min) {\n errors.push({type: 'min', message: message('min', rules.min)});\n }\n }\n if (rules.max !== undefined) {\n const n = Number(value);\n if (!Number.isNaN(n) && n > rules.max) {\n errors.push({type: 'max', message: message('max', rules.max)});\n }\n }\n if (\n rules.minLength !== undefined &&\n typeof value === 'string' &&\n value.length < rules.minLength\n ) {\n errors.push({\n type: 'minLength',\n message: message('minLength', rules.minLength)\n });\n }\n if (\n rules.maxLength !== undefined &&\n typeof value === 'string' &&\n value.length > rules.maxLength\n ) {\n errors.push({\n type: 'maxLength',\n message: message('maxLength', rules.maxLength)\n });\n }\n if (rules.pattern && !rules.pattern.value.test(value)) {\n errors.push({\n type: 'pattern',\n // pattern.message is type-required but JS consumers may omit it.\n message:\n rules.messages?.pattern ??\n rules.pattern.message ??\n defaultMessage('pattern')\n });\n }\n return errors.length ? errors : undefined;\n };\n}\n","/**\n * @license React\n * use-sync-external-store-shim.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar React = require(\"react\");\nfunction is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\nvar objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nfunction useSyncExternalStore$2(subscribe, getSnapshot) {\n var value = getSnapshot(),\n _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n}\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n}\nfunction useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n}\nvar shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\nexports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n","/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n }\n function useSyncExternalStore$2(subscribe, getSnapshot) {\n didWarnOld18Alpha ||\n void 0 === React.startTransition ||\n ((didWarnOld18Alpha = !0),\n console.error(\n \"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release.\"\n ));\n var value = getSnapshot();\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n objectIs(value, cachedValue) ||\n (console.error(\n \"The result of getSnapshot should be cached to avoid an infinite loop\"\n ),\n (didWarnUncachedGetSnapshot = !0));\n }\n cachedValue = useState({\n inst: { value: value, getSnapshot: getSnapshot }\n });\n var inst = cachedValue[0].inst,\n forceUpdate = cachedValue[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n }\n function checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n }\n function useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n }\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());\n var React = require(\"react\"),\n objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue,\n didWarnOld18Alpha = !1,\n didWarnUncachedGetSnapshot = !1,\n shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\n exports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","import {on} from '@for-fun/event-emitter';\nimport type {EventEmitter} from '@for-fun/event-emitter';\nimport createPath from './path';\nimport type {Name, Path} from './path';\nimport type {Form} from './form';\n\n/** Subscription granularity for {@link onPathEvent}.\n * - `'leaf'`: the subscriber reads exactly one key ({@link\n * useValueByPath}); only writes at that key or above it can change what\n * it reads.\n * - `'branch'`: the subscriber aggregates a whole subtree below a key\n * ({@link useFieldArray}); descendant writes matter too. */\nexport type WatchScope = 'leaf' | 'branch';\n\n/**\n * Is `key` a strict descendant of `ancestorKey`?\n *\n * Keys are JSON.stringify'd segment arrays ('[\"a\",\"b\"]'), so a descendant\n * key is the ancestor key minus its closing ']' followed by a ','\n * ('[\"a\",\"b\",'). The ',' separator is mandatory: a plain prefix match\n * would let the sibling '[\"tagsX\"]' pass as a descendant of '[\"tags\"]'.\n */\nfunction isDescendant(key: string, ancestorKey: string): boolean {\n return key.startsWith(`${ancestorKey.slice(0, -1)},`);\n}\n\n/**\n * Subscribe to `event`, invoking `cb` only when the emitted path is\n * relevant to `path`.\n *\n * Payload-less broadcasts (reset, removeFieldByPath, setInitialValues)\n * always invoke `cb` -- they are global syncs and the correctness\n * fallback. When the emit carries a path P:\n * - `'leaf'`: P.key equals `path.key` or is one of its ancestors -- a leaf\n * read falls back to ancestor values (getValueByPath), so ancestor\n * writes must invalidate, while sibling and descendant writes cannot\n * change what the leaf reads.\n * - `'branch'`: `'leaf'` semantics plus P.key being a descendant of\n * `path.key` -- changed descendants re-aggregate the subtree.\n *\n * @param emitter emitter to subscribe to\n * @param event event name\n * @param path the watched path\n * @param scope which writes around `path` are relevant\n * @param cb listener, invoked with no arguments\n * @return unsubscribe function\n */\nexport function onPathEvent(\n emitter: EventEmitter,\n event: string,\n path: Path,\n scope: WatchScope,\n cb: () => void\n): () => void {\n const {key} = path;\n return on(emitter, event, (changed?: Path) => {\n if (\n changed === undefined ||\n changed.key === key ||\n isDescendant(key, changed.key) ||\n (scope === 'branch' && isDescendant(changed.key, key))\n ) {\n cb();\n }\n });\n}\n\n/**\n * Subscribe to `event`, invoking `cb` only when the emitted path's key is\n * exactly `key` (or the emit carries no payload -- a global sync).\n *\n * For state stored per exact key (errors, touched) no ancestor or\n * descendant matching is wanted: another field's key must not wake this\n * subscriber.\n *\n * @param emitter emitter to subscribe to\n * @param event event name\n * @param key exact path key to match\n * @param cb listener, invoked with no arguments\n * @return unsubscribe function\n */\nexport function onKeyEvent(\n emitter: EventEmitter,\n event: string,\n key: string,\n cb: () => void\n): () => void {\n return on(emitter, event, (changed?: Path) => {\n if (changed === undefined || changed.key === key) cb();\n });\n}\n\n/** Events {@link subscribe} can watch. `'errors'` and `'touched'` are\n * stored per exact key, so they match exact keys ({@link onKeyEvent});\n * `'change'`, `'submitting'` and `'submitCount'` carry paths and go\n * through {@link onPathEvent}. */\nexport type SubscribeEvent =\n | 'change'\n | 'errors'\n | 'touched'\n | 'submitting'\n | 'submitCount';\n\n/** Options accepted by {@link subscribe}. */\nexport type SubscribeOptions = {\n /** Path (or list of paths) to watch. Omit to receive every emission of\n * `event`, payload-less broadcasts included. A single segments path\n * (`['tags', 0]`) and a list of names (`['tags', 'user.name']`) are told\n * apart by the same rule `trigger` uses: only a segments path can hold\n * a number. */\n name?: Name | Name[];\n /** Event to watch. Defaults to `'change'`. */\n event?: SubscribeEvent;\n /** Which writes around `name` are relevant — `'leaf'` or `'branch'`.\n * Only meaningful for `'change'`: `'errors'`/`'touched'` match exact\n * keys and `'submitting'`/`'submitCount'` are payload-less. Defaults to\n * `'branch'` — the intuitive linkage semantics, where subscribing to\n * `'tags'` means the whole branch. */\n scope?: WatchScope;\n /** Invoked with no arguments after each matching emission. Read fresh\n * state through the `get*` readers inside it. */\n callback: () => void;\n};\n\n/** Is `name` a list of names rather than one segments path? Numbers only\n * occur inside a segments path (`['a', 0]`), never as standalone names —\n * the same disambiguation `trigger` applies to its name argument. */\nfunction isNameList(name: Name | Name[]): name is Name[] {\n return (\n Array.isArray(name) &&\n (name as (number | unknown)[]).every(part => typeof part !== 'number')\n );\n}\n\n/**\n * Subscribe to form events imperatively — the non-render counterpart of\n * the `use*` hooks: linkages and side effects (province changed → clear\n * city, autosave, analytics) run without mounting a watching component.\n *\n * Without `name`, `callback` fires on every `event` emission, payload-less\n * broadcasts (reset, setInitialValues) included. With `name`, matching\n * follows the event's shape: `'errors'`/`'touched'` match the exact key\n * ({@link onKeyEvent}) — another field's error never wakes this\n * subscriber — while `'change'`/`'submitting'`/`'submitCount'` go through\n * {@link onPathEvent}, so the default `'branch'` scope wakes a `'tags'`\n * subscriber when any `tags.*` descendant is written. A `name` array\n * builds one subscription per path and the returned function unsubscribes\n * them all.\n *\n * @param form the form to watch\n * @param options event, name(s), scope and callback\n * @return unsubscribe function\n */\nexport function subscribe(form: Form, options: SubscribeOptions): () => void {\n const {name, event = 'change', scope = 'branch', callback} = options;\n if (name === undefined) return on(form.emitter, event, callback);\n const names = isNameList(name) ? name : [name];\n const unsubscribes = names.map(one => {\n const path = createPath(one);\n return event === 'errors' || event === 'touched'\n ? onKeyEvent(form.emitter, event, path.key, callback)\n : onPathEvent(form.emitter, event, path, scope, callback);\n });\n return unsubscribes.length === 1\n ? unsubscribes[0]\n : () => unsubscribes.forEach(unsubscribe => unsubscribe());\n}\n","import {useState, useEffect, useCallback, useRef} from 'react';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {on} from '@for-fun/event-emitter';\nimport type {EventEmitter} from '@for-fun/event-emitter';\nimport {onKeyEvent, onPathEvent} from '../subscribe';\nimport createForm, {\n getErrorByPath,\n getFieldErrorsByPath,\n getValueByPath,\n hasTouchedByPath,\n hasErrors,\n isDirty,\n getDirtyFields,\n getTouchedFields,\n setInitialValues\n} from '../form';\nimport type {FieldError, Form, Options, Name} from '../form';\nimport type {FieldPath, PathValueOf} from '../types';\nimport createPath from '../path';\nimport type {Path} from '../path';\n\n/**\n * Create a form instance bound to this component.\n *\n * Beyond {@link Options}, the optional `values` object enables controlled\n * usage: when it genuinely changes it is re-synced into the form with\n * setInitialValues semantics -- uncommitted user edits are discarded\n * (master-detail semantics: selecting another record replaces the draft),\n * while touched flags and errors survive. Change detection is\n * reference-first with a structural fallback, so re-renders that pass an\n * inline literal with equal content never re-sync -- the user's\n * in-progress typing is never clobbered.\n */\nexport default function useForm<T extends Record<string, any> = any>(\n options?: Options<T> & {values?: T}\n): Form<T> {\n // Lazy initialization: createForm runs once per mount and the returned\n // instance is stable across re-renders (and StrictMode double renders),\n // without writing to refs during render. A provided `values` object is\n // seeded synchronously here (createForm does the same for initialValues)\n // so the first paint and SSR already reflect the controlled values.\n const [form] = useState(() => {\n const created = createForm<T>(options);\n if (options && options.values !== undefined) {\n setInitialValues(created, options.values);\n }\n return created;\n });\n const initialValues = options && options.initialValues;\n const values = options && options.values;\n\n // Track which initialValues source object the form was last seeded from.\n // Inline options create a fresh object every render, and re-seeding\n // clears the values Map (setInitialValues semantics), which would revert\n // every committed edit right after each re-render -- on the client and\n // after hydration alike. Memoized callers are covered by the reference\n // check; inline literals by the structural one, so only genuinely new\n // content re-seeds.\n const seededRef = useRef<{done: boolean; source: any} | null>(null);\n if (seededRef.current === null)\n seededRef.current = {done: false, source: undefined};\n\n useEffect(() => {\n const seeded = seededRef.current!;\n if (\n seeded.done &&\n (seeded.source === initialValues || isEqual(seeded.source, initialValues))\n ) {\n return;\n }\n seeded.done = true;\n seeded.source = initialValues;\n setInitialValues(form, initialValues);\n }, [form, initialValues]);\n\n // Controlled values: re-sync only when the incoming object genuinely\n // differs from what the form was last seeded from. The reference check\n // is the fast path (memoized callers); inline literals get a fresh\n // object identity every render, so without the structural comparison\n // each re-render would clear the values Map (setInitialValues\n // semantics) and revert the user's uncommitted edits -- same hazard the\n // initialValues seed guard above protects against. Master-detail\n // semantics still apply whenever the content actually changed.\n const controlledRef = useRef<{done: boolean; source: any} | null>(null);\n if (controlledRef.current === null) {\n controlledRef.current = {done: false, source: undefined};\n }\n\n useEffect(() => {\n if (values === undefined) return;\n const seeded = controlledRef.current!;\n if (\n seeded.done &&\n (seeded.source === values || isEqual(seeded.source, values))\n ) {\n return;\n }\n seeded.done = true;\n seeded.source = values;\n setInitialValues(form, values);\n }, [form, values]);\n\n return form;\n}\n\n/** Per-hook snapshot cache for {@link useWatch}. */\ninterface WatchCache<T> {\n hasValue: boolean;\n value?: T;\n}\n\n/**\n * Shared core of {@link useWatch} and the path-scoped hooks: a\n * useSyncExternalStore binding over a custom event subscription.\n * `subscribeFactory` receives the invalidate callback (drop the snapshot\n * cache, then notify React) and returns its unsubscribe function, so the\n * core stays identical whether the subscription is global or scoped to\n * one path.\n */\nfunction useWatchCore<T>(\n subscribeFactory: (invalidate: () => void) => () => void,\n getter: () => T\n): T {\n // useSyncExternalStore requires getSnapshot to return the same reference\n // until the store actually changed, otherwise React warns and loops.\n // Cache the snapshot per hook instance and recompute it only on the first\n // read and after the watched event fired.\n const cacheRef = useRef<WatchCache<T> | null>(null);\n if (cacheRef.current === null) cacheRef.current = {hasValue: false};\n const cache = cacheRef.current;\n\n // Hold the latest getter in a ref so getSnapshot keeps a stable identity\n // (callers pass a freshly bound function on every render) while still\n // recomputing with the most recent getter when the cache is invalid.\n const getterRef = useRef(getter);\n getterRef.current = getter;\n\n const getSnapshot = useCallback(() => {\n if (!cache.hasValue) {\n cache.value = getterRef.current();\n cache.hasValue = true;\n }\n return cache.value as T;\n }, [cache]);\n\n const subscribe = useCallback(\n (notify: () => void) => {\n // The form may have changed between render and this subscription, and\n // those events were missed: drop the cache. React's consistency check\n // right after subscribing recomputes and re-renders only when the\n // fresh value differs from the committed snapshot.\n cache.hasValue = false;\n const invalidate = () => {\n cache.hasValue = false;\n notify();\n };\n return subscribeFactory(invalidate);\n },\n [subscribeFactory, cache]\n );\n\n // Form state lives entirely in synchronously readable Map/Set structures\n // seeded from initialValues/values during the lazy useState initializer,\n // so the server snapshot is computed exactly like the client's first\n // render -- pass getSnapshot itself as getServerSnapshot and hydration\n // matches.\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Subscribe to a form event and keep the component's snapshot of `getter()`\n * in sync with the form state.\n *\n * Built on useSyncExternalStore, so snapshots taken while React renders are\n * guaranteed consistent (no tearing under concurrent rendering) and changes\n * emitted before the subscription effect runs are still picked up.\n */\nexport function useWatch<T>(\n emitter: EventEmitter,\n event: string,\n getter: () => T\n): T {\n const subscribeFactory = useCallback(\n (invalidate: () => void) => on(emitter, event, invalidate),\n [emitter, event]\n );\n return useWatchCore(subscribeFactory, getter);\n}\n\n/**\n * Get field value state\n */\nexport function useValue<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): PathValueOf<T, P> {\n return useValueByPath(form, createPath(name));\n}\n\n/**\n * Get field value state by path\n */\nexport function useValueByPath(form: Form, path: Path): any {\n const {emitter} = form;\n const {key} = path;\n // 'leaf' scope: a leaf read depends only on its own key and its\n // ancestors' (getValueByPath fallback chain), so writes elsewhere --\n // siblings, descendants, string-prefix lookalikes ('[\"a\",\"bX\"]') -- never\n // invalidate the snapshot. Payload-less broadcasts (reset, removeField,\n // setInitialValues) still sync everything.\n const subscribeFactory = useCallback(\n (invalidate: () => void) =>\n onPathEvent(emitter, 'change', path, 'leaf', invalidate),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- deps are `key` on purpose: useValue creates a fresh Path per render, so the object must stay out of the deps while the key string pins the subscription\n [emitter, key]\n );\n return useWatchCore(subscribeFactory, getValueByPath.bind(null, form, path));\n}\n\n/**\n * Get field touched state\n */\nexport function useTouched<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): boolean {\n return useTouchedByPath(form, createPath(name));\n}\n\n/**\n * Get field touched state by path\n */\nexport function useTouchedByPath(form: Form, path: Path): boolean {\n const {emitter} = form;\n const {key} = path;\n // Touched is stored per exact key, so only this field's own setTouched\n // (now emitted with its path) matters; payload-less broadcasts (reset,\n // removeField) still sync everything.\n const subscribeFactory = useCallback(\n (invalidate: () => void) => onKeyEvent(emitter, 'touched', key, invalidate),\n [emitter, key]\n );\n return useWatchCore(\n subscribeFactory,\n hasTouchedByPath.bind(null, form, path)\n );\n}\n\n/**\n * Get field error message state\n * @return current error's message string (display text), or undefined\n */\nexport function useError<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): string | undefined {\n return useErrorByPath(form, createPath(name))?.message;\n}\n\n/**\n * Get field error state by path\n * @return current FieldError object ({type, message}), or undefined\n */\nexport function useErrorByPath(form: Form, path: Path): FieldError | undefined {\n const {emitter} = form;\n const {key} = path;\n // Errors are stored per exact key, so only writes to this field's error\n // (setErrorByPath now emits with its path) matter; payload-less\n // broadcasts (clearErrors, reset, removeField) still sync everything.\n const subscribeFactory = useCallback(\n (invalidate: () => void) => onKeyEvent(emitter, 'errors', key, invalidate),\n [emitter, key]\n );\n return useWatchCore(subscribeFactory, getErrorByPath.bind(null, form, path));\n}\n\n/**\n * Get all field errors\n * @return every error registered for the field (insertion order); an empty\n * array when the field has none\n */\nexport function useFieldErrors<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldError[] {\n return useFieldErrorsByPath(form, createPath(name));\n}\n\n/**\n * Get all field errors by path\n * @return every error registered for the field (insertion order); an empty\n * array when the field has none\n */\nexport function useFieldErrorsByPath(form: Form, path: Path): FieldError[] {\n const {emitter} = form;\n const {key} = path;\n // Same exact-key subscription and snapshot rules as useErrorByPath: the\n // getter returns the shared empty constant when clean and the stored\n // array by reference otherwise, so the useSyncExternalStore snapshot is\n // reference-stable between unrelated events.\n const subscribeFactory = useCallback(\n (invalidate: () => void) => onKeyEvent(emitter, 'errors', key, invalidate),\n [emitter, key]\n );\n return useWatchCore(\n subscribeFactory,\n getFieldErrorsByPath.bind(null, form, path)\n );\n}\n\nexport function useIsDirty(form: Form): boolean {\n // Dirty state is driven by value changes, not touch state: subscribe to\n // 'change' so typing flips this immediately, even before a blur.\n return useWatch(form.emitter, 'change', isDirty.bind(null, form));\n}\n\n/**\n * Get dirty fields state -- object mapping each dirty field's user-facing\n * dotted path ('a.b', 'a.0.c') to true; recalculated after 'change' events\n */\nexport function useDirtyFields(form: Form): Record<string, boolean> {\n return useWatch(form.emitter, 'change', getDirtyFields.bind(null, form));\n}\n\n/**\n * Get touched fields state -- array of touched fields' user-facing dotted\n * paths ('a.b', 'a.0.c'); recalculated after 'touched' events\n */\nexport function useTouchedFields(form: Form): string[] {\n return useWatch(form.emitter, 'touched', getTouchedFields.bind(null, form));\n}\n\nexport function useHasErrors(form: Form): boolean {\n return useWatch(form.emitter, 'errors', hasErrors.bind(null, form));\n}\n\nexport function useIsSubmitting(form: Form): boolean {\n return useWatch(form.emitter, 'submitting', () => form.isSubmitting);\n}\n\nexport function useSubmitCount(form: Form): number {\n return useWatch(form.emitter, 'submitCount', () => form.submitCount);\n}\n\n/**\n * Structural equality for form default data (primitives, arrays, plain\n * objects, Dates). Used by {@link useForm} to tell a re-rendered inline\n * initialValues literal from genuinely changed content: class instances\n * and other exotic objects compare as unequal, which errs on the side of\n * re-seeding (the pre-guard behavior).\n */\nfunction isEqual(a: any, b: any): boolean {\n if (Object.is(a, b)) return true;\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;\n const isArray = Array.isArray(a);\n if (isArray !== Array.isArray(b)) return false;\n if (isArray) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n return true;\n }\n const proto = Object.getPrototypeOf(a);\n if (proto !== Object.prototype && proto !== null) return false;\n if (Object.getPrototypeOf(b) !== proto) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!isEqual(a[key], b[key])) return false;\n }\n return true;\n}\n","import {useMemo} from 'react';\nimport create from '../path';\nimport type {Name, Path} from '../path';\nimport {normalizePath} from '../util';\n\nexport default function usePath(name: Name): Path {\n const path = useMemo(() => create(normalizePath(name)), [name]);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- deps are `path.key` on purpose: re-renders passing a fresh array for the same field name reuse the cached Path object (stable reference & Map key)\n return useMemo(() => path, [path.key]);\n}\n","import {useCallback, useRef, type MutableRefObject} from 'react';\n\nexport default function useStage<T>(value: T): MutableRefObject<T> {\n const ref = useRef(value);\n ref.current = value;\n return ref;\n}\n\nexport function useStageFn<T extends (...args: any[]) => any>(fn: T): T {\n const ref = useStage(fn);\n return useCallback(\n (...params: any[]) => ref.current(...params),\n [ref]\n ) as unknown as T;\n}\n","import {useContext, useEffect, useRef} from 'react';\nimport {FormContext} from '../context';\nimport {\n getValueByPath,\n setErrorByPath,\n setValidatingByPath,\n unsetValidatingByPath\n} from '../form';\nimport type {FieldError, Form} from '../form';\nimport type {Path} from '../path';\nimport {useStageFn} from './stage';\nimport {isPromise} from '../util';\n\n/**\n * Field validator. Returns an error (a string, a FieldError, or an array\n * mixing both) or undefined when valid; may return a Promise for async\n * validation.\n *\n * The second argument carries the validation context. `meta.signal` is\n * aborted as soon as the round is superseded — a newer round started, or\n * the field unregistered — so async validators can cancel their underlying\n * work (fetch, timers) instead of racing a stale result home. Stale\n * results are dropped independently by useValidate's lock, so validators\n * that ignore the signal stay correct too. Validators written against the\n * older two-argument signature keep working.\n */\nexport type Validator = (\n value: any,\n meta: {form: Form; path: Path; signal: AbortSignal}\n) =>\n | string\n | FieldError\n | (string | FieldError)[]\n | undefined\n | Promise<string | FieldError | (string | FieldError)[] | undefined>;\n\n/** Options for {@link useValidate}. */\nexport interface UseValidateOptions {\n /**\n * Delay in milliseconds before a validation kick actually runs the\n * validator. `0` (default) runs immediately; a positive value debounces\n * rapid kicks (e.g. typing) so only the last one executes. While the\n * timer is pending the field counts as validating, so `trigger` /\n * `ensureValidate` wait out the window.\n */\n debounce?: number;\n}\n\nexport default function useValidate(\n validate: Validator | undefined,\n path: Path,\n formProp?: Form,\n options?: UseValidateOptions\n): () => void {\n // Read the context unconditionally (hook call order must be stable), then\n // let an explicitly passed form win — works without a <FormProvider>.\n const contextForm = useContext(FormContext);\n const form = (formProp || contextForm) as Form;\n if (!form) throw new Error('no form provided');\n const lockRef = useRef<object | null>(null);\n const validateRef = useRef(validate);\n validateRef.current = validate;\n // Read the delay through a ref (like validateRef) so changing it doesn't\n // re-subscribe the validator mid-flight.\n const debounceRef = useRef(options?.debounce ?? 0);\n debounceRef.current = options?.debounce ?? 0;\n\n useEffect(() => {\n // The pending debounce timer and the current round's controller live in\n // this closure so the cleanup below can cancel them.\n let timer: ReturnType<typeof setTimeout> | null = null;\n let controller: AbortController | null = null;\n // Whether this registration currently holds the path's slot in\n // form.validating. The mark is taken when a debounce window opens or an\n // async round starts, and released by whichever round settles last —\n // including a later sync round that supersedes an in-flight async one\n // (its own .finally is lock-gated out by then).\n let marked = false;\n const mark = () => {\n if (marked) return;\n marked = true;\n setValidatingByPath(form, path);\n };\n const unmark = () => {\n if (!marked) return;\n marked = false;\n unsetValidatingByPath(form, path);\n };\n\n const run = () => {\n timer = null;\n const fn = validateRef.current;\n if (!fn) {\n unmark();\n return;\n }\n // Abort the superseded round's signal: a listening validator should\n // stop its underlying work. The lock refresh below independently\n // drops any result that still arrives, signal or not.\n controller?.abort();\n controller = new AbortController();\n const lock = (lockRef.current = {});\n let result;\n try {\n result = fn(getValueByPath(form, path), {\n form,\n path,\n signal: controller.signal\n });\n } catch (e) {\n // A throwing sync validator propagates to the caller as it always\n // has; just don't leave the validating mark stuck behind it.\n unmark();\n throw e;\n }\n if (!isPromise(result)) {\n setErrorByPath(form, path, result);\n // Error first, then release the mark: 'validating' subscribers\n // (trigger) re-read state on wake and must see the landed error.\n unmark();\n return;\n }\n mark();\n result\n .then(\n (\n error: string | FieldError | (string | FieldError)[] | undefined\n ) => {\n if (lock === lockRef.current) {\n setErrorByPath(form, path, error);\n }\n }\n )\n // A rejected round is the normal way a signal-listening validator\n // gives up (fetch throws AbortError once aborted); swallow it and\n // let the owning round write the outcome.\n .catch(() => {})\n .finally(() => {\n if (lock === lockRef.current) {\n unmark();\n lockRef.current = null;\n }\n });\n };\n\n const validator = () => {\n const debounce = debounceRef.current;\n if (debounce > 0) {\n // Only the last kick inside the window runs: restart the timer on\n // every kick. The mark keeps trigger/ensureValidate's validating-set\n // wait covering the pending timer, not just in-flight promises.\n if (timer !== null) clearTimeout(timer);\n else mark();\n timer = setTimeout(run, debounce);\n return;\n }\n run();\n };\n\n form.validators.set(path.key, validator);\n return () => {\n form.validators.delete(path.key);\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n unmark();\n controller?.abort();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- deps are `path.key` on purpose: usePath returns a stable Path per key, so re-subscribing on key (not object identity) is enough\n }, [form, path.key]);\n\n return useStageFn(() => form.validators.get(path.key)?.());\n}\n","import {useContext, useEffect, useState} from 'react';\nimport type {Context} from 'react';\nimport {FormContext} from '../context';\nimport {\n getValueByPath,\n hasTouchedByPath,\n removeFieldByPath,\n setTouchedByPath,\n setValueByPath\n} from '../form';\nimport type {FieldError, Form} from '../form';\nimport type {Name, Path} from '../path';\nimport type {FieldPath, PathValueOf} from '../types';\nimport {rulesToValidator} from '../rules';\nimport type {FieldRules} from '../rules';\nimport {useFieldErrorsByPath, useValueByPath, useWatch} from './form';\nimport usePath from './path';\nimport useValidate from './validate';\nimport type {Validator} from './validate';\nimport {useStageFn} from './stage';\nimport {isPromise} from '../util';\n\nexport interface UseFieldOptions<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n> {\n form?: Form<TValues>;\n name: TPath;\n initialValue?: any;\n shouldUnregister?: boolean;\n validate?: Validator;\n /**\n * Declarative rules (required/min/max/minLength/maxLength/pattern),\n * compiled into a validator that runs before `validate` — both sources'\n * errors merge into one FieldError[], rules errors ahead. Failures land\n * in the form's error state with the given or default messages.\n */\n rules?: FieldRules;\n /**\n * Milliseconds to debounce this field's validation kicks. Defaults to 0\n * (validate immediately); while the timer is pending the field counts as\n * validating, so `trigger`/`ensureValidate` wait out the window. Only the\n * last kick inside the window runs the validator.\n */\n validateDebounce?: number;\n /**\n * Milliseconds to delay showing a newly appearing error in the render\n * layer (`error`/`errorObject`/`errors` stay undefined/empty until the\n * window passes). The form's error state is never delayed — trigger,\n * submit and `getError` read it immediately. An error that clears inside\n * the window never shows; once an error is visible, later changes apply\n * immediately. Only the none → some transition waits.\n */\n delayError?: number;\n /**\n * Disable this field: OR-ed with the form-level flag\n * (`createForm({disabled})` / `setDisabled`) into the result's\n * `disabled`. A field cannot opt out of a disabled form.\n */\n disabled?: boolean;\n}\n\n/**\n * The result of {@link useField}. Deliberately a closed shape: no index\n * signature, so a typo'd property access (`field.vlaue`) is a type error\n * instead of silently reading `undefined`.\n */\nexport interface UseFieldResult<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n> {\n /** The form instance this field is bound to (explicit prop or context) —\n * handy for consumers that need direct access to the headless API. */\n form: Form<TValues>;\n value: PathValueOf<TValues, TPath>;\n /** Error message string (FieldError#message) for display, or undefined */\n error: string | undefined;\n /** Full FieldError object ({type, message}), or undefined */\n errorObject: FieldError | undefined;\n /** Every error registered for the field, in insertion order — `error`\n * and `errorObject` are its first entry. Empty (and reference-stable)\n * when the field has no errors. */\n errors: FieldError[];\n onChange: (v: any) => void;\n onBlur: () => void;\n name: string;\n /** Merged disabled flag: the form-level flag (`createForm({disabled})`\n * toggled by `setDisabled`) OR-ed with this field's own `disabled`\n * option, updated live through the form's event core. */\n disabled: boolean;\n}\n\n/**\n * Compose declarative rules with a user validator: rules run first, then\n * the user's validator (awaited when async), and the results merge into\n * one error list with rules errors ahead. Either side may be absent —\n * the other passes through untouched. Errors are returned as an array (or\n * undefined when both sides pass), which setErrorByPath stores as-is.\n */\nfunction combineRulesAndValidate(\n rules: FieldRules | undefined,\n validate: Validator | undefined\n): Validator | undefined {\n if (!rules) return validate;\n const ruleValidator = rulesToValidator(rules);\n if (!validate) return ruleValidator;\n return (value, meta) => {\n // rulesToValidator's contract is FieldError[] | undefined; the wider\n // Validator union here is only its declared type.\n const ruleErrors = ruleValidator(value, meta) as FieldError[] | undefined;\n const merge = (\n other: string | FieldError | (string | FieldError)[] | undefined\n ): (string | FieldError)[] | undefined => {\n const list: (string | FieldError)[] = [...(ruleErrors ?? [])];\n if (Array.isArray(other)) list.push(...other);\n else if (other) list.push(other);\n return list.length ? list : undefined;\n };\n const result = validate(value, meta);\n return isPromise(result) ? result.then(merge) : merge(result);\n };\n}\n\n/**\n * Render-layer gating for {@link UseFieldOptions}.delayError: hold a newly\n * appearing error back for `delay` ms while the form's error state stays\n * immediate. Only the none → some transition waits — an error that clears\n * inside the window never shows, and once an error is visible, later\n * changes (a new message, entries added or removed) apply immediately.\n * With `delay === undefined` the subscription value passes through\n * untouched: no timers and no state writes, so fields that do not opt in\n * pay nothing beyond the hook calls themselves.\n */\nfunction useDelayedErrors(\n errors: FieldError[],\n delay: number | undefined\n): FieldError[] {\n const [shown, setShown] = useState<FieldError[]>(errors);\n useEffect(() => {\n if (delay === undefined) return;\n // Clearing is always immediate: an error cleared inside the window is\n // cancelled before ever showing, a shown one hides at once (errors is\n // the shared empty constant on this branch).\n if (errors.length === 0) {\n setShown(errors);\n return;\n }\n // Already showing an error: swaps and list changes apply at once.\n if (shown.length > 0) {\n setShown(errors);\n return;\n }\n // Appearing from none: wait out the window. The cleanup clears the\n // timer when errors change again or the field unmounts.\n const timer = setTimeout(() => setShown(errors), delay);\n return () => clearTimeout(timer);\n }, [errors, delay, shown]);\n return delay === undefined ? errors : shown;\n}\n\n/**\n * Shared core of {@link useField} and the per-instance hooks returned by\n * `createFormContext()`: identical behavior, but the form is resolved from\n * whichever Context instance is passed in instead of the module-level one.\n *\n * `form` is always handed to `useValidate` explicitly, and an explicit form\n * wins over `useValidate`'s own context read — so scoped contexts need no\n * changes there.\n */\nexport function useFieldCore<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n>(\n {\n form: f1,\n name,\n initialValue,\n shouldUnregister,\n validate,\n rules,\n validateDebounce,\n delayError,\n disabled\n }: UseFieldOptions<TValues, TPath>,\n Context: Context<any>\n): UseFieldResult<TValues, TPath> {\n // Read the context unconditionally (hook call order must be stable), then\n // let an explicitly passed form win — works without a <FormProvider>.\n const contextForm = useContext(Context);\n const form = f1 || contextForm;\n if (!form) throw new Error('no form provided');\n const path = usePath(name);\n\n // Undeclared options are dropped on purpose: the return value carries\n // only the fields declared on UseFieldResult, so nothing rides it back\n // onto DOM elements through a component's prop spread.\n const validator = useValidate(\n combineRulesAndValidate(rules, validate),\n path,\n form,\n {\n debounce: validateDebounce\n }\n );\n\n // All errors of the field through one subscription; the array reference\n // is stable (stored array or shared empty constant), so consumers can\n // memo on it. delayError gates only this render-layer view of the list;\n // the live list keeps driving the reValidateMode kicks below.\n const liveErrors = useFieldErrorsByPath(form, path);\n const errors = useDelayedErrors(liveErrors, delayError);\n const errorObject = errors[0];\n const error = errorObject?.message;\n const value = useValueByPath(form, path);\n\n // The form-level disabled flag, subscribed so setDisabled re-renders\n // this field; the field's own option is OR-ed in on every render.\n const formDisabled = useWatch(form.emitter, 'disabled', () => form.disabled);\n\n // Seed initialValue in an effect (never during render, so no 'change' is\n // emitted while rendering) and only when the field has no value yet, so\n // user input survives re-renders and remounts.\n useEffect(() => {\n if (initialValue === undefined) return;\n if (getValueByPath(form, path) === undefined) {\n setValueByPath(form, path, initialValue);\n }\n }, [form, path, initialValue]);\n\n const onChange = useStageFn((v: any) => {\n setValueByPath(form, path, v);\n // The live (ungated) error drives the reValidate kick: an error hidden\n // inside the delayError window still counts as \"has an error\", so\n // typing re-validates and can clear it before it ever shows.\n if (\n form.mode === 'onChange' ||\n form.mode === 'all' ||\n (form.mode === 'onTouched' && hasTouchedByPath(form, path)) ||\n (liveErrors.length > 0 && form.reValidateMode === 'onChange')\n )\n validator();\n });\n\n const onBlur = useStageFn(() => {\n setTouchedByPath(form, path);\n if (\n form.mode === 'onBlur' ||\n form.mode === 'onTouched' ||\n form.mode === 'all' ||\n (liveErrors.length > 0 && form.reValidateMode === 'onBlur')\n )\n validator();\n });\n\n useEffect(\n () => () => {\n if (shouldUnregister !== false) {\n removeFieldByPath(form, path);\n }\n },\n [path, form, shouldUnregister]\n );\n\n return {\n form,\n value,\n error,\n errorObject,\n errors,\n onChange,\n onBlur,\n name: path.key,\n disabled: formDisabled || !!disabled\n };\n}\n\nexport default function useField<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n>(options: UseFieldOptions<TValues, TPath>): UseFieldResult<TValues, TPath> {\n return useFieldCore(options, FormContext);\n}\n","import {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef\n} from 'react';\nimport type {Context} from 'react';\nimport {FormContext} from '../context';\nimport {getValueByPath, setValueByPath} from '../form';\nimport type {Form, Name} from '../form';\nimport {onPathEvent} from '../subscribe';\nimport usePath from './path';\nimport {useStageFn} from './stage';\n\nlet idCounter = 0;\nfunction generateId(): string {\n return `_${++idCounter}`;\n}\n\ninterface FieldArrayItem {\n id: string;\n index: number;\n}\n\nexport interface UseFieldArrayResult {\n fields: FieldArrayItem[];\n append: (value: any) => void;\n prepend: (value: any) => void;\n insert: (index: number, value: any) => void;\n remove: (index: number) => void;\n swap: (from: number, to: number) => void;\n move: (from: number, to: number) => void;\n replace: (values: any[]) => void;\n update: (index: number, value: any) => void;\n}\n\n/**\n * Shared core of {@link useFieldArray} and the per-instance hook returned by\n * `createFormContext()`: identical behavior, but the form is resolved from\n * whichever Context instance is passed in instead of the module-level one.\n */\nexport function useFieldArrayCore(\n options: {name: Name; form?: Form},\n Context: Context<any>\n): UseFieldArrayResult {\n // Read the context unconditionally (hook call order must be stable), then\n // let an explicitly passed form win — works without a <FormProvider>.\n const contextForm = useContext(Context);\n const form = options.form || contextForm;\n if (!form) throw new Error('no form provided');\n const path = usePath(options.name);\n const idsRef = useRef<string[]>([]);\n\n const getArray = useCallback(\n (): any[] => getValueByPath(form, path) || [],\n [form, path]\n );\n\n const setArray = useCallback(\n (arr: any[]) => {\n setValueByPath(form, path, arr);\n },\n [form, path]\n );\n\n const computeFields = useCallback(() => {\n const arr = getArray();\n while (idsRef.current.length < arr.length) {\n idsRef.current.push(generateId());\n }\n while (idsRef.current.length > arr.length) {\n idsRef.current.pop();\n }\n return idsRef.current.map((id, index) => ({id, index}));\n }, [getArray]);\n\n // Subscribe to 'change' events scoped to this array's branch: the array\n // key itself, its ancestors (an ancestor write replaces what the leaf\n // read falls back to) and its descendants (item edits), so typing into\n // unrelated fields does not re-render the array component. Payload-less\n // 'change' emits (reset, removeFieldByPath, setInitialValues) always\n // sync. The comma-separated key prefix comparison lives in onPathEvent,\n // which keeps lookalike sibling keys ('[\"tagsX\"]') from matching.\n const [fields, syncFields] = useReducer(\n computeFields,\n undefined,\n computeFields\n );\n useEffect(\n () => onPathEvent(form.emitter, 'change', path, 'branch', syncFields),\n [form.emitter, path]\n );\n\n const append = useStageFn((value: any) => {\n const arr = getArray();\n idsRef.current.push(generateId());\n setArray([...arr, value]);\n });\n\n const prepend = useStageFn((value: any) => {\n const arr = getArray();\n idsRef.current.unshift(generateId());\n setArray([value, ...arr]);\n });\n\n const insert = useStageFn((index: number, value: any) => {\n const arr = getArray();\n idsRef.current.splice(index, 0, generateId());\n const newArr = [...arr.slice(0, index), value, ...arr.slice(index)];\n setArray(newArr);\n });\n\n const remove = useStageFn((index: number) => {\n const arr = getArray();\n idsRef.current.splice(index, 1);\n const newArr = arr.filter((_: any, i: number) => i !== index);\n setArray(newArr);\n });\n\n const swap = useStageFn((from: number, to: number) => {\n const arr = getArray();\n [idsRef.current[from], idsRef.current[to]] = [\n idsRef.current[to],\n idsRef.current[from]\n ];\n const newArr = [...arr];\n [newArr[from], newArr[to]] = [newArr[to], newArr[from]];\n setArray(newArr);\n });\n\n const move = useStageFn((from: number, to: number) => {\n const arr = getArray();\n const [id] = idsRef.current.splice(from, 1);\n idsRef.current.splice(to, 0, id);\n const newArr = [...arr];\n const [item] = newArr.splice(from, 1);\n newArr.splice(to, 0, item);\n setArray(newArr);\n });\n\n // replace is a full swap (length may change), so every row is conceptually\n // a new row: regenerate all ids to remount them, mirroring how reset works.\n const replace = useStageFn((values: any[]) => {\n idsRef.current = values.map(() => generateId());\n setArray([...values]);\n });\n\n // update only overwrites one value, so the id at that index is kept and the\n // row does not remount. Out-of-bounds indices are a silent no-op — plain\n // assignment would instead punch sparse-array holes into the form state.\n const update = useStageFn((index: number, value: any) => {\n const arr = getArray();\n if (index < 0 || index >= arr.length) return;\n const newArr = [...arr];\n newArr[index] = value;\n setArray(newArr);\n });\n\n return {fields, append, prepend, insert, remove, swap, move, replace, update};\n}\n\nexport default function useFieldArray(options: {\n name: Name;\n form?: Form;\n}): UseFieldArrayResult {\n return useFieldArrayCore(options, FormContext);\n}\n","import {\n createContext,\n createElement,\n useContext,\n type ComponentType,\n type ReactNode\n} from 'react';\nimport {\n useFieldCore,\n type UseFieldOptions,\n type UseFieldResult\n} from './hooks/field';\nimport {useFieldArrayCore, type UseFieldArrayResult} from './hooks/fieldArray';\nimport type {Form} from './form';\nimport type {Name} from './path';\nimport type {FieldPath} from './types';\n\nexport const FormContext = createContext<any>(null);\n\nexport const FormProvider = FormContext.Provider;\n\n/**\n * Read the form from the module-level {@link FormContext}. Pass the values\n * shape — `useFormContext<Values>()` — to get a fully typed `Form<Values>`\n * headless API; the `any` default keeps untyped call sites compiling.\n *\n * For multiple forms in one subtree use {@link createFormContext} instead.\n *\n * @throws when no `<FormProvider>` is mounted above the call site.\n */\nexport function useFormContext<T extends Record<string, any> = any>(): Form<T> {\n const form = useContext(FormContext);\n if (!form) throw new Error('no form provided');\n return form;\n}\n\n/**\n * Create an isolated bundle of form-context bindings: its own React context\n * plus `useField` / `useFieldArray` / `useFormContext` hooks that resolve\n * their form from it.\n *\n * Why: the module-level {@link FormContext} works fine for a single form per\n * subtree, but nesting two forms (or reusing a component inside a different\n * form) makes them fight over one context. Calling this factory once per app\n * area — `const Ctx = createFormContext<Values>()` — fixes the value shape\n * (`Ctx.useField({name: 'user.name'})` gets its `name` constrained by\n * `FieldPath<Values>` and its `value` typed accordingly), so call sites stop\n * hand-writing generics, and each instance's Provider scopes a strictly\n * separate form. The bundle also carries its raw React context\n * (`Ctx.context`) so `<Form context={Ctx.context}>` can provide into it.\n */\nexport function createFormContext<TValues extends Record<string, any> = any>() {\n const Context = createContext<Form<TValues> | null>(null);\n\n // A `form`-prop wrapper instead of exposing Context.Provider directly:\n // callers shouldn't have to know about the raw `value` prop shape.\n function FormProvider({\n form,\n children\n }: {\n form: Form<TValues>;\n children: ReactNode;\n }): ReactNode {\n return createElement(Context.Provider, {value: form}, children);\n }\n\n function useFormContext(): Form<TValues> {\n const form = useContext(Context);\n if (!form) throw new Error('no form provided');\n return form;\n }\n\n function useField<TPath extends FieldPath<TValues> | Name = Name>(\n // The bare `{name: TPath}` member keeps `name` a direct inference site\n // for TPath instead of routing it through the mapped Omit type.\n // `form` is omitted on purpose — the form always comes from this\n // factory's own Context.\n options: {name: TPath} & Omit<UseFieldOptions<TValues, TPath>, 'form'>\n ): UseFieldResult<TValues, TPath> {\n return useFieldCore(options as UseFieldOptions<TValues, TPath>, Context);\n }\n\n function useFieldArray(options: {\n name: FieldPath<TValues> | Name;\n }): UseFieldArrayResult {\n return useFieldArrayCore(options as {name: Name}, Context);\n }\n\n // The raw React context, for `<Form context={...}>`: the component keeps\n // its submit machinery while providing into this instance's private\n // context, so the bound hooks above resolve the form it manages.\n return {\n context: Context,\n FormProvider,\n useFormContext,\n useField,\n useFieldArray\n };\n}\n\nexport const CheckboxGroupContext = createContext<any>(null);\n\nexport const CheckboxGroupProvider = CheckboxGroupContext.Provider;\n\nexport function useCheckboxGroupContext(): any {\n const group = useContext(CheckboxGroupContext);\n if (!group) throw new Error('no group provided');\n return group;\n}\n","import * as React from 'react';\nimport {handleSubmit} from '../form';\nimport type {Form} from '../form';\nimport {FormContext} from '../context';\nimport useForm from '../hooks/form';\n\n/**\n * Props for <Form>.\n *\n * Native validation behavior: the rendered <form> always sets noValidate,\n * which suppresses the browser's built-in blocked-submit UI. However, native\n * constraint validation still gates submission — the form element's\n * checkValidity() runs before custom validators, and when it fails,\n * reportValidity() surfaces the offending constraints as native bubbles and\n * submission stops (onInvalidSubmit fires). onSubmit/onValidSubmit only run\n * once every native constraint (required, type=email, minLength, ...) passes.\n *\n * The submit flow itself lives in the headless `handleSubmit` (see form.ts);\n * this component is a thin wrapper that binds it to the rendered <form>.\n */\ninterface FormProps<T extends Record<string, any> = any> extends Omit<\n React.FormHTMLAttributes<HTMLFormElement>,\n 'onSubmit'\n> {\n form?: Form<T>;\n /**\n * Provide into an isolated context from `createFormContext()` instead of\n * the module-level one — `<Form context={ProfileForm.context}>` keeps the\n * component's full submit machinery while the factory's bound hooks\n * (`ProfileForm.useField`, `ProfileForm.useFormContext`, ...) resolve this\n * form from their private context. The module-level `useFormContext()` /\n * `useField` do not see it; that is the point of the isolation. Omitted,\n * the form lands in the module-level FormContext as before.\n */\n context?: React.Context<Form<any> | null>;\n initialValues?: T;\n /**\n * Controlled external values. When the `values` reference changes, the\n * new object is synced into the form (via setInitialValues semantics):\n * uncommitted user edits are discarded -- master-detail semantics, where\n * selecting another record replaces the draft -- while touched flags and\n * errors are kept. Sync is reference-based: re-renders that pass the same\n * `values` reference never clobber what the user is typing.\n */\n values?: T;\n onSubmit?: (values: T, e: React.FormEvent) => void;\n onValidSubmit?: (values: T, e: React.FormEvent) => void;\n /**\n * Called when validation fails.\n * @param errors array of {path, type, message} entries in insertion\n * order; path is the dotted field path ('a.b', 'list.0'), type is\n * the error kind ('custom' for plain string errors, 'native' for\n * failed DOM constraint validation), message is the display text\n * @param values current form values\n */\n onInvalidSubmit?: (\n errors: {path: string; type: string; message: string}[],\n values: T\n ) => void;\n /**\n * Focus the first field with an error after a failed submit: custom\n * validation failures focus the first errored field, native constraint\n * failures focus the first ':invalid' control. Defaults to true; pass\n * false to disable.\n */\n shouldFocusError?: boolean;\n}\n\nexport default function Form<T extends Record<string, any> = any>({\n form: f1,\n context,\n initialValues,\n values,\n onSubmit,\n onValidSubmit,\n onInvalidSubmit,\n shouldFocusError,\n ...props\n}: FormProps<T>) {\n const f2 = useForm<T>({initialValues, values});\n const form = f1 || f2;\n\n const submit = handleSubmit(form, {\n onSubmit,\n onValidSubmit,\n onInvalidSubmit,\n shouldFocusError\n });\n\n // Route the form into the caller's isolated context (createFormContext)\n // or the module-level default, whichever Provider we ended up with.\n const {Provider} = context ?? FormContext;\n\n return (\n <Provider value={form}>\n <form {...props} noValidate onSubmit={submit} />\n </Provider>\n );\n}\n","import * as React from 'react';\nimport {on} from '@for-fun/event-emitter';\nimport useField from '../hooks/field';\nimport type {Validator} from '../hooks/validate';\nimport type {Form} from '../form';\nimport type {FieldRules} from '../rules';\nimport type {Name, Path} from '../path';\nimport type {FieldPath, PathValueOf} from '../types';\n\n/**\n * Props shared by Field/Checkbox/Select. Generic so a typed form flows into\n * the `validate` callback: with `form` (a `Form<Values>`) and `name`\n * (a `FieldPath<Values>`) provided, `validate` receives the value at that\n * path — `PathValueOf<Values, P>` — instead of `any`. The defaults keep the\n * bare `<Field name=\"x\" />` (context-resolved, untyped) call sites exactly\n * as permissive as before.\n */\ninterface UseFieldOptions<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n> {\n form?: Form<TValues>;\n name?: TPath;\n initialValue?: any;\n shouldUnregister?: boolean;\n /**\n * Field-level validator. The value argument is typed when the field is\n * tied to a typed form (via the `form` prop); the return shape mirrors\n * {@link Validator} — an error (string / FieldError / mixed array) or\n * undefined when valid, possibly a Promise for async validation. The\n * second argument carries the validation context (`meta.signal` aborts\n * when the round is superseded).\n */\n validate?: (\n value: PathValueOf<TValues, TPath>,\n meta: {form: Form; path: Path; signal: AbortSignal}\n ) => ReturnType<Validator>;\n /**\n * Declarative rules (required/min/max/minLength/maxLength/pattern),\n * compiled into a validator that runs before `validate`; failures land\n * in the form's error state. Passed through to useField — like\n * validateDebounce it is never spread onto the DOM element.\n */\n rules?: FieldRules;\n /**\n * Milliseconds to debounce this field's validation kicks. Defaults to 0\n * (validate immediately); only the last kick inside the window runs the\n * validator, and `trigger` waits the window out. Passed through to\n * useField/useValidate.\n */\n validateDebounce?: number;\n /**\n * Disable this field's control: OR-ed with the form-level flag\n * (`createForm({disabled})` / `setDisabled`) — a field cannot opt out\n * of a disabled form. Passed through to useField, like every option,\n * never spread onto the DOM element from props.\n */\n disabled?: boolean;\n /**\n * Milliseconds to delay showing a newly appearing error (render layer\n * only — `aria-invalid`/`renderError` wait out the window while the\n * form's error state stays immediate for trigger/submit). An error\n * that clears inside the window never shows; once visible, error\n * changes apply immediately. Passed through to useField.\n */\n delayError?: number;\n [key: string]: any;\n}\n\ninterface FieldProps<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n> extends UseFieldOptions<TValues, TPath> {\n as?: React.ComponentType<any>;\n asProps?: Record<string, any>;\n eventToValue?: (e: any) => any;\n valueToProps?: (value: any) => Record<string, any>;\n /**\n * Optional error renderer. When provided and the field has an error,\n * Field renders `<span id={id} role=\"alert\">{renderError(error, id)}</span>`\n * next to the input and points the input's aria-describedby at that span.\n * When omitted, no extra element is rendered (headless) and no\n * aria-describedby is attached, avoiding dangling id references.\n */\n renderError?: (error: string, id: string) => React.ReactNode;\n}\n\nfunction setRef<T>(ref: React.Ref<T> | undefined, value: T | null) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n (ref as React.MutableRefObject<T | null>).current = value;\n }\n}\n\n/**\n * Converts a path key (the JSON.stringify'd path segments, e.g. '[\"a\",\"0\"]')\n * into a valid HTML id ('a-0'): quotes, brackets, commas and whitespace\n * become hyphens; leading/trailing hyphens are trimmed. Falls back to\n * 'field' if nothing remains.\n */\nfunction errorIdFromKey(key: string): string {\n const id = key.replace(/[\"'[\\],\\s]+/g, '-').replace(/^-+|-+$/g, '');\n return id || 'field';\n}\n\n/**\n * The callable shape of {@link Field}: `form` + `name` flow their generics\n * into `validate`'s value argument (`PathValueOf<TValues, TPath>`). A named\n * interface rather than an inline `as <TValues, ...>() => ...` signature —\n * same types, and the inline form trips no-use-before-define on the type\n * parameters.\n */\ninterface FieldComponent {\n <\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n >(\n props: FieldProps<TValues, TPath> & React.RefAttributes<HTMLInputElement>\n ): React.ReactElement | null;\n}\n\nexport const Field = React.forwardRef<HTMLInputElement, FieldProps>(\n (\n {\n validate,\n eventToValue,\n initialValue,\n name,\n asProps,\n renderError,\n as,\n valueToProps,\n form: formProp,\n shouldUnregister,\n rules,\n validateDebounce,\n disabled,\n delayError,\n ...props\n },\n ref\n ) => {\n const innerRef = React.useRef<HTMLInputElement | null>(null);\n const [nativeInvalidCount, setNativeInvalidCount] = React.useState(0);\n const mergedRef = React.useCallback(\n (node: HTMLInputElement | null) => {\n innerRef.current = node;\n setRef(ref, node);\n },\n [ref]\n );\n // Only declared options go into the hook; DOM props stay in `props` and\n // are spread onto the element below — useField no longer echoes unknown\n // options back, so `as`/`valueToProps`/DOM props are destructured here\n // instead of being fished out of its result.\n const {\n value,\n onChange,\n onBlur,\n error,\n form,\n name: fieldKey,\n disabled: isDisabled\n } = useField({\n name: name!,\n form: formProp,\n initialValue,\n shouldUnregister,\n rules,\n validateDebounce,\n delayError,\n disabled,\n validate: (...params: [any, any]) => {\n const el = innerRef.current;\n if (el && typeof el.checkValidity === 'function') {\n el.setCustomValidity('');\n if (el.checkValidity() === false) {\n setNativeInvalidCount(count => count + 1);\n return undefined;\n }\n }\n if (validate) return validate(...params);\n }\n });\n const Component = as || 'input';\n\n React.useEffect(() => {\n const el = innerRef.current;\n if (!el || typeof el.setCustomValidity !== 'function') return;\n if (typeof error === 'string') {\n el.setCustomValidity(error);\n el.reportValidity();\n } else {\n el.setCustomValidity('');\n }\n }, [error]);\n\n React.useEffect(() => {\n if (nativeInvalidCount > 0) innerRef.current?.reportValidity();\n }, [nativeInvalidCount]);\n\n // Focus this input when a failed submit names it as the first error:\n // handleSubmit emits 'focusError' with the first error's path key.\n // setFocus rides the same channel and may pass {shouldSelect} as a\n // second, optional argument to select the text after focusing.\n React.useEffect(\n () =>\n on(\n form.emitter,\n 'focusError',\n (key: string, options?: {shouldSelect?: boolean}) => {\n if (key !== fieldKey) return;\n const el = innerRef.current;\n if (!el || typeof el.focus !== 'function') return;\n el.focus();\n if (options?.shouldSelect && typeof el.select === 'function') {\n el.select();\n }\n }\n ),\n [form, fieldKey]\n );\n\n const toValue = eventToValue ?? ((e: any) => e.target.value);\n\n // fieldKey is the field's path key (set by useField), e.g. '[\"a\",\"0\"]'.\n const errorId = errorIdFromKey(fieldKey);\n\n return (\n <>\n <Component\n aria-invalid={error ? true : undefined}\n aria-describedby={error && renderError ? errorId : undefined}\n {...props}\n name={fieldKey}\n onBlur={onBlur}\n {...asProps}\n {...(valueToProps ? valueToProps(value) : {value})}\n disabled={isDisabled}\n onChange={(e: any) => onChange(toValue(e))}\n ref={mergedRef}\n />\n {error && renderError ? (\n <span id={errorId} role=\"alert\">\n {renderError(error, errorId)}\n </span>\n ) : null}\n </>\n );\n }\n) as FieldComponent;\n\ninterface CheckboxProps<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n> extends UseFieldOptions<TValues, TPath> {}\n\n/**\n * Callable shape of {@link Checkbox}: the same form-typed `validate`\n * inference contract as {@link FieldComponent}.\n */\ninterface CheckboxComponent {\n <\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n >(\n props: CheckboxProps<TValues, TPath> & React.RefAttributes<HTMLInputElement>\n ): React.ReactElement | null;\n}\n\nexport const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(\n (\n {\n name,\n form,\n initialValue,\n shouldUnregister,\n validate,\n rules,\n validateDebounce,\n disabled,\n delayError,\n ...props\n },\n ref\n ) => {\n const {\n value,\n onChange,\n onBlur,\n error,\n name: fieldKey,\n disabled: isDisabled\n } = useField({\n name: name!,\n form,\n initialValue,\n shouldUnregister,\n validate,\n rules,\n validateDebounce,\n delayError,\n disabled\n });\n return (\n <input\n aria-invalid={error ? true : undefined}\n {...props}\n name={fieldKey}\n onBlur={onBlur}\n type=\"checkbox\"\n checked={!!value}\n disabled={isDisabled}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n onChange(e.target.checked)\n }\n ref={ref}\n />\n );\n }\n) as CheckboxComponent;\n\ninterface SelectProps<\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n> extends UseFieldOptions<TValues, TPath> {\n multiple?: boolean;\n children?: React.ReactNode;\n}\n\n/**\n * Controlled <select>. Options are passed as children (<option> elements).\n * Single-select stores the selected option's value as a string, matching\n * Field's default event-to-value behavior; a multiple select stores the\n * values of all selected options as a string array.\n */\n/** Normalize a field value for a <select>: multiple wants a string array,\n * single-select wants a string. */\nfunction toSelectValue(\n multiple: boolean | undefined,\n value: any\n): string | string[] {\n if (multiple) return Array.isArray(value) ? value : [];\n return value ?? '';\n}\n\n/**\n * Callable shape of {@link Select}: the same form-typed `validate`\n * inference contract as {@link FieldComponent}.\n */\ninterface SelectComponent {\n <\n TValues extends Record<string, any> = any,\n TPath extends FieldPath<TValues> | Name = Name\n >(\n props: SelectProps<TValues, TPath> & React.RefAttributes<HTMLSelectElement>\n ): React.ReactElement | null;\n}\n\nexport const Select = React.forwardRef<HTMLSelectElement, SelectProps>(\n (\n {\n name,\n multiple,\n children,\n form,\n initialValue,\n shouldUnregister,\n validate,\n rules,\n validateDebounce,\n disabled,\n delayError,\n ...props\n },\n ref\n ) => {\n const {\n value,\n onChange,\n onBlur,\n error,\n name: fieldKey,\n disabled: isDisabled\n } = useField({\n name: name!,\n form,\n initialValue,\n shouldUnregister,\n validate,\n rules,\n validateDebounce,\n delayError,\n disabled\n });\n return (\n <select\n aria-invalid={error ? true : undefined}\n {...props}\n name={fieldKey}\n onBlur={onBlur}\n multiple={multiple}\n value={toSelectValue(multiple, value)}\n disabled={isDisabled}\n onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>\n onChange(\n multiple\n ? Array.from(e.target.selectedOptions, option => option.value)\n : e.target.value\n )\n }\n ref={ref}\n >\n {children}\n </select>\n );\n }\n) as SelectComponent;\n"],"names":["create","emit","_emit","createEmitter","createPath","require$$0","shimModule","require$$1","createForm","useSyncExternalStore","FormProvider","useFormContext"],"mappings":";;;AAAA,SAAS,MAAM,CAAC,EAAE,EAAE,GAAG,EAAE;AACzB,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACxB,EAAE,IAAI,GAAG,EAAE,OAAO,GAAG,CAAC;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