formstand 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +177 -0
- package/README.md +11 -3
- package/dist/chunk-MQ6262S3.js +20 -0
- package/dist/chunk-MQ6262S3.js.map +1 -0
- package/dist/{chunk-N7WPXYCU.js → chunk-OB23TUKY.js} +11 -4
- package/dist/chunk-OB23TUKY.js.map +1 -0
- package/dist/devtools/index.cjs +9 -2
- package/dist/devtools/index.cjs.map +1 -1
- package/dist/devtools/index.js +1 -1
- package/dist/index.cjs +306 -152
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +71 -25
- package/dist/index.d.ts +71 -25
- package/dist/index.js +290 -162
- package/dist/index.js.map +1 -1
- package/dist/testing/index.cjs +70 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +11 -0
- package/dist/testing/index.d.ts +11 -0
- package/dist/testing/index.js +49 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +11 -1
- package/dist/chunk-N7WPXYCU.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/array.ts","../src/core/arrayOpLog.ts","../src/core/validation.ts","../src/core/createForm.ts","../src/core/mode.ts","../src/core/persist.ts","../src/react/usePersistForm.ts","../src/react/useForm.ts","../src/react/useFormAction.ts","../src/react/FormContext.tsx","../src/react/useField.ts","../src/react/useVariantField.ts","../src/react/useFieldArray.ts","../src/react/useFormError.ts","../src/react/useFormValues.ts","../src/react/useFields.ts","../src/react/useFormFlags.ts","../src/react/createFormHooks.ts","../src/react/inputProps.ts","../src/react/fields.tsx","../src/react/focusError.ts"],"names":["useRef","useEffect","initialValue","useMemo","useCallback","validateAsync","useStore","useShallow","jsx"],"mappings":";;;;;;;;;;;AAEO,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,CAAA,KACC,CAAA,KAAM,CAAA,GAAI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,GAAa,CAAC,IAAA,EAAc,IAAA,KAA+B;AACtE,EAAA,MAAM,QAAQ,IAAA,IAAQ,QAAA;AACtB,EAAA,OAAO,IAAA,KAAS,EAAA,GAAA,CACX,IAAA,KAAS,MAAA,IACR,QAAA,CAAS,gBAAA,CAAiB,MAAM,CAAA,CAAE,MAAA,IAAU,CAAA,KAC5C,YAAA,CAAa,aAAA,CAAc,KAAK,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA,GAC5D,YAAA,CAAa,cAAA,CAAe,KAAA,EAAO,CAAC,IAAI,CAAC,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA;AACzE","file":"index.js","sourcesContent":["export type IndexMapper = (oldIndex: number) => number | null;\n\nexport const removeAt =\n (i: number): IndexMapper =>\n (n) =>\n n === i ? null : n > i ? n - 1 : n;\n\nexport const insertAt =\n (i: number): IndexMapper =>\n (n) =>\n n >= i ? n + 1 : n;\n\nexport const moveFromTo =\n (from: number, to: number): IndexMapper =>\n (n) => {\n if (n === from) return to;\n if (from < to && n > from && n <= to) return n - 1;\n if (from > to && n >= to && n < from) return n + 1;\n return n;\n };\n\nexport const swapIndices =\n (a: number, b: number): IndexMapper =>\n (n) =>\n n === a ? b : n === b ? a : n;\n\n// The new-index → old-index view of an op, materialized as an array (-1\n// marks a position with no old index: a freshly created row). Derived by\n// INVERTING the op's IndexMapper — the same mapper trusted to re-key\n// errors/touched — so the value transform and the id mapping cannot\n// diverge. Consumed by the array-op log for row-id derivation.\nexport const invertMapper = (\n mapper: IndexMapper,\n oldLength: number,\n newLength: number,\n): readonly number[] => {\n const oldByNew = new Map(\n Array.from({ length: oldLength }, (_, oldIndex) => oldIndex).flatMap(\n (oldIndex) => {\n const newIndex = mapper(oldIndex);\n return newIndex === null ? [] : ([[newIndex, oldIndex]] as const);\n },\n ),\n );\n return Array.from(\n { length: newLength },\n (_, newIndex) => oldByNew.get(newIndex) ?? -1,\n );\n};\n\nconst indexAndTail = (\n rest: string,\n): Readonly<{ index: number; tail: string }> | null => {\n const dotIdx = rest.indexOf(\".\");\n const idxStr = dotIdx === -1 ? rest : rest.slice(0, dotIdx);\n const tail = dotIdx === -1 ? \"\" : rest.slice(dotIdx);\n const idx = Number(idxStr);\n if (!Number.isInteger(idx) || idx < 0 || String(idx) !== idxStr) return null;\n return { index: idx, tail };\n};\n\nexport const reKeyByArrayPath = <V>(\n map: Readonly<Record<string, V>>,\n basePath: string,\n mapper: IndexMapper,\n): Readonly<Record<string, V>> => {\n const prefix = basePath === \"\" ? \"\" : `${basePath}.`;\n return Object.fromEntries(\n Object.entries(map).flatMap(([key, value]) => {\n if (key === basePath) return [[key, value]];\n if (!key.startsWith(prefix)) return [[key, value]];\n const parsed = indexAndTail(key.slice(prefix.length));\n if (parsed === null) return [[key, value]];\n const next = mapper(parsed.index);\n if (next === null) return [];\n return [[`${prefix}${next}${parsed.tail}`, value]];\n }),\n );\n};\n","// A per-store, per-path log of recent array ops, recorded by the core's\n// applyArrayOp and replayed by useFieldArray's row-id derivation. The ops\n// carry the EXACT new→old index mapping, so id derivation never has to\n// guess which of two Object.is-equal rows an op removed or moved — the one\n// case value-based reconciliation cannot decide. A sanctioned mutable-ref\n// cache (like the core's subschemaCache): the log is derived bookkeeping,\n// never part of form state, and the WeakMap releases it with the store.\n\nexport type ArrayOpRecord = Readonly<{\n // The array value the op consumed / produced — reference identity is the\n // chain link: a consumer replays from the record whose `from` matches its\n // last-seen array, on through consecutive records, until it reaches the\n // live array (or gives up and falls back to value reconciliation).\n from: readonly unknown[];\n to: readonly unknown[];\n // newIndex → oldIndex; -1 marks a freshly created row.\n mapping: readonly number[];\n}>;\n\n// Bounded two ways, both loss-limited: a path's record COUNT is capped by\n// COMPOSING its two oldest records into one when consecutive (op mappings\n// compose, so an arbitrarily long run of consecutive ops stays fully\n// replayable in OP_LOG_LIMIT records; only a chain already broken by an\n// external write drops its dead head) — and a store accumulating more than\n// MAX_LOG_PATHS distinct array paths (dynamic row paths on a long-lived\n// singleton form) evicts its oldest path's records, degrading that path to\n// value reconciliation.\nconst OP_LOG_LIMIT = 16;\nconst MAX_LOG_PATHS = 256;\n\n// (second ∘ first): newIndex → the FIRST record's old index. A -1 anywhere\n// along the way stays -1 (the row was created inside the composed span).\nconst composeOps = (\n first: ArrayOpRecord,\n second: ArrayOpRecord,\n): ArrayOpRecord => ({\n from: first.from,\n to: second.to,\n mapping: second.mapping.map((mid) =>\n mid === -1 ? -1 : (first.mapping[mid] ?? -1),\n ),\n});\n\nconst logs = new WeakMap<object, Map<string, readonly ArrayOpRecord[]>>();\n\n// Cap a path's record count, composing the two oldest records when they are\n// consecutive (lossless) and dropping the dead head otherwise. The slice\n// work only happens on overflow — the common case appends untouched.\nconst boundOps = (\n ops: readonly ArrayOpRecord[],\n): readonly ArrayOpRecord[] => {\n const [head, second] = ops;\n if (ops.length <= OP_LOG_LIMIT || head === undefined || second === undefined) {\n return ops;\n }\n return head.to === second.from\n ? [composeOps(head, second), ...ops.slice(2)]\n : ops.slice(1);\n};\n\nexport const recordArrayOp = (\n store: object,\n path: string,\n record: ArrayOpRecord,\n): void => {\n const existing = logs.get(store);\n const byPath = existing ?? new Map<string, readonly ArrayOpRecord[]>();\n if (existing === undefined) logs.set(store, byPath);\n const bounded = boundOps([...(byPath.get(path) ?? []), record]);\n byPath.delete(path);\n byPath.set(path, bounded);\n if (byPath.size > MAX_LOG_PATHS) {\n const oldest = byPath.keys().next().value;\n if (oldest !== undefined) byPath.delete(oldest);\n }\n};\n\nexport const arrayOpsFor = (\n store: object,\n path: string,\n): readonly ArrayOpRecord[] => logs.get(store)?.get(path) ?? [];\n\n// Drop a path's records — called by the consumer after a walk consumed them\n// (the log is per-batch bookkeeping, spent once derived).\nexport const clearArrayOps = (store: object, path: string): void => {\n logs.get(store)?.delete(path);\n};\n\n// Drop the records of the written path and its DESCENDANTS — the paths\n// where a value write can reintroduce a previously-seen array reference\n// (the caller supplies the subtree's values; reset/restore reinstate stored\n// ones; an array op re-seats existing descendant arrays under new indices),\n// which stale records could falsely chain against. Ancestor paths are\n// deliberately KEPT: setAtPath always builds fresh spine arrays, so an\n// ancestor reference can never recur — and an ancestor's earlier records\n// are real history the id walk still replays, bridging the gap this write\n// created. \"\" (whole-values writes) clears all. `keepSelf` is for\n// applyArrayOp itself: the op's own path is exactly what it is about to\n// record, and its earlier same-batch records still chain.\nexport const clearArrayOpsUnder = (\n store: object,\n path: string,\n keepSelf = false,\n): void => {\n const byPath = logs.get(store);\n if (byPath === undefined) return;\n if (path === \"\") {\n byPath.clear();\n return;\n }\n const related = [...byPath.keys()].filter(\n (p) => (p === path && !keepSelf) || p.startsWith(`${path}.`),\n );\n related.forEach((p) => byPath.delete(p));\n};\n","import { z } from \"zod\";\nimport { type PathSegment, parsePath } from \"./path\";\nimport type { ErrorMap } from \"./types\";\n\nexport type SettledValidationResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type ValidationResult<TOutput> =\n | SettledValidationResult<TOutput>\n // Returned by the sync `validate()` when the schema needs async parsing:\n // the async pass has already been started and `promise` resolves with its\n // outcome.\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledValidationResult<TOutput>>;\n }>;\n\nexport type SettledFieldValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: readonly string[] }>;\n\nexport type FieldValidationResult =\n | SettledFieldValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldValidationResult>;\n }>;\n\n// The plural (validateFields) mirrors the singular's discriminated shape\n// instead of returning boolean | Promise<boolean>: a returned Promise is\n// truthy, so the old union let `if (form.validateFields(paths))` silently\n// pass a gate the moment the schema gained an async refinement. `errors`\n// carries only the entries within the requested paths' scope.\nexport type SettledFieldsValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type FieldsValidationResult =\n | SettledFieldsValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldsValidationResult>;\n }>;\n\nconst issuePathToFormPath = (path: readonly PropertyKey[]): string =>\n path\n .filter((segment): segment is string | number => typeof segment !== \"symbol\")\n .join(\".\");\n\ntype FlatIssue = Readonly<{ path: string; message: string }>;\n\n// A failing plain `z.union` produces a single `invalid_union` issue whose real\n// per-branch issues live in `issue.errors` with paths relative to the union's\n// position. Recurse into them (prefixed with the union's own path) so users\n// get field-level messages instead of one generic \"Invalid input\"; keep the\n// union's own message only when no branch supplies anything more specific.\nconst expandIssue = (\n issue: z.core.$ZodIssue,\n prefix: readonly PropertyKey[],\n): readonly FlatIssue[] => {\n const at = [...prefix, ...issue.path];\n if (issue.code === \"invalid_union\") {\n const nested = issue.errors.flatMap((branch) =>\n branch.flatMap((sub) => expandIssue(sub, at)),\n );\n if (nested.length > 0) return nested;\n }\n return [{ path: issuePathToFormPath(at), message: issue.message }];\n};\n\nexport const flattenIssues = (\n issues: readonly z.core.$ZodIssue[],\n): ErrorMap =>\n issues\n .flatMap((issue) => expandIssue(issue, []))\n .reduce<Record<string, readonly string[]>>((acc, { path, message }) => {\n // Union branches often repeat the same complaint; drop exact duplicates.\n // Own-key read: a plain `acc[path]` for an issue path of \"__proto__\"\n // (reachable via ctx.addIssue in a superRefine) walks the prototype\n // chain and returns Object.prototype, crashing `.includes` below. The\n // spread write is safe as-is — a computed key always defines an own\n // property.\n const existing =\n (Object.hasOwn(acc, path) ? acc[path] : undefined) ?? [];\n return existing.includes(message)\n ? acc\n : { ...acc, [path]: [...existing, message] };\n }, {});\n\nexport const validateSync = <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): SettledValidationResult<z.output<TSchema>> => {\n const result = schema.safeParse(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\nexport const validateAsync = async <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): Promise<SettledValidationResult<z.output<TSchema>>> => {\n const result = await schema.safeParseAsync(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\n// The message fallback covers the dual-package hazard: with two zod copies\n// loaded, the thrown error is not an instance of *this* copy's class.\nexport const isAsyncRequiredError = (e: unknown): boolean =>\n e instanceof z.core.$ZodAsyncError ||\n (e instanceof Error &&\n /Encountered Promise during synchronous parse/i.test(e.message));\n\n// True when `key` is `path` itself or a descendant (\"a.b\" under \"a\"). The\n// root \"\" matches only the \"\" key — whole-form scope is never implicit;\n// call sites that want it (validateField(\"\"), focusFirstError's fallback)\n// handle the root explicitly instead of inheriting a wildcard.\nexport const isPathOrChild = (key: string, path: string): boolean =>\n key === path || key.startsWith(`${path}.`);\n\n// Re-key an error map produced by parsing a field's subschema so its keys are\n// absolute form paths (\"\" becomes the field path itself).\nexport const prefixErrorKeys = (errors: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? errors\n : Object.fromEntries(\n Object.entries(errors).map(([k, v]) => [\n k === \"\" ? path : `${path}.${k}`,\n v,\n ]),\n );\n\n// The empty representation a field's schema accepts: undefined when the\n// field is optional (or the wrappers are unrecognized — undefined is the\n// library-wide default empty), null when it is nullable but not optional.\n// Lets a cleared input round-trip to a valid blank based on what the schema\n// states rather than guessing from runtime values.\nexport const emptyValueForSchema = (schema: z.ZodType): null | undefined => {\n const walk = (s: z.ZodType, sawNullable: boolean): null | undefined => {\n if (s instanceof z.ZodOptional) return undefined;\n if (s instanceof z.ZodNullable) {\n return walk(s.unwrap() as z.ZodType, true);\n }\n return sawNullable ? null : undefined;\n };\n return walk(schema, false);\n};\n\n// Whether the schema ACCEPTS its own emptyValue as input — the judgment the\n// string-shaped bindings need before writing it on a cleared input. An\n// optional field takes undefined, a nullable one takes null, and a\n// defaulted/prefaulted one takes undefined too (the default fills it at\n// parse, so clearing reads as \"back to the default\"). A bare required field\n// does NOT: its emptyValue is undefined only as the library-wide fallback,\n// and writing that would trade a visible \"\" the schema can at least judge\n// for a hole it rejects — which is why text and select bindings keep \"\" for\n// non-clearable fields. The check is deliberately as shallow as\n// emptyValueForSchema's walk: a wrapper that hides the optionality from\n// emptyValue (readonly, catch, pipe) hides it here too, so the pair can\n// never disagree about whether the emptyValue is legal.\nexport const isClearableSchema = (schema: z.ZodType): boolean =>\n schema instanceof z.ZodOptional ||\n schema instanceof z.ZodNullable ||\n schema instanceof z.ZodDefault ||\n schema instanceof z.ZodPrefault;\n\n// One unwrap step for the lax structural walk below: wrappers that are\n// transparent to a path (optional/nullable/default/readonly/catch/pipe/...)\n// yield their inner schema; anything else returns null and is judged as-is.\nconst unwrapForWalk = (s: z.ZodType): z.ZodType | null => {\n if (s instanceof z.ZodOptional || s instanceof z.ZodNullable) {\n return s.unwrap() as z.ZodType;\n }\n if (\n s instanceof z.ZodDefault ||\n s instanceof z.ZodPrefault ||\n s instanceof z.ZodCatch ||\n s instanceof z.ZodReadonly ||\n s instanceof z.ZodNonOptional\n ) {\n return s.def.innerType as z.ZodType;\n }\n // Form values are z.input, so a pipe is traversed through its input side.\n if (s instanceof z.ZodPipe) return s.def.in as z.ZodType;\n return null;\n};\n\n// Leaves that provably have no children: remaining path segments under one of\n// these cannot exist in the schema.\nconst isLeafSchema = (s: z.ZodType): boolean =>\n s instanceof z.ZodString ||\n s instanceof z.ZodNumber ||\n s instanceof z.ZodBoolean ||\n s instanceof z.ZodBigInt ||\n s instanceof z.ZodDate ||\n s instanceof z.ZodEnum ||\n s instanceof z.ZodLiteral ||\n s instanceof z.ZodNull ||\n s instanceof z.ZodUndefined ||\n s instanceof z.ZodVoid ||\n s instanceof z.ZodNaN ||\n s instanceof z.ZodSymbol;\n\n// Every unwrap and every consumed segment costs one step — generous for any\n// real path, but it bounds pathological wrapper towers.\nconst SCHEMA_WALK_BUDGET = 64;\n\n// Lax structural check: can `path` possibly exist under `schema`? Used to\n// warn when validateField targets a path the schema cannot contain (which\n// would otherwise silently validate as always-valid). Deliberately biased\n// toward \"yes\": objects answer from their shape (a catchall/loose object\n// accepts any key), arrays accept any numeric index into their element, and\n// everything too dynamic to judge — records, maps, tuples, unions,\n// intersections, lazies, any/unknown, unrecognized nodes — answers true so\n// the warning can never be a false positive. Only a provable miss (a key\n// absent from a closed object shape, a string segment into an array, or\n// segments remaining under a scalar leaf) answers false.\nexport const schemaHasPath = (schema: z.ZodType, path: string): boolean => {\n const walk = (\n s: z.ZodType,\n segments: readonly PathSegment[],\n budget: number,\n ): boolean => {\n if (budget <= 0) return true;\n const inner = unwrapForWalk(s);\n if (inner !== null) return walk(inner, segments, budget - 1);\n const [head, ...rest] = segments;\n if (head === undefined) return true;\n if (s instanceof z.ZodObject) {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = s.shape;\n // Own-key read: a bare index would walk the prototype chain, so\n // \"constructor\" would resolve to Object's constructor and read as a\n // declared key of the shape.\n const child = Object.hasOwn(shape, String(head))\n ? shape[String(head)]\n : undefined;\n if (child !== undefined) return walk(child, rest, budget - 1);\n // A loose/catchall object accepts keys beyond the shape (a ZodNever\n // catchall — strictObject — rejects them like a closed shape does).\n const catchall = s.def.catchall;\n return catchall !== undefined && !(catchall instanceof z.ZodNever);\n }\n if (s instanceof z.ZodArray) {\n return typeof head === \"number\"\n ? walk(s.element as z.ZodType, rest, budget - 1)\n : false;\n }\n return !isLeafSchema(s);\n };\n return walk(schema, parsePath(path), SCHEMA_WALK_BUDGET);\n};\n\nconst hasChecks = (s: z.ZodType): boolean => {\n const checks = (s.def as Readonly<{ checks?: readonly unknown[] }>).checks;\n return checks !== undefined && checks.length > 0;\n};\n\n// Walk the schema along a dot path so field-level validation can parse just\n// that field instead of the whole form. Returns null (meaning: fall back to a\n// full-form parse) unless every *traversed* level is a plain ZodObject or\n// ZodArray with no checks — a refinement on a traversed level could target\n// this field's path, so extraction would miss or fail to clear its errors.\n// Wrappers (optional/nullable/default/pipe/union/record/...) also bail: their\n// error keying differs from a direct parse of the inner value. The leaf itself\n// may carry any checks — they belong to the field.\nexport const fieldSchemaAtPath = (\n schema: z.ZodType,\n path: string,\n): z.ZodType | null =>\n parsePath(path).reduce<z.ZodType | null>((current, segment: PathSegment) => {\n if (current === null || hasChecks(current)) return null;\n if (current instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> =\n current.shape;\n // Own-key read, like every other walk in the library: a bare index\n // resolves \"constructor\"/\"__proto__\" through the prototype chain to\n // a non-schema value, which then CRASHES the reduce (def.checks on a\n // function; safeParse on Object.prototype) — and the subschema cache\n // would keep the poisoned entry. Runtime-built paths (server error\n // fields mapped onto validateField) are the realistic entry point.\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (current instanceof z.ZodArray && typeof segment === \"number\") {\n return current.element as z.ZodType;\n }\n return null;\n }, schema);\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { createStore } from \"zustand/vanilla\";\nimport { devtools } from \"zustand/middleware\";\nimport {\n type IndexMapper,\n insertAt,\n invertMapper,\n moveFromTo,\n reKeyByArrayPath,\n removeAt,\n swapIndices,\n} from \"./array\";\nimport { clearArrayOpsUnder, recordArrayOp } from \"./arrayOpLog\";\nimport { isFieldDirty, isPlainObject, valuesEqual } from \"./equality\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n IsUnion,\n PathDepth,\n} from \"./fieldPath\";\nimport type { ValidationMode } from \"./mode\";\nimport { getAtPath, hasOwnSlot, setAtPath, slotAtPath } from \"./path\";\nimport type { BoolMap, ErrorMap, FormState } from \"./types\";\nimport {\n type FieldValidationResult,\n type FieldsValidationResult,\n type SettledFieldValidationResult,\n type SettledFieldsValidationResult,\n type SettledValidationResult,\n type ValidationResult,\n fieldSchemaAtPath,\n isAsyncRequiredError,\n isPathOrChild,\n prefixErrorKeys,\n schemaHasPath,\n validateAsync,\n validateSync,\n} from \"./validation\";\n\nexport type ReadonlyStoreApi<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type CreateFormOptions<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n initialValues: z.input<TSchema>;\n // TYPE-LEVEL ONLY: the typed-path depth budget for this form, in SEGMENTS\n // (default 9). The runtime ignores it entirely — every path API already\n // walks any depth — it only widens (or narrows) the FieldPath union the\n // form's typed surface is checked against. Raising it is a deliberate\n // TypeScript compile-time trade: the union's size grows with every level\n // the type recurses into, and every path-taking call pays for it in the\n // editor. Reach for it when one deep store backs many forms (a global\n // store whose leaves sit past 9 segments); must be a number LITERAL\n // (e.g. `pathDepth: 12`) so the budget stays a compile-time constant.\n // The `PathDepth` constraint (0-25, the Prev table's range) makes an\n // out-of-range literal or a widened `number` variable a compile error at\n // the call site. The intersection additionally rejects a UNION depth\n // (`cond ? 12 : 9` infers D = 9 | 12, a budget assignable to neither\n // Form<S, 9> nor Form<S, 12>): for a single literal the extra operand is\n // `unknown` and the type stays `D`, keeping literal inference intact; for\n // a union it becomes `never`, so the value can't satisfy the property and\n // the call errors instead of minting an unusable Form type.\n pathDepth?: D & (IsUnion<D> extends true ? never : unknown);\n mode?: ValidationMode;\n reValidateMode?: ValidationMode;\n // Run a full validation pass at creation so the error map (and flags derived\n // from it, like `useIsValid`) reflect the initial values immediately rather\n // than reading as error-free until the first blur/change/submit. Async\n // schemas validate in the background. Note this surfaces errors for untouched\n // fields right away — gate error display on `touched` if that's not wanted.\n validateOnMount?: boolean;\n // Connect the form's store to the Redux DevTools extension (zustand's\n // devtools middleware), named so multiple forms are distinguishable:\n // `devtools: \"checkout\"` shows a \"checkout\" instance with every state\n // write inspectable and time-travelable. `true` uses \"formstand\". Off by\n // default; when the extension isn't installed the middleware is inert.\n devtools?: boolean | string;\n}>;\n\nexport type SubmitHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n) => void | Promise<void>;\n\nexport type InvalidSubmitHandler = (errors: ErrorMap) => void;\n\nexport type SubmitOptions = Readonly<{\n force?: boolean;\n // Called when onValid throws or rejects (the \"error\" SubmitResult) — the\n // save-failure hook, mirroring onInvalid for the validation side. The\n // result still resolves {kind: \"error\"}, so imperative submit() callers\n // can keep switching on it instead.\n onError?: (error: unknown) => void;\n}>;\n\n// \"valid\": validation passed and onValid ran to completion. \"invalid\":\n// validation failed (onInvalid ran; errors written and their fields marked\n// touched, unless the values changed while validation was in flight — see\n// submit). \"skipped\": another submit was already in flight and force wasn't\n// set. \"error\": onValid threw or rejected — submit resolves with the thrown\n// value instead of rejecting, so handleSubmit used as an event handler never\n// produces an unhandled rejection. No error state is written for this kind;\n// surface the failure yourself (e.g. via setError).\nexport type SubmitResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>\n | Readonly<{ kind: \"skipped\" }>\n | Readonly<{ kind: \"error\"; error: unknown }>;\n\ntype ArrayItemOf<T> = T extends readonly (infer U)[] ? U : never;\n\n// Root-level errors (schema-wide .refine) live at the \"\" key.\ntype ErrorPath<TValues, D extends PathDepth = DefaultPathDepth> =\n | FieldPath<TValues, D>\n | \"\";\n\n// No keepDirty: per-field dirtiness is derived from values vs initialValues,\n// and reset makes those equal by definition — a kept dirty map would say\n// \"dirty\" while every field-level read says \"clean\".\nexport type ResetOptions = Readonly<{\n keepErrors?: boolean;\n keepTouched?: boolean;\n keepSubmitCount?: boolean;\n}>;\n\nexport type FieldSnapshot<TValue> = Readonly<{\n value: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\nconst shallowFieldEqual = <TValue>(\n a: FieldSnapshot<TValue>,\n b: FieldSnapshot<TValue>,\n): boolean =>\n Object.is(a.value, b.value) &&\n a.error === b.error &&\n a.touched === b.touched &&\n a.dirty === b.dirty &&\n a.isValidating === b.isValidating;\n\nexport type Form<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n // Type-level marker only — never present at runtime. It carries the form's\n // typed-path depth budget (createForm's `pathDepth`, default 9) in a\n // directly-inferable position so the React hooks' `Form<TSchema, D>`\n // parameters recover D from the form argument (inferring it out of the\n // FieldPath instantiations in the method types below is not something TS\n // can do). It also makes the budget part of the form's identity:\n // Form<S, 12> is deliberately not assignable to Form<S, 9>.\n \"~pathDepth\"?: D;\n schema: TSchema;\n store: ReadonlyStoreApi<FormState<z.input<TSchema>>>;\n getState: () => FormState<z.input<TSchema>>;\n subscribe: (\n listener: (\n state: FormState<z.input<TSchema>>,\n prev: FormState<z.input<TSchema>>,\n ) => void,\n ) => () => void;\n getField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldValue<z.input<TSchema>, P>;\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => () => void;\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => () => void;\n // Watches THE WHOLE values object — the name is watchValue + \"s\" as in\n // \"all the values\", not \"watchValue over many paths\". Fires whenever any\n // value changes (reference-compared). A multi-path watcher, if one ever\n // ships, would be a new API rather than a change to this one.\n watchValues: (\n listener: (\n values: z.input<TSchema>,\n previous: z.input<TSchema>,\n ) => void,\n ) => () => void;\n setValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n value: FieldValue<z.input<TSchema>, P>,\n ) => void;\n setValues: (next: z.input<TSchema>) => void;\n setTouched: (path: FieldPath<z.input<TSchema>, D>, touched?: boolean) => void;\n setSubmitting: (value: boolean) => void;\n setMode: (mode: ValidationMode) => void;\n setReValidateMode: (mode: ValidationMode) => void;\n setError: (\n path: ErrorPath<z.input<TSchema>, D>,\n errors: string | readonly string[],\n ) => void;\n setErrors: (errors: ErrorMap) => void;\n // The merge-many sibling of setError: server responses arrive as a MAP\n // of runtime-keyed field errors, and mapping them one setError at a time\n // forced a typed-path cast per call (the docs' own examples did), while\n // setErrors REPLACES the whole channel and cannot be used incrementally.\n // The server channel is inherently runtime-keyed, so this takes the map\n // as-is; an empty array removes its key, like setError.\n addErrors: (errors: ErrorMap) => void;\n clearErrors: (path?: ErrorPath<z.input<TSchema>, D>) => void;\n // The patch type omits `errors`: the merged map is derived from\n // schemaErrors/serverErrors, so writing it directly is unrepresentable for\n // TS callers (plain-JS writes are ignored with a warning).\n updateState: (\n updater: (\n state: FormState<z.input<TSchema>>,\n ) => Partial<Omit<FormState<z.input<TSchema>>, \"errors\">>,\n ) => void;\n reset: (\n nextInitial?: Partial<z.input<TSchema>>,\n options?: ResetOptions,\n ) => void;\n // Reset one field to its initial value, clearing its (and its descendants')\n // dirty/touched/error state.\n resetField: (path: FieldPath<z.input<TSchema>, D>) => void;\n adoptValues: (values: z.input<TSchema>) => void;\n // One-shot read of a field's full slice (value/error/touched/dirty/\n // isValidating) — the imperative sibling of useField's state.\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldSnapshot<FieldValue<z.input<TSchema>, P>>;\n validate: () => ValidationResult<z.output<TSchema>>;\n validateField: (path: ErrorPath<z.input<TSchema>, D>) => FieldValidationResult;\n // Mirrors validateField's discriminated result — \"pending\" (carrying the\n // already-started async pass's promise) when the schema needs async\n // parsing. A bare boolean | Promise<boolean> union would let a truthy\n // in-flight Promise silently pass `if (form.validateFields(...))` gates.\n validateFields: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => FieldsValidationResult;\n // Settled result types, deliberately: an AWAITED async pass can never\n // resolve \"pending\" (the promise IS the pending state), and the wider\n // union forced every exhaustive switch to carry a dead case — against\n // this codebase's own no-default-arm ethos. validateFieldsAsync below\n // was always typed this way; these two now match.\n validateAsync: () => Promise<SettledValidationResult<z.output<TSchema>>>;\n validateFieldAsync: (\n path: ErrorPath<z.input<TSchema>, D>,\n ) => Promise<SettledFieldValidationResult>;\n validateFieldsAsync: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => Promise<SettledFieldsValidationResult>;\n submit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => Promise<SubmitResult<z.output<TSchema>>>;\n arrayPush: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayRemove: (path: FieldPath<z.input<TSchema>, D>, index: number) => void;\n arrayInsert: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n index: number,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayMove: (\n path: FieldPath<z.input<TSchema>, D>,\n from: number,\n to: number,\n ) => void;\n arraySwap: (path: FieldPath<z.input<TSchema>, D>, a: number, b: number) => void;\n handleSubmit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => (event?: {\n preventDefault: () => void;\n }) => Promise<SubmitResult<z.output<TSchema>>>;\n diff: () => Readonly<Record<string, unknown>>;\n dirtyFields: () => readonly string[];\n snapshot: () => FormState<z.input<TSchema>>;\n restore: (snapshot: FormState<z.input<TSchema>>) => void;\n}>;\n\nconst emptyErrors = {} as ErrorMap;\nconst emptyBools = {} as BoolMap;\n\nconst identityMapper: IndexMapper = (n) => n;\n\nconst omitKey = <V>(\n map: Readonly<Record<string, V>>,\n key: string,\n): Readonly<Record<string, V>> =>\n Object.fromEntries(Object.entries(map).filter(([k]) => k !== key));\n\nconst inScopeOfAny = (key: string, paths: readonly string[]): boolean =>\n paths.some((p) => isPathOrChild(key, p));\n\n// Drop every entry keyed at or under any of `paths` (\"items\" covers\n// \"items.0.name\") — the shared scope filter for the path-keyed maps. Returns\n// the input map unchanged when nothing is in scope, so identity-based\n// subscribers don't re-fire.\nconst omitScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => !inScopeOfAny(k, paths));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\nconst pickScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> =>\n Object.fromEntries(\n Object.entries(map).filter(([k]) => inScopeOfAny(k, paths)),\n );\n\n// Replace the slice of `prev` at or under `paths` with `scoped` (whose keys\n// must already be within scope).\nconst mergeScopedErrors = (\n prev: ErrorMap,\n scoped: ErrorMap,\n paths: readonly string[],\n): ErrorMap => ({ ...omitScope(prev, paths), ...scoped });\n\n// Drop entries at `path` itself or an ancestor of it (\"a\" over \"a.b\"). The\n// root \"\" entry is an ancestor of every path, so any value write releases it\n// — a value write below a container stales the container-level server\n// verdict too, per the documented release contract.\nconst releaseAncestorEntries = <V>(\n map: Readonly<Record<string, V>>,\n path: string,\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => k !== \"\" && !isPathOrChild(path, k));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\n// Minimal divergent paths between values and initialValues: recurse through\n// plain objects, report anything else (scalars, arrays, type mismatches) at\n// its own path — arrays report their base path, and a divergent non-record\n// root reports \"\". This is the derived source for diff()/dirtyFields(); the\n// boolean per-field question is isFieldDirty.\nconst dirtyPathsOf = (\n values: unknown,\n initial: unknown,\n prefix: string,\n): readonly string[] => {\n if (Object.is(values, initial)) return [];\n if (isPlainObject(values) && isPlainObject(initial)) {\n // One structural recursion: the deep compare runs only at leaf/array\n // boundaries below, never per ancestor level — otherwise every node is\n // re-deep-compared once per level above it (O(n × depth) for diff()).\n const keys = new Set([...Object.keys(values), ...Object.keys(initial)]);\n const childPaths = [...keys].flatMap((k) =>\n dirtyPathsOf(\n values[k],\n initial[k],\n prefix === \"\" ? k : `${prefix}.${k}`,\n ),\n );\n if (childPaths.length > 0) return childPaths;\n // Every shared key compared equal, so the key SETS decide: a mismatch\n // where the extra key holds undefined ({} vs { nickname: undefined })\n // reports the object itself, keeping diff()/dirtyFields() non-empty\n // whenever isFieldDirty/useIsDirty say dirty (valuesEqual's own rule).\n const sameKeySet =\n Object.keys(values).length === Object.keys(initial).length &&\n Object.keys(values).every((k) => Object.hasOwn(initial, k));\n return sameKeySet ? [] : [prefix];\n }\n return valuesEqual(values, initial) ? [] : [prefix];\n};\n\n// Key for the whole-form async validation's ownership token (internal —\n// form-level in-flight state lives in FormState.isValidatingForm).\nconst FORM_SEQ_KEY = \"__form__\";\n\n// Key for submit's ownership token: reset()/adoptValues() clear the token\n// map, so an in-flight submit notices the form was rebased under it even\n// when the values reference is unchanged (a bare reset() on a pristine form\n// restores the same initialValues reference).\nconst SUBMIT_SEQ_KEY = \"__submit__\";\n\nconst stringArraysEqual = (\n a: readonly string[],\n b: readonly string[],\n): boolean => a === b || (a.length === b.length && a.every((v, i) => v === b[i]));\n\n// Preserve the previous array reference for entries whose messages didn't\n// change (and the previous map itself when nothing changed at all), so field\n// subscriptions comparing errors by identity don't re-fire on every pass.\nconst reuseErrorRefs = (next: ErrorMap, prev: ErrorMap): ErrorMap => {\n if (next === prev) return prev;\n const entries = Object.entries(next).map(([k, v]) => {\n const old = prev[k];\n return [\n k,\n old !== undefined && stringArraysEqual(old, v) ? old : v,\n ] as const;\n });\n const sameShape =\n entries.length === Object.keys(prev).length &&\n entries.every(([k, v]) => prev[k] === v);\n return sameShape ? prev : Object.fromEntries(entries);\n};\n\n// Shape a parse result into an error map scoped to `path`: sub-schema results\n// re-key to absolute form paths; full-form results filter to the path's scope,\n// except the root \"\" whose scope is explicitly the whole form.\nconst scopeSettledResult = (\n result: SettledValidationResult<unknown>,\n path: string,\n viaSubschema: boolean,\n): ErrorMap =>\n result.kind !== \"invalid\"\n ? emptyErrors\n : viaSubschema\n ? prefixErrorKeys(result.errors, path)\n : path === \"\"\n ? result.errors\n : pickScope(result.errors, [path]);\n\n// The one merge rule between the two error channels: the schema's message\n// wins at a key (it re-judged the same value the server did), server entries\n// show where the schema is silent. Returns the schema map's identity when\n// the server channel adds nothing.\nconst mergeErrorChannels = (schema: ErrorMap, server: ErrorMap): ErrorMap => {\n // Own-key check, not `schema[k] === undefined`: for a runtime-built key\n // like \"__proto__\" the bare read returns Object.prototype (never\n // undefined), which would silently drop the server entry from the merge.\n const extra = Object.entries(server).filter(\n ([k]) => !Object.hasOwn(schema, k),\n );\n return extra.length === 0\n ? schema\n : { ...schema, ...Object.fromEntries(extra) };\n};\n\ntype ErrorChannels = Readonly<{\n errors: ErrorMap;\n schemaErrors: ErrorMap;\n serverErrors: ErrorMap;\n}>;\n\n// The one way error state is written: patch a channel (or both) and the\n// user-visible `errors` map is re-derived, reusing per-key refs so\n// identity-based subscribers don't re-fire.\nconst errorChannels = (\n state: ErrorChannels,\n patch: Readonly<{ schemaErrors?: ErrorMap; serverErrors?: ErrorMap }>,\n): ErrorChannels => {\n const schemaErrors = patch.schemaErrors ?? state.schemaErrors;\n const serverErrors = patch.serverErrors ?? state.serverErrors;\n // Unchanged channels mean an unchanged merge — skip it, so no-op writes\n // (every keystroke with an empty server channel) don't rescan the map.\n if (\n schemaErrors === state.schemaErrors &&\n serverErrors === state.serverErrors\n ) {\n return { errors: state.errors, schemaErrors, serverErrors };\n }\n return {\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n state.errors,\n ),\n };\n};\n\n// The release contract for a value write at `path`: server entries at the\n// path or below go (that subtree was replaced), entries at ancestors go too\n// (container verdicts are stale), and a runtime \"\" path (the imperative\n// surface is string-typed) releases everything.\nconst releaseSpine = (server: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? emptyErrors\n : releaseAncestorEntries(omitScope(server, [path]), path);\n\n// A bulk values write releases only the verdicts whose value slice actually\n// changed — a server error on an untouched field survives a setValues that\n// rewrites its siblings. The \"\" entry compares the whole values object, so\n// any change releases a form-level verdict.\nconst releaseChangedSlices = (\n server: ErrorMap,\n prevValues: unknown,\n nextValues: unknown,\n): ErrorMap => {\n const entries = Object.entries(server);\n const kept = entries.filter(([k]) =>\n valuesEqual(getAtPath(prevValues, k), getAtPath(nextValues, k)),\n );\n return kept.length === entries.length ? server : Object.fromEntries(kept);\n};\n\n// D infers as a LITERAL from `options.pathDepth` (the `D extends PathDepth`\n// constraint is a union of literals, so inference stays literal); when the\n// option is omitted, D falls back to the default budget of 9. An\n// out-of-range literal (26, -1) or a `number`-typed variable fails the\n// constraint here, at the call site.\nexport const createForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n): Form<TSchema, D> => {\n type Values = z.input<TSchema>;\n\n const initialMode: ValidationMode = options.mode ?? \"onBlur\";\n const initialReValidateMode: ValidationMode =\n options.reValidateMode ?? \"onChange\";\n\n const initial: FormState<Values> = {\n values: options.initialValues,\n initialValues: options.initialValues,\n errors: emptyErrors,\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n touched: emptyBools,\n isSubmitting: false,\n submitCount: 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n mode: initialMode,\n reValidateMode: initialReValidateMode,\n };\n\n // The devtools middleware is opt-in and otherwise absent — a plain store\n // has zero overhead. `enabled` stays true when opted in even in\n // production builds: opting in IS the signal, and without the browser\n // extension the middleware is inert anyway.\n const store =\n options.devtools === undefined || options.devtools === false\n ? createStore<FormState<Values>>(() => initial)\n : createStore<FormState<Values>>()(\n devtools(() => initial, {\n name:\n typeof options.devtools === \"string\"\n ? options.devtools\n : \"formstand\",\n // Non-production only, matching zustand's own devtools default:\n // opting in during development must NOT stream every keystroke to\n // an end user who happens to have the extension installed, where\n // a module-singleton form's unbounded time-travel history is a\n // real memory + serialization cost. Guarded for environments\n // without process (a bundler defines NODE_ENV in real dev).\n enabled:\n typeof process !== \"undefined\" &&\n process.env?.[\"NODE_ENV\"] !== \"production\",\n }),\n );\n\n // A full pass replaces the schema channel wholesale; the server channel is\n // untouched, which is the whole preservation story — a background pass\n // can't wipe a server verdict because it never writes that channel.\n const commitFullPass = (\n state: FormState<Values>,\n next: ErrorMap,\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(next, state.schemaErrors),\n });\n\n const validate = (): ValidationResult<z.output<TSchema>> => {\n if (asyncScopes.has(\"\")) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n try {\n const result = validateSyncLatched(\"\", schema, store.getState().values);\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n }));\n return result;\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n throw e;\n }\n };\n\n const validateFields = (\n paths: readonly string[],\n ): FieldsValidationResult => {\n if (paths.length === 0) return { kind: \"valid\" };\n // A \"\" path means whole-form scope (only reachable past the FieldPath\n // type, e.g. runtime-built path lists): delegate to the full pass so\n // manual errors are preserved, mirroring validateField(\"\").\n if (paths.some((p) => p === \"\")) {\n const result = validate();\n return result.kind === \"pending\"\n ? { kind: \"pending\", promise: result.promise.then(settledFormResult) }\n : settledFormResult(result);\n }\n const values = store.getState().values;\n // Fast path: when every requested path extracts a subschema, parse\n // just those slots instead of the whole form (a wizard step on a\n // 200-field schema stops paying for the other 190 fields per click).\n // This matches the full parse EXACTLY because extraction bailing is\n // what guards cross-field rules: fieldSchemaAtPath returns null when\n // any traversed level carries refinements or wrappers, so an\n // ancestor refine that could key errors into these paths forces the\n // full parse below.\n const scopes = paths.map((path) => ({\n path,\n scope: fieldScopeFor(path, values),\n }));\n const allViaSubschema = scopes.every(\n ({ scope }) =>\n scope.kind === \"skip\" ||\n (scope.kind === \"parse\" && scope.viaSubschema),\n );\n // Scopes already latched as async-requiring go straight to the async\n // pass. Skip scopes parse nothing and contribute no latch key — a\n // latched full-form \"\" must not divert a batch whose parses are all\n // sync subschemas (or nothing at all).\n const anyLatched = allViaSubschema\n ? scopes.some(\n ({ path, scope }) =>\n scope.kind === \"parse\" && asyncScopes.has(path),\n )\n : asyncScopes.has(\"\");\n if (anyLatched) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n try {\n if (allViaSubschema) {\n const merged = scopes.reduce<ErrorMap>(\n (acc, { path, scope }) =>\n scope.kind === \"skip\"\n ? acc\n : {\n ...acc,\n ...scopeSettledResult(\n validateSyncLatched(path, scope.schema, scope.value),\n path,\n true,\n ),\n },\n {},\n );\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, merged, paths),\n }));\n return settledFields(merged);\n }\n const result = validateSyncLatched(\"\", schema, values);\n const fullErrors =\n result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedErrors = pickScope(fullErrors, paths);\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, requestedErrors, paths),\n }));\n return settledFields(requestedErrors);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n throw e;\n }\n };\n\n // How to validate one field: parse its extracted subschema against the\n // slot's value when the path is reachable through check-free objects/\n // arrays, parse the full form filtered to the path's scope otherwise (so\n // cross-field refinements targeting the path still land), or skip when the\n // path addresses no slot (an out-of-range array index — parsing the\n // subschema against undefined would fabricate an error no full-form parse\n // produces). One \"parse\" variant carries the whole triple so the sync and\n // async passes cannot diverge arm-by-arm.\n type FieldScope =\n | Readonly<{ kind: \"skip\" }>\n | Readonly<{\n kind: \"parse\";\n schema: z.ZodType;\n value: unknown;\n viaSubschema: boolean;\n }>;\n\n // Scopes whose sync parse has hit an async refinement. The schema is fixed\n // for the form's lifetime, so once a scope requires async parsing it always\n // will — remember it and go straight to the async pass instead of paying a\n // doomed sync parse per validation (per keystroke in onChange mode). Keyed\n // like the parses themselves: \"\" for full-form, the path for subschema\n // parses. A sanctioned mutable-ref cache, like subschemaCache below.\n const asyncScopes = new Set<string>();\n\n // validateSync, latching the scope when its parse turns out to need async\n // — the caller still routes the rethrown error to the async pass.\n const validateSyncLatched = <S extends z.ZodType>(\n key: string,\n scopeSchema: S,\n value: z.input<S>,\n ): SettledValidationResult<z.output<S>> => {\n try {\n return validateSync(scopeSchema, value);\n } catch (e) {\n if (isAsyncRequiredError(e)) asyncScopes.add(key);\n throw e;\n }\n };\n\n // The subschema for a path is a pure function of the form's fixed schema —\n // cache it so per-keystroke validation doesn't re-walk the schema.\n const subschemaCache = new Map<string, z.ZodType | null>();\n const subschemaAt = (path: string): z.ZodType | null => {\n const cached = subschemaCache.get(path);\n if (cached !== undefined) return cached;\n const sub = fieldSchemaAtPath(schema, path);\n subschemaCache.set(path, sub);\n return sub;\n };\n\n // Field validation on a path the schema cannot contain silently returns\n // valid — easy to hit through the docs-sanctioned casts for runtime-built\n // paths. Warn once per path per form (a sanctioned mutable-ref cache, like\n // subschemaCache above: checked paths never need re-walking).\n const checkedSchemaPaths = new Set<string>();\n const warnMissingSchemaPath = (fn: string, path: string): void => {\n if (path === \"\" || checkedSchemaPaths.has(path)) return;\n checkedSchemaPaths.add(path);\n if (!schemaHasPath(schema, path)) {\n console.warn(\n `[formstand] ${fn}(\"${path}\"): path does not exist in the schema — result will always be valid.`,\n );\n }\n };\n\n const fieldScopeFor = (path: string, values: Values): FieldScope => {\n const sub = path === \"\" ? null : subschemaAt(path);\n if (sub === null) {\n return { kind: \"parse\", schema, value: values, viaSubschema: false };\n }\n const slot = slotAtPath(values, path);\n return slot.exists\n ? { kind: \"parse\", schema: sub, value: slot.value, viaSubschema: true }\n : { kind: \"skip\" };\n };\n\n const scopedFieldErrorsAsync = async (\n path: string,\n values: Values,\n ): Promise<ErrorMap> => {\n const scope = fieldScopeFor(path, values);\n return scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n await validateAsync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\n );\n };\n\n const fieldResult = (scoped: ErrorMap): SettledFieldValidationResult => {\n const messages = Object.values(scoped).flat();\n return messages.length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: messages };\n };\n\n // The plural counterpart: reports the scoped error MAP (entries under the\n // requested paths) rather than one field's flat message list. Every input\n // derives from flattenIssues, which never emits an empty message list, so\n // key presence alone decides validity.\n const settledFields = (scoped: ErrorMap): SettledFieldsValidationResult =>\n Object.keys(scoped).length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: scoped };\n\n // Whole-form (\"\" path) delegation, shared by the sync and async plural\n // passes so their scoping of a full-pass verdict cannot diverge.\n const settledFormResult = (\n result: SettledValidationResult<z.output<TSchema>>,\n ): SettledFieldsValidationResult =>\n settledFields(result.kind === \"invalid\" ? result.errors : emptyErrors);\n\n // The commit rule for any scoped validation: replace the schema-error\n // slice under `paths` and release the server verdicts there — a\n // validation explicitly targeting a scope supersedes the server's word on\n // it. Shared by the singular and plural, sync and async passes so the\n // supersede rule lives exactly once.\n const commitScopedErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n paths: readonly string[],\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(state.schemaErrors, scoped, paths),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, paths),\n });\n\n // How ONE field validation's scoped errors land. validateField(\"\") is a\n // whole-form pass, so it lands like validate() (server channel untouched).\n const commitFieldErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n path: string,\n ): ErrorChannels =>\n path === \"\"\n ? commitFullPass(state, scoped)\n : commitScopedErrors(state, scoped, [path]);\n\n const validateField = (path: string): FieldValidationResult => {\n warnMissingSchemaPath(\"validateField\", path);\n const scope = fieldScopeFor(path, store.getState().values);\n // Only PARSE scopes consult the latch — a skip scope parses nothing, so\n // it can never require async parsing and settles synchronously (below)\n // even while the full-form \"\" key is latched. The latch key mirrors\n // what the parse would run: the path for a subschema parse, the full\n // form (\"\") for a bailed extraction.\n if (\n scope.kind === \"parse\" &&\n asyncScopes.has(scope.viaSubschema ? path : \"\")\n ) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n try {\n const scoped =\n scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n validateSyncLatched(\n scope.viaSubschema ? path : \"\",\n scope.schema,\n scope.value,\n ),\n path,\n scope.viaSubschema,\n );\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, scoped, path),\n }));\n return fieldResult(scoped);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n throw e;\n }\n };\n\n const snapshotField = (\n state: FormState<Values>,\n path: string,\n ): FieldSnapshot<unknown> => {\n const value = getAtPath(state.values, path);\n return {\n value,\n error: state.errors[path],\n touched: state.touched[path] ?? false,\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: state.isValidating[path] ?? false,\n };\n };\n\n // Ownership tokens for in-flight async passes (a sanctioned mutable-ref\n // cache, like the subscription refs). Tokens are unique by construction —\n // each claim mints a fresh Symbol — so cleared or reissued keys can never\n // collide with a token an in-flight pass still holds.\n const sequences = new Map<string, symbol>();\n\n const claimPass = (key: string): symbol => {\n const pass = Symbol(key);\n sequences.set(key, pass);\n return pass;\n };\n\n const validateAsyncOnForm = async (): Promise<\n SettledValidationResult<z.output<TSchema>>\n > => {\n const pass = claimPass(FORM_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({ ...state, isValidatingForm: true }));\n\n const result = await validateAsync(schema, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(FORM_SEQ_KEY) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\n if (stillOwns) {\n store.setState((state) => ({ ...state, isValidatingForm: false }));\n }\n return result;\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n isValidatingForm: false,\n }));\n return result;\n };\n\n const validateFieldsAsync = async (\n paths: readonly string[],\n ): Promise<SettledFieldsValidationResult> => {\n if (paths.length === 0) return { kind: \"valid\" };\n // Whole-form scope: same delegation as validateFields (see above).\n if (paths.some((p) => p === \"\")) {\n return settledFormResult(await validateAsyncOnForm());\n }\n const passes = new Map(paths.map((p) => [p, claimPass(p)]));\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({\n ...state,\n isValidating: paths.reduce<Record<string, boolean>>(\n (acc, p) => ({ ...acc, [p]: true }),\n { ...state.isValidating },\n ),\n }));\n\n const result = await validateAsync(schema, valuesAtStart);\n const fullErrors = result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedErrors = pickScope(fullErrors, paths);\n const requested = settledFields(requestedErrors);\n\n const live = store.getState();\n const stillCurrent = paths.filter(\n (p) => sequences.get(p) === passes.get(p),\n );\n if (live.values !== valuesAtStart) {\n if (stillCurrent.length > 0) {\n store.setState((state) => ({\n ...state,\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n }\n return requested;\n }\n\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(\n state,\n pickScope(fullErrors, stillCurrent),\n stillCurrent,\n ),\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n\n return requested;\n };\n\n const validateFieldAsync = async (\n path: string,\n ): Promise<SettledFieldValidationResult> => {\n warnMissingSchemaPath(\"validateFieldAsync\", path);\n // The root \"\" is whole-form scope: delegate to the form-level pass so\n // the in-flight flag lands in isValidatingForm — the single slot for\n // whole-form validation — instead of booking an isValidating[\"\"] entry\n // no consumer watches.\n if (path === \"\") {\n const result = await validateAsyncOnForm();\n return fieldResult(\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n );\n }\n const pass = claimPass(path);\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({\n ...state,\n isValidating: { ...state.isValidating, [path]: true },\n }));\n\n const scoped = await scopedFieldErrorsAsync(path, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(path) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\n if (stillOwns) {\n store.setState((state) => ({\n ...state,\n isValidating: omitKey(state.isValidating, path),\n }));\n }\n return fieldResult(scoped);\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, scoped, path),\n isValidating: omitKey(state.isValidating, path),\n }));\n\n return fieldResult(scoped);\n };\n\n const applyArrayOp = (\n path: string,\n nextArray: (current: readonly unknown[]) => readonly unknown[],\n mapper: IndexMapper,\n // Validated against the current length before anything mutates — a bad\n // index (arrayRemove(path, -1)) would otherwise corrupt both the array\n // and the re-keyed error/touched maps.\n indexInBounds?: (length: number) => boolean,\n ): void => {\n const current = getAtPath(store.getState().values, path);\n // null passes like undefined: it is the canonical empty of a NULLABLE\n // array field (emptyValue), and the op item types are built on\n // NonNullable<FieldValue<...>> precisely so nullable/optional arrays\n // accept ops — refusing null made those calls typecheck and then\n // silently no-op at runtime. Both empties start the op from [].\n if (current !== undefined && current !== null && !Array.isArray(current)) {\n console.warn(\n `[formstand] array op on \"${path}\" but the value at that path is not an array (got ${typeof current}). Operation skipped.`,\n );\n return;\n }\n const length = Array.isArray(current) ? current.length : 0;\n if (indexInBounds !== undefined && !indexInBounds(length)) {\n console.warn(\n `[formstand] array op on \"${path}\" with an out-of-range or non-integer index (length ${length}). Operation skipped.`,\n );\n return;\n }\n const arr: readonly unknown[] = Array.isArray(current) ? current : [];\n const next = nextArray(arr);\n const written = setAtPath(store.getState().values, path, next);\n // The op rebuilds every ancestor's array (spine copy) and re-seats its\n // rows' descendant arrays under new indices — those paths' records no\n // longer describe the arrays now living there. The op's OWN path keeps\n // its records: earlier same-batch ops still chain.\n clearArrayOpsUnder(store, path, true);\n // Record BEFORE the write, from the exact references the write uses:\n // zustand notifies subscribers synchronously inside setState, so a\n // reentrant same-path write would otherwise interleave the log order\n // AND make a post-setState getState() read pair this op's mapping with\n // a `to` spanning two writes — a corrupt record that can replay to\n // wrong row ids. The mapping is the inverted IndexMapper — the same\n // mapper that re-keys errors/touched below, one source of truth.\n // Guards: an op on an absent slot (push into an undefined array) has no\n // prior reference to chain from, and a write setAtPath REFUSES (huge\n // index, non-plain ancestor) must not log a transition the store never\n // performed — value reconciliation covers both.\n if (Array.isArray(current) && getAtPath(written, path) === next) {\n recordArrayOp(store, path, {\n from: current,\n to: next,\n mapping: invertMapper(mapper, current.length, next.length),\n });\n }\n store.setState((state) => {\n return {\n ...state,\n values: written,\n ...errorChannels(state, {\n schemaErrors: reKeyByArrayPath(state.schemaErrors, path, mapper),\n // Server entries on rows follow their rows through the index\n // mapping — a verdict on \"items.1.name\" is still vouched for after\n // the op moves it to \"items.0.name\" (that row's value didn't\n // change). Entries at the array itself or an ancestor release: the\n // op changed that value.\n serverErrors: releaseAncestorEntries(\n reKeyByArrayPath(state.serverErrors, path, mapper),\n path,\n ),\n }),\n touched: reKeyByArrayPath(state.touched, path, mapper),\n // Drop (don't re-key) in-flight flags under the array: the op changes\n // `values`, so every pass they belong to fails its values-changed\n // guard and never commits — but each pass's cleanup omits its\n // ORIGINAL key, so a re-keyed entry would be orphaned and stick\n // forever. Dropped, the flag is gone now and the cleanup is a\n // harmless no-op.\n isValidating: omitScope(state.isValidating, [path]),\n };\n });\n };\n\n const inFlight: { count: number; baseline: boolean } = {\n count: 0,\n baseline: false,\n };\n\n const submit = async (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n submitOptions?: SubmitOptions,\n ): Promise<SubmitResult<z.output<TSchema>>> => {\n if (inFlight.count > 0 && submitOptions?.force !== true) {\n return { kind: \"skipped\" };\n }\n if (inFlight.count === 0) {\n inFlight.baseline = store.getState().isSubmitting;\n }\n inFlight.count += 1;\n store.setState((state) => ({\n ...state,\n isSubmitting: true,\n submitCount: state.submitCount + 1,\n }));\n\n try {\n const pass = claimPass(SUBMIT_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n const result = await validateAsync(schema, valuesAtStart);\n\n // Stale-commit contract (mirrors validateAsyncOnForm's guard): if the\n // values changed while validation was in flight (setValue/reset/\n // adoptValues), the verdict describes a snapshot the form no longer\n // holds — skip every state write (no error commit, no touched marks;\n // that state belongs to the new values). The ownership token catches\n // what the values reference can't: a bare reset() on a pristine form\n // restores the same values reference but clears the token map, and a\n // concurrent submit({ force: true }) re-claims the token — the LAST\n // submit owns the writes. The handlers still run and the result still\n // reports the snapshot's verdict, so callers decide what it means for\n // them.\n const stale =\n sequences.get(SUBMIT_SEQ_KEY) !== pass ||\n store.getState().values !== valuesAtStart;\n\n if (result.kind === \"invalid\") {\n if (!stale) {\n store.setState((state) => {\n const committed = commitFullPass(state, result.errors);\n return {\n ...state,\n ...committed,\n // Mark every errored field touched so touched-gated error UIs\n // show something after the canonical first failed submit. The\n // \"\" key (schema-level refine) has no field to touch.\n touched: {\n ...state.touched,\n ...Object.fromEntries(\n Object.keys(committed.errors)\n .filter((k) => k !== \"\")\n .map((k) => [k, true]),\n ),\n },\n };\n });\n }\n const merged = stale ? result.errors : store.getState().errors;\n try {\n onInvalid?.(merged);\n } catch (error) {\n // Same contract as a throwing onValid below: a failing caller\n // handler resolves as { kind: \"error\" }, never a rejection out of\n // a DOM event handler.\n return { kind: \"error\", error };\n }\n return { kind: \"invalid\", errors: merged };\n }\n\n if (!stale) {\n store.setState((state) => ({\n ...state,\n ...commitFullPass(state, emptyErrors),\n }));\n }\n try {\n await onValid(result.data);\n } catch (error) {\n // A throwing onValid is the caller's failure, not a validation\n // verdict: resolve with it (so handleSubmit-as-event-handler never\n // leaves an unhandled rejection) and write no error state.\n submitOptions?.onError?.(error);\n return { kind: \"error\", error };\n }\n return { kind: \"valid\", data: result.data };\n } finally {\n inFlight.count -= 1;\n if (inFlight.count === 0) {\n const baseline = inFlight.baseline;\n store.setState((state) => ({ ...state, isSubmitting: baseline }));\n }\n }\n };\n\n if (options.validateOnMount === true) {\n // Async schemas route themselves: validate() returns a \"pending\" result\n // whose background pass writes the error map when it settles.\n validate();\n }\n\n return Object.freeze({\n schema,\n store,\n getState: store.getState,\n subscribe: store.subscribe,\n getField: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n getAtPath(store.getState().values, path) as FieldValue<\n z.input<TSchema>,\n P\n >,\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n snapshotField(store.getState(), path) as FieldSnapshot<\n FieldValue<z.input<TSchema>, P>\n >,\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => {\n const ref: { current: FieldSnapshot<unknown> } = {\n current: snapshotField(store.getState(), path),\n };\n return store.subscribe((state) => {\n const next = snapshotField(state, path);\n if (!shallowFieldEqual(ref.current, next)) {\n ref.current = next;\n listener(next as FieldSnapshot<FieldValue<z.input<TSchema>, P>>);\n }\n });\n },\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => {\n const ref: { current: unknown } = {\n current: getAtPath(store.getState().values, path),\n };\n return store.subscribe((state) => {\n const next = getAtPath(state.values, path);\n if (!Object.is(ref.current, next)) {\n const prev = ref.current;\n ref.current = next;\n listener(\n next as FieldValue<z.input<TSchema>, P>,\n prev as FieldValue<z.input<TSchema>, P>,\n );\n }\n });\n },\n watchValues: (listener) => {\n const ref: { current: Values } = { current: store.getState().values };\n return store.subscribe((state) => {\n if (state.values !== ref.current) {\n const prev = ref.current;\n ref.current = state.values;\n listener(state.values, prev);\n }\n });\n },\n setValue: (path: string, value: unknown) => {\n // Identity guard: writing the value already at the path is a FULL\n // no-op — same state reference, no values rebuild, no dirty/error\n // recompute, no subscriber notifications. Without it, every no-op\n // write rebuilt the values spine, so useFormValues re-rendered and\n // watchValues/onValuesChange fired on nothing — and a two-way sync\n // that echoes values back (form A watches form B and vice versa)\n // recursed until the stack overflowed. Object.is matches the\n // library's other change detectors (watchValue, useStore); note it\n // also skips the server-error release and op-log clearing below —\n // deliberately, since no value changed. One carve-out: an\n // `undefined` write only no-ops when the slot actually EXISTS —\n // writing undefined over an absent key CREATES the key (a real\n // change: key-count dirtiness, the persisted shape), so it must\n // still go through. A non-undefined Object.is match implies the own\n // slot exists (reads are own-key only), so the walk runs for\n // undefined writes alone.\n const currentValues = store.getState().values;\n if (\n Object.is(getAtPath(currentValues, path), value) &&\n (value !== undefined || hasOwnSlot(currentValues, path))\n ) {\n return;\n }\n // A value write outside the array ops breaks every op chain whose\n // array it could rebuild — drop those records at the source so a\n // stale (or recurring, e.g. reset-restored) array reference can never\n // falsely chain against them.\n clearArrayOpsUnder(store, path);\n store.setState((state) => ({\n ...state,\n values: setAtPath(state.values, path, value),\n ...errorChannels(state, {\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n }));\n },\n setValues: (next) => {\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values: next,\n ...errorChannels(state, {\n serverErrors: releaseChangedSlices(\n state.serverErrors,\n state.values,\n next,\n ),\n }),\n }));\n },\n setTouched: (path: string, touched: boolean = true) =>\n store.setState((state) => ({\n ...state,\n touched: { ...state.touched, [path]: touched },\n })),\n setSubmitting: (value) =>\n store.setState((state) => ({ ...state, isSubmitting: value })),\n setMode: (mode) => store.setState((state) => ({ ...state, mode })),\n setReValidateMode: (reValidateMode) =>\n store.setState((state) => ({ ...state, reValidateMode })),\n setError: (path: string, errors: string | readonly string[]) => {\n const list = typeof errors === \"string\" ? [errors] : errors;\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n serverErrors:\n list.length === 0\n ? omitKey(state.serverErrors, path)\n : { ...state.serverErrors, [path]: list },\n }),\n }));\n },\n setErrors: (errors) =>\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, { serverErrors: errors }),\n })),\n addErrors: (errors) =>\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n serverErrors: Object.entries(errors).reduce<ErrorMap>(\n // Computed keys throughout, so a server field named\n // \"__proto__\" lands as an own property like everywhere else.\n (acc, [key, list]) =>\n list === undefined || list.length === 0\n ? omitKey(acc, key)\n : { ...acc, [key]: list },\n state.serverErrors,\n ),\n }),\n })),\n clearErrors: (path?: string) =>\n store.setState((state) => {\n // Clears both channels (schema errors return on the next validation\n // pass). A field path also clears its descendants (\"items\" covers\n // \"items.0.name\"), consistent with field-scoped validation; the root\n // \"\" is a single key (the schema-level refine slot, symmetric with\n // setError(\"\")); clearing everything is clearErrors() with no\n // argument.\n const scrub = (map: ErrorMap): ErrorMap =>\n path === undefined ? emptyErrors : omitScope(map, [path]);\n return {\n ...state,\n ...errorChannels(state, {\n schemaErrors: scrub(state.schemaErrors),\n serverErrors: scrub(state.serverErrors),\n }),\n };\n }),\n updateState: (updater) => {\n const valuesBefore = store.getState().values;\n store.setState((state) => {\n const patch: Partial<FormState<Values>> = updater(state);\n if (Object.keys(patch).length === 0) return state;\n // Spread-style updaters carry `errors` with its current reference —\n // only a genuinely foreign map (a plain-JS write; TS forbids it via\n // the patch type) earns the warning.\n if (patch.errors !== undefined && patch.errors !== state.errors) {\n console.warn(\n \"[formstand] `errors` is derived from schemaErrors/serverErrors — patch those channels instead; the direct `errors` patch is ignored.\",\n );\n }\n // Re-derive against the CURRENT merged map (not the patched one), so\n // an ignored `errors` patch can't leak even its object identity into\n // state and re-fire identity-based subscribers.\n const next = { ...state, ...patch };\n return {\n ...next,\n ...errorChannels(state, {\n schemaErrors: next.schemaErrors,\n serverErrors: next.serverErrors,\n }),\n };\n });\n // A values patch is a chain-breaking write like setValues.\n if (store.getState().values !== valuesBefore) {\n clearArrayOpsUnder(store, \"\");\n }\n },\n adoptValues: (values) => {\n // Rebasing values invalidates any in-flight async validation (the\n // values-reference guard drops its write), so the per-path ownership\n // tokens can be released too rather than growing without bound.\n sequences.clear();\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values,\n initialValues: values,\n ...errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n }),\n // Clearing `sequences` disowns every in-flight pass, including its\n // flag cleanup (the ownership check fails, so it never writes) —\n // clear the flags here too, mirroring reset(), or they'd stick.\n isValidating: emptyBools,\n isValidatingForm: false,\n }));\n },\n reset: (nextInitial, resetOptions) => {\n sequences.clear();\n // reset can restore the exact initialValues REFERENCE, so stale\n // records must go before an old array reference recurs and falsely\n // chains against them.\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => {\n // Merge only when both sides are plain records; a partial for an\n // array/scalar-rooted schema replaces wholesale (spreading an array\n // into {...} would corrupt the values shape).\n const init: typeof state.initialValues =\n nextInitial === undefined\n ? state.initialValues\n : isPlainObject(state.initialValues) && isPlainObject(nextInitial)\n ? ({\n ...state.initialValues,\n ...nextInitial,\n } as typeof state.initialValues)\n : (nextInitial as typeof state.initialValues);\n return {\n ...state,\n values: init,\n initialValues: init,\n ...(resetOptions?.keepErrors === true\n ? {}\n : errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n })),\n touched:\n resetOptions?.keepTouched === true ? state.touched : emptyBools,\n isSubmitting: false,\n submitCount:\n resetOptions?.keepSubmitCount === true ? state.submitCount : 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n };\n });\n },\n resetField: (path: string) => {\n // slotAtPath, not getAtPath: a path addressing NO slot in\n // initialValues (an out-of-range array index — an appended row past\n // the initial length, or a path through an absent ancestor) must not\n // be \"reset\" by writing undefined into the values tree — that would\n // leave a mid-array hole ([rowA, undefined]) that crashes row renders\n // and fails the schema. The value stays as-is; the field state still\n // clears. A key merely absent on an initial plain record IS an\n // addressable slot: resetting it writes the legitimate empty\n // undefined, exactly as before.\n const initialSlot = slotAtPath(\n store.getState().initialValues,\n path,\n );\n if (!initialSlot.exists) {\n console.warn(\n `[formstand] resetField(\"${path}\"): path has no initial value (e.g. an appended array row); value left unchanged, field state cleared.`,\n );\n }\n if (initialSlot.exists) {\n // A restored initial slice can carry array references the op log\n // has already seen (chain-breaking write, like setValue).\n clearArrayOpsUnder(store, path);\n }\n store.setState((state) => ({\n ...state,\n values: initialSlot.exists\n ? setAtPath(state.values, path, initialSlot.value)\n : state.values,\n // A runtime \"\" path scopes the whole form (the imperative surface is\n // string-typed even though FieldPath excludes \"\"). Server entries\n // follow the setValue release contract (releaseSpine).\n ...errorChannels(state, {\n schemaErrors:\n path === \"\" ? emptyErrors : omitScope(state.schemaErrors, [path]),\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n touched:\n path === \"\" ? emptyBools : omitScope(state.touched, [path]),\n isValidating:\n path === \"\" ? emptyBools : omitScope(state.isValidating, [path]),\n }));\n },\n validate,\n validateField,\n validateFields,\n validateAsync: validateAsyncOnForm,\n validateFieldAsync,\n validateFieldsAsync,\n submit,\n arrayPush: (path: string, item: unknown) =>\n applyArrayOp(path, (arr) => [...arr, item], identityMapper),\n arrayRemove: (path: string, index: number) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), ...arr.slice(index + 1)],\n removeAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index < len,\n ),\n arrayInsert: (path: string, index: number, item: unknown) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), item, ...arr.slice(index)],\n insertAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index <= len,\n ),\n arrayMove: (path: string, from: number, to: number) =>\n applyArrayOp(\n path,\n (arr) => {\n const without = [...arr.slice(0, from), ...arr.slice(from + 1)];\n return [...without.slice(0, to), arr[from], ...without.slice(to)];\n },\n moveFromTo(from, to),\n (len) =>\n Number.isInteger(from) &&\n Number.isInteger(to) &&\n from >= 0 &&\n from < len &&\n to >= 0 &&\n to < len,\n ),\n arraySwap: (path: string, a: number, b: number) =>\n applyArrayOp(\n path,\n (arr) => arr.map((v, i) => (i === a ? arr[b] : i === b ? arr[a] : v)),\n swapIndices(a, b),\n (len) =>\n Number.isInteger(a) &&\n Number.isInteger(b) &&\n a >= 0 &&\n a < len &&\n b >= 0 &&\n b < len,\n ),\n handleSubmit:\n (onValid, onInvalid, opts) =>\n async (event) => {\n event?.preventDefault();\n const result = await submit(onValid, onInvalid, opts);\n // The event-handler form is fire-and-forget: nobody reads the\n // resolved result, so a save failure with no onError handler\n // would otherwise vanish COMPLETELY — no state, no rejection, no\n // log — and the button just re-enables. Dev builds say so once\n // per occurrence; production stays silent by design (resolving\n // instead of rejecting is the documented contract).\n if (\n result.kind === \"error\" &&\n opts?.onError === undefined &&\n process.env.NODE_ENV !== \"production\"\n ) {\n console.warn(\n \"[formstand] submit handler threw and nothing observed it — the form shows no feedback. Pass { onError } to handleSubmit (or setError inside your handler):\",\n result.error,\n );\n }\n return result;\n },\n diff: () => {\n const state = store.getState();\n return Object.fromEntries(\n dirtyPathsOf(state.values, state.initialValues, \"\").map((path) => [\n path,\n getAtPath(state.values, path),\n ]),\n );\n },\n dirtyFields: () => {\n const state = store.getState();\n return dirtyPathsOf(state.values, state.initialValues, \"\");\n },\n snapshot: () => store.getState(),\n restore: (snap) => {\n // A snapshot restores PRIOR array references — exactly the recurring\n // references stale op records could falsely chain against.\n clearArrayOpsUnder(store, \"\");\n store.setState(() => {\n // Snapshots can come from persistence or hand construction: default\n // missing channels (pre-channel shapes) and re-derive the merged map\n // so the errors-is-derived invariant holds at this boundary too —\n // otherwise an inconsistent snapshot renders phantom errors until\n // the next write silently rewrites them (or crashes a channel scan).\n const schemaErrors = snap.schemaErrors ?? emptyErrors;\n const serverErrors = snap.serverErrors ?? emptyErrors;\n return {\n ...snap,\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n snap.errors ?? emptyErrors,\n ),\n // In-flight state is owned by live passes, never by snapshots: a\n // snapshotted flag has no pass left to clear it (the pass that set\n // it cleared its ORIGINAL entry when it settled), so restoring one\n // would stick it forever. isSubmitting follows the same rule — a\n // mid-submit snapshot restored later must not disable submit\n // buttons forever, so it reflects the LIVE submit count instead of\n // the snapshotted flag (a live pass's finally still resets it).\n isValidating: emptyBools,\n isValidatingForm: false,\n isSubmitting: inFlight.count > 0,\n };\n });\n },\n }) as Form<TSchema, D>;\n};\n","export type ValidationMode =\n | \"onChange\"\n | \"onBlur\"\n | \"onSubmit\"\n // Validate on blur always; on change only once the field has been touched.\n | \"onTouched\"\n // Validate on both change and blur.\n | \"all\";\n\nexport type ValidationTrigger = \"change\" | \"blur\";\n\nexport const shouldValidateOn = (\n trigger: ValidationTrigger,\n mode: ValidationMode,\n reValidateMode: ValidationMode,\n submitAttempted: boolean,\n touched: boolean = false,\n): boolean => {\n const effective = submitAttempted ? reValidateMode : mode;\n switch (effective) {\n case \"onChange\":\n return trigger === \"change\";\n case \"onBlur\":\n return trigger === \"blur\";\n case \"onSubmit\":\n return false;\n case \"onTouched\":\n return trigger === \"blur\" || touched;\n case \"all\":\n return true;\n }\n};\n","import type { z } from \"zod\";\nimport type { Form } from \"./createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"./fieldPath\";\n\n// Draft persistence for a form: watch the values, debounce-write them as JSON\n// under a storage key, and re-apply a found draft on the next visit. This is\n// the autosave recipe (examples/AutosaveForm) promoted to a helper — same\n// caveat as the recipe: drafts round-trip through JSON, so they are for\n// JSON-safe values only (Dates become strings, undefined slots drop; the\n// helper does NOT try to revive them).\n\n// Structural storage contract — window.localStorage and sessionStorage\n// satisfy it, as does any Map-backed stub in tests.\nexport type PersistStorage = Readonly<{\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n}>;\n\n// TSchema is phantom for now (no option carries schema-typed data — drafts\n// are typed at the persistForm call, not here), but the parameter keeps the\n// option bag tied to the form it configures and leaves room for schema-typed\n// options later without a breaking signature change.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type PersistOptions<TSchema extends z.ZodType> = Readonly<{\n // Storage key the draft lives under.\n key: string;\n // Defaults to globalThis.localStorage, guarded: where it is absent or\n // throws on access (SSR, locked-down browsers), persistence is a no-op but\n // the helper still returns working handles.\n storage?: PersistStorage;\n // Trailing-edge debounce for writes. Default 300; 0 writes synchronously\n // on every change.\n debounceMs?: number;\n // Bump when the schema's SHAPE changes and old drafts should be discarded\n // rather than applied. A draft is stored with the version it was written\n // under and ignored when the two disagree, which is the only reliable way\n // to catch a renamed or removed field: an absent key is indistinguishable\n // from an optional the user never filled in, so the automatic guard below\n // cannot tell those apart. Leaving this unset keeps the stored format\n // exactly as it was, so existing drafts survive an upgrade.\n version?: string | number;\n // How a found draft is applied on start, and what load() does later.\n // \"adopt\" (default) uses form.adoptValues — the draft becomes the new\n // baseline, so the form reads CLEAN. \"restore\" uses form.setValues — the\n // draft loads but stays DIRTY vs the original initial values. \"manual\"\n // never auto-applies; the caller decides when via the returned load(),\n // which then applies with adopt semantics (a caller-triggered load is a\n // rebase, not an edit — pick \"restore\" if you want dirty-vs-initials).\n apply?: \"adopt\" | \"restore\" | \"manual\";\n}>;\n\nexport type PersistHandle = Readonly<{\n // Load + apply the stored draft now (see `apply` for the semantics):\n // returns true if a draft existed, parsed, and applied. Corrupt or absent\n // JSON returns false and never throws. (Named load, not restore: the\n // DEFAULT application is adoptValues — a rebase that reads clean — and\n // \"restore\" promised setValues semantics the method only has when the\n // apply option asks for them.)\n load: () => boolean;\n // Delete the stored draft (e.g. after a successful submit). Also cancels\n // any pending debounced write, so a stale draft isn't re-written right\n // after clearing.\n clear: () => void;\n // Stop watching the form (does not clear storage). Cancels any pending\n // debounced write.\n dispose: () => void;\n}>;\n\n// The JSON kind of a value, as it exists AFTER a storage round trip. The\n// reference side is round-tripped before comparison rather than special-cased,\n// so a Date (which stores as a string) compares against a string and the\n// documented Date-becomes-string limitation is not mistaken for corruption.\nconst kindOf = (value: unknown): string =>\n value === null\n ? \"null\"\n : Array.isArray(value)\n ? \"array\"\n : typeof value;\n\n// Does the draft CONFLICT with the shape the form expects? Only overlapping\n// paths are compared, and only their kinds.\n//\n// Deliberately not a key-set equality check. JSON drops undefined slots, so an\n// optional the user never filled is absent from the reference, and an optional\n// they did fill is present only in the draft. Neither is evidence of a schema\n// change, so treating a key-set difference as corruption would throw away\n// perfectly good drafts on any form with an optional field. What IS\n// unambiguous is a path holding a string on one side and an object on the\n// other: no edit produces that, only a changed schema. Renames and removals\n// are the `version` option's job.\nconst conflictsWith = (draft: unknown, reference: unknown): boolean => {\n // null and undefined carry NO shape information, on either side. null is the\n // canonical empty for a nullable field (see emptyValue), so it can legally\n // appear at any nullable path whatever that path's filled shape is: a\n // nullable object starting null and then filled in, or starting filled and\n // then cleared, are both ordinary edits. Reading either as a kind conflict\n // would discard the drafts of every form with a nullable field.\n if (draft === undefined || draft === null) return false;\n if (reference === undefined || reference === null) return false;\n const draftKind = kindOf(draft);\n const referenceKind = kindOf(reference);\n if (draftKind !== referenceKind) return true;\n if (draftKind === \"array\") {\n const [d] = draft as readonly unknown[];\n const [r] = reference as readonly unknown[];\n // Row counts differ for ordinary reasons; the ROW SHAPE is the signal.\n return conflictsWith(d, r);\n }\n if (draftKind === \"object\") {\n const d = draft as Record<string, unknown>;\n const r = reference as Record<string, unknown>;\n return Object.keys(d).some((key) => conflictsWith(d[key], r[key]));\n }\n return false;\n};\n\n// Resolved lazily inside persistForm — never at module scope — so importing\n// this module is SSR-safe. jsdom provides localStorage; node without DOM may\n// lack it (typeof check) or throw on access (try/catch).\nconst defaultStorage = (): PersistStorage | null => {\n try {\n return typeof globalThis.localStorage === \"undefined\"\n ? null\n : globalThis.localStorage;\n } catch {\n return null;\n }\n};\n\nexport const persistForm = <TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const storage = options.storage ?? defaultStorage();\n const debounceMs = options.debounceMs ?? 300;\n const apply = options.apply ?? \"adopt\";\n\n // \"restore\" is a plain values write (dirty vs the original initials);\n // \"adopt\" and \"manual\" rebase via adoptValues so the draft reads clean.\n const applyDraft = (values: z.input<TSchema>): void =>\n apply === \"restore\" ? form.setValues(values) : form.adoptValues(values);\n\n // The shape the draft is checked against, in stored form. Round-tripping\n // the reference through JSON puts both sides in the same representation.\n const referenceShape = (): unknown => {\n try {\n return JSON.parse(JSON.stringify(form.getState().initialValues));\n } catch {\n // A non-serializable initial value means we cannot compare; the write\n // path would have failed too, so let the draft through unchecked\n // rather than rejecting every draft for this form.\n return undefined;\n }\n };\n\n const load = (): boolean => {\n // Every storage touch is guarded: private-mode/security errors read as\n // \"no draft\", corrupt JSON parses as \"no draft\" — load never throws.\n try {\n const raw = storage === null ? null : storage.getItem(options.key);\n if (raw === null) return false;\n const parsed: unknown = JSON.parse(raw);\n // Versioned drafts are wrapped; unversioned ones are the bare values,\n // which is the format every existing draft is already in.\n const versioned =\n options.version !== undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"__v\" in parsed;\n if (options.version !== undefined && !versioned) return false;\n // The config-downgrade hole: a draft WRITTEN with a version is the\n // {__v, values} wrapper, and if the app later ships without the\n // version option, nothing above catches it — the wrapper's keys\n // don't overlap the reference shape, so conflictsWith stays quiet\n // and the WRAPPER OBJECT gets adopted as form values (then\n // re-persisted, making the corruption self-sustaining). A versioned\n // draft under a version-less config is a contract the current app\n // no longer declares: discard it, like every other draft the config\n // cannot vouch for.\n if (\n options.version === undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n Object.hasOwn(parsed, \"__v\") &&\n Object.hasOwn(parsed, \"values\")\n ) {\n return false;\n }\n const wrapper = parsed as unknown as {\n readonly __v?: unknown;\n readonly values?: unknown;\n };\n if (versioned && wrapper.__v !== options.version) return false;\n // A wrapper with no payload is not a draft. Only reachable via tampered\n // or foreign storage, but applying it would write undefined over the\n // whole values object.\n if (versioned && wrapper.values === undefined) return false;\n const values = (versioned ? wrapper.values : parsed) as z.input<TSchema>;\n // A draft whose shape conflicts with the form's is from another schema.\n // Applying it would rebase the form onto values it cannot validate, and\n // because \"adopt\" clears errors, the form would read CLEAN while holding\n // them. Ignore it instead; the next change overwrites it.\n const reference = referenceShape();\n if (reference !== undefined && conflictsWith(values, reference)) {\n return false;\n }\n applyDraft(values);\n return true;\n } catch {\n return false;\n }\n };\n\n const writeDraft = (values: z.input<TSchema>): void => {\n // Quota/private-mode setItem errors just skip this write. The wrapper is\n // written ONLY when a version is configured, so a form that never opts in\n // keeps the exact bytes it wrote before and its existing drafts still load.\n try {\n storage?.setItem(\n options.key,\n JSON.stringify(\n options.version === undefined\n ? values\n : { __v: options.version, values },\n ),\n );\n } catch {\n /* persistence is best-effort */\n }\n };\n\n // Sanctioned mutable ref for the trailing-edge debounce timer (same shape\n // as the codebase's other timer/subscription refs).\n const timerRef: { current: ReturnType<typeof setTimeout> | null } = {\n current: null,\n };\n\n const cancelPending = (): void => {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n };\n\n // Auto-apply BEFORE subscribing, so applying the draft doesn't immediately\n // schedule a write of the values we just read.\n if (apply !== \"manual\") {\n load();\n }\n\n const unsubscribe = form.watchValues((values) => {\n cancelPending();\n if (debounceMs === 0) {\n writeDraft(values);\n } else {\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n writeDraft(values);\n }, debounceMs);\n }\n });\n\n return Object.freeze({\n load,\n clear: () => {\n // Cancel first: a pending debounced write landing after removeItem\n // would silently resurrect the draft.\n cancelPending();\n try {\n storage?.removeItem(options.key);\n } catch {\n /* persistence is best-effort */\n }\n },\n dispose: () => {\n cancelPending();\n unsubscribe();\n },\n });\n};\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport {\n type PersistHandle,\n type PersistOptions,\n persistForm,\n} from \"../core/persist\";\n\n// The React lifecycle wrapper persistForm was missing: every useForm\n// consumer hand-wrote the mount/dispose effect (plus a ref to reach\n// clear() after submit), and calling persistForm during render\n// double-subscribed under StrictMode. This hook owns that dance:\n//\n// const form = useForm(schema, { initialValues });\n// const draft = usePersistForm(form, { key: \"profile-draft\" });\n// // ... later: draft.clear() after a successful submit.\n//\n// The returned handle is REFERENCE-STABLE across renders and delegates to\n// whichever inner subscription is currently live, so it is safe to close\n// over in submit handlers. Before the mount effect has run (and after\n// unmount) load() reads false and clear() is a no-op — the same\n// guarded no-throw posture persistForm itself has.\n//\n// Options are read when the subscription (re)starts — on mount, and again\n// if `form` or `options.key` changes — not on every render, mirroring\n// useForm's locked-options rule; pass a stable options object or accept\n// that later edits to it are ignored until the key or form changes.\nexport const usePersistForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const inner = useRef<PersistHandle | null>(null);\n const latestOptions = useRef(options);\n // An effect, not a render-time ref write (refs are off-limits during\n // render): it runs before the subscription effect below in the same\n // commit, so a resubscribe always reads the options of the render that\n // triggered it.\n useEffect(() => {\n latestOptions.current = options;\n });\n\n const key = options.key;\n useEffect(() => {\n const handle = persistForm(form, latestOptions.current);\n inner.current = handle;\n return () => {\n inner.current = null;\n handle.dispose();\n };\n // StrictMode's mount-cleanup-mount runs this twice: each pass gets its\n // own subscription and disposes the previous, so no double-writes.\n }, [form, key]);\n\n return useMemo(\n () => ({\n load: () => inner.current?.load() ?? false,\n clear: () => inner.current?.clear(),\n // dispose stops THIS component's watching early; the effect cleanup\n // still runs its own dispose harmlessly (persistForm's dispose is\n // idempotent by construction — it only cancels and unsubscribes).\n dispose: () => inner.current?.dispose(),\n }),\n [],\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport {\n type CreateFormOptions,\n type Form,\n createForm,\n} from \"../core/createForm\";\nimport { valuesEqual } from \"../core/equality\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// Lazy-creates a Form bound to this component instance. Schema and options are\n// locked in on the first render; later changes are ignored (warned once below).\n// D mirrors createForm's inference: a literal from `options.pathDepth`\n// (constrained to PathDepth, 0-25), defaulting to the 9-segment typed-path\n// budget.\nexport const useForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n): Form<TSchema, D> => {\n const formRef = useRef<Form<TSchema, D> | null>(null);\n if (formRef.current === null) {\n formRef.current = createForm(schema, options);\n }\n // Lazy init of an external store handle — the sanctioned useRef exception\n // (react.dev: \"avoiding recreating the ref contents\"); the rule can't see\n // that this read is guarded by the null-check init above.\n // eslint-disable-next-line react-hooks/refs\n const form = formRef.current;\n\n const mountInitialsRef = useRef(options.initialValues);\n const warnedRef = useRef(false);\n useEffect(() => {\n // Two footguns, one warning: a new schema reference, or initial values\n // whose CONTENT changed after mount (the async-fetch pattern\n // `initialValues: data ?? {}` with a module-hoisted schema — the schema\n // check alone would never see it). Structural compare, so inline object\n // literals that re-create identical options every render stay silent.\n const changedInitials =\n !Object.is(options.initialValues, mountInitialsRef.current) &&\n !valuesEqual(options.initialValues, mountInitialsRef.current);\n if (!warnedRef.current && (form.schema !== schema || changedInitials)) {\n warnedRef.current = true;\n console.warn(\n \"[formstand] useForm received a different schema or initial values \" +\n \"after the first render; schema and options changes are ignored \" +\n \"for the life of the component. If the schema is defined inline \" +\n \"this is harmless (but consider hoisting it to module scope). For \" +\n \"initial values that arrive later (e.g. from a fetch), call \" +\n \"form.adoptValues(values) or form.reset(values) instead.\",\n );\n }\n }, [form, schema, options.initialValues]);\n\n return form;\n};\n","import { useActionState, useCallback, useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type {\n Form,\n InvalidSubmitHandler,\n SubmitResult,\n} from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// The React 19 form-actions bridge: bind a formstand form's validation and\n// submit lifecycle to `<form action={...}>` and useActionState, so the\n// action world gets what onSubmit callers already have — schema\n// validation before the action runs, isSubmitting/submitCount tracking,\n// errors written and their fields marked touched on a failed submit, and\n// the two-channel error model for the action's own verdicts.\n//\n// The handler receives PARSED, TYPED data (z.output of the schema), not\n// FormData: formstand inputs are controlled, so the store is the source of\n// truth and the schema has already judged it. The raw FormData still\n// arrives as the last argument for what only it can carry — uncontrolled\n// inputs in the same <form>, file pickers — and because a server action\n// can take it across the wire (FormData serializes under RSC).\n//\n// Honest scope: this is a CLIENT-side integration. React's no-JS\n// progressive enhancement only works when the server action itself is\n// passed to the form/useActionState, which by definition skips any\n// client-side wrapper — for that path, validate on the server with the\n// same zod schema and keep this bridge for the hydrated experience.\n//\n// Note on React's post-action reset: React 19 resets UNCONTROLLED form\n// fields after an action completes. formstand inputs are controlled, so\n// the form's values survive the action untouched.\n\nexport type FormActionHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n formData: FormData,\n) => void | Promise<void>;\n\n// S is the AWAITED state (what the reducer stores), so the handler's\n// return may be the state or a promise of it — the shape a \"use server\"\n// async function naturally has.\nexport type FormActionStateHandler<TSchema extends z.ZodType, S> = (\n prevState: S,\n data: z.output<TSchema>,\n formData: FormData,\n) => S | Promise<S>;\n\nexport type FormActionOptions = Readonly<{\n // Mirrors handleSubmit's second parameter: runs when validation fails\n // (errors are written and fields marked touched either way).\n onInvalid?: InvalidSubmitHandler;\n // Mirrors SubmitOptions.onError: the save-failure hook for a throwing\n // handler. Without it, dev builds warn when a failure resolves\n // unobserved — the action form is fire-and-forget, like handleSubmit.\n onError?: (error: unknown) => void;\n}>;\n\n// The fire-and-forget dev warning, same contract as handleSubmit's: a\n// throwing handler resolves {kind: \"error\"} writing no state, so with no\n// onError the failure would vanish completely.\nconst warnUnobserved = (\n result: SubmitResult<unknown>,\n options: FormActionOptions | undefined,\n site: string,\n): void => {\n if (\n result.kind === \"error\" &&\n options?.onError === undefined &&\n process.env.NODE_ENV !== \"production\"\n ) {\n console.warn(\n `[formstand] action handler threw and nothing observed it — the form shows no feedback. Pass { onError } to ${site} (or setError inside your handler):`,\n result.error,\n );\n }\n};\n\n// The plain bridge: an action for `<form action={...}>`. Validation and\n// the submit lifecycle run first; the handler only sees data the schema\n// accepted. The returned function is REFERENCE-STABLE across renders\n// (handler and options are read through refs assigned in an effect —\n// actions only fire after mount, so the refs are always populated), which\n// keeps memoized subtrees quiet however the caller writes the handler.\nexport const useFormAction = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n onValid: FormActionHandler<TSchema>,\n options?: FormActionOptions,\n): ((formData: FormData) => Promise<void>) => {\n const latest = useRef({ onValid, options });\n useEffect(() => {\n latest.current = { onValid, options };\n });\n return useCallback(\n async (formData: FormData) => {\n const { onValid: handler, options: opts } = latest.current;\n const result = await form.submit(\n (data) => handler(data, formData),\n opts?.onInvalid,\n opts?.onError === undefined ? undefined : { onError: opts.onError },\n );\n warnUnobserved(result, opts, \"useFormAction\");\n },\n [form],\n );\n};\n\n// The stateful bridge: useActionState with schema-validated data. The\n// handler's shape mirrors the native (prevState, formData) signature with\n// the parsed data spliced in, so a \"use server\" function slots straight\n// in. A submission that fails validation (or is skipped, or throws)\n// returns the PREVIOUS state unchanged: field errors already live in the\n// form store where the bound components read them, so the action state\n// stays what it is — the last verdict an action actually produced.\nexport const useFormActionState = <\n TSchema extends z.ZodType,\n S,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n action: FormActionStateHandler<TSchema, S>,\n initialState: S,\n options?: FormActionOptions,\n): [state: S, formAction: (formData: FormData) => void, isPending: boolean] => {\n const [state, formAction, isPending] = useActionState<S, FormData>(\n async (prevState, formData): Promise<S> => {\n // React hands the reducer Awaited<S>; S is declared as the awaited\n // state, so for any non-thenable state (the only kind a reducer can\n // meaningfully hold) the two are the same type — TS just won't\n // simplify the deferred conditional for an unconstrained S.\n const prev = prevState as S;\n // Sanctioned mutable ref for the handler's return value: submit owns\n // the lifecycle and its onValid returns void, so the next state\n // rides out through the closure (same shape as the codebase's other\n // capture refs).\n const nextRef: { current: S } = { current: prev };\n const result = await form.submit(\n async (data) => {\n nextRef.current = await action(prev, data, formData);\n },\n options?.onInvalid,\n options?.onError === undefined\n ? undefined\n : { onError: options.onError },\n );\n warnUnobserved(result, options, \"useFormActionState\");\n return nextRef.current;\n },\n initialState as Awaited<S>,\n );\n return [state as S, formAction, isPending];\n};\n","import {\n type ReactNode,\n createContext,\n useContext,\n} from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\nexport type FormProviderProps<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n form: Form<TSchema, D>;\n children: ReactNode;\n}>;\n\nexport type FormContextApi<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n Provider: (props: FormProviderProps<TSchema, D>) => ReactNode;\n useFormContext: () => Form<TSchema, D>;\n}>;\n\n// A form created with a non-default `pathDepth` names it here too:\n// createFormContext<typeof schema, 12>() — the context can't infer it (there\n// is no value argument), and Form<S, 12> is deliberately not Form<S, 9>.\n// The `PathDepth` constraint makes an out-of-range literal (26, -1) or a\n// widened `number` argument a compile error, same as createForm's option.\nexport const createFormContext = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(): FormContextApi<TSchema, D> => {\n const Context = createContext<Form<TSchema, D> | null>(null);\n\n const Provider = ({ form, children }: FormProviderProps<TSchema, D>) => (\n <Context.Provider value={form}>{children}</Context.Provider>\n );\n\n const useFormContext = (): Form<TSchema, D> => {\n const ctx = useContext(Context);\n if (ctx === null) {\n throw new Error(\n \"useFormContext must be used inside the matching <Provider>\",\n );\n }\n return ctx;\n };\n\n return { Provider, useFormContext };\n};\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n emptyValueForSchema,\n isClearableSchema,\n fieldSchemaAtPath,\n} from \"../core/validation\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose write methods take the narrower\n// FieldPath<...> instead of string — still satisfies this API. Prefer calling\n// these through a typed Form when you have one.\nexport type FieldFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n setValue(path: string, value: unknown): void;\n setTouched(path: string, touched?: boolean): void;\n setError(path: string, errors: string | readonly string[]): void;\n clearErrors(path?: string): void;\n validateField(path: string): FieldValidationResult;\n // Settled by contract: an awaited pass can never resolve \"pending\" —\n // the promise IS the pending state, and a resolved {kind: \"pending\"}\n // would carry a promise that never runs. Custom implementations were\n // always expected to resolve settled; the type now says so.\n validateFieldAsync(path: string): Promise<SettledFieldValidationResult>;\n}>;\n\nexport type FieldPathArg<TValues> =\n | string\n | ((state: FormState<TValues>) => string);\n\nexport type UseFieldOptions = Readonly<{\n debounceMs?: number;\n}>;\n\nexport type UseFieldReturn<TValue> = Readonly<{\n // The resolved field path — useful as an input's `name` attribute (the\n // bound prop builders spread it as `name`).\n path: string;\n value: TValue;\n // The slice of initialValues at this path (what `dirty` compares against).\n initialValue: TValue;\n // What a cleared input writes back: null when the field's schema is\n // nullable (introspected when the form carries its schema — the zod-first\n // source of truth), undefined when it is optional or unknown. Falls back\n // to \"the initial value was null\" for schema-less FieldFormApi forms.\n emptyValue: null | undefined;\n // Whether the schema ACCEPTS that emptyValue (optional / nullable /\n // defaulted — see isClearableSchema). The string-shaped bindings write\n // emptyValue on a cleared input only when this is true; a required\n // string cleared to \"\" stays \"\" so the schema judges a visible value\n // instead of a hole it rejects. Schema-less forms fall back to the same\n // heuristic as emptyValue: a null initial value reads as clearable.\n clearable: boolean;\n error: readonly string[] | undefined;\n // The first error message, or undefined when the channel is empty — the\n // display shorthand every adapter otherwise re-derives by hand (the\n // `error?.[0]`-with-empty-array-guard helper each generated kit adapter\n // used to open with).\n firstError: string | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n setValue: (value: TValue) => void;\n setTouched: (touched?: boolean) => void;\n // A single string is shorthand for a one-element array (like form.setError).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n validate: () => FieldValidationResult;\n // Settled: awaited passes never resolve \"pending\" (see FieldFormApi).\n validateAsync: () => Promise<SettledFieldValidationResult>;\n onBlur: () => void;\n}>;\n\ntype FieldSlice<TValue> = Readonly<{\n path: string;\n value: TValue;\n initialValue: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\n// The readable-error trap-guard for `useField<Values>(typedForm, \"email\")`:\n// any explicit type argument arity-matches ONLY the one-type-parameter\n// overloads, and the structural one's `schema?: undefined` brand then\n// rejects the Form with a baffling \"... not assignable to type 'undefined'\".\n// The error overload below intercepts that shape: its TValue defaults to\n// this unexported sentinel — an INFERRED call can never produce it (TValue\n// has no inference site, so it always falls back to the default), which\n// collapses `path` to `never` and fails the overload silently — while an\n// EXPLICIT TValue (never assignable to the unexported brand) on a\n// schema-carrying form types `path` as a string-literal error message, so\n// the compiler blames the path argument with instructions instead of brand\n// internals.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order is deliberate. When no overload matches, TypeScript reports\n// the LAST candidate's error — so the typed-path overload sits last, and a\n// typo'd path on a Form<TSchema> is blamed on the path argument against the\n// full FieldPath union ('\"naem\"' is not assignable to '\"name\" | \"age\" | ...')\n// instead of on the form argument.\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useField<Schema, \"name\">`) —\n// TS applies explicit type args to every arity-compatible overload, so a\n// second parameter here would check \"name\" against it.\nexport function useField<TSchema extends z.ZodType>(\n form: FieldFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): an explicit type argument on a\n// schema-carrying form binds here and blames the path argument with a\n// readable instruction. Inferred calls can never select it — TValue stays\n// at its sentinel default and `path` collapses to `never`.\nexport function useField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n path: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the value type from the path\",\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// The `schema?: undefined` brand forces TS past this widened overload when a\n// real Form is passed (Form has `schema: TSchema`, not undefined). Without\n// it, a Form<TSchema> with an invalid path would silently bind here and\n// return UseFieldReturn<unknown>.\nexport function useField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker), so a `pathDepth: 12` form checks paths against its widened union.\n// It sits LAST (P's constraint forward-references it — legal in TS) with a\n// default, so pre-existing explicit instantiations like\n// `useField<typeof schema, \"name\">` keep their arity.\nexport function useField<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n options?: UseFieldOptions,\n): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\nexport function useField<TValue = unknown>(\n form: FieldFormApi,\n pathArg: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue> {\n const slice = useStore(\n form.store,\n useShallow((state): FieldSlice<TValue> => {\n const p =\n typeof pathArg === \"function\" ? pathArg(state) : pathArg;\n const value = getAtPath(state.values, p);\n const initialValue = getAtPath(state.initialValues, p);\n return {\n path: p,\n value: value as TValue,\n initialValue: initialValue as TValue,\n error: state.errors[p],\n touched: state.touched[p] ?? false,\n dirty: isFieldDirty(value, initialValue),\n isValidating: state.isValidating[p] ?? false,\n };\n }),\n );\n const path = slice.path;\n\n // Schema introspection wins over the runtime heuristic when the form\n // carries its schema (Form<TSchema> does; a bare FieldFormApi may not).\n const formSchema = (form as Readonly<{ schema?: z.ZodType }>).schema;\n const initialValue = slice.initialValue;\n const { emptyValue, clearable } = useMemo(() => {\n if (formSchema !== undefined) {\n const sub = fieldSchemaAtPath(formSchema, path);\n if (sub !== null) {\n return {\n emptyValue: emptyValueForSchema(sub),\n clearable: isClearableSchema(sub),\n };\n }\n }\n // Schema-less heuristic: a null initial value is the one runtime signal\n // that null round-trips, so it drives both answers.\n return initialValue === null\n ? { emptyValue: null, clearable: true }\n : { emptyValue: undefined, clearable: false };\n }, [formSchema, path, initialValue]);\n\n const debounceMs = options?.debounceMs;\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (debounceTimerRef.current !== null) {\n clearTimeout(debounceTimerRef.current);\n debounceTimerRef.current = null;\n }\n };\n }, [form, path, debounceMs]);\n\n const triggerValidate = useCallback(() => {\n if (debounceMs !== undefined && debounceMs > 0) {\n if (debounceTimerRef.current !== null) {\n clearTimeout(debounceTimerRef.current);\n }\n // The pending timer is invisible to the store, so a reset() /\n // adoptValues() inside the debounce window cannot cancel it the way\n // it invalidates in-flight validation (the ownership tokens) — the\n // fire would claim a FRESH token and re-commit errors onto the\n // pristine form. Two fire-time guards close it: a pristine form\n // (values IS initialValues by reference — exactly what reset and\n // adoptValues leave behind) never receives a debounced commit, and\n // a path whose value changed since scheduling is stale (the write\n // that changed it scheduled its own validation, or was a\n // restore/reset to different values). Scheduling runs after\n // setValue, so the captured value is the keystroke being validated.\n const scheduled = getAtPath(form.store.getState().values, path);\n debounceTimerRef.current = setTimeout(() => {\n debounceTimerRef.current = null;\n const state = form.store.getState();\n if (state.values === state.initialValues) return;\n if (!Object.is(getAtPath(state.values, path), scheduled)) return;\n void form.validateFieldAsync(path);\n }, debounceMs);\n return;\n }\n // The core routes async schemas itself: validateField returns\n // { kind: \"pending\" } having already started the async pass, which\n // commits its errors and isValidating flags to the store — so the\n // result needs no handling here.\n form.validateField(path);\n }, [form, path, debounceMs]);\n\n const setValue = useCallback(\n (value: TValue) => {\n const before = form.store.getState();\n form.setValue(path, value);\n const state = form.store.getState();\n // A no-op write (the identical value — createForm's setValue identity\n // guard leaves the state reference untouched) skips the revalidation\n // gate too: nothing changed, so the current error state already\n // reflects this value. Custom FieldFormApi implementations without\n // the guard produce a fresh state and keep the old behavior.\n if (state === before) return;\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n state.touched[path] ?? false,\n )\n ) {\n triggerValidate();\n }\n },\n [form, path, triggerValidate],\n );\n\n const setTouched = useCallback(\n (touched?: boolean) => form.setTouched(path, touched),\n [form, path],\n );\n\n const setError = useCallback(\n // Normalize the string shorthand HERE, before forwarding: custom\n // FieldFormApi implementations written against the pre-0.4 surface are\n // typed for readonly string[] and must never receive a bare string.\n (errors: string | readonly string[]) =>\n form.setError(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(\n () => form.clearErrors(path),\n [form, path],\n );\n\n const validate = useCallback(() => form.validateField(path), [form, path]);\n\n const validateAsync = useCallback(\n () => form.validateFieldAsync(path),\n [form, path],\n );\n\n const onBlur = useCallback(() => {\n form.setTouched(path, true);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"blur\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n true,\n )\n ) {\n triggerValidate();\n }\n }, [form, path, triggerValidate]);\n\n return useMemo(\n () => ({\n path: slice.path,\n value: slice.value,\n initialValue: slice.initialValue,\n emptyValue,\n clearable,\n error: slice.error,\n // `?.[0]` covers both the undefined channel and an empty array.\n firstError: slice.error?.[0],\n touched: slice.touched,\n dirty: slice.dirty,\n isValidating: slice.isValidating,\n setValue,\n setTouched,\n setError,\n clearError,\n validate,\n validateAsync,\n onBlur,\n }),\n [slice, emptyValue, clearable, setValue, setTouched, setError, clearError, validate, validateAsync, onBlur],\n );\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// Discriminated-union support. A z.discriminatedUnion field types its value\n// as a union of variant objects, and FieldPath<T> only exposes the keys\n// COMMON to every union member (via `keyof T`) — so the DISCRIMINANT binds\n// with plain useField (it's common), but a variant-specific field\n// (\"payment.cardNumber\", present only in the card branch) resolves to a\n// path FieldPath omits. useVariantField is the typed accessor for those.\n//\n// It binds `${unionPath}.${field}` and types the result as the field's value\n// across every variant that declares it, widened with `| undefined` because\n// the field is absent while a different variant is active:\n//\n// const method = useField(form, \"payment.method\"); // discriminant\n// const cardNumber = useVariantField(form, \"payment\", \"cardNumber\");\n// // -> UseFieldReturn<string | undefined>, rendered when method.value === \"card\"\n//\n// The hook is called unconditionally (React's rules) — every variant's\n// fields bind every render; you render the matching ones based on the\n// discriminant. Runtime behavior is exactly useField on the joined path.\n//\n// Gate WRITES on the discriminant too, not just rendering: the returned\n// setter writes `${unionPath}.${field}` regardless of the active variant, so\n// calling a card field's setValue while the paypal variant is active injects\n// a stray key into the stored object. z.discriminatedUnion strips it on\n// parse (validation looks clean), but dirtyFields()/persistForm see the\n// polluted shape. Render the matching fields only — as the example shows —\n// and their setters fire only for the active variant. formstand-gen's output\n// follows this; hand-written forms must too.\n\n// The value of `field` across the members of union `V` that declare it.\n// Distributes over V: each member contributes V[field] when it has field,\n// never otherwise; the union of those is the result. `| undefined` is added\n// by the caller (the field is absent while another variant is active).\nexport type VariantFieldValue<V, TField extends string> = V extends unknown\n ? TField extends keyof V\n ? V[TField]\n : never\n : never;\n\n// The variant-only field keys of union `V`: every member's keys minus the\n// keys shared by all members (the discriminant and any other common field,\n// which bind with plain useField). `keyof V` on a union is ALREADY the\n// common keys (the intersection) — it must NOT distribute, or it would\n// equal AllKeys and leave no variant keys. AllKeys distributes to collect\n// every member's keys.\ntype CommonKeys<V> = keyof V;\ntype AllKeys<V> = V extends unknown ? keyof V : never;\nexport type VariantKeys<V> = Exclude<AllKeys<V>, CommonKeys<V>> & string;\n\n// The paths in `TValues` whose value is a discriminated union — an object\n// whose members don't all share the same keys. Kept permissive (any\n// top-level or nested key reaching a union of objects); misuse on a\n// non-union path yields `never` field keys, so the call simply won't\n// typecheck a field argument.\nexport type UnionValueAt<TValues, P extends string> = P extends keyof TValues\n ? // NonNullable is essential: for an OPTIONAL/nullable union field the\n // resolved value includes undefined, which collapses `keyof V` to never\n // — VariantKeys would then leak EVERY key (discriminant included) and\n // the whole guard inverts. Strip the nullish part first.\n NonNullable<TValues[P]>\n : TValues extends readonly (infer Item)[]\n ? // Array rows: a numeric segment — a literal \"0\" or the `${number}`\n // a template path like `pavements.${index}` produces — selects the\n // ELEMENT type, so a union that IS the row item resolves the same\n // way a static object path does. (`keyof` above cannot do this:\n // an array's numeric index signature is `number`, and the string\n // segment types never extend it.) Without this branch every\n // row-indexed union path collapsed the field keys to `never`,\n // making unions inside array rows unbindable — the exact wall the\n // generated array-row TODO used to steer people into.\n P extends `${number}`\n ? NonNullable<Item>\n : P extends `${infer Head}.${infer Tail}`\n ? // Tuple positionality first: a tuple's keyof carries its literal\n // indices, so \"wrap.0.pay\" resolves element 0's OWN shape\n // instead of the all-elements union `Item` (whose keyof\n // collapses to common keys and killed the variant-key set). A\n // plain array's keyof has no numeric-string members, so it\n // falls through to the element branch unchanged.\n Head extends keyof TValues\n ? UnionValueAt<NonNullable<TValues[Head]>, Tail>\n : Head extends `${number}`\n ? UnionValueAt<NonNullable<Item>, Tail>\n : never\n : never\n : P extends `${infer Head}.${infer Tail}`\n ? Head extends keyof TValues\n ? UnionValueAt<NonNullable<TValues[Head]>, Tail>\n : never\n : never;\n\n// The readable-error trap-guard, mirroring useField's/useFieldArray's: an\n// explicit type argument (`useVariantField<string>(typedForm, \"payment\",\n// \"cardNumber\")`) arity-matches ONLY the one-type-parameter overloads, and\n// the structural one's `schema?: undefined` brand then rejects the Form\n// with a baffling \"... not assignable to type 'undefined'\". The error\n// overload below intercepts that shape — TValue defaults to this unexported\n// sentinel, which inferred calls can never escape (TValue has no inference\n// site), collapsing `unionPath` to `never`; an explicit TValue on a\n// schema-carrying form instead types `unionPath` as a string-literal\n// instruction the compiler blames the argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the trap\n// guard sits before the widened structural overload, and the typed overload\n// sits LAST so a bad union path / field name on a Form<TSchema> is blamed\n// on that argument against the real union instead of on the form argument.\nexport function useVariantField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n unionPath: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the variant value from the union path and field\",\n field: string,\n): UseFieldReturn<TValue | undefined>;\n// Schema-less forms keep the plain-string, caller-typed shape. The\n// `schema?: undefined` brand forces a real Form past this widened overload\n// (Form has `schema: TSchema`, not undefined).\nexport function useVariantField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n unionPath: string,\n field: string,\n): UseFieldReturn<TValue | undefined>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker). It sits LAST with a default, so pre-existing explicit\n// instantiation expressions like\n// `typeof useVariantField<typeof schema, \"payment\", \"cardNumber\">` keep\n// their arity.\nexport function useVariantField<\n TSchema extends z.ZodType,\n P extends string,\n TField extends VariantKeys<UnionValueAt<z.input<TSchema>, P>>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n unionPath: P,\n field: TField,\n): UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\nexport function useVariantField(\n form: FieldFormApi,\n unionPath: string,\n field: string,\n): UseFieldReturn<unknown> {\n // Structural string-path bind: the joined path is exactly what a variant\n // field lives at; only its TYPE was unreachable through FieldPath, so the\n // runtime is ordinary useField.\n return useField(\n form as FieldFormApi & { readonly schema?: undefined },\n `${unionPath}.${field}`,\n );\n}\n","import { useCallback, useMemo } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport {\n type ArrayOpRecord,\n arrayOpsFor,\n clearArrayOps,\n} from \"../core/arrayOpLog\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport type { FieldValidationResult } from \"../core/validation\";\nimport type { FieldPathArg } from \"./useField\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose array ops take the narrower\n// FieldPath<...> instead of string — still satisfies this API.\n// NOTE for custom implementations: exact row-id tracking for ops on\n// Object.is-equal rows is a createForm feature (its ops record their index\n// mappings internally) — a hand-rolled implementation of these methods gets\n// value-based id reconciliation only.\nexport type FieldArrayFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n arrayPush(path: string, item: unknown): void;\n arrayRemove(path: string, index: number): void;\n arrayInsert(path: string, index: number, item: unknown): void;\n arrayMove(path: string, from: number, to: number): void;\n arraySwap(path: string, a: number, b: number): void;\n // OPTIONAL, probed before use: when present (createForm always provides\n // it), the hook's op wrappers revalidate the array path after an op under\n // the same change-trigger gate useField.setValue applies — so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. NOTE for custom implementations: a hand-rolled FieldArrayFormApi\n // without this member still works — the ops simply skip revalidation.\n validateField?(path: string): FieldValidationResult;\n // OPTIONAL like validateField, same custom-implementation contract: when\n // present (createForm always provides them), the hook exposes the\n // array-level server-error channel — a \"too many rows\" verdict from the\n // API is set and cleared from the hook that owns the array, the same\n // symmetry useField has had all along. Absent members make the returned\n // setError/clearError no-ops.\n setError?(path: string, errors: string | readonly string[]): void;\n clearErrors?(path?: string): void;\n}>;\n\nexport type FieldArrayEntry<TItem> = Readonly<{\n id: string;\n value: TItem;\n}>;\n\nexport type UseFieldArrayReturn<TItem> = Readonly<{\n // The resolved array path — the same convenience useField exposes.\n path: string;\n fields: readonly FieldArrayEntry<TItem>[];\n items: readonly TItem[];\n length: number;\n error: readonly string[] | undefined;\n // The first array-level message, or undefined — same shorthand as\n // useField.firstError (the docs used to hand-roll error[0] here).\n firstError: string | undefined;\n // The array-level server channel, scoped to this path (see the\n // FieldArrayFormApi note: no-ops on custom implementations without the\n // optional members).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n push: (item: TItem) => void;\n remove: (index: number) => void;\n insert: (index: number, item: TItem) => void;\n move: (from: number, to: number) => void;\n swap: (a: number, b: number) => void;\n}>;\n\ntype IdState = Readonly<{\n items: readonly unknown[];\n ids: readonly string[];\n counter: number;\n // Unique per (form, path) entry, so ids minted for different arrays (or\n // for the same hook after a dynamic path switch) can never collide as\n // React keys.\n prefix: string;\n}>;\n\n// Stable reference for \"path holds no array yet\" — a fresh [] per selector\n// run would defeat useShallow and re-render on every store change.\nconst EMPTY_ITEMS: readonly never[] = [];\n\n// 1-based mint numbers for the positions needing a fresh id, in order.\n// BOTH id-derivation paths (value reconciliation in reconcileIds and the\n// exact op mappings in mappedIdState) number their mints through this one\n// helper, so the collision-free scheme — counter + consecutive 1-based\n// counts, counter advanced by the map's size — cannot diverge between them.\nconst mintNumbers = (\n needsMint: readonly boolean[],\n): ReadonlyMap<number, number> =>\n new Map(\n needsMint\n .flatMap((mint, i) => (mint ? [i] : []))\n .map((position, k) => [position, k + 1] as const),\n );\n\n// Derive a stable id per item by reconciling the live items against the\n// last-seen items. Ids follow items by identity/value, so resets and\n// mutations that bypass the array ops (setValue of a whole array, restore)\n// keep keys glued to their rows — not just length-preserving appends/\n// truncations. A same-index fallback keeps an edited row's id (editing\n// produces a fresh item reference at the same position) without remounting\n// it. This is the FALLBACK path: array ops (hook-issued OR imperative)\n// replay their exact recorded mappings via the core's op log first (see\n// deriveIds), because value matching cannot tell Object.is-equal rows\n// apart.\nconst reconcileIds = (prev: IdState, nextItems: readonly unknown[]): IdState => {\n if (prev.items === nextItems) return prev;\n if (\n prev.items.length === nextItems.length &&\n prev.items.every((item, i) => Object.is(item, nextItems[i]))\n ) {\n // Same rows, fresh array reference (a normalization pass, a server\n // refresh of unchanged data): the ids are unchanged but the anchor\n // MUST move to the live reference — a later op's record chains from\n // it, and a stale anchor would silently break replay back to value\n // matching (the duplicate-row bug all over again).\n return { ...prev, items: nextItems };\n }\n\n // Bucket prev positions by item so duplicate primitives match in order.\n const buckets = prev.items.reduce<Map<unknown, number[]>>((acc, item, i) => {\n const bucket = acc.get(item);\n if (bucket === undefined) {\n acc.set(item, [i]);\n } else {\n bucket.push(i);\n }\n return acc;\n }, new Map());\n\n // First pass: reuse the id of the matching prev item, consuming that slot so\n // each id is reused at most once (`shift` empties the bucket as we go).\n const matchedIds: readonly (string | null)[] = nextItems.map((item) => {\n const prevIndex = buckets.get(item)?.shift();\n return prevIndex === undefined ? null : (prev.ids[prevIndex] ?? null);\n });\n\n // Second pass: an unmatched item reuses its SAME-INDEX leftover id (an\n // in-place edit keeps its row); any other leftover id belongs to a row\n // that is genuinely gone. Handing those out positionally would let a\n // remove-then-push in one batch key the new row with the deleted row's\n // id — a React reorder that resurrects the dead row's DOM state — so\n // they die and new items mint fresh ids instead. (Trade-off: an edit\n // that also MOVES in the same write remounts; value-identity matching\n // above already covers pure moves.)\n const leftoverAt = new Map(\n [...buckets.values()].flat().flatMap((i) => {\n const id = prev.ids[i];\n return id === undefined ? [] : ([[i, id]] as const);\n }),\n );\n const reused = matchedIds.map((id, i) => id ?? leftoverAt.get(i) ?? null);\n\n const mints = mintNumbers(reused.map((id) => id === null));\n const ids = reused.map(\n (id, i) => id ?? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`,\n );\n\n return {\n items: nextItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// Apply an exact index mapping to the id list: nextIds[i] =\n// prev.ids[mapping[i]], with -1 minting a fresh id (a new row). Returns null\n// — falling back to value reconciliation — unless every carried position's\n// live item is identity-equal to the recorded previous item, so a mapping\n// can never mis-key rows the store changed some other way (a refused\n// out-of-bounds op, an interleaved setValue).\nconst mappedIdState = (\n prev: IdState,\n mapping: readonly number[],\n liveItems: readonly unknown[],\n): IdState | null => {\n if (liveItems.length !== mapping.length) return null;\n const aligned = mapping.every((src, i) =>\n src === -1\n ? true\n : prev.ids[src] !== undefined &&\n Object.is(liveItems[i], prev.items[src]),\n );\n if (!aligned) return null;\n // (In practice an op mapping mints at most one row — push/insert — but\n // the numbering stays general via the shared scheme.)\n const mints = mintNumbers(mapping.map((src) => src === -1));\n const ids = mapping.map((src, i) =>\n src === -1\n ? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`\n : (prev.ids[src] as string),\n );\n return {\n items: liveItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// One id state per (form store, path), shared by EVERY hook instance on\n// that array so sibling hooks always agree on row ids. A sanctioned\n// mutable-ref cache (like the core's subschemaCache): the entry is derived\n// bookkeeping — each commit is a pure function of a REAL store state, so a\n// discarded render leaves a sound (if not identical) state behind: rows may\n// remint where reuse was possible (a cosmetic remount), but a surviving row\n// can never receive another row's id. Entries are access-ordered and capped\n// so a long-lived store with churning dynamic paths (rows.N.tags) can't\n// accumulate snapshots forever; the WeakMap releases the rest with the\n// store.\ntype SharedIdEntry = { state: IdState };\ntype StoreIdEntries = { byPath: Map<string, SharedIdEntry>; seq: number };\n\n// Generous like path.ts's PARSE_CACHE_MAX: eviction of a MOUNTED array's\n// entry remints every row id (a full remount), so the cap is a backstop\n// against unbounded dynamic-path churn, never a working-set limit.\nconst MAX_ID_PATHS = 4096;\nconst sharedIdEntries = new WeakMap<object, StoreIdEntries>();\n\nconst sharedIdEntry = (store: object, path: string): SharedIdEntry => {\n const existingStore = sharedIdEntries.get(store);\n const forStore = existingStore ?? { byPath: new Map(), seq: 1 };\n if (existingStore === undefined) sharedIdEntries.set(store, forStore);\n const existing = forStore.byPath.get(path);\n if (existing !== undefined) {\n // Re-insert to refresh recency, so eviction takes the longest-unused\n // path, not merely the oldest-created.\n forStore.byPath.delete(path);\n forStore.byPath.set(path, existing);\n return existing;\n }\n // Prefix from a PER-STORE sequence (deterministic per form, unlike a\n // module-global counter whose value depends on app-wide first-touch\n // order), so ids from different arrays — or a hook whose dynamic path\n // switches — can never collide as React keys.\n const created: SharedIdEntry = {\n state: {\n items: EMPTY_ITEMS,\n ids: [],\n counter: 0,\n prefix: `__zfa_${forStore.seq}_`,\n },\n };\n forStore.seq += 1;\n forStore.byPath.set(path, created);\n if (forStore.byPath.size > MAX_ID_PATHS) {\n const oldest = forStore.byPath.keys().next().value;\n if (oldest !== undefined) forStore.byPath.delete(oldest);\n }\n return created;\n};\n\n// Walk EVERY record in order, applying its exact mapping. A gap before a\n// record (a chain-breaking write between ops — though the core now clears\n// records at such writes, so gaps are rare) bridges by value to the\n// record's `from` first, so an op keeps its exactness no matter which side\n// of a whole-array write it fell on. The final hop to the live items — when\n// the last record didn't land there — reconciles by value too.\nconst walkOps = (\n start: IdState,\n items: readonly unknown[],\n ops: readonly ArrayOpRecord[],\n): IdState => {\n const walked = ops.reduce<IdState>((acc, op) => {\n const base = acc.items === op.from ? acc : reconcileIds(acc, op.from);\n return mappedIdState(base, op.mapping, op.to) ?? base;\n }, start);\n return walked.items === items ? walked : reconcileIds(walked, items);\n};\n\nconst deriveIds = (\n store: object,\n path: string,\n items: readonly unknown[],\n): IdState => {\n const entry = sharedIdEntry(store, path);\n if (entry.state.items === items) return entry.state;\n const ops = arrayOpsFor(store, path);\n // The walk consumes every record, so the log is spent bookkeeping\n // afterwards — clear it, which also keeps ring composition from ever\n // merging a record a consumer is still anchored at. (The one residual:\n // a render discarded between clear and commit re-derives the final hop\n // by value — sound ids, possibly reminted where reuse was possible.)\n if (ops.length > 0) clearArrayOps(store, path);\n const next = walkOps(entry.state, items, ops);\n entry.state = next;\n return next;\n};\n\n// The element type at an array-valued path. FieldValue re-adds `| undefined`\n// for arrays reached through optional ancestors, so strip that before\n// extracting; a non-array path yields `never`, which makes every write\n// (`push(never)`) an immediate error instead of a silently-`unknown` bind.\nexport type ArrayItemOf<T> = [NonNullable<T>] extends [readonly (infer U)[]]\n ? U\n : never;\n\n// The readable-error trap-guard, mirroring useField's: an explicit type\n// argument (`useFieldArray<Item>(typedForm, \"users\")`) arity-matches ONLY\n// the one-type-parameter overloads, and the structural one's brand then\n// rejects the Form with a baffling \"... not assignable to type\n// 'undefined'\". The error overload below intercepts that shape — TItem\n// defaults to this unexported sentinel, which inferred calls can never\n// escape (TItem has no inference site), collapsing `path` to `never`; an\n// explicit TItem on a schema-carrying form instead types `path` as a\n// string-literal instruction the compiler blames the path argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the\n// typed-path overload sits last so a typo'd path on a Form<TSchema> is\n// blamed on the path argument against the full FieldPath union, and the\n// `schema?: undefined` brand forces a real Form past the widened structural\n// overload — without it, `useFieldArray(form, \"users\")` would bind there\n// and return UseFieldArrayReturn<unknown> instead of inferring the item\n// type from the path. Schema-less FieldFormApi forms keep the explicit\n// TItem parameter (there is nothing to infer from).\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useFieldArray<Schema,\n// \"tags\">`) — TS applies explicit type args to every arity-compatible\n// overload, so a second parameter here would check \"tags\" against it.\nexport function useFieldArray<TSchema extends z.ZodType>(\n form: FieldArrayFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n): UseFieldArrayReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): explicit type argument on a\n// schema-carrying form → readable error on the path argument; inferred\n// calls fall through (path collapses to never).\nexport function useFieldArray<TItem = InferredTypeArg>(\n form: FieldArrayFormApi & Readonly<{ schema: z.ZodType }>,\n path: TItem extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the item type from the path\",\n): UseFieldArrayReturn<TItem>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem>;\n// D last with a default (P's constraint forward-references it), preserving\n// the arity of explicit instantiations like\n// `useFieldArray<typeof schema, \"tags\">`.\nexport function useFieldArray<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi,\n pathArg: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem> {\n const path = useStore(form.store, (state) =>\n typeof pathArg === \"function\" ? pathArg(state) : pathArg,\n );\n const slice = useStore(\n form.store,\n useShallow((state) => {\n const value = getAtPath(state.values, path);\n return {\n items: (Array.isArray(value) ? value : EMPTY_ITEMS) as readonly TItem[],\n error: state.errors[path],\n };\n }),\n );\n const items = slice.items;\n const error = slice.error;\n\n // Ids derive from the shared per-(store, path) entry: the core's op log\n // replays each array op's exact index mapping (hook-issued or imperative\n // — both go through applyArrayOp, which records them), and value\n // reconciliation covers everything else (setValue of a whole array,\n // restore, resets). Deriving during render is safe because the entry is\n // a convergent cache — every commit is a pure function of a real store\n // state — and cheap because it early-exits on the same items reference.\n // All hook instances on the same path read the same entry, so their ids\n // can never disagree.\n const ids = deriveIds(form.store, path, items).ids;\n\n // After every op, revalidate the ARRAY path under the exact change-trigger\n // gate useField.setValue applies (same shouldValidateOn call), so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. The result is deliberately unhandled — the core self-routes async\n // schemas (validateField returns { kind: \"pending\" } having already started\n // the async pass). validateField is probed: a hand-rolled FieldArrayFormApi\n // without it skips revalidation instead of crashing. The IMPERATIVE\n // form.arrayPush/arrayRemove stay non-revalidating on purpose — the same\n // layering as form.setValue (raw write) vs useField.setValue (write + gate).\n const revalidate = useCallback(() => {\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n state.touched[path] ?? false,\n )\n ) {\n form.validateField?.(path);\n }\n }, [form, path]);\n\n const push = useCallback(\n (item: TItem) => {\n form.arrayPush(path, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const remove = useCallback(\n (index: number) => {\n form.arrayRemove(path, index);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const insert = useCallback(\n (index: number, item: TItem) => {\n form.arrayInsert(path, index, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const move = useCallback(\n (from: number, to: number) => {\n form.arrayMove(path, from, to);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const swap = useCallback(\n (a: number, b: number) => {\n form.arraySwap(path, a, b);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const fields = useMemo<readonly FieldArrayEntry<TItem>[]>(\n () =>\n items.map((value, index) => ({\n id: ids[index] ?? `__zfa_fallback_${index}`,\n value,\n })),\n [items, ids],\n );\n\n const setError = useCallback(\n // Same string-shorthand normalization as useField.setError, so custom\n // implementations typed for readonly string[] never receive a bare\n // string.\n (errors: string | readonly string[]) =>\n form.setError?.(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(() => form.clearErrors?.(path), [form, path]);\n\n return useMemo(\n () => ({\n path,\n fields,\n items,\n length: items.length,\n error,\n firstError: error?.[0],\n setError,\n clearError,\n push,\n remove,\n insert,\n move,\n swap,\n }),\n [path, fields, items, error, setError, clearError, push, remove, insert, move, swap],\n );\n}\n","import { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\nexport const useFormError = (\n form: FormStateApi,\n): readonly string[] | undefined =>\n useStore(\n form.store,\n useShallow((state) => state.errors[\"\"]),\n );\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Whole-values subscription in render — sugar for\n// useFormSelector(form, (s) => s.values), the render-side sibling of\n// form.watchValues. The classic use is derived rendering driven by live\n// form values (a map re-rendering as coordinates are edited).\n//\n// Deliberately NOT shallow-compared: the store replaces the values object\n// immutably on every value change, so reference equality (useStore's\n// default Object.is) is exactly right — one comparison, re-render if and\n// only if some value changed. Unrelated state changes (touched, errors,\n// isSubmitting) leave the values reference alone and cause no re-render.\n\nexport function useFormValues<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>): z.input<TSchema>;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above — same rule as\n// useFormSelector. Structural forms have nothing to infer from and read\n// `unknown`.\nexport function useFormValues(\n form: FormStateApi & { readonly schema?: undefined },\n): unknown;\nexport function useFormValues(form: FormStateApi): unknown {\n return useStore(form.store, (state) => state.values);\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// Composite fields: ONE control backed by SEVERAL schema paths — a\n// coordinate pair behind a single map-driven input, a range's min/max, a\n// date span. Binding each path with its own useField works, but the\n// coordination (a combined error line, one blur, one touched/dirty answer)\n// is the same hand-written boilerplate every time. useFields binds the\n// paths together:\n//\n// const location = useFields(form, [\"latitude\", \"longitude\"]);\n// const [latitude, longitude] = location.fields; // full UseFieldReturns\n// <span>{location.firstError}</span> // combined error line\n//\n// Each element of `fields` is a REAL UseFieldReturn — it spreads into the\n// same prop builders and Bound components a solo binding would — and the\n// wrapper adds the combined view: errors merged in path order (deduped, so\n// a cross-field superRefine that stamps both paths reads once), touched /\n// dirty / isValidating as \"any of them\", and one onBlur that blurs every\n// path (each under the form's own validation mode gate).\n//\n// THE PATHS TUPLE IS PART OF THE HOOK CONTRACT: its length and order must\n// be stable across renders, because it expands to exactly that many hook\n// calls. React enforces this itself — a tuple that changes length throws\n// the \"Rendered fewer/more hooks than expected\" dev error at the very\n// render that broke the contract (pinned by the test suite), so pass a\n// literal or a module-level constant, never a filtered array.\n\nexport type UseFieldsReturn<TFields extends readonly unknown[]> = Readonly<{\n fields: TFields;\n // Every bound path's messages, merged in path order and deduped.\n error: readonly string[] | undefined;\n firstError: string | undefined;\n // \"Any of them\": one answer for the composite control's chrome.\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n // Blurs every bound path — each under the form's validation mode gate,\n // so the composite behaves like one control losing focus.\n onBlur: () => void;\n}>;\n\n// Schema-less forms keep the caller-typed shape (the `schema?: undefined`\n// brand forces a real Form past this overload, mirroring useField).\nexport function useFields(\n form: FieldFormApi & { readonly schema?: undefined },\n paths: readonly string[],\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]>;\n// The typed overload: `paths` is a const-inferred tuple and `fields` maps\n// it position-for-position, so destructuring keeps each path's exact value\n// type. D is recovered from the form (the \"~pathDepth\" marker), like the\n// sibling hooks.\nexport function useFields<\n TSchema extends z.ZodType,\n const P extends readonly FieldPath<z.input<TSchema>, D>[],\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n paths: P,\n): UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\nexport function useFields(\n form: FieldFormApi,\n paths: readonly string[],\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> {\n const fields = paths.map((path) =>\n // eslint-disable-next-line react-hooks/rules-of-hooks -- a fixed hook count by the stable-arity contract above; each element must be a REAL UseFieldReturn so it spreads into the prop builders\n useField(form as FieldFormApi & { readonly schema?: undefined }, path),\n );\n const merged = [...new Set(fields.flatMap((field) => field.error ?? []))];\n return {\n fields,\n error: merged.length > 0 ? merged : undefined,\n firstError: merged[0],\n touched: fields.some((field) => field.touched),\n dirty: fields.some((field) => field.dirty),\n isValidating: fields.some((field) => field.isValidating),\n onBlur: () => {\n fields.forEach((field) => {\n field.onBlur();\n });\n },\n };\n}\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type { DefaultPathDepth, FieldPath, PathDepth } from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport { isPathOrChild } from \"../core/validation\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Both flag hooks take an optional path and scope to it with the same\n// prefix semantics as the rest of the library (isPathOrChild): \"shipping\"\n// covers \"shipping.city\". Omitted path = whole form. Overload order mirrors\n// useField: the typed-path overload sits last so a typo'd path on a\n// Form<TSchema> is blamed against the full FieldPath union, and the\n// `schema?: undefined` brand keeps real Forms off the widened string\n// overload. Subscriptions are boolean-only — the component re-renders when\n// the flag flips, not on every keystroke (unlike useField(...).dirty).\n\n// Derived from the values (memoized per values reference), so it always\n// agrees with per-field dirty reads. The scoped form compares just the\n// subtree at `path` — a missing path on both sides reads as clean.\nexport function useIsDirty(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsDirty<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsDirty(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) =>\n path === undefined || path === \"\"\n ? isFieldDirty(state.values, state.initialValues)\n : isFieldDirty(\n getAtPath(state.values, path),\n getAtPath(state.initialValues, path),\n ),\n );\n}\n\n// \"No errors currently in the merged map\" (not a fresh validation pass);\n// the scoped form only looks at errors at or under `path`, including the\n// path's own key (array-level errors like `items` count for path \"items\").\nexport function useIsValid(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValid<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValid(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n // A loop rather than Object.entries().some(): this selector re-runs on\n // EVERY store change, and the loop exits at the first error without\n // materializing an entries array for a map that is usually empty.\n for (const k in state.errors) {\n const errs = state.errors[k];\n if (\n errs !== undefined &&\n errs.length > 0 &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return false;\n }\n }\n return true;\n });\n}\n\n// Whether async validation is in flight — form-level (a whole-form pass,\n// or any field's own pass) or scoped to a path subtree, boolean-only like\n// the sibling flags. The form-level read was previously reachable only\n// through a selector, asymmetric with useIsSubmitting.\nexport function useIsValidating(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValidating<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValidating(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n if (path === undefined || path === \"\") {\n if (state.isValidatingForm) return true;\n }\n // Same first-hit loop rationale as useIsValid: this selector re-runs\n // on every store change over a usually-empty map.\n for (const k in state.isValidating) {\n if (\n state.isValidating[k] === true &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return true;\n }\n }\n return false;\n });\n}\n\nexport const useIsSubmitting = (form: FormStateApi): boolean =>\n useStore(form.store, (state) => state.isSubmitting);\n\nexport const useSubmitCount = (form: FormStateApi): number =>\n useStore(form.store, (state) => state.submitCount);\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldFormApi,\n type UseFieldOptions,\n type UseFieldReturn,\n useField,\n} from \"./useField\";\nimport {\n type UnionValueAt,\n type VariantFieldValue,\n type VariantKeys,\n useVariantField,\n} from \"./useVariantField\";\nimport {\n type ArrayItemOf,\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport { useFormError } from \"./useFormError\";\nimport { useFormValues } from \"./useFormValues\";\nimport { type UseFieldsReturn, useFields } from \"./useFields\";\nimport {\n useIsDirty,\n useIsSubmitting,\n useIsValid,\n useIsValidating,\n useSubmitCount,\n} from \"./useFormFlags\";\nimport {\n type FormStateApi,\n useFormSelector,\n useFormSelectorShallow,\n} from \"./useFormSelector\";\n\n// createFormHooks(form, name?) — every hook, pre-wired to one form. The\n// context-free way to share a form: create it at module scope, export the\n// returned hooks, and no component ever passes `form` through props or a\n// provider. The optional name is baked into the hook names (both at the\n// type level and at runtime), so a module reads like a domain API:\n//\n// const form = createForm(invoiceSchema, { initialValues });\n// export const { useInvoiceField, useInvoiceFieldArray, useInvoiceIsDirty } =\n// createFormHooks(form, \"invoice\");\n//\n// Typed paths survive the binding: useInvoiceField(\"customer\") infers the\n// value type from the schema, and a typo'd path is a compile error.\n//\n// Reach for this when the form is a genuine module-level singleton (one\n// instance for the app's lifetime — settings, a global compose box). For a\n// form that mounts per page/dialog with its own lifecycle, use useForm and\n// createFormContext instead: a module singleton never unmounts, so state\n// persists across navigations until you reset() it.\n\n// The bound signatures mirror the unbound hooks minus the form parameter;\n// the typed-path call signature sits last for the same error-blame reason\n// as the originals.\nexport type BoundUseField<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n options?: UseFieldOptions,\n ): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\n};\n\n// The variant-field accessor bound to the form: the type math (variant-only\n// field keys, value across declaring variants) lives in useVariantField; the\n// bound signature just drops the form parameter.\nexport type BoundUseVariantField<TSchema extends z.ZodType> = <\n P extends string,\n TField extends VariantKeys<UnionValueAt<z.input<TSchema>, P>>,\n>(\n unionPath: P,\n field: TField,\n) => UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\n\nexport type BoundUseFieldArray<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n ): UseFieldArrayReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\n};\n\nexport type BoundUseSelector<TSchema extends z.ZodType> = <U>(\n selector: (state: FormState<z.input<TSchema>>) => U,\n) => U;\n\nexport type BoundUseFlag<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = (\n path?: FieldPath<z.input<TSchema>, D>,\n) => boolean;\n\n// One single-key mapped type per hook, intersected: template-literal keys\n// carry the capitalized name, so the destructured names are typo-checked\n// ({ useInvoceField } fails to compile against createFormHooks(f, \"invoice\")).\nexport type FormHooks<\n TSchema extends z.ZodType,\n N extends string,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<\n { [K in `use${Capitalize<N>}Field`]: BoundUseField<TSchema, D> } & {\n [K in `use${Capitalize<N>}VariantField`]: BoundUseVariantField<TSchema>;\n } & {\n [K in `use${Capitalize<N>}FieldArray`]: BoundUseFieldArray<TSchema, D>;\n } & { [K in `use${Capitalize<N>}Selector`]: BoundUseSelector<TSchema> } & {\n [K in `use${Capitalize<N>}SelectorShallow`]: BoundUseSelector<TSchema>;\n } & {\n [K in `use${Capitalize<N>}Error`]: () => readonly string[] | undefined;\n } & { [K in `use${Capitalize<N>}IsDirty`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsValid`]: BoundUseFlag<TSchema, D>;\n } & { [K in `use${Capitalize<N>}IsValidating`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsSubmitting`]: () => boolean;\n } & {\n [K in `use${Capitalize<N>}SubmitCount`]: () => number;\n } & { [K in `use${Capitalize<N>}Values`]: () => z.input<TSchema> } & {\n [K in `use${Capitalize<N>}Fields`]: BoundUseFields<TSchema, D>;\n }\n>;\n\n// The bound composite-fields hook: same const-inferred tuple and\n// position-typed fields as the plain useFields.\nexport type BoundUseFields<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = <const P extends readonly FieldPath<z.input<TSchema>, D>[]>(\n paths: P,\n) => UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\n\n// Runtime twin of TypeScript's Capitalize<N> (ASCII names; a leading\n// non-letter passes through unchanged in both).\nconst capitalize = (name: string): string =>\n name.length === 0 ? name : name.charAt(0).toUpperCase() + name.slice(1);\n\n// D (the form's typed-path depth budget) sits LAST so existing explicit\n// instantiations — createFormHooks<Schema, \"invoice\"> — keep compiling; it\n// is inferred from the form argument anyway.\nexport const createFormHooks = <\n TSchema extends z.ZodType,\n N extends string = \"\",\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n name?: N,\n): FormHooks<TSchema, N, D> => {\n // Calling the unbound hooks through a structural view (no `schema`\n // property) binds their widened overloads — the precise typing is\n // re-established by the Bound* signatures above, which the type tests pin.\n const structural: FieldFormApi & FieldArrayFormApi & FormStateApi = form;\n\n const useBoundField = (\n path: string | ((state: FormState<unknown>) => string),\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown> => useField(structural, path, options);\n\n const useBoundVariantField = (\n unionPath: string,\n field: string,\n ): UseFieldReturn<unknown> =>\n useVariantField(\n structural as FieldFormApi & { readonly schema?: undefined },\n unionPath,\n field,\n );\n\n const useBoundFieldArray = (\n path: string | ((state: FormState<unknown>) => string),\n ): UseFieldArrayReturn<unknown> => useFieldArray(structural, path);\n\n const useBoundSelector = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelector(structural, selector);\n\n const useBoundSelectorShallow = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelectorShallow(structural, selector);\n\n const useBoundError = (): readonly string[] | undefined =>\n useFormError(structural);\n\n const useBoundIsDirty = (path?: string): boolean =>\n useIsDirty(structural, path);\n\n const useBoundIsValid = (path?: string): boolean =>\n useIsValid(structural, path);\n\n const useBoundIsValidating = (path?: string): boolean =>\n useIsValidating(structural, path);\n\n const useBoundIsSubmitting = (): boolean => useIsSubmitting(structural);\n\n const useBoundValues = (): unknown => useFormValues(structural);\n\n const useBoundFields = (\n paths: readonly string[],\n ): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> =>\n useFields(\n structural as FieldFormApi & { readonly schema?: undefined },\n paths,\n );\n\n const useBoundSubmitCount = (): number => useSubmitCount(structural);\n\n const prefix = capitalize(name ?? \"\");\n // Computed keys erase to an index signature, so the literal is asserted\n // to the mapped FormHooks type — the real contract, verified by type\n // tests on both the key names and the bound signatures.\n return {\n [`use${prefix}Field`]: useBoundField,\n [`use${prefix}VariantField`]: useBoundVariantField,\n [`use${prefix}FieldArray`]: useBoundFieldArray,\n [`use${prefix}Selector`]: useBoundSelector,\n [`use${prefix}SelectorShallow`]: useBoundSelectorShallow,\n [`use${prefix}Error`]: useBoundError,\n [`use${prefix}IsDirty`]: useBoundIsDirty,\n [`use${prefix}IsValid`]: useBoundIsValid,\n [`use${prefix}IsValidating`]: useBoundIsValidating,\n [`use${prefix}IsSubmitting`]: useBoundIsSubmitting,\n [`use${prefix}SubmitCount`]: useBoundSubmitCount,\n [`use${prefix}Values`]: useBoundValues,\n [`use${prefix}Fields`]: useBoundFields,\n } as FormHooks<TSchema, N, D>;\n};\n","import type { ChangeEvent } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\n\nexport type TextInputProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type NumberInputProps = Readonly<{\n type: \"number\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type DateInputProps = Readonly<{\n type: \"date\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type CheckboxProps = Readonly<{\n type: \"checkbox\";\n name: string;\n checked: boolean;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type SelectProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLSelectElement>) => void;\n onBlur: () => void;\n}>;\n\n// THE predicate for \"does this field currently show an error\" — shared by\n// the aria-invalid mapping here and the field shells in fields.tsx, so the\n// notion of \"showing an error\" cannot drift between bindings.\nexport const hasFieldError = (\n error: readonly string[] | undefined,\n): boolean => error !== undefined && error.length > 0;\n\nconst ariaInvalid = (\n field: Readonly<{ error: readonly string[] | undefined }>,\n): true | undefined => (hasFieldError(field.error) ? true : undefined);\n\n// A cleared input writes back `field.emptyValue` when the schema ACCEPTS it\n// (`field.clearable`: optional, nullable, or defaulted — useField introspects\n// the form's zod schema), so z.number().nullable() round-trips to null and\n// z.string().optional() to undefined instead of a lingering \"\". A required\n// string cleared to \"\" stays \"\": writing undefined there would trade a\n// visible value the schema can judge for a hole it rejects.\n\n// Canonical display text for a numeric field value (\"\" for empty/NaN; null\n// counts as empty so nullable fields don't render the literal text \"null\").\n// Shared with NumberField so the two number bindings can't drift.\nexport const numberToInputText = (value: number | null | undefined): string =>\n value === undefined || value === null || Number.isNaN(value)\n ? \"\"\n : String(value);\n\nexport type ParsedNumberText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"number\"; value: number }>\n // Text that doesn't parse to a finite number — partial entries (\"-\",\n // \"1.\", \"1e\") or Infinity.\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning user-typed text into a numeric field value:\n// whitespace counts as empty (Number(\" \") is 0) and non-finite results are\n// rejected. Shared with NumberField.\nexport const parseNumberText = (text: string): ParsedNumberText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const parsed = Number(text);\n return Number.isFinite(parsed)\n ? { kind: \"number\", value: parsed }\n : { kind: \"invalid\" };\n};\n\nexport const textInputProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): TextInputProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const text = e.target.value;\n // Deleting all text from a clearable field restores its emptyValue\n // (null or undefined), so it isn't left permanently dirty (or invalid)\n // by a visual no-op.\n field.setValue((text === \"\" && field.clearable ? field.emptyValue : text) as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const numberInputProps = <T extends number | null | undefined>(\n field: UseFieldReturn<T>,\n): NumberInputProps => ({\n type: \"number\",\n name: field.path,\n value: numberToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseNumberText(e.target.value);\n // \"invalid\" is a PARTIAL entry (a lone \"-\", \"1e\") — keep the stored\n // value untouched, matching useNumberInput's deliberate semantics,\n // instead of writing emptyValue mid-keystroke (which flashed a\n // required error and flipped dirty while the user was still typing).\n // \"empty\" still clears to emptyValue. Note browsers report \"\" for\n // badInput on type=\"number\", so some partial entries arrive as\n // \"empty\" regardless — useNumberInput (a text input with its own raw\n // state) remains the binding that preserves every keystroke.\n if (parsed.kind === \"invalid\") return;\n field.setValue(\n (parsed.kind === \"number\" ? parsed.value : field.emptyValue) as T,\n );\n },\n onBlur: field.onBlur,\n});\n\n// Canonical display text for a Date field value — the local calendar date\n// as \"yyyy-MM-dd\" (what <input type=\"date\"> speaks). Local parts, NOT\n// toISOString(): a date picked as June 1 must not render as May 31 for\n// users west of UTC. Invalid Dates count as empty. Shared with DateField.\nexport const dateToInputText = (value: Date | null | undefined): string => {\n if (value === undefined || value === null || Number.isNaN(value.getTime())) {\n return \"\";\n }\n const pad = (part: number): string => String(part).padStart(2, \"0\");\n return `${String(value.getFullYear()).padStart(4, \"0\")}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;\n};\n\nexport type ParsedDateText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"date\"; value: Date }>\n // Not \"yyyy-MM-dd\", or parts that roll over (2026-02-31).\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning \"yyyy-MM-dd\" into a Date field value: LOCAL\n// midnight — a calendar date, not a UTC instant (new Date(\"2026-06-01\")\n// would be UTC midnight and read back as May 31 west of Greenwich).\n// Shared with DateField.\nexport const parseDateText = (text: string): ParsedDateText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text);\n if (match === null) return { kind: \"invalid\" };\n const [, year, month, day] = match;\n const y = Number(year);\n const date = new Date(y, Number(month) - 1, Number(day));\n // The Date constructor maps two-digit years 0–99 to 1900–1999, so a valid\n // \"0099-01-01\" would fail the survival check below; force the literal year\n // back on for years under 100 before checking rollover.\n if (y < 100) date.setFullYear(y);\n // The parts must survive the Date constructor — rollovers are invalid,\n // not silently the 3rd of next month.\n return date.getFullYear() === y &&\n date.getMonth() === Number(month) - 1 &&\n date.getDate() === Number(day)\n ? { kind: \"date\", value: date }\n : { kind: \"invalid\" };\n};\n\nexport const dateInputProps = <T extends Date | null | undefined>(\n field: UseFieldReturn<T>,\n): DateInputProps => ({\n type: \"date\",\n name: field.path,\n value: dateToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseDateText(e.target.value);\n if (parsed.kind !== \"date\") {\n field.setValue(field.emptyValue as T);\n return;\n }\n // Preserve the existing value's time-of-day: <input type=\"date\"> only\n // edits the calendar date, so re-picking the SAME day on a value that\n // carried a time (an initial `new Date()`) must stay a no-op — otherwise\n // the new local-midnight Date differs from the timestamped original and\n // the field reads spuriously dirty. Changing the day keeps that time.\n const current = field.value;\n const next =\n current instanceof Date && !Number.isNaN(current.getTime())\n ? new Date(\n parsed.value.getFullYear(),\n parsed.value.getMonth(),\n parsed.value.getDate(),\n current.getHours(),\n current.getMinutes(),\n current.getSeconds(),\n current.getMilliseconds(),\n )\n : parsed.value;\n field.setValue(next as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const checkboxProps = <T extends boolean | null | undefined>(\n field: UseFieldReturn<T>,\n): CheckboxProps => ({\n type: \"checkbox\",\n name: field.path,\n checked: field.value ?? false,\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => field.setValue(e.target.checked as T),\n onBlur: field.onBlur,\n});\n\n// `?? \"\"` keeps the <select> controlled when the field has no value yet\n// (undefined for optional fields, null for nullable ones); pair it with an\n// <option value=\"\"> (SelectField renders one) so the blank state is a real\n// option instead of silently showing the first entry.\nexport const selectProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): SelectProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const v = e.target.value;\n field.setValue((v === \"\" && field.clearable ? field.emptyValue : v) as T);\n },\n onBlur: field.onBlur,\n});\n","import { type ChangeEvent, type ReactNode, useId, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { FieldPath, PathDepth } from \"../core/fieldPath\";\nimport {\n checkboxProps,\n dateInputProps,\n hasFieldError,\n numberToInputText,\n parseNumberText,\n selectProps,\n textInputProps,\n} from \"./inputProps\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// The paths a bound component accepts for a given `form` prop: when the form\n// carries its schema (a real Form<TSchema>), `path` narrows to the schema's\n// FieldPath union — a typo'd path is a compile error, matching useField's\n// typed overloads. Template-literal paths with a numeric hole\n// (`users.${index}.email`) are part of that union, so dynamic array rows\n// still typecheck. A bare structural FieldFormApi keeps plain string paths.\n// The form's own depth budget (createForm's `pathDepth`, default 9) is\n// recovered alongside the schema, so a widened form widens its bound\n// components' paths too.\nexport type PathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? FieldPath<z.input<TSchema>, D>\n : string;\n\n// Structural stand-in for React.Ref<T>: accepts useRef objects and callback\n// refs (including React 19 cleanup-returning ones — any return type is\n// assignable to a void-returning signature). Declared structurally instead of\n// as React.Ref so it unifies even when the consumer resolves a different\n// @types/react copy than the library.\nexport type FieldRef<T> =\n | ((instance: T | null) => void)\n | Readonly<{ current: T | null }>\n | null;\n\n// The chrome every bound field renders: wrapper, optional label, the\n// control, and the error line. `wrapLabel` puts the control INSIDE the\n// label (the checkbox layout: box, then text) instead of after a preceding\n// sibling label. One component so an a11y change lands everywhere at once.\ntype FieldShellProps = Readonly<{\n id: string;\n errorId: string;\n label: ReactNode | undefined;\n error: readonly string[] | undefined;\n wrapLabel?: boolean;\n children: ReactNode;\n}>;\n\n// Shared id wiring for every bound field: a stable control id, the error\n// line's id derived from it, and the aria-describedby value — set only\n// while an error shows, so assistive tech is never pointed at a node that\n// isn't rendered.\nconst useFieldA11y = (\n error: readonly string[] | undefined,\n): Readonly<{ id: string; errorId: string; describedBy: string | undefined }> => {\n const id = useId();\n const errorId = `${id}-error`;\n return {\n id,\n errorId,\n describedBy: hasFieldError(error) ? errorId : undefined,\n };\n};\n\n// role=\"alert\" announces the message to assistive tech when it appears; the\n// id lets the input point at it via aria-describedby.\nconst ErrorText = ({\n id,\n error,\n}: Readonly<{ id: string; error: readonly string[] | undefined }>) =>\n hasFieldError(error) ? (\n <span className=\"zf-error\" id={id} role=\"alert\">\n {error?.[0]}\n </span>\n ) : null;\n\nconst FieldShell = ({\n id,\n errorId,\n label,\n error,\n wrapLabel,\n children,\n}: FieldShellProps) => (\n <div className=\"zf-field\">\n {wrapLabel === true ? (\n <label htmlFor={id} className=\"zf-label\">\n {children} {label}\n </label>\n ) : (\n <>\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n {children}\n </>\n )}\n <ErrorText id={errorId} error={error} />\n </div>\n);\n\nexport type TextFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n placeholder?: string;\n type?: \"text\" | \"password\" | \"email\" | \"url\" | \"tel\";\n autoComplete?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\nexport const TextField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n type = \"text\",\n autoComplete,\n ref,\n}: TextFieldProps<F>) => {\n const field = useField<string | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...textInputProps(field)}\n type={type}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type DateFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n min?: string;\n max?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\n// <input type=\"date\"> holds Date-typed state: display and parsing go\n// through the shared dateInputProps rules (local calendar-date semantics —\n// see inputProps.ts), so a nullable date clears back to null and an\n// invalid/partial entry writes the field's emptyValue. No raw-text state:\n// unlike number inputs, the date control has no partial entries to\n// preserve — the browser only fires change with \"\" or a complete date.\nexport const DateField = <F extends FieldFormApi>({\n form,\n path,\n label,\n min,\n max,\n ref,\n}: DateFieldProps<F>) => {\n const field = useField<Date | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...dateInputProps(field)}\n min={min}\n max={max}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type NumberFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n placeholder?: string;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport type NumberInputBinding = Readonly<{\n name: string;\n value: string;\n inputMode: \"decimal\";\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype NumberEditState = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a partial\n // entry). When field.value diverges, an external writer (reset/adoptValues/\n // another field) changed it — drop the raw text so the input shows it.\n pushed: number | null | undefined;\n}>;\n\nconst IDLE_EDIT: NumberEditState = { raw: null, pushed: undefined };\n\n// Holds the raw text while editing so intermediate, not-yet-valid numbers\n// (\"-\", \"1.\", \"1e\") stay visible instead of being coerced to \"\". Keystrokes\n// that parse to a number (via the shared parseNumberText rules) are pushed to\n// the form; partial input is kept locally. On blur the display snaps back to\n// the form's canonical value, and an external value change while editing wins\n// over the local text (render-phase derived-state reset).\n// Exported for custom number inputs (and the CLI's kit adapters mirror its\n// semantics): spread the binding onto an <input type=\"text\"> — a naive\n// value={String(field.value)} controlled input eats the \".\" of \"85000.50\"\n// and the \"-\" of \"-5\" as they're typed.\nexport const useNumberInput = (\n field: UseFieldReturn<number | null | undefined>,\n): NumberInputBinding => {\n const [edit, setEdit] = useState<NumberEditState>(IDLE_EDIT);\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit(IDLE_EDIT);\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value: raw ?? numberToInputText(field.value),\n inputMode: \"decimal\",\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = parseNumberText(text);\n switch (parsed.kind) {\n case \"empty\": {\n const empty = field.emptyValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"number\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form value\n // so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n setEdit(IDLE_EDIT);\n field.onBlur();\n },\n };\n};\n\nexport const NumberField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n ref,\n}: NumberFieldProps<F>) => {\n const field = useField<number | null | undefined>(form, path);\n const binding = useNumberInput(field);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n type=\"text\"\n {...binding}\n placeholder={placeholder}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type CheckboxFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport const CheckboxField = <F extends FieldFormApi>({\n form,\n path,\n label,\n ref,\n}: CheckboxFieldProps<F>) => {\n const field = useField<boolean | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n wrapLabel\n >\n <input\n id={a11y.id}\n ref={ref}\n {...checkboxProps(field)}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type SelectFieldOption<T extends string> = Readonly<{\n value: T;\n label: ReactNode;\n}>;\n\nexport type SelectFieldProps<\n T extends string,\n F extends FieldFormApi = FieldFormApi,\n> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n options: readonly SelectFieldOption<T>[];\n // Shown as a disabled first option while the field has no value, so the\n // select stays controlled and the blank state is visible instead of\n // silently displaying the first option. Ignored when `options` itself\n // contains a \"\"-valued entry — that explicit, labelled option IS the\n // blank state and renders instead.\n placeholder?: string;\n ref?: FieldRef<HTMLSelectElement>;\n}>;\n\nexport const SelectField = <T extends string, F extends FieldFormApi>({\n form,\n path,\n label,\n options,\n placeholder,\n ref,\n}: SelectFieldProps<T, F>) => {\n // null included: a nullable enum's \"not chosen yet\" must render the empty\n // option, or the browser shows the first real option while state stays null.\n const field = useField<T | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n const select = selectProps(field);\n // A clearable field (nullable, optional, or defaulted) must be clearable\n // BACK to its emptyValue through the UI, so its empty option stays\n // visible after a choice and stays selectable — selectProps writes the\n // emptyValue for it. Everywhere else the empty option is only a\n // placeholder: visible while nothing is chosen, never selectable.\n // The value condition derives from selectProps' own coercion (undefined,\n // null, and \"\" all render as value \"\"), so any blank the select displays\n // has a matching option by construction. When the options list supplies\n // its OWN \"\"-valued entry, that explicit option IS the blank state —\n // rendering the implicit one too would duplicate the value, and the\n // browser would select the first (unlabelled) match instead.\n const clearable = field.clearable;\n const hasExplicitEmptyOption = options.some((opt) => opt.value === \"\");\n const showEmptyOption =\n !hasExplicitEmptyOption &&\n (clearable || select.value === \"\" || placeholder !== undefined);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <select\n id={a11y.id}\n ref={ref}\n {...select}\n aria-describedby={a11y.describedBy}\n >\n {showEmptyOption ? (\n <option value=\"\" disabled={!clearable}>\n {placeholder ?? \"\"}\n </option>\n ) : null}\n {options.map((opt, index) => (\n // Index-qualified: option lists may legitimately repeat a value\n // (e.g. differently-labelled aliases), and bare value keys would\n // collide.\n <option key={`${index}-${opt.value}`} value={opt.value}>\n {opt.label}\n </option>\n ))}\n </select>\n </FieldShell>\n );\n};\n","import type { ErrorMap } from \"../core/types\";\nimport { isPathOrChild } from \"../core/validation\";\n\n// The shared candidate walk for focusFirstError/focusField: form controls\n// with a `name`, in DOM order. Focusability is a SEPARATE, later filter —\n// matches()/closest() are ancestor walks, so they run on the few\n// name-matched candidates instead of every named control in the document\n// (a failed submit on a page with hundreds of controls shouldn't pay\n// hundreds of DOM traversals to focus one input).\nconst namedControls = (scope: ParentNode): readonly HTMLElement[] => [\n ...scope.querySelectorAll<HTMLElement>(\n \"input[name], select[name], textarea[name]\",\n ),\n];\n\n// Hidden and disabled controls, and controls inside a closed <dialog>,\n// can't take focus — without the filter, a leading <input type=\"hidden\"\n// name=\"csrf\"> would swallow focusFirstError's root fallback, and a name\n// match inside a not-yet-opened dialog would shadow the visible one.\nconst isFocusCandidate = (el: HTMLElement): boolean =>\n !el.matches(':disabled, [type=\"hidden\"]') &&\n el.closest(\"dialog:not([open])\") === null;\n\n// Does `el` actually hold focus? Ask the element's OWN root (document or\n// shadow root): document.activeElement retargets to the shadow HOST for a\n// focused control inside a shadow root, so it would read a successfully\n// focused shadow-DOM control as unfocused. A root that is neither (a\n// detached fragment) has no activeElement — fall back to the document,\n// where a detached element can never be the active one.\nconst holdsFocus = (el: HTMLElement): boolean => {\n const rootNode = el.getRootNode();\n const active =\n rootNode instanceof Document || rootNode instanceof ShadowRoot\n ? rootNode.activeElement\n : document.activeElement;\n return active === el;\n};\n\n// focus() can silently no-op (display:none ancestors and other unfocusable\n// states the cheap filters above can't see) — verify it took, and fall\n// through to the next candidate in DOM order. True only when a control\n// actually holds focus.\nconst focusFirstOf = (candidates: readonly HTMLElement[]): boolean =>\n candidates.some((el) => {\n el.focus();\n return holdsFocus(el);\n });\n\nconst nameMatchesAny = (\n el: HTMLElement,\n paths: readonly string[],\n): boolean => {\n const name = el.getAttribute(\"name\");\n return name !== null && paths.some((p) => isPathOrChild(name, p));\n};\n\n// CSS attribute-selector value for an arbitrary path: quoted, with the two\n// characters that are active inside a double-quoted CSS string escaped —\n// so paths with dots (\"address.region\") and hostile names select literally.\n// Control characters (a stray \"\\n\" in a computed path, DEL) are additionally\n// hex-escaped (`\\a `, with CSS's required trailing space): a raw newline\n// inside a quoted CSS string is a parse error, and querySelectorAll on an\n// invalid selector THROWS instead of matching nothing.\nconst cssQuoted = (value: string): string =>\n `\"${value\n .replace(/[\\\\\"]/g, (ch) => `\\\\${ch}`)\n .replace(\n /[\\x00-\\x1f\\x7f]/g,\n (ch) => `\\\\${ch.codePointAt(0)!.toString(16)} `,\n )}\"`;\n\n// The id fallback for composite widgets that render no `name` at all (e.g.\n// antd's Select — no form-posting input exists in it) but DO forward\n// `id={path}` to their real focusable control, the way the CLI's antd\n// adapter emits it. EXACT id match only, by design: descendant semantics\n// (\"address\" covering \"address.city\") belong to the name walk — an id names\n// one element, and inventing prefix matching over ids would guess. Runs\n// through the same focusability filter and post-focus verification as name\n// matches.\nconst idMatches = (\n scope: ParentNode,\n path: string,\n): readonly HTMLElement[] =>\n path === \"\"\n ? []\n : [...scope.querySelectorAll<HTMLElement>(`[id=${cssQuoted(path)}]`)];\n\n// Document order for a merged candidate list (name matches + id fallbacks\n// come from separate queries, but \"first error\" means first in the DOM).\nconst inDomOrder = (\n els: readonly HTMLElement[],\n): readonly HTMLElement[] =>\n [...els].sort((a, b) =>\n a === b\n ? 0\n : (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n ? -1\n : 1,\n );\n\n// The candidate walk shared by focusFirstError and focusField: name-matched\n// form controls for every path, plus — per path that matched NO named\n// control — the element whose `id` is exactly that path. Paths with a named\n// match never consult ids, so the name walk's semantics (descendants\n// included) stay authoritative wherever a `name` exists.\nconst pathCandidates = (\n scope: ParentNode,\n paths: readonly string[],\n): readonly HTMLElement[] => {\n const controls = namedControls(scope);\n const named = controls.filter((el) => nameMatchesAny(el, paths));\n // \"Has a named match\" is judged against focus-CANDIDATE controls only: a\n // hidden name-carrier (react-select's <input type=\"hidden\" name={path}>\n // value input, notably) can never take focus, so letting it claim the\n // path would suppress the id fallback and leave the real, id={path}\n // focusable control unreachable. The `named` list itself stays\n // pre-filter — callers apply isFocusCandidate to the merged result.\n const focusableControls = controls.filter(isFocusCandidate);\n const unnamedPaths = paths.filter(\n (p) => !focusableControls.some((el) => nameMatchesAny(el, [p])),\n );\n const byId = unnamedPaths.flatMap((p) => idMatches(scope, p));\n return inDomOrder([...new Set([...named, ...byId])]);\n};\n\n// Focus the first form control (in DOM order) whose `name` attribute matches\n// an entry in the error map — either exactly, or as a descendant of an\n// errored container path, so array-level errors (\"lineItems\" from\n// z.array().min()) and object-level refines (\"address\") land on their first\n// rendered field. Most specific wins: the root \"\" key (a form-wide refine)\n// falls back to the first control only when no field-keyed error matches\n// anything — otherwise a root error would steal focus from the actually\n// errored field. A path that matches NO named control at all additionally\n// tries the element whose `id` is exactly that path (see pathCandidates) —\n// how composite widgets with no `name` anywhere, like antd's Select with\n// id={path}, still get focused. The bound components and prop builders set\n// name={path}, so this works out of the box:\n//\n// form.handleSubmit(onValid, (errors) => focusFirstError(errors))\n//\n// Pass `root` to scope the search (e.g. the <form> element via a ref) — on a\n// page with several forms this is the way to keep focus inside YOUR form:\n// without it the search spans the whole document, and the root-\"\" fallback\n// refuses to guess between forms (it returns false when the document holds\n// more than one <form>). Returns whether a control actually received focus —\n// candidates that can't take it (disabled, hidden, inside a closed <dialog>,\n// display:none, ...) are passed over for the next match in DOM order. Safe to\n// import during SSR — it only touches the DOM when called.\nexport const focusFirstError = (\n errors: ErrorMap,\n root?: ParentNode,\n): boolean => {\n const scope = root ?? document;\n const erroredPaths = Object.keys(errors).filter(\n (k) => k !== \"\" && (errors[k]?.length ?? 0) > 0,\n );\n const hasRootError = (errors[\"\"]?.length ?? 0) > 0;\n const controls = namedControls(scope);\n const fieldMatches = pathCandidates(scope, erroredPaths).filter(\n isFocusCandidate,\n );\n // The root-\"\" fallback (\"focus the first control\") is only meaningful when\n // \"first control\" is unambiguous. With the default document scope on a\n // page holding several <form>s, the first control could belong to a form\n // that had nothing to do with this submit — refuse to guess and report\n // false; pass the form element as `root` to disambiguate.\n const rootFallbackApplies =\n hasRootError &&\n (root !== undefined || document.querySelectorAll(\"form\").length <= 1);\n const candidates =\n fieldMatches.length > 0\n ? fieldMatches\n : rootFallbackApplies\n ? controls.filter(isFocusCandidate)\n : [];\n return focusFirstOf(candidates);\n};\n\n// Imperative sibling of focusFirstError, keyed by a path instead of an error\n// map: focus the first control (in DOM order) whose `name` is `path` itself\n// or a descendant of it — focusField(\"address\") lands on the first rendered\n// address field. Same candidate walk (unfocusable controls are passed over,\n// focus is verified to have taken, a name-less path falls back to the\n// element whose `id` is exactly the path) and the same `root` scoping.\n// This is the \"setFocus\" of the library — reach for it after opening a\n// dialog or appending an array row:\n//\n// items.push(emptyItem);\n// requestAnimationFrame(() =>\n// focusField(`items.${items.length}.name`, formRef.current ?? undefined),\n// );\n//\n// The root \"\" path is whole-form scope, consistent with the imperative\n// surface (validateField(\"\") / resetField(\"\")): focus the first focusable\n// control in scope. Like focusFirstError's root-\"\" fallback, \"first control\"\n// under the default document scope is a guess when the page holds several\n// <form>s — focusField refuses to guess and returns false; pass the form\n// element as `root` to disambiguate.\n//\n// Returns whether a control actually received focus. Safe to import during\n// SSR — it only touches the DOM when called.\nexport const focusField = (path: string, root?: ParentNode): boolean => {\n const scope = root ?? document;\n return path === \"\"\n ? (root !== undefined ||\n document.querySelectorAll(\"form\").length <= 1) &&\n focusFirstOf(namedControls(scope).filter(isFocusCandidate))\n : focusFirstOf(pathCandidates(scope, [path]).filter(isFocusCandidate));\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/array.ts","../src/core/arrayOpLog.ts","../src/core/validation.ts","../src/core/createForm.ts","../src/core/debounce.ts","../src/core/persist.ts","../src/react/usePersistForm.ts","../src/react/useForm.ts","../src/react/inputProps.ts","../src/react/useMaskedInput.ts","../src/react/useFormSteps.ts","../src/react/useFormAction.ts","../src/react/FormContext.tsx","../src/react/useField.ts","../src/react/useVariantField.ts","../src/react/useFieldArray.ts","../src/react/useFormError.ts","../src/react/useFormValues.ts","../src/react/useFields.ts","../src/react/useFormFlags.ts","../src/react/createFormHooks.ts","../src/react/fields.tsx","../src/react/focusError.ts"],"names":["useRef","useEffect","useState","useMemo","useCallback","initialValue","validateAsync","useStore","useShallow","jsx"],"mappings":";;;;;;;;;;;;;AAEO,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,CAAA,KACC,CAAA,KAAM,CAAA,GAAI,IAAA,GAAO,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAA;AAE9B,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,MACC,CAAA,IAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAEd,IAAM,UAAA,GACX,CAAC,IAAA,EAAc,EAAA,KACf,CAAC,CAAA,KAAM;AACL,EAAA,IAAI,CAAA,KAAM,MAAM,OAAO,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AAA,IAAa,SAAS,gBAAA,CAAiB,MAAM,EAAE,MAAA,IAAU,CAAA,CAAA;AACrE,EAAA,MAAM,UAAA,GACJ,YAAA,CAAa,MAAA,GAAS,CAAA,GAClB,YAAA,GACA,sBACE,QAAA,CAAS,MAAA,CAAO,gBAAgB,CAAA,GAChC,EAAC;AACT,EAAA,OAAO,aAAa,UAAU,CAAA;AAChC;AAyBO,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,IAAA,KAA+B;AACtE,EAAA,MAAM,QAAQ,IAAA,IAAQ,QAAA;AACtB,EAAA,OAAO,IAAA,KAAS,EAAA,GAAA,CACX,IAAA,KAAS,MAAA,IACR,QAAA,CAAS,gBAAA,CAAiB,MAAM,CAAA,CAAE,MAAA,IAAU,CAAA,KAC5C,YAAA,CAAa,aAAA,CAAc,KAAK,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA,GAC5D,YAAA,CAAa,cAAA,CAAe,KAAA,EAAO,CAAC,IAAI,CAAC,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA;AACzE","file":"index.js","sourcesContent":["export type IndexMapper = (oldIndex: number) => number | null;\n\nexport const removeAt =\n (i: number): IndexMapper =>\n (n) =>\n n === i ? null : n > i ? n - 1 : n;\n\nexport const insertAt =\n (i: number): IndexMapper =>\n (n) =>\n n >= i ? n + 1 : n;\n\nexport const moveFromTo =\n (from: number, to: number): IndexMapper =>\n (n) => {\n if (n === from) return to;\n if (from < to && n > from && n <= to) return n - 1;\n if (from > to && n >= to && n < from) return n + 1;\n return n;\n };\n\nexport const swapIndices =\n (a: number, b: number): IndexMapper =>\n (n) =>\n n === a ? b : n === b ? a : n;\n\n// The new-index → old-index view of an op, materialized as an array (-1\n// marks a position with no old index: a freshly created row). Derived by\n// INVERTING the op's IndexMapper — the same mapper trusted to re-key\n// errors/touched — so the value transform and the id mapping cannot\n// diverge. Consumed by the array-op log for row-id derivation.\nexport const invertMapper = (\n mapper: IndexMapper,\n oldLength: number,\n newLength: number,\n): readonly number[] => {\n const oldByNew = new Map(\n Array.from({ length: oldLength }, (_, oldIndex) => oldIndex).flatMap(\n (oldIndex) => {\n const newIndex = mapper(oldIndex);\n return newIndex === null ? [] : ([[newIndex, oldIndex]] as const);\n },\n ),\n );\n return Array.from(\n { length: newLength },\n (_, newIndex) => oldByNew.get(newIndex) ?? -1,\n );\n};\n\nconst indexAndTail = (\n rest: string,\n): Readonly<{ index: number; tail: string }> | null => {\n const dotIdx = rest.indexOf(\".\");\n const idxStr = dotIdx === -1 ? rest : rest.slice(0, dotIdx);\n const tail = dotIdx === -1 ? \"\" : rest.slice(dotIdx);\n const idx = Number(idxStr);\n if (!Number.isInteger(idx) || idx < 0 || String(idx) !== idxStr) return null;\n return { index: idx, tail };\n};\n\nexport const reKeyByArrayPath = <V>(\n map: Readonly<Record<string, V>>,\n basePath: string,\n mapper: IndexMapper,\n): Readonly<Record<string, V>> => {\n const prefix = basePath === \"\" ? \"\" : `${basePath}.`;\n return Object.fromEntries(\n Object.entries(map).flatMap(([key, value]) => {\n if (key === basePath) return [[key, value]];\n if (!key.startsWith(prefix)) return [[key, value]];\n const parsed = indexAndTail(key.slice(prefix.length));\n if (parsed === null) return [[key, value]];\n const next = mapper(parsed.index);\n if (next === null) return [];\n return [[`${prefix}${next}${parsed.tail}`, value]];\n }),\n );\n};\n","// A per-store, per-path log of recent array ops, recorded by the core's\n// applyArrayOp and replayed by useFieldArray's row-id derivation. The ops\n// carry the EXACT new→old index mapping, so id derivation never has to\n// guess which of two Object.is-equal rows an op removed or moved — the one\n// case value-based reconciliation cannot decide. A sanctioned mutable-ref\n// cache (like the core's subschemaCache): the log is derived bookkeeping,\n// never part of form state, and the WeakMap releases it with the store.\n\nexport type ArrayOpRecord = Readonly<{\n // The array value the op consumed / produced — reference identity is the\n // chain link: a consumer replays from the record whose `from` matches its\n // last-seen array, on through consecutive records, until it reaches the\n // live array (or gives up and falls back to value reconciliation).\n from: readonly unknown[];\n to: readonly unknown[];\n // newIndex → oldIndex; -1 marks a freshly created row.\n mapping: readonly number[];\n}>;\n\n// Bounded two ways, both loss-limited: a path's record COUNT is capped by\n// COMPOSING its two oldest records into one when consecutive (op mappings\n// compose, so an arbitrarily long run of consecutive ops stays fully\n// replayable in OP_LOG_LIMIT records; only a chain already broken by an\n// external write drops its dead head) — and a store accumulating more than\n// MAX_LOG_PATHS distinct array paths (dynamic row paths on a long-lived\n// singleton form) evicts its oldest path's records, degrading that path to\n// value reconciliation.\nconst OP_LOG_LIMIT = 16;\nconst MAX_LOG_PATHS = 256;\n\n// (second ∘ first): newIndex → the FIRST record's old index. A -1 anywhere\n// along the way stays -1 (the row was created inside the composed span).\nconst composeOps = (\n first: ArrayOpRecord,\n second: ArrayOpRecord,\n): ArrayOpRecord => ({\n from: first.from,\n to: second.to,\n mapping: second.mapping.map((mid) =>\n mid === -1 ? -1 : (first.mapping[mid] ?? -1),\n ),\n});\n\nconst logs = new WeakMap<object, Map<string, readonly ArrayOpRecord[]>>();\n\n// Cap a path's record count, composing the two oldest records when they are\n// consecutive (lossless) and dropping the dead head otherwise. The slice\n// work only happens on overflow — the common case appends untouched.\nconst boundOps = (\n ops: readonly ArrayOpRecord[],\n): readonly ArrayOpRecord[] => {\n const [head, second] = ops;\n if (ops.length <= OP_LOG_LIMIT || head === undefined || second === undefined) {\n return ops;\n }\n return head.to === second.from\n ? [composeOps(head, second), ...ops.slice(2)]\n : ops.slice(1);\n};\n\nexport const recordArrayOp = (\n store: object,\n path: string,\n record: ArrayOpRecord,\n): void => {\n const existing = logs.get(store);\n const byPath = existing ?? new Map<string, readonly ArrayOpRecord[]>();\n if (existing === undefined) logs.set(store, byPath);\n const bounded = boundOps([...(byPath.get(path) ?? []), record]);\n byPath.delete(path);\n byPath.set(path, bounded);\n if (byPath.size > MAX_LOG_PATHS) {\n const oldest = byPath.keys().next().value;\n if (oldest !== undefined) byPath.delete(oldest);\n }\n};\n\nexport const arrayOpsFor = (\n store: object,\n path: string,\n): readonly ArrayOpRecord[] => logs.get(store)?.get(path) ?? [];\n\n// Drop a path's records — called by the consumer after a walk consumed them\n// (the log is per-batch bookkeeping, spent once derived).\nexport const clearArrayOps = (store: object, path: string): void => {\n logs.get(store)?.delete(path);\n};\n\n// Drop the records of the written path and its DESCENDANTS — the paths\n// where a value write can reintroduce a previously-seen array reference\n// (the caller supplies the subtree's values; reset/restore reinstate stored\n// ones; an array op re-seats existing descendant arrays under new indices),\n// which stale records could falsely chain against. Ancestor paths are\n// deliberately KEPT: setAtPath always builds fresh spine arrays, so an\n// ancestor reference can never recur — and an ancestor's earlier records\n// are real history the id walk still replays, bridging the gap this write\n// created. \"\" (whole-values writes) clears all. `keepSelf` is for\n// applyArrayOp itself: the op's own path is exactly what it is about to\n// record, and its earlier same-batch records still chain.\nexport const clearArrayOpsUnder = (\n store: object,\n path: string,\n keepSelf = false,\n): void => {\n const byPath = logs.get(store);\n if (byPath === undefined) return;\n if (path === \"\") {\n byPath.clear();\n return;\n }\n const related = [...byPath.keys()].filter(\n (p) => (p === path && !keepSelf) || p.startsWith(`${path}.`),\n );\n related.forEach((p) => byPath.delete(p));\n};\n","import { z } from \"zod\";\nimport { type PathSegment, parsePath } from \"./path\";\nimport type { ErrorMap } from \"./types\";\n\nexport type SettledValidationResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type ValidationResult<TOutput> =\n | SettledValidationResult<TOutput>\n // Returned by the sync `validate()` when the schema needs async parsing:\n // the async pass has already been started and `promise` resolves with its\n // outcome.\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledValidationResult<TOutput>>;\n }>;\n\nexport type SettledFieldValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: readonly string[] }>;\n\nexport type FieldValidationResult =\n | SettledFieldValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldValidationResult>;\n }>;\n\n// The plural (validateFields) mirrors the singular's discriminated shape\n// instead of returning boolean | Promise<boolean>: a returned Promise is\n// truthy, so the old union let `if (form.validateFields(paths))` silently\n// pass a gate the moment the schema gained an async refinement. `errors`\n// carries only the entries within the requested paths' scope.\nexport type SettledFieldsValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type FieldsValidationResult =\n | SettledFieldsValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldsValidationResult>;\n }>;\n\nconst issuePathToFormPath = (path: readonly PropertyKey[]): string =>\n path\n .filter((segment): segment is string | number => typeof segment !== \"symbol\")\n .join(\".\");\n\ntype FlatIssue = Readonly<{ path: string; message: string }>;\n\n// A failing plain `z.union` produces a single `invalid_union` issue whose real\n// per-branch issues live in `issue.errors` with paths relative to the union's\n// position. Recurse into them (prefixed with the union's own path) so users\n// get field-level messages instead of one generic \"Invalid input\"; keep the\n// union's own message only when no branch supplies anything more specific.\nconst expandIssue = (\n issue: z.core.$ZodIssue,\n prefix: readonly PropertyKey[],\n): readonly FlatIssue[] => {\n const at = [...prefix, ...issue.path];\n if (issue.code === \"invalid_union\") {\n const nested = issue.errors.flatMap((branch) =>\n branch.flatMap((sub) => expandIssue(sub, at)),\n );\n if (nested.length > 0) return nested;\n }\n return [{ path: issuePathToFormPath(at), message: issue.message }];\n};\n\nexport const flattenIssues = (\n issues: readonly z.core.$ZodIssue[],\n): ErrorMap =>\n issues\n .flatMap((issue) => expandIssue(issue, []))\n .reduce<Record<string, readonly string[]>>((acc, { path, message }) => {\n // Union branches often repeat the same complaint; drop exact duplicates.\n // Own-key read: a plain `acc[path]` for an issue path of \"__proto__\"\n // (reachable via ctx.addIssue in a superRefine) walks the prototype\n // chain and returns Object.prototype, crashing `.includes` below. The\n // spread write is safe as-is — a computed key always defines an own\n // property.\n const existing =\n (Object.hasOwn(acc, path) ? acc[path] : undefined) ?? [];\n return existing.includes(message)\n ? acc\n : { ...acc, [path]: [...existing, message] };\n }, {});\n\nexport const validateSync = <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): SettledValidationResult<z.output<TSchema>> => {\n const result = schema.safeParse(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\nexport const validateAsync = async <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): Promise<SettledValidationResult<z.output<TSchema>>> => {\n const result = await schema.safeParseAsync(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\n// The message fallback covers the dual-package hazard: with two zod copies\n// loaded, the thrown error is not an instance of *this* copy's class.\nexport const isAsyncRequiredError = (e: unknown): boolean =>\n e instanceof z.core.$ZodAsyncError ||\n (e instanceof Error &&\n /Encountered Promise during synchronous parse/i.test(e.message));\n\n// True when `key` is `path` itself or a descendant (\"a.b\" under \"a\"). The\n// root \"\" matches only the \"\" key — whole-form scope is never implicit;\n// call sites that want it (validateField(\"\"), focusFirstError's fallback)\n// handle the root explicitly instead of inheriting a wildcard.\nexport const isPathOrChild = (key: string, path: string): boolean =>\n key === path || key.startsWith(`${path}.`);\n\n// Re-key an error map produced by parsing a field's subschema so its keys are\n// absolute form paths (\"\" becomes the field path itself).\nexport const prefixErrorKeys = (errors: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? errors\n : Object.fromEntries(\n Object.entries(errors).map(([k, v]) => [\n k === \"\" ? path : `${path}.${k}`,\n v,\n ]),\n );\n\n// The empty representation a field's schema accepts: undefined when the\n// field is optional (or the wrappers are unrecognized — undefined is the\n// library-wide default empty), null when it is nullable but not optional.\n// Lets a cleared input round-trip to a valid blank based on what the schema\n// states rather than guessing from runtime values.\nexport const emptyValueForSchema = (schema: z.ZodType): null | undefined => {\n const walk = (s: z.ZodType, sawNullable: boolean): null | undefined => {\n if (s instanceof z.ZodOptional) return undefined;\n if (s instanceof z.ZodNullable) {\n return walk(s.unwrap() as z.ZodType, true);\n }\n return sawNullable ? null : undefined;\n };\n return walk(schema, false);\n};\n\n// Whether the schema ACCEPTS its own emptyValue as input — the judgment the\n// string-shaped bindings need before writing it on a cleared input. An\n// optional field takes undefined, a nullable one takes null, and a\n// defaulted/prefaulted one takes undefined too (the default fills it at\n// parse, so clearing reads as \"back to the default\"). A bare required field\n// does NOT: its emptyValue is undefined only as the library-wide fallback,\n// and writing that would trade a visible \"\" the schema can at least judge\n// for a hole it rejects — which is why text and select bindings keep \"\" for\n// non-clearable fields. The check is deliberately as shallow as\n// emptyValueForSchema's walk: a wrapper that hides the optionality from\n// emptyValue (readonly, catch, pipe) hides it here too, so the pair can\n// never disagree about whether the emptyValue is legal.\nexport const isClearableSchema = (schema: z.ZodType): boolean =>\n schema instanceof z.ZodOptional ||\n schema instanceof z.ZodNullable ||\n schema instanceof z.ZodDefault ||\n schema instanceof z.ZodPrefault;\n\n// One unwrap step for the lax structural walk below: wrappers that are\n// transparent to a path (optional/nullable/default/readonly/catch/pipe/...)\n// yield their inner schema; anything else returns null and is judged as-is.\nconst unwrapForWalk = (s: z.ZodType): z.ZodType | null => {\n if (s instanceof z.ZodOptional || s instanceof z.ZodNullable) {\n return s.unwrap() as z.ZodType;\n }\n if (\n s instanceof z.ZodDefault ||\n s instanceof z.ZodPrefault ||\n s instanceof z.ZodCatch ||\n s instanceof z.ZodReadonly ||\n s instanceof z.ZodNonOptional\n ) {\n return s.def.innerType as z.ZodType;\n }\n // Form values are z.input, so a pipe is traversed through its input side.\n if (s instanceof z.ZodPipe) return s.def.in as z.ZodType;\n return null;\n};\n\n// Leaves that provably have no children: remaining path segments under one of\n// these cannot exist in the schema.\nconst isLeafSchema = (s: z.ZodType): boolean =>\n s instanceof z.ZodString ||\n s instanceof z.ZodNumber ||\n s instanceof z.ZodBoolean ||\n s instanceof z.ZodBigInt ||\n s instanceof z.ZodDate ||\n s instanceof z.ZodEnum ||\n s instanceof z.ZodLiteral ||\n s instanceof z.ZodNull ||\n s instanceof z.ZodUndefined ||\n s instanceof z.ZodVoid ||\n s instanceof z.ZodNaN ||\n s instanceof z.ZodSymbol;\n\n// Every unwrap and every consumed segment costs one step — generous for any\n// real path, but it bounds pathological wrapper towers.\nconst SCHEMA_WALK_BUDGET = 64;\n\n// Lax structural check: can `path` possibly exist under `schema`? Used to\n// warn when validateField targets a path the schema cannot contain (which\n// would otherwise silently validate as always-valid). Deliberately biased\n// toward \"yes\": objects answer from their shape (a catchall/loose object\n// accepts any key), arrays accept any numeric index into their element, and\n// everything too dynamic to judge — records, maps, tuples, unions,\n// intersections, lazies, any/unknown, unrecognized nodes — answers true so\n// the warning can never be a false positive. Only a provable miss (a key\n// absent from a closed object shape, a string segment into an array, or\n// segments remaining under a scalar leaf) answers false.\nexport const schemaHasPath = (schema: z.ZodType, path: string): boolean => {\n const walk = (\n s: z.ZodType,\n segments: readonly PathSegment[],\n budget: number,\n ): boolean => {\n if (budget <= 0) return true;\n const inner = unwrapForWalk(s);\n if (inner !== null) return walk(inner, segments, budget - 1);\n const [head, ...rest] = segments;\n if (head === undefined) return true;\n if (s instanceof z.ZodObject) {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = s.shape;\n // Own-key read: a bare index would walk the prototype chain, so\n // \"constructor\" would resolve to Object's constructor and read as a\n // declared key of the shape.\n const child = Object.hasOwn(shape, String(head))\n ? shape[String(head)]\n : undefined;\n if (child !== undefined) return walk(child, rest, budget - 1);\n // A loose/catchall object accepts keys beyond the shape (a ZodNever\n // catchall — strictObject — rejects them like a closed shape does).\n const catchall = s.def.catchall;\n return catchall !== undefined && !(catchall instanceof z.ZodNever);\n }\n if (s instanceof z.ZodArray) {\n return typeof head === \"number\"\n ? walk(s.element as z.ZodType, rest, budget - 1)\n : false;\n }\n return !isLeafSchema(s);\n };\n return walk(schema, parsePath(path), SCHEMA_WALK_BUDGET);\n};\n\nconst hasChecks = (s: z.ZodType): boolean => {\n const checks = (s.def as Readonly<{ checks?: readonly unknown[] }>).checks;\n return checks !== undefined && checks.length > 0;\n};\n\n// Walk the schema along a dot path so field-level validation can parse just\n// that field instead of the whole form. Returns null (meaning: fall back to a\n// full-form parse) unless every *traversed* level is a plain ZodObject or\n// ZodArray with no checks — a refinement on a traversed level could target\n// this field's path, so extraction would miss or fail to clear its errors.\n// Wrappers (optional/nullable/default/pipe/union/record/...) also bail: their\n// error keying differs from a direct parse of the inner value. The leaf itself\n// may carry any checks — they belong to the field.\nexport const fieldSchemaAtPath = (\n schema: z.ZodType,\n path: string,\n): z.ZodType | null =>\n parsePath(path).reduce<z.ZodType | null>((current, segment: PathSegment) => {\n if (current === null || hasChecks(current)) return null;\n if (current instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> =\n current.shape;\n // Own-key read, like every other walk in the library: a bare index\n // resolves \"constructor\"/\"__proto__\" through the prototype chain to\n // a non-schema value, which then CRASHES the reduce (def.checks on a\n // function; safeParse on Object.prototype) — and the subschema cache\n // would keep the poisoned entry. Runtime-built paths (server error\n // fields mapped onto validateField) are the realistic entry point.\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (current instanceof z.ZodArray && typeof segment === \"number\") {\n return current.element as z.ZodType;\n }\n return null;\n }, schema);\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { createStore } from \"zustand/vanilla\";\nimport { devtools } from \"zustand/middleware\";\nimport {\n type IndexMapper,\n insertAt,\n invertMapper,\n moveFromTo,\n reKeyByArrayPath,\n removeAt,\n swapIndices,\n} from \"./array\";\nimport { clearArrayOpsUnder, recordArrayOp } from \"./arrayOpLog\";\nimport { isFieldDirty, isPlainObject, valuesEqual } from \"./equality\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n IsUnion,\n PathDepth,\n} from \"./fieldPath\";\nimport type { ValidationMode } from \"./mode\";\nimport { getAtPath, hasOwnSlot, setAtPath, slotAtPath } from \"./path\";\nimport type { BoolMap, ErrorMap, FormState } from \"./types\";\nimport {\n type FieldValidationResult,\n type FieldsValidationResult,\n type SettledFieldValidationResult,\n type SettledFieldsValidationResult,\n type SettledValidationResult,\n type ValidationResult,\n fieldSchemaAtPath,\n isAsyncRequiredError,\n isPathOrChild,\n prefixErrorKeys,\n schemaHasPath,\n validateAsync,\n validateSync,\n} from \"./validation\";\n\nexport type ReadonlyStoreApi<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type CreateFormOptions<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n initialValues: z.input<TSchema>;\n // TYPE-LEVEL ONLY: the typed-path depth budget for this form, in SEGMENTS\n // (default 9). The runtime ignores it entirely — every path API already\n // walks any depth — it only widens (or narrows) the FieldPath union the\n // form's typed surface is checked against. Raising it is a deliberate\n // TypeScript compile-time trade: the union's size grows with every level\n // the type recurses into, and every path-taking call pays for it in the\n // editor. Reach for it when one deep store backs many forms (a global\n // store whose leaves sit past 9 segments); must be a number LITERAL\n // (e.g. `pathDepth: 12`) so the budget stays a compile-time constant.\n // The `PathDepth` constraint (0-25, the Prev table's range) makes an\n // out-of-range literal or a widened `number` variable a compile error at\n // the call site. The intersection additionally rejects a UNION depth\n // (`cond ? 12 : 9` infers D = 9 | 12, a budget assignable to neither\n // Form<S, 9> nor Form<S, 12>): for a single literal the extra operand is\n // `unknown` and the type stays `D`, keeping literal inference intact; for\n // a union it becomes `never`, so the value can't satisfy the property and\n // the call errors instead of minting an unusable Form type.\n pathDepth?: D & (IsUnion<D> extends true ? never : unknown);\n mode?: ValidationMode;\n reValidateMode?: ValidationMode;\n // Run a full validation pass at creation so the error map (and flags derived\n // from it, like `useIsValid`) reflect the initial values immediately rather\n // than reading as error-free until the first blur/change/submit. Async\n // schemas validate in the background. Note this surfaces errors for untouched\n // fields right away — gate error display on `touched` if that's not wanted.\n validateOnMount?: boolean;\n // Connect the form's store to the Redux DevTools extension (zustand's\n // devtools middleware), named so multiple forms are distinguishable:\n // `devtools: \"checkout\"` shows a \"checkout\" instance with every state\n // write inspectable and time-travelable. `true` uses \"formstand\". Off by\n // default; when the extension isn't installed the middleware is inert.\n devtools?: boolean | string;\n}>;\n\nexport type SubmitHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n) => void | Promise<void>;\n\nexport type InvalidSubmitHandler = (errors: ErrorMap) => void;\n\nexport type SubmitOptions = Readonly<{\n force?: boolean;\n // Called when onValid throws or rejects (the \"error\" SubmitResult) — the\n // save-failure hook, mirroring onInvalid for the validation side. The\n // result still resolves {kind: \"error\"}, so imperative submit() callers\n // can keep switching on it instead.\n onError?: (error: unknown) => void;\n}>;\n\n// \"valid\": validation passed and onValid ran to completion. \"invalid\":\n// validation failed (onInvalid ran; errors written and their fields marked\n// touched, unless the values changed while validation was in flight — see\n// submit). \"skipped\": another submit was already in flight and force wasn't\n// set. \"error\": onValid threw or rejected — submit resolves with the thrown\n// value instead of rejecting, so handleSubmit used as an event handler never\n// produces an unhandled rejection. No error state is written for this kind;\n// surface the failure yourself (e.g. via setError).\nexport type SubmitResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>\n | Readonly<{ kind: \"skipped\" }>\n | Readonly<{ kind: \"error\"; error: unknown }>;\n\ntype ArrayItemOf<T> = T extends readonly (infer U)[] ? U : never;\n\n// Root-level errors (schema-wide .refine) live at the \"\" key.\ntype ErrorPath<TValues, D extends PathDepth = DefaultPathDepth> =\n | FieldPath<TValues, D>\n | \"\";\n\n// No keepDirty: per-field dirtiness is derived from values vs initialValues,\n// and reset makes those equal by definition — a kept dirty map would say\n// \"dirty\" while every field-level read says \"clean\".\nexport type ResetOptions = Readonly<{\n keepErrors?: boolean;\n keepTouched?: boolean;\n keepSubmitCount?: boolean;\n}>;\n\nexport type FieldSnapshot<TValue> = Readonly<{\n value: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\nconst shallowFieldEqual = <TValue>(\n a: FieldSnapshot<TValue>,\n b: FieldSnapshot<TValue>,\n): boolean =>\n Object.is(a.value, b.value) &&\n a.error === b.error &&\n a.touched === b.touched &&\n a.dirty === b.dirty &&\n a.isValidating === b.isValidating;\n\nexport type Form<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n // Type-level marker only — never present at runtime. It carries the form's\n // typed-path depth budget (createForm's `pathDepth`, default 9) in a\n // directly-inferable position so the React hooks' `Form<TSchema, D>`\n // parameters recover D from the form argument (inferring it out of the\n // FieldPath instantiations in the method types below is not something TS\n // can do). It also makes the budget part of the form's identity:\n // Form<S, 12> is deliberately not assignable to Form<S, 9>.\n \"~pathDepth\"?: D;\n schema: TSchema;\n store: ReadonlyStoreApi<FormState<z.input<TSchema>>>;\n getState: () => FormState<z.input<TSchema>>;\n subscribe: (\n listener: (\n state: FormState<z.input<TSchema>>,\n prev: FormState<z.input<TSchema>>,\n ) => void,\n ) => () => void;\n getField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldValue<z.input<TSchema>, P>;\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => () => void;\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => () => void;\n // Watches THE WHOLE values object — the name is watchValue + \"s\" as in\n // \"all the values\", not \"watchValue over many paths\". Fires whenever any\n // value changes (reference-compared). A multi-path watcher, if one ever\n // ships, would be a new API rather than a change to this one.\n watchValues: (\n listener: (\n values: z.input<TSchema>,\n previous: z.input<TSchema>,\n ) => void,\n ) => () => void;\n setValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n value: FieldValue<z.input<TSchema>, P>,\n ) => void;\n setValues: (next: z.input<TSchema>) => void;\n setTouched: (path: FieldPath<z.input<TSchema>, D>, touched?: boolean) => void;\n setSubmitting: (value: boolean) => void;\n setMode: (mode: ValidationMode) => void;\n setReValidateMode: (mode: ValidationMode) => void;\n setError: (\n path: ErrorPath<z.input<TSchema>, D>,\n errors: string | readonly string[],\n ) => void;\n setErrors: (errors: ErrorMap) => void;\n // The merge-many sibling of setError: server responses arrive as a MAP\n // of runtime-keyed field errors, and mapping them one setError at a time\n // forced a typed-path cast per call (the docs' own examples did), while\n // setErrors REPLACES the whole channel and cannot be used incrementally.\n // The server channel is inherently runtime-keyed, so this takes the map\n // as-is; an empty array removes its key, like setError.\n addErrors: (errors: ErrorMap) => void;\n clearErrors: (path?: ErrorPath<z.input<TSchema>, D>) => void;\n // The patch type omits `errors`: the merged map is derived from\n // schemaErrors/serverErrors, so writing it directly is unrepresentable for\n // TS callers (plain-JS writes are ignored with a warning).\n updateState: (\n updater: (\n state: FormState<z.input<TSchema>>,\n ) => Partial<Omit<FormState<z.input<TSchema>>, \"errors\">>,\n ) => void;\n reset: (\n nextInitial?: Partial<z.input<TSchema>>,\n options?: ResetOptions,\n ) => void;\n // Reset one field to its initial value, clearing its (and its descendants')\n // dirty/touched/error state.\n resetField: (path: FieldPath<z.input<TSchema>, D>) => void;\n adoptValues: (values: z.input<TSchema>) => void;\n // One-shot read of a field's full slice (value/error/touched/dirty/\n // isValidating) — the imperative sibling of useField's state.\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldSnapshot<FieldValue<z.input<TSchema>, P>>;\n validate: () => ValidationResult<z.output<TSchema>>;\n validateField: (path: ErrorPath<z.input<TSchema>, D>) => FieldValidationResult;\n // Mirrors validateField's discriminated result — \"pending\" (carrying the\n // already-started async pass's promise) when the schema needs async\n // parsing. A bare boolean | Promise<boolean> union would let a truthy\n // in-flight Promise silently pass `if (form.validateFields(...))` gates.\n validateFields: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => FieldsValidationResult;\n // Settled result types, deliberately: an AWAITED async pass can never\n // resolve \"pending\" (the promise IS the pending state), and the wider\n // union forced every exhaustive switch to carry a dead case — against\n // this codebase's own no-default-arm ethos. validateFieldsAsync below\n // was always typed this way; these two now match.\n validateAsync: () => Promise<SettledValidationResult<z.output<TSchema>>>;\n validateFieldAsync: (\n path: ErrorPath<z.input<TSchema>, D>,\n ) => Promise<SettledFieldValidationResult>;\n validateFieldsAsync: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => Promise<SettledFieldsValidationResult>;\n submit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => Promise<SubmitResult<z.output<TSchema>>>;\n arrayPush: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayRemove: (path: FieldPath<z.input<TSchema>, D>, index: number) => void;\n arrayInsert: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n index: number,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayMove: (\n path: FieldPath<z.input<TSchema>, D>,\n from: number,\n to: number,\n ) => void;\n arraySwap: (path: FieldPath<z.input<TSchema>, D>, a: number, b: number) => void;\n handleSubmit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => (event?: {\n preventDefault: () => void;\n }) => Promise<SubmitResult<z.output<TSchema>>>;\n diff: () => Readonly<Record<string, unknown>>;\n dirtyFields: () => readonly string[];\n snapshot: () => FormState<z.input<TSchema>>;\n restore: (snapshot: FormState<z.input<TSchema>>) => void;\n}>;\n\nconst emptyErrors = {} as ErrorMap;\nconst emptyBools = {} as BoolMap;\n\nconst identityMapper: IndexMapper = (n) => n;\n\nconst omitKey = <V>(\n map: Readonly<Record<string, V>>,\n key: string,\n): Readonly<Record<string, V>> =>\n Object.fromEntries(Object.entries(map).filter(([k]) => k !== key));\n\nconst inScopeOfAny = (key: string, paths: readonly string[]): boolean =>\n paths.some((p) => isPathOrChild(key, p));\n\n// Drop every entry keyed at or under any of `paths` (\"items\" covers\n// \"items.0.name\") — the shared scope filter for the path-keyed maps. Returns\n// the input map unchanged when nothing is in scope, so identity-based\n// subscribers don't re-fire.\nconst omitScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => !inScopeOfAny(k, paths));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\nconst pickScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> =>\n Object.fromEntries(\n Object.entries(map).filter(([k]) => inScopeOfAny(k, paths)),\n );\n\n// Replace the slice of `prev` at or under `paths` with `scoped` (whose keys\n// must already be within scope).\nconst mergeScopedErrors = (\n prev: ErrorMap,\n scoped: ErrorMap,\n paths: readonly string[],\n): ErrorMap => ({ ...omitScope(prev, paths), ...scoped });\n\n// Drop entries at `path` itself or an ancestor of it (\"a\" over \"a.b\"). The\n// root \"\" entry is an ancestor of every path, so any value write releases it\n// — a value write below a container stales the container-level server\n// verdict too, per the documented release contract.\nconst releaseAncestorEntries = <V>(\n map: Readonly<Record<string, V>>,\n path: string,\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => k !== \"\" && !isPathOrChild(path, k));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\n// Minimal divergent paths between values and initialValues: recurse through\n// plain objects, report anything else (scalars, arrays, type mismatches) at\n// its own path — arrays report their base path, and a divergent non-record\n// root reports \"\". This is the derived source for diff()/dirtyFields(); the\n// boolean per-field question is isFieldDirty.\nconst dirtyPathsOf = (\n values: unknown,\n initial: unknown,\n prefix: string,\n): readonly string[] => {\n if (Object.is(values, initial)) return [];\n if (isPlainObject(values) && isPlainObject(initial)) {\n // One structural recursion: the deep compare runs only at leaf/array\n // boundaries below, never per ancestor level — otherwise every node is\n // re-deep-compared once per level above it (O(n × depth) for diff()).\n const keys = new Set([...Object.keys(values), ...Object.keys(initial)]);\n const childPaths = [...keys].flatMap((k) =>\n dirtyPathsOf(\n values[k],\n initial[k],\n prefix === \"\" ? k : `${prefix}.${k}`,\n ),\n );\n if (childPaths.length > 0) return childPaths;\n // Every shared key compared equal, so the key SETS decide: a mismatch\n // where the extra key holds undefined ({} vs { nickname: undefined })\n // reports the object itself, keeping diff()/dirtyFields() non-empty\n // whenever isFieldDirty/useIsDirty say dirty (valuesEqual's own rule).\n const sameKeySet =\n Object.keys(values).length === Object.keys(initial).length &&\n Object.keys(values).every((k) => Object.hasOwn(initial, k));\n return sameKeySet ? [] : [prefix];\n }\n return valuesEqual(values, initial) ? [] : [prefix];\n};\n\n// Key for the whole-form async validation's ownership token (internal —\n// form-level in-flight state lives in FormState.isValidatingForm).\nconst FORM_SEQ_KEY = \"__form__\";\n\n// Key for submit's ownership token: reset()/adoptValues() clear the token\n// map, so an in-flight submit notices the form was rebased under it even\n// when the values reference is unchanged (a bare reset() on a pristine form\n// restores the same initialValues reference).\nconst SUBMIT_SEQ_KEY = \"__submit__\";\n\nconst stringArraysEqual = (\n a: readonly string[],\n b: readonly string[],\n): boolean => a === b || (a.length === b.length && a.every((v, i) => v === b[i]));\n\n// Preserve the previous array reference for entries whose messages didn't\n// change (and the previous map itself when nothing changed at all), so field\n// subscriptions comparing errors by identity don't re-fire on every pass.\nconst reuseErrorRefs = (next: ErrorMap, prev: ErrorMap): ErrorMap => {\n if (next === prev) return prev;\n const entries = Object.entries(next).map(([k, v]) => {\n const old = prev[k];\n return [\n k,\n old !== undefined && stringArraysEqual(old, v) ? old : v,\n ] as const;\n });\n const sameShape =\n entries.length === Object.keys(prev).length &&\n entries.every(([k, v]) => prev[k] === v);\n return sameShape ? prev : Object.fromEntries(entries);\n};\n\n// Shape a parse result into an error map scoped to `path`: sub-schema results\n// re-key to absolute form paths; full-form results filter to the path's scope,\n// except the root \"\" whose scope is explicitly the whole form.\nconst scopeSettledResult = (\n result: SettledValidationResult<unknown>,\n path: string,\n viaSubschema: boolean,\n): ErrorMap =>\n result.kind !== \"invalid\"\n ? emptyErrors\n : viaSubschema\n ? prefixErrorKeys(result.errors, path)\n : path === \"\"\n ? result.errors\n : pickScope(result.errors, [path]);\n\n// The one merge rule between the two error channels: the schema's message\n// wins at a key (it re-judged the same value the server did), server entries\n// show where the schema is silent. Returns the schema map's identity when\n// the server channel adds nothing.\nconst mergeErrorChannels = (schema: ErrorMap, server: ErrorMap): ErrorMap => {\n // Own-key check, not `schema[k] === undefined`: for a runtime-built key\n // like \"__proto__\" the bare read returns Object.prototype (never\n // undefined), which would silently drop the server entry from the merge.\n const extra = Object.entries(server).filter(\n ([k]) => !Object.hasOwn(schema, k),\n );\n return extra.length === 0\n ? schema\n : { ...schema, ...Object.fromEntries(extra) };\n};\n\ntype ErrorChannels = Readonly<{\n errors: ErrorMap;\n schemaErrors: ErrorMap;\n serverErrors: ErrorMap;\n}>;\n\n// The one way error state is written: patch a channel (or both) and the\n// user-visible `errors` map is re-derived, reusing per-key refs so\n// identity-based subscribers don't re-fire.\nconst errorChannels = (\n state: ErrorChannels,\n patch: Readonly<{ schemaErrors?: ErrorMap; serverErrors?: ErrorMap }>,\n): ErrorChannels => {\n const schemaErrors = patch.schemaErrors ?? state.schemaErrors;\n const serverErrors = patch.serverErrors ?? state.serverErrors;\n // Unchanged channels mean an unchanged merge — skip it, so no-op writes\n // (every keystroke with an empty server channel) don't rescan the map.\n if (\n schemaErrors === state.schemaErrors &&\n serverErrors === state.serverErrors\n ) {\n return { errors: state.errors, schemaErrors, serverErrors };\n }\n return {\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n state.errors,\n ),\n };\n};\n\n// The release contract for a value write at `path`: server entries at the\n// path or below go (that subtree was replaced), entries at ancestors go too\n// (container verdicts are stale), and a runtime \"\" path (the imperative\n// surface is string-typed) releases everything.\nconst releaseSpine = (server: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? emptyErrors\n : releaseAncestorEntries(omitScope(server, [path]), path);\n\n// A bulk values write releases only the verdicts whose value slice actually\n// changed — a server error on an untouched field survives a setValues that\n// rewrites its siblings. The \"\" entry compares the whole values object, so\n// any change releases a form-level verdict.\nconst releaseChangedSlices = (\n server: ErrorMap,\n prevValues: unknown,\n nextValues: unknown,\n): ErrorMap => {\n const entries = Object.entries(server);\n const kept = entries.filter(([k]) =>\n valuesEqual(getAtPath(prevValues, k), getAtPath(nextValues, k)),\n );\n return kept.length === entries.length ? server : Object.fromEntries(kept);\n};\n\n// D infers as a LITERAL from `options.pathDepth` (the `D extends PathDepth`\n// constraint is a union of literals, so inference stays literal); when the\n// option is omitted, D falls back to the default budget of 9. An\n// out-of-range literal (26, -1) or a `number`-typed variable fails the\n// constraint here, at the call site.\nexport const createForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n): Form<TSchema, D> => {\n type Values = z.input<TSchema>;\n\n const initialMode: ValidationMode = options.mode ?? \"onBlur\";\n const initialReValidateMode: ValidationMode =\n options.reValidateMode ?? \"onChange\";\n\n const initial: FormState<Values> = {\n values: options.initialValues,\n initialValues: options.initialValues,\n errors: emptyErrors,\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n touched: emptyBools,\n isSubmitting: false,\n submitCount: 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n mode: initialMode,\n reValidateMode: initialReValidateMode,\n };\n\n // The devtools middleware is opt-in and otherwise absent — a plain store\n // has zero overhead. `enabled` stays true when opted in even in\n // production builds: opting in IS the signal, and without the browser\n // extension the middleware is inert anyway.\n const store =\n options.devtools === undefined || options.devtools === false\n ? createStore<FormState<Values>>(() => initial)\n : createStore<FormState<Values>>()(\n devtools(() => initial, {\n name:\n typeof options.devtools === \"string\"\n ? options.devtools\n : \"formstand\",\n // Non-production only, matching zustand's own devtools default:\n // opting in during development must NOT stream every keystroke to\n // an end user who happens to have the extension installed, where\n // a module-singleton form's unbounded time-travel history is a\n // real memory + serialization cost. Guarded for environments\n // without process (a bundler defines NODE_ENV in real dev).\n enabled:\n typeof process !== \"undefined\" &&\n process.env?.[\"NODE_ENV\"] !== \"production\",\n }),\n );\n\n // A full pass replaces the schema channel wholesale; the server channel is\n // untouched, which is the whole preservation story — a background pass\n // can't wipe a server verdict because it never writes that channel.\n const commitFullPass = (\n state: FormState<Values>,\n next: ErrorMap,\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(next, state.schemaErrors),\n });\n\n const validate = (): ValidationResult<z.output<TSchema>> => {\n if (asyncScopes.has(\"\")) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n try {\n const result = validateSyncLatched(\"\", schema, store.getState().values);\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n }));\n return result;\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n throw e;\n }\n };\n\n const validateFields = (\n paths: readonly string[],\n ): FieldsValidationResult => {\n if (paths.length === 0) return { kind: \"valid\" };\n // A \"\" path means whole-form scope (only reachable past the FieldPath\n // type, e.g. runtime-built path lists): delegate to the full pass so\n // manual errors are preserved, mirroring validateField(\"\").\n if (paths.some((p) => p === \"\")) {\n const result = validate();\n return result.kind === \"pending\"\n ? { kind: \"pending\", promise: result.promise.then(settledFormResult) }\n : settledFormResult(result);\n }\n const values = store.getState().values;\n // Fast path: when every requested path extracts a subschema, parse\n // just those slots instead of the whole form (a wizard step on a\n // 200-field schema stops paying for the other 190 fields per click).\n // This matches the full parse EXACTLY because extraction bailing is\n // what guards cross-field rules: fieldSchemaAtPath returns null when\n // any traversed level carries refinements or wrappers, so an\n // ancestor refine that could key errors into these paths forces the\n // full parse below.\n const scopes = paths.map((path) => ({\n path,\n scope: fieldScopeFor(path, values),\n }));\n const allViaSubschema = scopes.every(\n ({ scope }) =>\n scope.kind === \"skip\" ||\n (scope.kind === \"parse\" && scope.viaSubschema),\n );\n // Scopes already latched as async-requiring go straight to the async\n // pass. Skip scopes parse nothing and contribute no latch key — a\n // latched full-form \"\" must not divert a batch whose parses are all\n // sync subschemas (or nothing at all).\n const anyLatched = allViaSubschema\n ? scopes.some(\n ({ path, scope }) =>\n scope.kind === \"parse\" && asyncScopes.has(path),\n )\n : asyncScopes.has(\"\");\n if (anyLatched) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n try {\n if (allViaSubschema) {\n const merged = scopes.reduce<ErrorMap>(\n (acc, { path, scope }) =>\n scope.kind === \"skip\"\n ? acc\n : {\n ...acc,\n ...scopeSettledResult(\n validateSyncLatched(path, scope.schema, scope.value),\n path,\n true,\n ),\n },\n {},\n );\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, merged, paths),\n }));\n return settledFields(merged);\n }\n const result = validateSyncLatched(\"\", schema, values);\n const fullErrors =\n result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedErrors = pickScope(fullErrors, paths);\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, requestedErrors, paths),\n }));\n return settledFields(requestedErrors);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n throw e;\n }\n };\n\n // How to validate one field: parse its extracted subschema against the\n // slot's value when the path is reachable through check-free objects/\n // arrays, parse the full form filtered to the path's scope otherwise (so\n // cross-field refinements targeting the path still land), or skip when the\n // path addresses no slot (an out-of-range array index — parsing the\n // subschema against undefined would fabricate an error no full-form parse\n // produces). One \"parse\" variant carries the whole triple so the sync and\n // async passes cannot diverge arm-by-arm.\n type FieldScope =\n | Readonly<{ kind: \"skip\" }>\n | Readonly<{\n kind: \"parse\";\n schema: z.ZodType;\n value: unknown;\n viaSubschema: boolean;\n }>;\n\n // Scopes whose sync parse has hit an async refinement. The schema is fixed\n // for the form's lifetime, so once a scope requires async parsing it always\n // will — remember it and go straight to the async pass instead of paying a\n // doomed sync parse per validation (per keystroke in onChange mode). Keyed\n // like the parses themselves: \"\" for full-form, the path for subschema\n // parses. A sanctioned mutable-ref cache, like subschemaCache below.\n const asyncScopes = new Set<string>();\n\n // validateSync, latching the scope when its parse turns out to need async\n // — the caller still routes the rethrown error to the async pass.\n const validateSyncLatched = <S extends z.ZodType>(\n key: string,\n scopeSchema: S,\n value: z.input<S>,\n ): SettledValidationResult<z.output<S>> => {\n try {\n return validateSync(scopeSchema, value);\n } catch (e) {\n if (isAsyncRequiredError(e)) asyncScopes.add(key);\n throw e;\n }\n };\n\n // The subschema for a path is a pure function of the form's fixed schema —\n // cache it so per-keystroke validation doesn't re-walk the schema.\n const subschemaCache = new Map<string, z.ZodType | null>();\n const subschemaAt = (path: string): z.ZodType | null => {\n const cached = subschemaCache.get(path);\n if (cached !== undefined) return cached;\n const sub = fieldSchemaAtPath(schema, path);\n subschemaCache.set(path, sub);\n return sub;\n };\n\n // Field validation on a path the schema cannot contain silently returns\n // valid — easy to hit through the docs-sanctioned casts for runtime-built\n // paths. Warn once per path per form (a sanctioned mutable-ref cache, like\n // subschemaCache above: checked paths never need re-walking).\n const checkedSchemaPaths = new Set<string>();\n const warnMissingSchemaPath = (fn: string, path: string): void => {\n if (path === \"\" || checkedSchemaPaths.has(path)) return;\n checkedSchemaPaths.add(path);\n if (!schemaHasPath(schema, path)) {\n console.warn(\n `[formstand] ${fn}(\"${path}\"): path does not exist in the schema — result will always be valid.`,\n );\n }\n };\n\n const fieldScopeFor = (path: string, values: Values): FieldScope => {\n const sub = path === \"\" ? null : subschemaAt(path);\n if (sub === null) {\n return { kind: \"parse\", schema, value: values, viaSubschema: false };\n }\n const slot = slotAtPath(values, path);\n return slot.exists\n ? { kind: \"parse\", schema: sub, value: slot.value, viaSubschema: true }\n : { kind: \"skip\" };\n };\n\n const scopedFieldErrorsAsync = async (\n path: string,\n values: Values,\n ): Promise<ErrorMap> => {\n const scope = fieldScopeFor(path, values);\n return scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n await validateAsync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\n );\n };\n\n const fieldResult = (scoped: ErrorMap): SettledFieldValidationResult => {\n const messages = Object.values(scoped).flat();\n return messages.length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: messages };\n };\n\n // The plural counterpart: reports the scoped error MAP (entries under the\n // requested paths) rather than one field's flat message list. Every input\n // derives from flattenIssues, which never emits an empty message list, so\n // key presence alone decides validity.\n const settledFields = (scoped: ErrorMap): SettledFieldsValidationResult =>\n Object.keys(scoped).length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: scoped };\n\n // Whole-form (\"\" path) delegation, shared by the sync and async plural\n // passes so their scoping of a full-pass verdict cannot diverge.\n const settledFormResult = (\n result: SettledValidationResult<z.output<TSchema>>,\n ): SettledFieldsValidationResult =>\n settledFields(result.kind === \"invalid\" ? result.errors : emptyErrors);\n\n // The commit rule for any scoped validation: replace the schema-error\n // slice under `paths` and release the server verdicts there — a\n // validation explicitly targeting a scope supersedes the server's word on\n // it. Shared by the singular and plural, sync and async passes so the\n // supersede rule lives exactly once.\n const commitScopedErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n paths: readonly string[],\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(state.schemaErrors, scoped, paths),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, paths),\n });\n\n // How ONE field validation's scoped errors land. validateField(\"\") is a\n // whole-form pass, so it lands like validate() (server channel untouched).\n const commitFieldErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n path: string,\n ): ErrorChannels =>\n path === \"\"\n ? commitFullPass(state, scoped)\n : commitScopedErrors(state, scoped, [path]);\n\n const validateField = (path: string): FieldValidationResult => {\n warnMissingSchemaPath(\"validateField\", path);\n const scope = fieldScopeFor(path, store.getState().values);\n // Only PARSE scopes consult the latch — a skip scope parses nothing, so\n // it can never require async parsing and settles synchronously (below)\n // even while the full-form \"\" key is latched. The latch key mirrors\n // what the parse would run: the path for a subschema parse, the full\n // form (\"\") for a bailed extraction.\n if (\n scope.kind === \"parse\" &&\n asyncScopes.has(scope.viaSubschema ? path : \"\")\n ) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n try {\n const scoped =\n scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n validateSyncLatched(\n scope.viaSubschema ? path : \"\",\n scope.schema,\n scope.value,\n ),\n path,\n scope.viaSubschema,\n );\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, scoped, path),\n }));\n return fieldResult(scoped);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n throw e;\n }\n };\n\n const snapshotField = (\n state: FormState<Values>,\n path: string,\n ): FieldSnapshot<unknown> => {\n const value = getAtPath(state.values, path);\n return {\n value,\n error: state.errors[path],\n touched: state.touched[path] ?? false,\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: state.isValidating[path] ?? false,\n };\n };\n\n // Ownership tokens for in-flight async passes (a sanctioned mutable-ref\n // cache, like the subscription refs). Tokens are unique by construction —\n // each claim mints a fresh Symbol — so cleared or reissued keys can never\n // collide with a token an in-flight pass still holds.\n const sequences = new Map<string, symbol>();\n\n const claimPass = (key: string): symbol => {\n const pass = Symbol(key);\n sequences.set(key, pass);\n return pass;\n };\n\n const validateAsyncOnForm = async (): Promise<\n SettledValidationResult<z.output<TSchema>>\n > => {\n const pass = claimPass(FORM_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({ ...state, isValidatingForm: true }));\n\n const result = await validateAsync(schema, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(FORM_SEQ_KEY) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\n if (stillOwns) {\n store.setState((state) => ({ ...state, isValidatingForm: false }));\n }\n return result;\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n isValidatingForm: false,\n }));\n return result;\n };\n\n const validateFieldsAsync = async (\n paths: readonly string[],\n ): Promise<SettledFieldsValidationResult> => {\n if (paths.length === 0) return { kind: \"valid\" };\n // Whole-form scope: same delegation as validateFields (see above).\n if (paths.some((p) => p === \"\")) {\n return settledFormResult(await validateAsyncOnForm());\n }\n const passes = new Map(paths.map((p) => [p, claimPass(p)]));\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({\n ...state,\n isValidating: paths.reduce<Record<string, boolean>>(\n (acc, p) => ({ ...acc, [p]: true }),\n { ...state.isValidating },\n ),\n }));\n\n const result = await validateAsync(schema, valuesAtStart);\n const fullErrors = result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedErrors = pickScope(fullErrors, paths);\n const requested = settledFields(requestedErrors);\n\n const live = store.getState();\n const stillCurrent = paths.filter(\n (p) => sequences.get(p) === passes.get(p),\n );\n if (live.values !== valuesAtStart) {\n if (stillCurrent.length > 0) {\n store.setState((state) => ({\n ...state,\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n }\n return requested;\n }\n\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(\n state,\n pickScope(fullErrors, stillCurrent),\n stillCurrent,\n ),\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n\n return requested;\n };\n\n const validateFieldAsync = async (\n path: string,\n ): Promise<SettledFieldValidationResult> => {\n warnMissingSchemaPath(\"validateFieldAsync\", path);\n // The root \"\" is whole-form scope: delegate to the form-level pass so\n // the in-flight flag lands in isValidatingForm — the single slot for\n // whole-form validation — instead of booking an isValidating[\"\"] entry\n // no consumer watches.\n if (path === \"\") {\n const result = await validateAsyncOnForm();\n return fieldResult(\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n );\n }\n const pass = claimPass(path);\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({\n ...state,\n isValidating: { ...state.isValidating, [path]: true },\n }));\n\n const scoped = await scopedFieldErrorsAsync(path, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(path) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\n if (stillOwns) {\n store.setState((state) => ({\n ...state,\n isValidating: omitKey(state.isValidating, path),\n }));\n }\n return fieldResult(scoped);\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, scoped, path),\n isValidating: omitKey(state.isValidating, path),\n }));\n\n return fieldResult(scoped);\n };\n\n const applyArrayOp = (\n path: string,\n nextArray: (current: readonly unknown[]) => readonly unknown[],\n mapper: IndexMapper,\n // Validated against the current length before anything mutates — a bad\n // index (arrayRemove(path, -1)) would otherwise corrupt both the array\n // and the re-keyed error/touched maps.\n indexInBounds?: (length: number) => boolean,\n ): void => {\n const current = getAtPath(store.getState().values, path);\n // null passes like undefined: it is the canonical empty of a NULLABLE\n // array field (emptyValue), and the op item types are built on\n // NonNullable<FieldValue<...>> precisely so nullable/optional arrays\n // accept ops — refusing null made those calls typecheck and then\n // silently no-op at runtime. Both empties start the op from [].\n if (current !== undefined && current !== null && !Array.isArray(current)) {\n console.warn(\n `[formstand] array op on \"${path}\" but the value at that path is not an array (got ${typeof current}). Operation skipped.`,\n );\n return;\n }\n const length = Array.isArray(current) ? current.length : 0;\n if (indexInBounds !== undefined && !indexInBounds(length)) {\n console.warn(\n `[formstand] array op on \"${path}\" with an out-of-range or non-integer index (length ${length}). Operation skipped.`,\n );\n return;\n }\n const arr: readonly unknown[] = Array.isArray(current) ? current : [];\n const next = nextArray(arr);\n const written = setAtPath(store.getState().values, path, next);\n // The op rebuilds every ancestor's array (spine copy) and re-seats its\n // rows' descendant arrays under new indices — those paths' records no\n // longer describe the arrays now living there. The op's OWN path keeps\n // its records: earlier same-batch ops still chain.\n clearArrayOpsUnder(store, path, true);\n // Record BEFORE the write, from the exact references the write uses:\n // zustand notifies subscribers synchronously inside setState, so a\n // reentrant same-path write would otherwise interleave the log order\n // AND make a post-setState getState() read pair this op's mapping with\n // a `to` spanning two writes — a corrupt record that can replay to\n // wrong row ids. The mapping is the inverted IndexMapper — the same\n // mapper that re-keys errors/touched below, one source of truth.\n // Guards: an op on an absent slot (push into an undefined array) has no\n // prior reference to chain from, and a write setAtPath REFUSES (huge\n // index, non-plain ancestor) must not log a transition the store never\n // performed — value reconciliation covers both.\n if (Array.isArray(current) && getAtPath(written, path) === next) {\n recordArrayOp(store, path, {\n from: current,\n to: next,\n mapping: invertMapper(mapper, current.length, next.length),\n });\n }\n store.setState((state) => {\n return {\n ...state,\n values: written,\n ...errorChannels(state, {\n schemaErrors: reKeyByArrayPath(state.schemaErrors, path, mapper),\n // Server entries on rows follow their rows through the index\n // mapping — a verdict on \"items.1.name\" is still vouched for after\n // the op moves it to \"items.0.name\" (that row's value didn't\n // change). Entries at the array itself or an ancestor release: the\n // op changed that value.\n serverErrors: releaseAncestorEntries(\n reKeyByArrayPath(state.serverErrors, path, mapper),\n path,\n ),\n }),\n touched: reKeyByArrayPath(state.touched, path, mapper),\n // Drop (don't re-key) in-flight flags under the array: the op changes\n // `values`, so every pass they belong to fails its values-changed\n // guard and never commits — but each pass's cleanup omits its\n // ORIGINAL key, so a re-keyed entry would be orphaned and stick\n // forever. Dropped, the flag is gone now and the cleanup is a\n // harmless no-op.\n isValidating: omitScope(state.isValidating, [path]),\n };\n });\n };\n\n const inFlight: { count: number; baseline: boolean } = {\n count: 0,\n baseline: false,\n };\n\n const submit = async (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n submitOptions?: SubmitOptions,\n ): Promise<SubmitResult<z.output<TSchema>>> => {\n if (inFlight.count > 0 && submitOptions?.force !== true) {\n return { kind: \"skipped\" };\n }\n if (inFlight.count === 0) {\n inFlight.baseline = store.getState().isSubmitting;\n }\n inFlight.count += 1;\n store.setState((state) => ({\n ...state,\n isSubmitting: true,\n submitCount: state.submitCount + 1,\n }));\n\n try {\n const pass = claimPass(SUBMIT_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n const result = await validateAsync(schema, valuesAtStart);\n\n // Stale-commit contract (mirrors validateAsyncOnForm's guard): if the\n // values changed while validation was in flight (setValue/reset/\n // adoptValues), the verdict describes a snapshot the form no longer\n // holds — skip every state write (no error commit, no touched marks;\n // that state belongs to the new values). The ownership token catches\n // what the values reference can't: a bare reset() on a pristine form\n // restores the same values reference but clears the token map, and a\n // concurrent submit({ force: true }) re-claims the token — the LAST\n // submit owns the writes. The handlers still run and the result still\n // reports the snapshot's verdict, so callers decide what it means for\n // them.\n const stale =\n sequences.get(SUBMIT_SEQ_KEY) !== pass ||\n store.getState().values !== valuesAtStart;\n\n if (result.kind === \"invalid\") {\n if (!stale) {\n store.setState((state) => {\n const committed = commitFullPass(state, result.errors);\n return {\n ...state,\n ...committed,\n // Mark every errored field touched so touched-gated error UIs\n // show something after the canonical first failed submit. The\n // \"\" key (schema-level refine) has no field to touch.\n touched: {\n ...state.touched,\n ...Object.fromEntries(\n Object.keys(committed.errors)\n .filter((k) => k !== \"\")\n .map((k) => [k, true]),\n ),\n },\n };\n });\n }\n const merged = stale ? result.errors : store.getState().errors;\n try {\n onInvalid?.(merged);\n } catch (error) {\n // Same contract as a throwing onValid below: a failing caller\n // handler resolves as { kind: \"error\" }, never a rejection out of\n // a DOM event handler.\n return { kind: \"error\", error };\n }\n return { kind: \"invalid\", errors: merged };\n }\n\n if (!stale) {\n store.setState((state) => ({\n ...state,\n ...commitFullPass(state, emptyErrors),\n }));\n }\n try {\n await onValid(result.data);\n } catch (error) {\n // A throwing onValid is the caller's failure, not a validation\n // verdict: resolve with it (so handleSubmit-as-event-handler never\n // leaves an unhandled rejection) and write no error state.\n submitOptions?.onError?.(error);\n return { kind: \"error\", error };\n }\n return { kind: \"valid\", data: result.data };\n } finally {\n inFlight.count -= 1;\n if (inFlight.count === 0) {\n const baseline = inFlight.baseline;\n store.setState((state) => ({ ...state, isSubmitting: baseline }));\n }\n }\n };\n\n if (options.validateOnMount === true) {\n // Async schemas route themselves: validate() returns a \"pending\" result\n // whose background pass writes the error map when it settles.\n validate();\n }\n\n return Object.freeze({\n schema,\n store,\n getState: store.getState,\n subscribe: store.subscribe,\n getField: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n getAtPath(store.getState().values, path) as FieldValue<\n z.input<TSchema>,\n P\n >,\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n snapshotField(store.getState(), path) as FieldSnapshot<\n FieldValue<z.input<TSchema>, P>\n >,\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => {\n const ref: { current: FieldSnapshot<unknown> } = {\n current: snapshotField(store.getState(), path),\n };\n return store.subscribe((state) => {\n const next = snapshotField(state, path);\n if (!shallowFieldEqual(ref.current, next)) {\n ref.current = next;\n listener(next as FieldSnapshot<FieldValue<z.input<TSchema>, P>>);\n }\n });\n },\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => {\n const ref: { current: unknown } = {\n current: getAtPath(store.getState().values, path),\n };\n return store.subscribe((state) => {\n const next = getAtPath(state.values, path);\n if (!Object.is(ref.current, next)) {\n const prev = ref.current;\n ref.current = next;\n listener(\n next as FieldValue<z.input<TSchema>, P>,\n prev as FieldValue<z.input<TSchema>, P>,\n );\n }\n });\n },\n watchValues: (listener) => {\n const ref: { current: Values } = { current: store.getState().values };\n return store.subscribe((state) => {\n if (state.values !== ref.current) {\n const prev = ref.current;\n ref.current = state.values;\n listener(state.values, prev);\n }\n });\n },\n setValue: (path: string, value: unknown) => {\n // Identity guard: writing the value already at the path is a FULL\n // no-op — same state reference, no values rebuild, no dirty/error\n // recompute, no subscriber notifications. Without it, every no-op\n // write rebuilt the values spine, so useFormValues re-rendered and\n // watchValues/onValuesChange fired on nothing — and a two-way sync\n // that echoes values back (form A watches form B and vice versa)\n // recursed until the stack overflowed. Object.is matches the\n // library's other change detectors (watchValue, useStore); note it\n // also skips the server-error release and op-log clearing below —\n // deliberately, since no value changed. One carve-out: an\n // `undefined` write only no-ops when the slot actually EXISTS —\n // writing undefined over an absent key CREATES the key (a real\n // change: key-count dirtiness, the persisted shape), so it must\n // still go through. A non-undefined Object.is match implies the own\n // slot exists (reads are own-key only), so the walk runs for\n // undefined writes alone.\n const currentValues = store.getState().values;\n if (\n Object.is(getAtPath(currentValues, path), value) &&\n (value !== undefined || hasOwnSlot(currentValues, path))\n ) {\n return;\n }\n // A value write outside the array ops breaks every op chain whose\n // array it could rebuild — drop those records at the source so a\n // stale (or recurring, e.g. reset-restored) array reference can never\n // falsely chain against them.\n clearArrayOpsUnder(store, path);\n store.setState((state) => ({\n ...state,\n values: setAtPath(state.values, path, value),\n ...errorChannels(state, {\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n }));\n },\n setValues: (next) => {\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values: next,\n ...errorChannels(state, {\n serverErrors: releaseChangedSlices(\n state.serverErrors,\n state.values,\n next,\n ),\n }),\n }));\n },\n setTouched: (path: string, touched: boolean = true) =>\n store.setState((state) => ({\n ...state,\n touched: { ...state.touched, [path]: touched },\n })),\n setSubmitting: (value) =>\n store.setState((state) => ({ ...state, isSubmitting: value })),\n setMode: (mode) => store.setState((state) => ({ ...state, mode })),\n setReValidateMode: (reValidateMode) =>\n store.setState((state) => ({ ...state, reValidateMode })),\n setError: (path: string, errors: string | readonly string[]) => {\n const list = typeof errors === \"string\" ? [errors] : errors;\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n serverErrors:\n list.length === 0\n ? omitKey(state.serverErrors, path)\n : { ...state.serverErrors, [path]: list },\n }),\n }));\n },\n setErrors: (errors) =>\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, { serverErrors: errors }),\n })),\n addErrors: (errors) =>\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n serverErrors: Object.entries(errors).reduce<ErrorMap>(\n // Computed keys throughout, so a server field named\n // \"__proto__\" lands as an own property like everywhere else.\n (acc, [key, list]) =>\n list === undefined || list.length === 0\n ? omitKey(acc, key)\n : { ...acc, [key]: list },\n state.serverErrors,\n ),\n }),\n })),\n clearErrors: (path?: string) =>\n store.setState((state) => {\n // Clears both channels (schema errors return on the next validation\n // pass). A field path also clears its descendants (\"items\" covers\n // \"items.0.name\"), consistent with field-scoped validation; the root\n // \"\" is a single key (the schema-level refine slot, symmetric with\n // setError(\"\")); clearing everything is clearErrors() with no\n // argument.\n const scrub = (map: ErrorMap): ErrorMap =>\n path === undefined ? emptyErrors : omitScope(map, [path]);\n return {\n ...state,\n ...errorChannels(state, {\n schemaErrors: scrub(state.schemaErrors),\n serverErrors: scrub(state.serverErrors),\n }),\n };\n }),\n updateState: (updater) => {\n // The updater runs against the current state OUTSIDE setState so the\n // op-log decision below can precede the notification: subscribers\n // derive array row ids synchronously inside setState, and a values\n // patch that reintroduces an earlier array reference (a snapshot of\n // values taken before an op) would otherwise chain the op's stale\n // record against it during that notification, then have the log\n // cleared too late to matter. Same ordering setValues/adoptValues\n // keep. Semantically identical to setState(updater): both read the\n // same synchronous state.\n const state = store.getState();\n const patch: Partial<FormState<Values>> = updater(state);\n if (Object.keys(patch).length === 0) return;\n // Spread-style updaters carry `errors` with its current reference —\n // only a genuinely foreign map (a plain-JS write; TS forbids it via\n // the patch type) earns the warning.\n if (patch.errors !== undefined && patch.errors !== state.errors) {\n console.warn(\n \"[formstand] `errors` is derived from schemaErrors/serverErrors — patch those channels instead; the direct `errors` patch is ignored.\",\n );\n }\n // Re-derive against the CURRENT merged map (not the patched one), so\n // an ignored `errors` patch can't leak even its object identity into\n // state and re-fire identity-based subscribers.\n const next = { ...state, ...patch };\n // A values patch is a chain-breaking write like setValues.\n if (next.values !== state.values) {\n clearArrayOpsUnder(store, \"\");\n }\n store.setState(() => ({\n ...next,\n ...errorChannels(state, {\n schemaErrors: next.schemaErrors,\n serverErrors: next.serverErrors,\n }),\n }));\n },\n adoptValues: (values) => {\n // Rebasing values invalidates any in-flight async validation (the\n // values-reference guard drops its write), so the per-path ownership\n // tokens can be released too rather than growing without bound.\n sequences.clear();\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values,\n initialValues: values,\n ...errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n }),\n // Clearing `sequences` disowns every in-flight pass, including its\n // flag cleanup (the ownership check fails, so it never writes) —\n // clear the flags here too, mirroring reset(), or they'd stick.\n isValidating: emptyBools,\n isValidatingForm: false,\n }));\n },\n reset: (nextInitial, resetOptions) => {\n sequences.clear();\n // reset can restore the exact initialValues REFERENCE, so stale\n // records must go before an old array reference recurs and falsely\n // chains against them.\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => {\n // Merge only when both sides are plain records; a partial for an\n // array/scalar-rooted schema replaces wholesale (spreading an array\n // into {...} would corrupt the values shape).\n const init: typeof state.initialValues =\n nextInitial === undefined\n ? state.initialValues\n : isPlainObject(state.initialValues) && isPlainObject(nextInitial)\n ? ({\n ...state.initialValues,\n ...nextInitial,\n } as typeof state.initialValues)\n : (nextInitial as typeof state.initialValues);\n return {\n ...state,\n values: init,\n initialValues: init,\n ...(resetOptions?.keepErrors === true\n ? {}\n : errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n })),\n touched:\n resetOptions?.keepTouched === true ? state.touched : emptyBools,\n isSubmitting: false,\n submitCount:\n resetOptions?.keepSubmitCount === true ? state.submitCount : 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n };\n });\n },\n resetField: (path: string) => {\n // slotAtPath, not getAtPath: a path addressing NO slot in\n // initialValues (an out-of-range array index — an appended row past\n // the initial length, or a path through an absent ancestor) must not\n // be \"reset\" by writing undefined into the values tree — that would\n // leave a mid-array hole ([rowA, undefined]) that crashes row renders\n // and fails the schema. The value stays as-is; the field state still\n // clears. A key merely absent on an initial plain record IS an\n // addressable slot: resetting it writes the legitimate empty\n // undefined, exactly as before.\n const initialSlot = slotAtPath(\n store.getState().initialValues,\n path,\n );\n if (!initialSlot.exists) {\n console.warn(\n `[formstand] resetField(\"${path}\"): path has no initial value (e.g. an appended array row); value left unchanged, field state cleared.`,\n );\n }\n if (initialSlot.exists) {\n // A restored initial slice can carry array references the op log\n // has already seen (chain-breaking write, like setValue).\n clearArrayOpsUnder(store, path);\n }\n store.setState((state) => ({\n ...state,\n values: initialSlot.exists\n ? setAtPath(state.values, path, initialSlot.value)\n : state.values,\n // A runtime \"\" path scopes the whole form (the imperative surface is\n // string-typed even though FieldPath excludes \"\"). Server entries\n // follow the setValue release contract (releaseSpine).\n ...errorChannels(state, {\n schemaErrors:\n path === \"\" ? emptyErrors : omitScope(state.schemaErrors, [path]),\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n touched:\n path === \"\" ? emptyBools : omitScope(state.touched, [path]),\n isValidating:\n path === \"\" ? emptyBools : omitScope(state.isValidating, [path]),\n }));\n },\n validate,\n validateField,\n validateFields,\n validateAsync: validateAsyncOnForm,\n validateFieldAsync,\n validateFieldsAsync,\n submit,\n arrayPush: (path: string, item: unknown) =>\n applyArrayOp(path, (arr) => [...arr, item], identityMapper),\n arrayRemove: (path: string, index: number) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), ...arr.slice(index + 1)],\n removeAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index < len,\n ),\n arrayInsert: (path: string, index: number, item: unknown) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), item, ...arr.slice(index)],\n insertAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index <= len,\n ),\n arrayMove: (path: string, from: number, to: number) =>\n applyArrayOp(\n path,\n (arr) => {\n const without = [...arr.slice(0, from), ...arr.slice(from + 1)];\n return [...without.slice(0, to), arr[from], ...without.slice(to)];\n },\n moveFromTo(from, to),\n (len) =>\n Number.isInteger(from) &&\n Number.isInteger(to) &&\n from >= 0 &&\n from < len &&\n to >= 0 &&\n to < len,\n ),\n arraySwap: (path: string, a: number, b: number) =>\n applyArrayOp(\n path,\n (arr) => arr.map((v, i) => (i === a ? arr[b] : i === b ? arr[a] : v)),\n swapIndices(a, b),\n (len) =>\n Number.isInteger(a) &&\n Number.isInteger(b) &&\n a >= 0 &&\n a < len &&\n b >= 0 &&\n b < len,\n ),\n handleSubmit:\n (onValid, onInvalid, opts) =>\n async (event) => {\n event?.preventDefault();\n const result = await submit(onValid, onInvalid, opts);\n // The event-handler form is fire-and-forget: nobody reads the\n // resolved result, so a save failure with no onError handler\n // would otherwise vanish COMPLETELY — no state, no rejection, no\n // log — and the button just re-enables. Dev builds say so once\n // per occurrence; production stays silent by design (resolving\n // instead of rejecting is the documented contract).\n if (\n result.kind === \"error\" &&\n opts?.onError === undefined &&\n process.env.NODE_ENV !== \"production\"\n ) {\n console.warn(\n \"[formstand] submit handler threw and nothing observed it — the form shows no feedback. Pass { onError } to handleSubmit (or setError inside your handler):\",\n result.error,\n );\n }\n return result;\n },\n diff: () => {\n const state = store.getState();\n return Object.fromEntries(\n dirtyPathsOf(state.values, state.initialValues, \"\").map((path) => [\n path,\n getAtPath(state.values, path),\n ]),\n );\n },\n dirtyFields: () => {\n const state = store.getState();\n return dirtyPathsOf(state.values, state.initialValues, \"\");\n },\n snapshot: () => store.getState(),\n restore: (snap) => {\n // A snapshot restores PRIOR array references — exactly the recurring\n // references stale op records could falsely chain against.\n clearArrayOpsUnder(store, \"\");\n store.setState(() => {\n // Snapshots can come from persistence or hand construction: default\n // missing channels (pre-channel shapes) and re-derive the merged map\n // so the errors-is-derived invariant holds at this boundary too —\n // otherwise an inconsistent snapshot renders phantom errors until\n // the next write silently rewrites them (or crashes a channel scan).\n const schemaErrors = snap.schemaErrors ?? emptyErrors;\n const serverErrors = snap.serverErrors ?? emptyErrors;\n return {\n ...snap,\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n snap.errors ?? emptyErrors,\n ),\n // In-flight state is owned by live passes, never by snapshots: a\n // snapshotted flag has no pass left to clear it (the pass that set\n // it cleared its ORIGINAL entry when it settled), so restoring one\n // would stick it forever. isSubmitting follows the same rule — a\n // mid-submit snapshot restored later must not disable submit\n // buttons forever, so it reflects the LIVE submit count instead of\n // the snapshotted flag (a live pass's finally still resets it).\n isValidating: emptyBools,\n isValidatingForm: false,\n isSubmitting: inFlight.count > 0,\n };\n });\n },\n }) as Form<TSchema, D>;\n};\n","// A trailing-edge debouncer: `schedule` replaces any pending call, `cancel`\n// drops it. One production for the two timers the library keeps (the\n// persistence draft writer and useField's async-validation debounce), so\n// the cancel-then-reschedule rule lives in one place. Deliberately NOT a\n// `debounce(fn)` wrapper: both callers close over per-call data (the values\n// to write, the value that scheduled a validation) and decide at fire time,\n// so the scheduled thunk is the unit, not a fixed function.\nexport type Debouncer = Readonly<{\n schedule: (run: () => void) => void;\n cancel: () => void;\n // True while a scheduled run has not fired or been cancelled.\n readonly pending: () => boolean;\n}>;\n\n// A delay of 0 runs synchronously — the callers treat 0 as \"no debounce\"\n// and the caller-visible ordering (write happens before schedule returns)\n// is part of their contract.\nexport const createDebouncer = (ms: number): Debouncer => {\n // Sanctioned mutable ref for the timer handle (same shape as the\n // codebase's other timer/subscription refs).\n const timer: { current: ReturnType<typeof setTimeout> | null } = {\n current: null,\n };\n const cancel = (): void => {\n if (timer.current !== null) {\n clearTimeout(timer.current);\n timer.current = null;\n }\n };\n const schedule = (run: () => void): void => {\n cancel();\n if (ms === 0) {\n run();\n return;\n }\n timer.current = setTimeout(() => {\n timer.current = null;\n run();\n }, ms);\n };\n return Object.freeze({\n schedule,\n cancel,\n pending: () => timer.current !== null,\n });\n};\n","import type { z } from \"zod\";\nimport type { Form } from \"./createForm\";\nimport { createDebouncer } from \"./debounce\";\nimport type { DefaultPathDepth, PathDepth } from \"./fieldPath\";\n\n// Draft persistence for a form: watch the values, debounce-write them as JSON\n// under a storage key, and re-apply a found draft on the next visit. This is\n// the autosave recipe (examples/AutosaveForm) promoted to a helper — same\n// caveat as the recipe: drafts round-trip through JSON, so they are for\n// JSON-safe values only (Dates become strings, undefined slots drop; the\n// helper does NOT try to revive them).\n\n// Structural storage contract — window.localStorage and sessionStorage\n// satisfy it, as does any Map-backed stub in tests.\nexport type PersistStorage = Readonly<{\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n}>;\n\n// TSchema is phantom for now (no option carries schema-typed data — drafts\n// are typed at the persistForm call, not here), but the parameter keeps the\n// option bag tied to the form it configures and leaves room for schema-typed\n// options later without a breaking signature change.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type PersistOptions<TSchema extends z.ZodType> = Readonly<{\n // Storage key the draft lives under.\n key: string;\n // Defaults to globalThis.localStorage, guarded: where it is absent or\n // throws on access (SSR, locked-down browsers), persistence is a no-op but\n // the helper still returns working handles.\n storage?: PersistStorage;\n // Trailing-edge debounce for writes. Default 300; 0 writes synchronously\n // on every change.\n debounceMs?: number;\n // Bump when the schema's SHAPE changes and old drafts should be discarded\n // rather than applied. A draft is stored with the version it was written\n // under and ignored when the two disagree, which is the only reliable way\n // to catch a renamed or removed field: an absent key is indistinguishable\n // from an optional the user never filled in, so the automatic guard below\n // cannot tell those apart. Leaving this unset keeps the stored format\n // exactly as it was, so existing drafts survive an upgrade.\n version?: string | number;\n // How a found draft is applied on start, and what load() does later.\n // \"adopt\" (default) uses form.adoptValues — the draft becomes the new\n // baseline, so the form reads CLEAN. \"restore\" uses form.setValues — the\n // draft loads but stays DIRTY vs the original initial values. \"manual\"\n // never auto-applies; the caller decides when via the returned load(),\n // which then applies with adopt semantics (a caller-triggered load is a\n // rebase, not an edit — pick \"restore\" if you want dirty-vs-initials).\n apply?: \"adopt\" | \"restore\" | \"manual\";\n}>;\n\nexport type PersistHandle = Readonly<{\n // Load + apply the stored draft now (see `apply` for the semantics):\n // returns true if a draft existed, parsed, and applied. Corrupt or absent\n // JSON returns false and never throws. (Named load, not restore: the\n // DEFAULT application is adoptValues — a rebase that reads clean — and\n // \"restore\" promised setValues semantics the method only has when the\n // apply option asks for them.)\n load: () => boolean;\n // Delete the stored draft (e.g. after a successful submit). Also cancels\n // any pending debounced write, so a stale draft isn't re-written right\n // after clearing.\n clear: () => void;\n // Stop watching the form (does not clear storage). Cancels any pending\n // debounced write.\n dispose: () => void;\n}>;\n\n// The JSON kind of a value, as it exists AFTER a storage round trip. The\n// reference side is round-tripped before comparison rather than special-cased,\n// so a Date (which stores as a string) compares against a string and the\n// documented Date-becomes-string limitation is not mistaken for corruption.\nconst kindOf = (value: unknown): string =>\n value === null\n ? \"null\"\n : Array.isArray(value)\n ? \"array\"\n : typeof value;\n\n// Does the draft CONFLICT with the shape the form expects? Only overlapping\n// paths are compared, and only their kinds.\n//\n// Deliberately not a key-set equality check. JSON drops undefined slots, so an\n// optional the user never filled is absent from the reference, and an optional\n// they did fill is present only in the draft. Neither is evidence of a schema\n// change, so treating a key-set difference as corruption would throw away\n// perfectly good drafts on any form with an optional field. What IS\n// unambiguous is a path holding a string on one side and an object on the\n// other: no edit produces that, only a changed schema. Renames and removals\n// are the `version` option's job.\nconst conflictsWith = (draft: unknown, reference: unknown): boolean => {\n // null and undefined carry NO shape information, on either side. null is the\n // canonical empty for a nullable field (see emptyValue), so it can legally\n // appear at any nullable path whatever that path's filled shape is: a\n // nullable object starting null and then filled in, or starting filled and\n // then cleared, are both ordinary edits. Reading either as a kind conflict\n // would discard the drafts of every form with a nullable field.\n if (draft === undefined || draft === null) return false;\n if (reference === undefined || reference === null) return false;\n const draftKind = kindOf(draft);\n const referenceKind = kindOf(reference);\n if (draftKind !== referenceKind) return true;\n if (draftKind === \"array\") {\n const [d] = draft as readonly unknown[];\n const [r] = reference as readonly unknown[];\n // Row counts differ for ordinary reasons; the ROW SHAPE is the signal.\n return conflictsWith(d, r);\n }\n if (draftKind === \"object\") {\n const d = draft as Record<string, unknown>;\n const r = reference as Record<string, unknown>;\n return Object.keys(d).some((key) => conflictsWith(d[key], r[key]));\n }\n return false;\n};\n\n// Resolved lazily inside persistForm — never at module scope — so importing\n// this module is SSR-safe. jsdom provides localStorage; node without DOM may\n// lack it (typeof check) or throw on access (try/catch).\nconst defaultStorage = (): PersistStorage | null => {\n try {\n return typeof globalThis.localStorage === \"undefined\"\n ? null\n : globalThis.localStorage;\n } catch {\n return null;\n }\n};\n\nexport const persistForm = <TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const storage = options.storage ?? defaultStorage();\n const debounceMs = options.debounceMs ?? 300;\n const apply = options.apply ?? \"adopt\";\n\n // \"restore\" is a plain values write (dirty vs the original initials);\n // \"adopt\" and \"manual\" rebase via adoptValues so the draft reads clean.\n const applyDraft = (values: z.input<TSchema>): void =>\n apply === \"restore\" ? form.setValues(values) : form.adoptValues(values);\n\n // The shape the draft is checked against, in stored form. Round-tripping\n // the reference through JSON puts both sides in the same representation.\n const referenceShape = (): unknown => {\n try {\n return JSON.parse(JSON.stringify(form.getState().initialValues));\n } catch {\n // A non-serializable initial value means we cannot compare; the write\n // path would have failed too, so let the draft through unchecked\n // rather than rejecting every draft for this form.\n return undefined;\n }\n };\n\n const load = (): boolean => {\n // Every storage touch is guarded: private-mode/security errors read as\n // \"no draft\", corrupt JSON parses as \"no draft\" — load never throws.\n try {\n const raw = storage === null ? null : storage.getItem(options.key);\n if (raw === null) return false;\n const parsed: unknown = JSON.parse(raw);\n // Versioned drafts are wrapped; unversioned ones are the bare values,\n // which is the format every existing draft is already in.\n const versioned =\n options.version !== undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"__v\" in parsed;\n if (options.version !== undefined && !versioned) return false;\n // The config-downgrade hole: a draft WRITTEN with a version is the\n // {__v, values} wrapper, and if the app later ships without the\n // version option, nothing above catches it — the wrapper's keys\n // don't overlap the reference shape, so conflictsWith stays quiet\n // and the WRAPPER OBJECT gets adopted as form values (then\n // re-persisted, making the corruption self-sustaining). A versioned\n // draft under a version-less config is a contract the current app\n // no longer declares: discard it, like every other draft the config\n // cannot vouch for.\n if (\n options.version === undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n Object.hasOwn(parsed, \"__v\") &&\n Object.hasOwn(parsed, \"values\")\n ) {\n return false;\n }\n const wrapper = parsed as unknown as {\n readonly __v?: unknown;\n readonly values?: unknown;\n };\n if (versioned && wrapper.__v !== options.version) return false;\n // A wrapper with no payload is not a draft. Only reachable via tampered\n // or foreign storage, but applying it would write undefined over the\n // whole values object.\n if (versioned && wrapper.values === undefined) return false;\n const values = (versioned ? wrapper.values : parsed) as z.input<TSchema>;\n // A draft whose shape conflicts with the form's is from another schema.\n // Applying it would rebase the form onto values it cannot validate, and\n // because \"adopt\" clears errors, the form would read CLEAN while holding\n // them. Ignore it instead; the next change overwrites it.\n const reference = referenceShape();\n if (reference !== undefined && conflictsWith(values, reference)) {\n return false;\n }\n applyDraft(values);\n return true;\n } catch {\n return false;\n }\n };\n\n const writeDraft = (values: z.input<TSchema>): void => {\n // Quota/private-mode setItem errors just skip this write. The wrapper is\n // written ONLY when a version is configured, so a form that never opts in\n // keeps the exact bytes it wrote before and its existing drafts still load.\n try {\n storage?.setItem(\n options.key,\n JSON.stringify(\n options.version === undefined\n ? values\n : { __v: options.version, values },\n ),\n );\n } catch {\n /* persistence is best-effort */\n }\n };\n\n // Trailing-edge debounce of draft writes (0 = write synchronously).\n const writes = createDebouncer(debounceMs);\n const cancelPending = (): void => writes.cancel();\n\n // Auto-apply BEFORE subscribing, so applying the draft doesn't immediately\n // schedule a write of the values we just read.\n if (apply !== \"manual\") {\n load();\n }\n\n const unsubscribe = form.watchValues((values) => {\n writes.schedule(() => writeDraft(values));\n });\n\n return Object.freeze({\n load,\n clear: () => {\n // Cancel first: a pending debounced write landing after removeItem\n // would silently resurrect the draft.\n cancelPending();\n try {\n storage?.removeItem(options.key);\n } catch {\n /* persistence is best-effort */\n }\n },\n dispose: () => {\n cancelPending();\n unsubscribe();\n },\n });\n};\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport {\n type PersistHandle,\n type PersistOptions,\n persistForm,\n} from \"../core/persist\";\n\n// The React lifecycle wrapper persistForm was missing: every useForm\n// consumer hand-wrote the mount/dispose effect (plus a ref to reach\n// clear() after submit), and calling persistForm during render\n// double-subscribed under StrictMode. This hook owns that dance:\n//\n// const form = useForm(schema, { initialValues });\n// const draft = usePersistForm(form, { key: \"profile-draft\" });\n// // ... later: draft.clear() after a successful submit.\n//\n// The returned handle is REFERENCE-STABLE across renders and delegates to\n// whichever inner subscription is currently live, so it is safe to close\n// over in submit handlers. Before the mount effect has run (and after\n// unmount) load() reads false and clear() is a no-op — the same\n// guarded no-throw posture persistForm itself has.\n//\n// Options are read when the subscription (re)starts — on mount, and again\n// if `form` or `options.key` changes — not on every render, mirroring\n// useForm's locked-options rule; pass a stable options object or accept\n// that later edits to it are ignored until the key or form changes.\nexport const usePersistForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const inner = useRef<PersistHandle | null>(null);\n const latestOptions = useRef(options);\n // An effect, not a render-time ref write (refs are off-limits during\n // render): it runs before the subscription effect below in the same\n // commit, so a resubscribe always reads the options of the render that\n // triggered it.\n useEffect(() => {\n latestOptions.current = options;\n });\n\n const key = options.key;\n useEffect(() => {\n const handle = persistForm(form, latestOptions.current);\n inner.current = handle;\n return () => {\n inner.current = null;\n handle.dispose();\n };\n // StrictMode's mount-cleanup-mount runs this twice: each pass gets its\n // own subscription and disposes the previous, so no double-writes.\n }, [form, key]);\n\n return useMemo(\n () => ({\n load: () => inner.current?.load() ?? false,\n clear: () => inner.current?.clear(),\n // dispose stops THIS component's watching early; the effect cleanup\n // still runs its own dispose harmlessly (persistForm's dispose is\n // idempotent by construction — it only cancels and unsubscribes).\n dispose: () => inner.current?.dispose(),\n }),\n [],\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport {\n type CreateFormOptions,\n type Form,\n createForm,\n} from \"../core/createForm\";\nimport { valuesEqual } from \"../core/equality\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// Lazy-creates a Form bound to this component instance. Schema and options are\n// locked in on the first render; later changes are ignored (warned once below).\n// D mirrors createForm's inference: a literal from `options.pathDepth`\n// (constrained to PathDepth, 0-25), defaulting to the 9-segment typed-path\n// budget.\nexport const useForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n): Form<TSchema, D> => {\n const formRef = useRef<Form<TSchema, D> | null>(null);\n if (formRef.current === null) {\n formRef.current = createForm(schema, options);\n }\n // Lazy init of an external store handle — the sanctioned useRef exception\n // (react.dev: \"avoiding recreating the ref contents\"); the rule can't see\n // that this read is guarded by the null-check init above.\n // eslint-disable-next-line react-hooks/refs\n const form = formRef.current;\n\n const mountInitialsRef = useRef(options.initialValues);\n const warnedRef = useRef(false);\n useEffect(() => {\n // Two footguns, one warning: a new schema reference, or initial values\n // whose CONTENT changed after mount (the async-fetch pattern\n // `initialValues: data ?? {}` with a module-hoisted schema — the schema\n // check alone would never see it). Structural compare, so inline object\n // literals that re-create identical options every render stay silent.\n const changedInitials =\n !Object.is(options.initialValues, mountInitialsRef.current) &&\n !valuesEqual(options.initialValues, mountInitialsRef.current);\n if (!warnedRef.current && (form.schema !== schema || changedInitials)) {\n warnedRef.current = true;\n console.warn(\n \"[formstand] useForm received a different schema or initial values \" +\n \"after the first render; schema and options changes are ignored \" +\n \"for the life of the component. If the schema is defined inline \" +\n \"this is harmless (but consider hoisting it to module scope). For \" +\n \"initial values that arrive later (e.g. from a fetch), call \" +\n \"form.adoptValues(values) or form.reset(values) instead.\",\n );\n }\n }, [form, schema, options.initialValues]);\n\n return form;\n};\n","import type { ChangeEvent } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\n\nexport type TextInputProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type NumberInputProps = Readonly<{\n type: \"number\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type DateInputProps = Readonly<{\n type: \"date\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type CheckboxProps = Readonly<{\n type: \"checkbox\";\n name: string;\n checked: boolean;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type SelectProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLSelectElement>) => void;\n onBlur: () => void;\n}>;\n\n// THE predicate for \"does this field currently show an error\" — shared by\n// the aria-invalid mapping here and the field shells in fields.tsx, so the\n// notion of \"showing an error\" cannot drift between bindings.\nexport const hasFieldError = (\n error: readonly string[] | undefined,\n): boolean => error !== undefined && error.length > 0;\n\nconst ariaInvalid = (\n field: Readonly<{ error: readonly string[] | undefined }>,\n): true | undefined => (hasFieldError(field.error) ? true : undefined);\n\n// A cleared input writes back `field.emptyValue` when the schema ACCEPTS it\n// (`field.clearable`: optional, nullable, or defaulted — useField introspects\n// the form's zod schema), so z.number().nullable() round-trips to null and\n// z.string().optional() to undefined instead of a lingering \"\". A required\n// string cleared to \"\" stays \"\": writing undefined there would trade a\n// visible value the schema can judge for a hole it rejects.\n\n// Canonical display text for a numeric field value (\"\" for empty/NaN; null\n// counts as empty so nullable fields don't render the literal text \"null\").\n// Shared with NumberField so the two number bindings can't drift.\nexport const numberToInputText = (value: number | null | undefined): string =>\n value === undefined || value === null || Number.isNaN(value)\n ? \"\"\n : String(value);\n\nexport type ParsedNumberText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"number\"; value: number }>\n // Text that doesn't parse to a finite number — partial entries (\"-\",\n // \"1.\", \"1e\") or Infinity.\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning user-typed text into a numeric field value:\n// whitespace counts as empty (Number(\" \") is 0) and non-finite results are\n// rejected. Shared with NumberField.\nexport const parseNumberText = (text: string): ParsedNumberText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const parsed = Number(text);\n return Number.isFinite(parsed)\n ? { kind: \"number\", value: parsed }\n : { kind: \"invalid\" };\n};\n\nexport const textInputProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): TextInputProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const text = e.target.value;\n // Deleting all text from a clearable field restores its emptyValue\n // (null or undefined), so it isn't left permanently dirty (or invalid)\n // by a visual no-op.\n field.setValue((text === \"\" && field.clearable ? field.emptyValue : text) as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const numberInputProps = <T extends number | null | undefined>(\n field: UseFieldReturn<T>,\n): NumberInputProps => ({\n type: \"number\",\n name: field.path,\n value: numberToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseNumberText(e.target.value);\n // \"invalid\" is a PARTIAL entry (a lone \"-\", \"1e\") — keep the stored\n // value untouched, matching useNumberInput's deliberate semantics,\n // instead of writing emptyValue mid-keystroke (which flashed a\n // required error and flipped dirty while the user was still typing).\n // \"empty\" still clears to emptyValue. Note browsers report \"\" for\n // badInput on type=\"number\", so some partial entries arrive as\n // \"empty\" regardless — useNumberInput (a text input with its own raw\n // state) remains the binding that preserves every keystroke.\n if (parsed.kind === \"invalid\") return;\n field.setValue(\n (parsed.kind === \"number\" ? parsed.value : field.emptyValue) as T,\n );\n },\n onBlur: field.onBlur,\n});\n\n// Canonical display text for a Date field value — the local calendar date\n// as \"yyyy-MM-dd\" (what <input type=\"date\"> speaks). Local parts, NOT\n// toISOString(): a date picked as June 1 must not render as May 31 for\n// users west of UTC. Invalid Dates count as empty. Shared with DateField.\nexport const dateToInputText = (value: Date | null | undefined): string => {\n if (value === undefined || value === null || Number.isNaN(value.getTime())) {\n return \"\";\n }\n const pad = (part: number): string => String(part).padStart(2, \"0\");\n return `${String(value.getFullYear()).padStart(4, \"0\")}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;\n};\n\nexport type ParsedDateText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"date\"; value: Date }>\n // Not \"yyyy-MM-dd\", or parts that roll over (2026-02-31).\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning \"yyyy-MM-dd\" into a Date field value: LOCAL\n// midnight — a calendar date, not a UTC instant (new Date(\"2026-06-01\")\n// would be UTC midnight and read back as May 31 west of Greenwich).\n// Shared with DateField.\nexport const parseDateText = (text: string): ParsedDateText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text);\n if (match === null) return { kind: \"invalid\" };\n const [, year, month, day] = match;\n const y = Number(year);\n const date = new Date(y, Number(month) - 1, Number(day));\n // The Date constructor maps two-digit years 0–99 to 1900–1999, so a valid\n // \"0099-01-01\" would fail the survival check below; force the literal year\n // back on for years under 100 before checking rollover.\n if (y < 100) date.setFullYear(y);\n // The parts must survive the Date constructor — rollovers are invalid,\n // not silently the 3rd of next month.\n return date.getFullYear() === y &&\n date.getMonth() === Number(month) - 1 &&\n date.getDate() === Number(day)\n ? { kind: \"date\", value: date }\n : { kind: \"invalid\" };\n};\n\nexport const dateInputProps = <T extends Date | null | undefined>(\n field: UseFieldReturn<T>,\n): DateInputProps => ({\n type: \"date\",\n name: field.path,\n value: dateToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseDateText(e.target.value);\n if (parsed.kind !== \"date\") {\n field.setValue(field.emptyValue as T);\n return;\n }\n // Preserve the existing value's time-of-day: <input type=\"date\"> only\n // edits the calendar date, so re-picking the SAME day on a value that\n // carried a time (an initial `new Date()`) must stay a no-op — otherwise\n // the new local-midnight Date differs from the timestamped original and\n // the field reads spuriously dirty. Changing the day keeps that time.\n const current = field.value;\n const next =\n current instanceof Date && !Number.isNaN(current.getTime())\n ? new Date(\n parsed.value.getFullYear(),\n parsed.value.getMonth(),\n parsed.value.getDate(),\n current.getHours(),\n current.getMinutes(),\n current.getSeconds(),\n current.getMilliseconds(),\n )\n : parsed.value;\n field.setValue(next as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const checkboxProps = <T extends boolean | null | undefined>(\n field: UseFieldReturn<T>,\n): CheckboxProps => ({\n type: \"checkbox\",\n name: field.path,\n checked: field.value ?? false,\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => field.setValue(e.target.checked as T),\n onBlur: field.onBlur,\n});\n\n// `?? \"\"` keeps the <select> controlled when the field has no value yet\n// (undefined for optional fields, null for nullable ones); pair it with an\n// <option value=\"\"> (SelectField renders one) so the blank state is a real\n// option instead of silently showing the first entry.\nexport const selectProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): SelectProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const v = e.target.value;\n field.setValue((v === \"\" && field.clearable ? field.emptyValue : v) as T);\n },\n onBlur: field.onBlur,\n});\n","import { type ChangeEvent, useState } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\nimport { hasFieldError } from \"./inputProps\";\n\n// The raw-text editing pattern behind NumberField/useNumberInput,\n// generalized to ANY parsed-and-formatted value: phone numbers, currency,\n// percentages, locale-formatted anything. A naive controlled input\n// re-renders the canonical format on every keystroke, which eats the\n// separators and partial entries the user is mid-way through typing. This\n// hook keeps the raw text locally while editing, pushes PARSED values to\n// the form as soon as a keystroke parses, and snaps the display back to\n// the canonical format on blur — so the form always holds a real value\n// while the input stays typeable.\n\nexport type MaskedParse<TValue> =\n // A complete value — pushed to the form immediately.\n | Readonly<{ kind: \"value\"; value: TValue }>\n // Nothing entered — the field's emptyValue is pushed (null/undefined\n // per the schema, same rule as the number and date bindings).\n | Readonly<{ kind: \"empty\" }>\n // A partial or unparseable entry — kept as local text, the form value\n // untouched (matching useNumberInput's deliberate semantics).\n | Readonly<{ kind: \"invalid\" }>;\n\nexport type MaskedInputOptions<TValue> = Readonly<{\n // The single rule for turning user-typed text into a field value.\n parse: (text: string) => MaskedParse<TValue>;\n // Canonical display text for a field value — what blur snaps back to.\n format: (value: TValue) => string;\n}>;\n\nexport type MaskedInputBinding = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype MaskedEditState<TValue> = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a\n // partial entry). When field.value diverges, an external writer\n // (reset/adoptValues/another component) changed it — drop the raw text\n // so the input shows the external value.\n pushed: TValue | null | undefined;\n}>;\n\n// Generic over the field's OWN value type (nullability included), so an\n// optional field binds as naturally as a nullable one: parse/format speak\n// the non-null value, and the nullish side is the emptyValue round trip.\nexport const useMaskedInput = <TValue>(\n field: UseFieldReturn<TValue>,\n options: MaskedInputOptions<NonNullable<TValue>>,\n): MaskedInputBinding => {\n const [edit, setEdit] = useState<MaskedEditState<TValue>>({\n raw: null,\n pushed: undefined,\n });\n // Render-phase derived-state reset, same as useNumberInput: an external\n // value change while editing wins over the local text. Object.is works\n // for reference values too — the hook pushed the very instance it holds.\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit({ raw: null, pushed: undefined });\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value:\n raw ??\n (field.value === undefined || field.value === null\n ? \"\"\n : options.format(field.value as NonNullable<TValue>)),\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = options.parse(text);\n switch (parsed.kind) {\n case \"value\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"empty\": {\n // The schema-legal blank (null/nullable, undefined/optional) —\n // the same write every other clearing binding performs; the\n // cast is the emptyValue contract, not a guess.\n const empty = field.emptyValue as TValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form\n // value so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n // Snap the display to the canonical format of whatever the form\n // holds, then run the field's ordinary blur (touched + mode gate).\n setEdit({ raw: null, pushed: undefined });\n field.onBlur();\n },\n };\n};\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { isPathOrChild } from \"../core/validation\";\nimport { useFormSelectorShallow } from \"./useFormSelector\";\n\n// The multi-step (wizard) story: one form, one schema, one values object —\n// and a step index that gates progress on the CURRENT step's fields\n// validating clean. Everything else falls out of what the library already\n// does: next() runs validateFieldsAsync over the step's paths (the full\n// schema parses, so cross-field refines inside a step fire; the errors are\n// scoped to the step), a failed advance marks the errored fields touched\n// exactly the way a failed submit does (so touched-gated error UIs show),\n// and going BACK never validates — leaving a half-filled step is normal.\n//\n// The step index is deliberately React state, not form state: it is UI\n// navigation, not form data, and FormState's shape is owned by the\n// library. Render a progress bar elsewhere by lifting the returned value,\n// exactly as you would any other component state.\n//\n// Cross-STEP rules (a schema-level refine over fields in different steps)\n// surface at submit, like every wizard: a step only re-judges its own\n// paths, and the root \"\" key belongs to the whole form.\n\nexport type FormStep<TValues, D extends PathDepth = DefaultPathDepth> = Readonly<{\n // For progress UIs; steps are addressed by index either way.\n name?: string;\n // The paths this step owns — a container path covers its whole subtree.\n fields: readonly FieldPath<TValues, D>[];\n}>;\n\nexport type StepStatus = Readonly<{\n name: string | undefined;\n // The user has been ON this step (the first step starts visited).\n visited: boolean;\n // Any error currently at or under the step's fields — live, so a\n // progress bar can flag a step the user broke after leaving it.\n hasErrors: boolean;\n}>;\n\nexport type UseFormStepsReturn = Readonly<{\n step: number;\n name: string | undefined;\n count: number;\n isFirst: boolean;\n isLast: boolean;\n // Validate the current step; on clean, advance (no-op advance on the\n // last step — submit is the last step's \"next\"). Resolves whether the\n // step validated clean, so `if (await steps.next())` reads naturally on\n // any step, the last included.\n next: () => Promise<boolean>;\n // Never validates: leaving a half-filled step backward is normal.\n back: () => void;\n // Backward jumps are free. A forward jump validates each step from the\n // current one up to (not including) the target and LANDS ON THE FIRST\n // ONE THAT FAILS, errors visible — so a step header can be a plain\n // goTo() without letting anyone skip past an invalid step. Resolves the\n // index actually landed on.\n goTo: (target: number) => Promise<number>;\n // Per-step live status, index-aligned with the definitions.\n steps: readonly StepStatus[];\n}>;\n\nexport const useFormSteps = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n steps: readonly FormStep<z.input<TSchema>, D>[],\n): UseFormStepsReturn => {\n const [step, setStep] = useState(0);\n const [visited, setVisited] = useState<ReadonlySet<number>>(\n () => new Set([0]),\n );\n\n // Latest-ref so next/goTo/back are reference-stable however the caller\n // writes the steps array (the usePersistForm pattern; navigation only\n // fires after mount, so the ref is always populated). The COUNT should\n // stay stable for sensible UX, but nothing here breaks if it doesn't —\n // there are no per-step hooks.\n const latest = useRef(steps);\n useEffect(() => {\n latest.current = steps;\n });\n\n // Validate one step's paths and mirror submit's convention on failure:\n // the errored keys (already scoped to the step by validateFieldsAsync)\n // are marked touched, so touched-gated error UIs show why the advance\n // refused.\n const validateStep = useCallback(\n async (index: number): Promise<boolean> => {\n const definition = latest.current[index];\n if (definition === undefined) return true;\n const result = await form.validateFieldsAsync(definition.fields);\n if (result.kind === \"invalid\") {\n Object.keys(result.errors).forEach((key) => {\n form.setTouched(key as FieldPath<z.input<TSchema>, D>, true);\n });\n return false;\n }\n return true;\n },\n [form],\n );\n\n const next = useCallback(async (): Promise<boolean> => {\n // Functional reads through state setters would race the async\n // validation; the render-time `step` is the one the user acted on.\n const ok = await validateStep(step);\n if (!ok) return false;\n const target = Math.min(step + 1, latest.current.length - 1);\n setStep(target);\n setVisited((prev) => new Set([...prev, target]));\n return true;\n }, [validateStep, step]);\n\n const back = useCallback((): void => {\n setStep((prev) => Math.max(prev - 1, 0));\n }, []);\n\n const goTo = useCallback(\n async (target: number): Promise<number> => {\n const count = latest.current.length;\n const clamped = Math.max(0, Math.min(target, count - 1));\n if (clamped <= step) {\n setStep(clamped);\n return clamped;\n }\n // Walk forward, validating each step on the way; land on the first\n // failure so its errors are on screen.\n const walk = async (from: number): Promise<number> => {\n if (from >= clamped) return clamped;\n return (await validateStep(from)) ? walk(from + 1) : from;\n };\n const landed = await walk(step);\n setStep(landed);\n setVisited(\n (prev) =>\n new Set([\n ...prev,\n ...Array.from({ length: landed - step + 1 }, (_, i) => step + i),\n ]),\n );\n return landed;\n },\n [validateStep, step],\n );\n\n // Live per-step error presence, shallow-compared so renders happen only\n // when some step's flag flips — not on every error-map write.\n const errorFlags = useFormSelectorShallow(form, (state) =>\n steps.map((definition) =>\n definition.fields.some((path) =>\n Object.keys(state.errors).some((key) => isPathOrChild(key, path)),\n ),\n ),\n );\n\n const statuses = useMemo(\n () =>\n steps.map(\n (definition, index): StepStatus => ({\n name: definition.name,\n visited: visited.has(index),\n hasErrors: errorFlags[index] ?? false,\n }),\n ),\n [steps, visited, errorFlags],\n );\n\n return useMemo(\n () => ({\n step,\n name: steps[step]?.name,\n count: steps.length,\n isFirst: step === 0,\n isLast: step === steps.length - 1,\n next,\n back,\n goTo,\n steps: statuses,\n }),\n [step, steps, next, back, goTo, statuses],\n );\n};\n","import { useActionState, useCallback, useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type {\n Form,\n InvalidSubmitHandler,\n SubmitResult,\n} from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// The React 19 form-actions bridge: bind a formstand form's validation and\n// submit lifecycle to `<form action={...}>` and useActionState, so the\n// action world gets what onSubmit callers already have — schema\n// validation before the action runs, isSubmitting/submitCount tracking,\n// errors written and their fields marked touched on a failed submit, and\n// the two-channel error model for the action's own verdicts.\n//\n// The handler receives PARSED, TYPED data (z.output of the schema), not\n// FormData: formstand inputs are controlled, so the store is the source of\n// truth and the schema has already judged it. The raw FormData still\n// arrives as the last argument for what only it can carry — uncontrolled\n// inputs in the same <form>, file pickers — and because a server action\n// can take it across the wire (FormData serializes under RSC).\n//\n// Honest scope: this is a CLIENT-side integration. React's no-JS\n// progressive enhancement only works when the server action itself is\n// passed to the form/useActionState, which by definition skips any\n// client-side wrapper — for that path, validate on the server with the\n// same zod schema and keep this bridge for the hydrated experience.\n//\n// Note on React's post-action reset: React 19 resets UNCONTROLLED form\n// fields after an action completes. formstand inputs are controlled, so\n// the form's values survive the action untouched.\n\nexport type FormActionHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n formData: FormData,\n) => void | Promise<void>;\n\n// S is the AWAITED state (what the reducer stores), so the handler's\n// return may be the state or a promise of it — the shape a \"use server\"\n// async function naturally has.\nexport type FormActionStateHandler<TSchema extends z.ZodType, S> = (\n prevState: S,\n data: z.output<TSchema>,\n formData: FormData,\n) => S | Promise<S>;\n\nexport type FormActionOptions = Readonly<{\n // Mirrors handleSubmit's second parameter: runs when validation fails\n // (errors are written and fields marked touched either way).\n onInvalid?: InvalidSubmitHandler;\n // Mirrors SubmitOptions.onError: the save-failure hook for a throwing\n // handler. Without it, dev builds warn when a failure resolves\n // unobserved — the action form is fire-and-forget, like handleSubmit.\n onError?: (error: unknown) => void;\n}>;\n\n// The fire-and-forget dev warning, same contract as handleSubmit's: a\n// throwing handler resolves {kind: \"error\"} writing no state, so with no\n// onError the failure would vanish completely.\nconst warnUnobserved = (\n result: SubmitResult<unknown>,\n options: FormActionOptions | undefined,\n site: string,\n): void => {\n if (\n result.kind === \"error\" &&\n options?.onError === undefined &&\n process.env.NODE_ENV !== \"production\"\n ) {\n console.warn(\n `[formstand] action handler threw and nothing observed it — the form shows no feedback. Pass { onError } to ${site} (or setError inside your handler):`,\n result.error,\n );\n }\n};\n\n// The plain bridge: an action for `<form action={...}>`. Validation and\n// the submit lifecycle run first; the handler only sees data the schema\n// accepted. The returned function is REFERENCE-STABLE across renders\n// (handler and options are read through refs assigned in an effect —\n// actions only fire after mount, so the refs are always populated), which\n// keeps memoized subtrees quiet however the caller writes the handler.\nexport const useFormAction = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n onValid: FormActionHandler<TSchema>,\n options?: FormActionOptions,\n): ((formData: FormData) => Promise<void>) => {\n const latest = useRef({ onValid, options });\n useEffect(() => {\n latest.current = { onValid, options };\n });\n return useCallback(\n async (formData: FormData) => {\n const { onValid: handler, options: opts } = latest.current;\n const result = await form.submit(\n (data) => handler(data, formData),\n opts?.onInvalid,\n opts?.onError === undefined ? undefined : { onError: opts.onError },\n );\n warnUnobserved(result, opts, \"useFormAction\");\n },\n [form],\n );\n};\n\n// The stateful bridge: useActionState with schema-validated data. The\n// handler's shape mirrors the native (prevState, formData) signature with\n// the parsed data spliced in, so a \"use server\" function slots straight\n// in. A submission that fails validation (or is skipped, or throws)\n// returns the PREVIOUS state unchanged: field errors already live in the\n// form store where the bound components read them, so the action state\n// stays what it is — the last verdict an action actually produced.\nexport const useFormActionState = <\n TSchema extends z.ZodType,\n S,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n action: FormActionStateHandler<TSchema, S>,\n initialState: S,\n options?: FormActionOptions,\n): [state: S, formAction: (formData: FormData) => void, isPending: boolean] => {\n const [state, formAction, isPending] = useActionState<S, FormData>(\n async (prevState, formData): Promise<S> => {\n // React hands the reducer Awaited<S>; S is declared as the awaited\n // state, so for any non-thenable state (the only kind a reducer can\n // meaningfully hold) the two are the same type — TS just won't\n // simplify the deferred conditional for an unconstrained S.\n const prev = prevState as S;\n // Sanctioned mutable ref for the handler's return value: submit owns\n // the lifecycle and its onValid returns void, so the next state\n // rides out through the closure (same shape as the codebase's other\n // capture refs).\n const nextRef: { current: S } = { current: prev };\n const result = await form.submit(\n async (data) => {\n nextRef.current = await action(prev, data, formData);\n },\n options?.onInvalid,\n options?.onError === undefined\n ? undefined\n : { onError: options.onError },\n );\n warnUnobserved(result, options, \"useFormActionState\");\n return nextRef.current;\n },\n initialState as Awaited<S>,\n );\n return [state as S, formAction, isPending];\n};\n","import {\n type ReactNode,\n createContext,\n useContext,\n} from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\nexport type FormProviderProps<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n form: Form<TSchema, D>;\n children: ReactNode;\n}>;\n\nexport type FormContextApi<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n Provider: (props: FormProviderProps<TSchema, D>) => ReactNode;\n useFormContext: () => Form<TSchema, D>;\n}>;\n\n// A form created with a non-default `pathDepth` names it here too:\n// createFormContext<typeof schema, 12>() — the context can't infer it (there\n// is no value argument), and Form<S, 12> is deliberately not Form<S, 9>.\n// The `PathDepth` constraint makes an out-of-range literal (26, -1) or a\n// widened `number` argument a compile error, same as createForm's option.\nexport const createFormContext = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(): FormContextApi<TSchema, D> => {\n const Context = createContext<Form<TSchema, D> | null>(null);\n\n const Provider = ({ form, children }: FormProviderProps<TSchema, D>) => (\n <Context.Provider value={form}>{children}</Context.Provider>\n );\n\n const useFormContext = (): Form<TSchema, D> => {\n const ctx = useContext(Context);\n if (ctx === null) {\n throw new Error(\n \"useFormContext must be used inside the matching <Provider>\",\n );\n }\n return ctx;\n };\n\n return { Provider, useFormContext };\n};\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport { type Debouncer, createDebouncer } from \"../core/debounce\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n emptyValueForSchema,\n isClearableSchema,\n fieldSchemaAtPath,\n} from \"../core/validation\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose write methods take the narrower\n// FieldPath<...> instead of string — still satisfies this API. Prefer calling\n// these through a typed Form when you have one.\nexport type FieldFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n setValue(path: string, value: unknown): void;\n setTouched(path: string, touched?: boolean): void;\n setError(path: string, errors: string | readonly string[]): void;\n clearErrors(path?: string): void;\n validateField(path: string): FieldValidationResult;\n // Settled by contract: an awaited pass can never resolve \"pending\" —\n // the promise IS the pending state, and a resolved {kind: \"pending\"}\n // would carry a promise that never runs. Custom implementations were\n // always expected to resolve settled; the type now says so.\n validateFieldAsync(path: string): Promise<SettledFieldValidationResult>;\n}>;\n\nexport type FieldPathArg<TValues> =\n | string\n | ((state: FormState<TValues>) => string);\n\nexport type UseFieldOptions = Readonly<{\n debounceMs?: number;\n}>;\n\nexport type UseFieldReturn<TValue> = Readonly<{\n // The resolved field path — useful as an input's `name` attribute (the\n // bound prop builders spread it as `name`).\n path: string;\n value: TValue;\n // The slice of initialValues at this path (what `dirty` compares against).\n initialValue: TValue;\n // What a cleared input writes back: null when the field's schema is\n // nullable (introspected when the form carries its schema — the zod-first\n // source of truth), undefined when it is optional or unknown. Falls back\n // to \"the initial value was null\" for schema-less FieldFormApi forms.\n emptyValue: null | undefined;\n // Whether the schema ACCEPTS that emptyValue (optional / nullable /\n // defaulted — see isClearableSchema). The string-shaped bindings write\n // emptyValue on a cleared input only when this is true; a required\n // string cleared to \"\" stays \"\" so the schema judges a visible value\n // instead of a hole it rejects. Schema-less forms fall back to the same\n // heuristic as emptyValue: a null initial value reads as clearable.\n clearable: boolean;\n error: readonly string[] | undefined;\n // The first error message, or undefined when the channel is empty — the\n // display shorthand every adapter otherwise re-derives by hand (the\n // `error?.[0]`-with-empty-array-guard helper each generated kit adapter\n // used to open with).\n firstError: string | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n setValue: (value: TValue) => void;\n setTouched: (touched?: boolean) => void;\n // A single string is shorthand for a one-element array (like form.setError).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n validate: () => FieldValidationResult;\n // Settled: awaited passes never resolve \"pending\" (see FieldFormApi).\n validateAsync: () => Promise<SettledFieldValidationResult>;\n onBlur: () => void;\n}>;\n\ntype FieldSlice<TValue> = Readonly<{\n path: string;\n value: TValue;\n initialValue: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\n// The readable-error trap-guard for `useField<Values>(typedForm, \"email\")`:\n// any explicit type argument arity-matches ONLY the one-type-parameter\n// overloads, and the structural one's `schema?: undefined` brand then\n// rejects the Form with a baffling \"... not assignable to type 'undefined'\".\n// The error overload below intercepts that shape: its TValue defaults to\n// this unexported sentinel — an INFERRED call can never produce it (TValue\n// has no inference site, so it always falls back to the default), which\n// collapses `path` to `never` and fails the overload silently — while an\n// EXPLICIT TValue (never assignable to the unexported brand) on a\n// schema-carrying form types `path` as a string-literal error message, so\n// the compiler blames the path argument with instructions instead of brand\n// internals.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order is deliberate. When no overload matches, TypeScript reports\n// the LAST candidate's error — so the typed-path overload sits last, and a\n// typo'd path on a Form<TSchema> is blamed on the path argument against the\n// full FieldPath union ('\"naem\"' is not assignable to '\"name\" | \"age\" | ...')\n// instead of on the form argument.\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useField<Schema, \"name\">`) —\n// TS applies explicit type args to every arity-compatible overload, so a\n// second parameter here would check \"name\" against it.\nexport function useField<TSchema extends z.ZodType>(\n form: FieldFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): an explicit type argument on a\n// schema-carrying form binds here and blames the path argument with a\n// readable instruction. Inferred calls can never select it — TValue stays\n// at its sentinel default and `path` collapses to `never`.\nexport function useField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n path: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the value type from the path\",\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// The `schema?: undefined` brand forces TS past this widened overload when a\n// real Form is passed (Form has `schema: TSchema`, not undefined). Without\n// it, a Form<TSchema> with an invalid path would silently bind here and\n// return UseFieldReturn<unknown>.\nexport function useField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker), so a `pathDepth: 12` form checks paths against its widened union.\n// It sits LAST (P's constraint forward-references it — legal in TS) with a\n// default, so pre-existing explicit instantiations like\n// `useField<typeof schema, \"name\">` keep their arity.\nexport function useField<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n options?: UseFieldOptions,\n): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\nexport function useField<TValue = unknown>(\n form: FieldFormApi,\n pathArg: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue> {\n const slice = useStore(\n form.store,\n useShallow((state): FieldSlice<TValue> => {\n const p =\n typeof pathArg === \"function\" ? pathArg(state) : pathArg;\n const value = getAtPath(state.values, p);\n const initialValue = getAtPath(state.initialValues, p);\n return {\n path: p,\n value: value as TValue,\n initialValue: initialValue as TValue,\n error: state.errors[p],\n touched: state.touched[p] ?? false,\n dirty: isFieldDirty(value, initialValue),\n isValidating: state.isValidating[p] ?? false,\n };\n }),\n );\n const path = slice.path;\n\n // Schema introspection wins over the runtime heuristic when the form\n // carries its schema (Form<TSchema> does; a bare FieldFormApi may not).\n const formSchema = (form as Readonly<{ schema?: z.ZodType }>).schema;\n const initialValue = slice.initialValue;\n const { emptyValue, clearable } = useMemo(() => {\n if (formSchema !== undefined) {\n const sub = fieldSchemaAtPath(formSchema, path);\n if (sub !== null) {\n return {\n emptyValue: emptyValueForSchema(sub),\n clearable: isClearableSchema(sub),\n };\n }\n }\n // Schema-less heuristic: a null initial value is the one runtime signal\n // that null round-trips, so it drives both answers.\n return initialValue === null\n ? { emptyValue: null, clearable: true }\n : { emptyValue: undefined, clearable: false };\n }, [formSchema, path, initialValue]);\n\n const debounceMs = options?.debounceMs;\n // One debouncer per (form, path, debounceMs) identity, created lazily on\n // the first debounced trigger and cancelled by the effect cleanup on\n // unmount or identity change — the ref keeps it across renders.\n const debouncerRef = useRef<Debouncer | null>(null);\n\n useEffect(() => {\n return () => {\n debouncerRef.current?.cancel();\n debouncerRef.current = null;\n };\n }, [form, path, debounceMs]);\n\n const triggerValidate = useCallback(() => {\n if (debounceMs !== undefined && debounceMs > 0) {\n const debouncer = debouncerRef.current ?? createDebouncer(debounceMs);\n debouncerRef.current = debouncer;\n // The pending timer is invisible to the store, so a reset() /\n // adoptValues() inside the debounce window cannot cancel it the way\n // it invalidates in-flight validation (the ownership tokens) — the\n // fire would claim a FRESH token and re-commit errors onto the\n // pristine form. Two fire-time guards close it: a pristine form\n // (values IS initialValues by reference — exactly what reset and\n // adoptValues leave behind) never receives a debounced commit, and\n // a path whose value changed since scheduling is stale (the write\n // that changed it scheduled its own validation, or was a\n // restore/reset to different values). Scheduling runs after\n // setValue, so the captured value is the keystroke being validated.\n const scheduled = getAtPath(form.store.getState().values, path);\n debouncer.schedule(() => {\n const state = form.store.getState();\n if (state.values === state.initialValues) return;\n if (!Object.is(getAtPath(state.values, path), scheduled)) return;\n void form.validateFieldAsync(path);\n });\n return;\n }\n // The core routes async schemas itself: validateField returns\n // { kind: \"pending\" } having already started the async pass, which\n // commits its errors and isValidating flags to the store — so the\n // result needs no handling here.\n form.validateField(path);\n }, [form, path, debounceMs]);\n\n const setValue = useCallback(\n (value: TValue) => {\n const before = form.store.getState();\n form.setValue(path, value);\n const state = form.store.getState();\n // A no-op write (the identical value — createForm's setValue identity\n // guard leaves the state reference untouched) skips the revalidation\n // gate too: nothing changed, so the current error state already\n // reflects this value. Custom FieldFormApi implementations without\n // the guard produce a fresh state and keep the old behavior.\n if (state === before) return;\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n state.touched[path] ?? false,\n )\n ) {\n triggerValidate();\n }\n },\n [form, path, triggerValidate],\n );\n\n const setTouched = useCallback(\n (touched?: boolean) => form.setTouched(path, touched),\n [form, path],\n );\n\n const setError = useCallback(\n // Normalize the string shorthand HERE, before forwarding: custom\n // FieldFormApi implementations written against the pre-0.4 surface are\n // typed for readonly string[] and must never receive a bare string.\n (errors: string | readonly string[]) =>\n form.setError(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(\n () => form.clearErrors(path),\n [form, path],\n );\n\n const validate = useCallback(() => form.validateField(path), [form, path]);\n\n const validateAsync = useCallback(\n () => form.validateFieldAsync(path),\n [form, path],\n );\n\n const onBlur = useCallback(() => {\n form.setTouched(path, true);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"blur\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n true,\n )\n ) {\n triggerValidate();\n }\n }, [form, path, triggerValidate]);\n\n return useMemo(\n () => ({\n path: slice.path,\n value: slice.value,\n initialValue: slice.initialValue,\n emptyValue,\n clearable,\n error: slice.error,\n // `?.[0]` covers both the undefined channel and an empty array.\n firstError: slice.error?.[0],\n touched: slice.touched,\n dirty: slice.dirty,\n isValidating: slice.isValidating,\n setValue,\n setTouched,\n setError,\n clearError,\n validate,\n validateAsync,\n onBlur,\n }),\n [slice, emptyValue, clearable, setValue, setTouched, setError, clearError, validate, validateAsync, onBlur],\n );\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// Discriminated-union support. A z.discriminatedUnion field types its value\n// as a union of variant objects, and FieldPath<T> only exposes the keys\n// COMMON to every union member (via `keyof T`) — so the DISCRIMINANT binds\n// with plain useField (it's common), but a variant-specific field\n// (\"payment.cardNumber\", present only in the card branch) resolves to a\n// path FieldPath omits. useVariantField is the typed accessor for those.\n//\n// It binds `${unionPath}.${field}` and types the result as the field's value\n// across every variant that declares it, widened with `| undefined` because\n// the field is absent while a different variant is active:\n//\n// const method = useField(form, \"payment.method\"); // discriminant\n// const cardNumber = useVariantField(form, \"payment\", \"cardNumber\");\n// // -> UseFieldReturn<string | undefined>, rendered when method.value === \"card\"\n//\n// The hook is called unconditionally (React's rules) — every variant's\n// fields bind every render; you render the matching ones based on the\n// discriminant. Runtime behavior is exactly useField on the joined path.\n//\n// Gate WRITES on the discriminant too, not just rendering: the returned\n// setter writes `${unionPath}.${field}` regardless of the active variant, so\n// calling a card field's setValue while the paypal variant is active injects\n// a stray key into the stored object. z.discriminatedUnion strips it on\n// parse (validation looks clean), but dirtyFields()/persistForm see the\n// polluted shape. Render the matching fields only — as the example shows —\n// and their setters fire only for the active variant. formstand-gen's output\n// follows this; hand-written forms must too.\n\n// The value of variant path `TField` across the members of union `V` that\n// resolve it. Distributes over V: each member contributes its FieldValue\n// when TField is one of ITS typed paths, never otherwise; the union of\n// those is the result. `| undefined` is added by the caller (the field is\n// absent while another variant is active). Since 0.20 TField is a PATH,\n// not just a key — \"size.w\" reaches inside a variant-only object — so the\n// resolution rides the same FieldPath/FieldValue machinery as useField\n// (leaf classification, tuple positions, and the depth budget included;\n// the budget applies to the path WITHIN the variant, the union path\n// having already been budget-checked by its own binding).\nexport type VariantFieldValue<V, TField extends string> = V extends unknown\n ? // No FieldPath gate needed: FieldValue resolves a path a member does\n // not declare to `never` (StepValue's miss arm), so non-declaring\n // members drop out of the union by themselves — and the constraint\n // side (VariantFieldPath) already vouches that SOME member declares\n // it.\n FieldValue<V, TField>\n : never;\n\n// The variant-only field keys of union `V`: every member's keys minus the\n// keys shared by all members (the discriminant and any other common field,\n// which bind with plain useField). `keyof V` on a union is ALREADY the\n// common keys (the intersection) — it must NOT distribute, or it would\n// equal AllKeys and leave no variant keys. AllKeys distributes to collect\n// every member's keys.\ntype CommonKeys<V> = keyof V;\ntype AllKeys<V> = V extends unknown ? keyof V : never;\nexport type VariantKeys<V> = Exclude<AllKeys<V>, CommonKeys<V>> & string;\n\n// Every typed path of every member — FieldPath distributes over the union\n// — minus the paths ROOTED at a common key: the discriminant and other\n// common fields (and anything under them) bind with plain useField, so\n// offering them here would just duplicate the plain hook with a widened\n// `| undefined`. What remains is exactly what FieldPath on the union\n// cannot offer: variant-only keys and every path INSIDE them\n// (\"cardNumber\", \"size\", \"size.w\", \"lines.0.qty\").\nexport type VariantFieldPath<\n V,\n D extends PathDepth = DefaultPathDepth,\n> = Exclude<\n V extends unknown ? FieldPath<V, D> : never,\n (CommonKeys<V> & string) | `${CommonKeys<V> & string}.${string}`\n> &\n string;\n\n// The paths in `TValues` whose value is a discriminated union — an object\n// whose members don't all share the same keys. Kept permissive (any\n// top-level or nested key reaching a union of objects); misuse on a\n// non-union path yields `never` field keys, so the call simply won't\n// typecheck a field argument.\nexport type UnionValueAt<TValues, P extends string> = P extends keyof TValues\n ? // NonNullable is essential: for an OPTIONAL/nullable union field the\n // resolved value includes undefined, which collapses `keyof V` to never\n // — VariantKeys would then leak EVERY key (discriminant included) and\n // the whole guard inverts. Strip the nullish part first.\n NonNullable<TValues[P]>\n : TValues extends readonly (infer Item)[]\n ? // Array rows: a numeric segment — a literal \"0\" or the `${number}`\n // a template path like `pavements.${index}` produces — selects the\n // ELEMENT type, so a union that IS the row item resolves the same\n // way a static object path does. (`keyof` above cannot do this:\n // an array's numeric index signature is `number`, and the string\n // segment types never extend it.) Without this branch every\n // row-indexed union path collapsed the field keys to `never`,\n // making unions inside array rows unbindable — the exact wall the\n // generated array-row TODO used to steer people into.\n P extends `${number}`\n ? NonNullable<Item>\n : P extends `${infer Head}.${infer Tail}`\n ? // Tuple positionality first: a tuple's keyof carries its literal\n // indices, so \"wrap.0.pay\" resolves element 0's OWN shape\n // instead of the all-elements union `Item` (whose keyof\n // collapses to common keys and killed the variant-key set). A\n // plain array's keyof has no numeric-string members, so it\n // falls through to the element branch unchanged.\n Head extends keyof TValues\n ? UnionValueAt<NonNullable<TValues[Head]>, Tail>\n : Head extends `${number}`\n ? UnionValueAt<NonNullable<Item>, Tail>\n : never\n : never\n : P extends `${infer Head}.${infer Tail}`\n ? Head extends keyof TValues\n ? UnionValueAt<NonNullable<TValues[Head]>, Tail>\n : never\n : never;\n\n// The readable-error trap-guard, mirroring useField's/useFieldArray's: an\n// explicit type argument (`useVariantField<string>(typedForm, \"payment\",\n// \"cardNumber\")`) arity-matches ONLY the one-type-parameter overloads, and\n// the structural one's `schema?: undefined` brand then rejects the Form\n// with a baffling \"... not assignable to type 'undefined'\". The error\n// overload below intercepts that shape — TValue defaults to this unexported\n// sentinel, which inferred calls can never escape (TValue has no inference\n// site), collapsing `unionPath` to `never`; an explicit TValue on a\n// schema-carrying form instead types `unionPath` as a string-literal\n// instruction the compiler blames the argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the trap\n// guard sits before the widened structural overload, and the typed overload\n// sits LAST so a bad union path / field name on a Form<TSchema> is blamed\n// on that argument against the real union instead of on the form argument.\nexport function useVariantField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n unionPath: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the variant value from the union path and field\",\n field: string,\n): UseFieldReturn<TValue | undefined>;\n// Schema-less forms keep the plain-string, caller-typed shape. The\n// `schema?: undefined` brand forces a real Form past this widened overload\n// (Form has `schema: TSchema`, not undefined).\nexport function useVariantField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n unionPath: string,\n field: string,\n): UseFieldReturn<TValue | undefined>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker). It sits LAST with a default, so pre-existing explicit\n// instantiation expressions like\n// `typeof useVariantField<typeof schema, \"payment\", \"cardNumber\">` keep\n// their arity.\nexport function useVariantField<\n TSchema extends z.ZodType,\n P extends string,\n // The DEFAULT depth budget on purpose, not D: a constraint may not\n // consume a later type parameter before inference resolves it — TS\n // substitutes D's CONSTRAINT (the whole PathDepth union) while checking\n // TField, which collapses the offered paths to never. Variant subtrees\n // are shallow by construction (they sit under an already-budgeted union\n // path), so the fixed default costs nothing real.\n TField extends VariantFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n unionPath: P,\n field: TField,\n): UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\nexport function useVariantField(\n form: FieldFormApi,\n unionPath: string,\n field: string,\n): UseFieldReturn<unknown> {\n // Structural string-path bind: the joined path is exactly what a variant\n // field lives at; only its TYPE was unreachable through FieldPath, so the\n // runtime is ordinary useField.\n return useField(\n form as FieldFormApi & { readonly schema?: undefined },\n `${unionPath}.${field}`,\n );\n}\n","import { useCallback, useMemo } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport {\n type ArrayOpRecord,\n arrayOpsFor,\n clearArrayOps,\n} from \"../core/arrayOpLog\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport type { FieldValidationResult } from \"../core/validation\";\nimport type { FieldPathArg } from \"./useField\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose array ops take the narrower\n// FieldPath<...> instead of string — still satisfies this API.\n// NOTE for custom implementations: exact row-id tracking for ops on\n// Object.is-equal rows is a createForm feature (its ops record their index\n// mappings internally) — a hand-rolled implementation of these methods gets\n// value-based id reconciliation only.\nexport type FieldArrayFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n arrayPush(path: string, item: unknown): void;\n arrayRemove(path: string, index: number): void;\n arrayInsert(path: string, index: number, item: unknown): void;\n arrayMove(path: string, from: number, to: number): void;\n arraySwap(path: string, a: number, b: number): void;\n // OPTIONAL, probed before use: when present (createForm always provides\n // it), the hook's op wrappers revalidate the array path after an op under\n // the same change-trigger gate useField.setValue applies — so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. NOTE for custom implementations: a hand-rolled FieldArrayFormApi\n // without this member still works — the ops simply skip revalidation.\n validateField?(path: string): FieldValidationResult;\n // OPTIONAL like validateField, same custom-implementation contract: when\n // present (createForm always provides them), the hook exposes the\n // array-level server-error channel — a \"too many rows\" verdict from the\n // API is set and cleared from the hook that owns the array, the same\n // symmetry useField has had all along. Absent members make the returned\n // setError/clearError no-ops.\n setError?(path: string, errors: string | readonly string[]): void;\n clearErrors?(path?: string): void;\n}>;\n\nexport type FieldArrayEntry<TItem> = Readonly<{\n id: string;\n value: TItem;\n}>;\n\nexport type UseFieldArrayReturn<TItem> = Readonly<{\n // The resolved array path — the same convenience useField exposes.\n path: string;\n fields: readonly FieldArrayEntry<TItem>[];\n items: readonly TItem[];\n length: number;\n error: readonly string[] | undefined;\n // The first array-level message, or undefined — same shorthand as\n // useField.firstError (the docs used to hand-roll error[0] here).\n firstError: string | undefined;\n // The array-level server channel, scoped to this path (see the\n // FieldArrayFormApi note: no-ops on custom implementations without the\n // optional members).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n push: (item: TItem) => void;\n remove: (index: number) => void;\n insert: (index: number, item: TItem) => void;\n move: (from: number, to: number) => void;\n swap: (a: number, b: number) => void;\n}>;\n\ntype IdState = Readonly<{\n items: readonly unknown[];\n ids: readonly string[];\n counter: number;\n // Unique per (form, path) entry, so ids minted for different arrays (or\n // for the same hook after a dynamic path switch) can never collide as\n // React keys.\n prefix: string;\n}>;\n\n// Stable reference for \"path holds no array yet\" — a fresh [] per selector\n// run would defeat useShallow and re-render on every store change.\nconst EMPTY_ITEMS: readonly never[] = [];\n\n// 1-based mint numbers for the positions needing a fresh id, in order.\n// BOTH id-derivation paths (value reconciliation in reconcileIds and the\n// exact op mappings in mappedIdState) number their mints through this one\n// helper, so the collision-free scheme — counter + consecutive 1-based\n// counts, counter advanced by the map's size — cannot diverge between them.\nconst mintNumbers = (\n needsMint: readonly boolean[],\n): ReadonlyMap<number, number> =>\n new Map(\n needsMint\n .flatMap((mint, i) => (mint ? [i] : []))\n .map((position, k) => [position, k + 1] as const),\n );\n\n// Derive a stable id per item by reconciling the live items against the\n// last-seen items. Ids follow items by identity/value, so resets and\n// mutations that bypass the array ops (setValue of a whole array, restore)\n// keep keys glued to their rows — not just length-preserving appends/\n// truncations. A same-index fallback keeps an edited row's id (editing\n// produces a fresh item reference at the same position) without remounting\n// it. This is the FALLBACK path: array ops (hook-issued OR imperative)\n// replay their exact recorded mappings via the core's op log first (see\n// deriveIds), because value matching cannot tell Object.is-equal rows\n// apart.\nconst reconcileIds = (prev: IdState, nextItems: readonly unknown[]): IdState => {\n if (prev.items === nextItems) return prev;\n if (\n prev.items.length === nextItems.length &&\n prev.items.every((item, i) => Object.is(item, nextItems[i]))\n ) {\n // Same rows, fresh array reference (a normalization pass, a server\n // refresh of unchanged data): the ids are unchanged but the anchor\n // MUST move to the live reference — a later op's record chains from\n // it, and a stale anchor would silently break replay back to value\n // matching (the duplicate-row bug all over again).\n return { ...prev, items: nextItems };\n }\n\n // Bucket prev positions by item so duplicate primitives match in order.\n const buckets = prev.items.reduce<Map<unknown, number[]>>((acc, item, i) => {\n const bucket = acc.get(item);\n if (bucket === undefined) {\n acc.set(item, [i]);\n } else {\n bucket.push(i);\n }\n return acc;\n }, new Map());\n\n // First pass: reuse the id of the matching prev item, consuming that slot so\n // each id is reused at most once (`shift` empties the bucket as we go).\n const matchedIds: readonly (string | null)[] = nextItems.map((item) => {\n const prevIndex = buckets.get(item)?.shift();\n return prevIndex === undefined ? null : (prev.ids[prevIndex] ?? null);\n });\n\n // Second pass: an unmatched item reuses its SAME-INDEX leftover id (an\n // in-place edit keeps its row); any other leftover id belongs to a row\n // that is genuinely gone. Handing those out positionally would let a\n // remove-then-push in one batch key the new row with the deleted row's\n // id — a React reorder that resurrects the dead row's DOM state — so\n // they die and new items mint fresh ids instead. (Trade-off: an edit\n // that also MOVES in the same write remounts; value-identity matching\n // above already covers pure moves.)\n const leftoverAt = new Map(\n [...buckets.values()].flat().flatMap((i) => {\n const id = prev.ids[i];\n return id === undefined ? [] : ([[i, id]] as const);\n }),\n );\n const reused = matchedIds.map((id, i) => id ?? leftoverAt.get(i) ?? null);\n\n const mints = mintNumbers(reused.map((id) => id === null));\n const ids = reused.map(\n (id, i) => id ?? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`,\n );\n\n return {\n items: nextItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// Apply an exact index mapping to the id list: nextIds[i] =\n// prev.ids[mapping[i]], with -1 minting a fresh id (a new row). Returns null\n// — falling back to value reconciliation — unless every carried position's\n// live item is identity-equal to the recorded previous item, so a mapping\n// can never mis-key rows the store changed some other way (a refused\n// out-of-bounds op, an interleaved setValue).\nconst mappedIdState = (\n prev: IdState,\n mapping: readonly number[],\n liveItems: readonly unknown[],\n): IdState | null => {\n if (liveItems.length !== mapping.length) return null;\n const aligned = mapping.every((src, i) =>\n src === -1\n ? true\n : prev.ids[src] !== undefined &&\n Object.is(liveItems[i], prev.items[src]),\n );\n if (!aligned) return null;\n // (In practice an op mapping mints at most one row — push/insert — but\n // the numbering stays general via the shared scheme.)\n const mints = mintNumbers(mapping.map((src) => src === -1));\n const ids = mapping.map((src, i) =>\n src === -1\n ? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`\n : (prev.ids[src] as string),\n );\n return {\n items: liveItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// One id state per (form store, path), shared by EVERY hook instance on\n// that array so sibling hooks always agree on row ids. A sanctioned\n// mutable-ref cache (like the core's subschemaCache): the entry is derived\n// bookkeeping — each commit is a pure function of a REAL store state, so a\n// discarded render leaves a sound (if not identical) state behind: rows may\n// remint where reuse was possible (a cosmetic remount), but a surviving row\n// can never receive another row's id. Entries are access-ordered and capped\n// so a long-lived store with churning dynamic paths (rows.N.tags) can't\n// accumulate snapshots forever; the WeakMap releases the rest with the\n// store.\ntype SharedIdEntry = { state: IdState };\ntype StoreIdEntries = { byPath: Map<string, SharedIdEntry>; seq: number };\n\n// Generous like path.ts's PARSE_CACHE_MAX: eviction of a MOUNTED array's\n// entry remints every row id (a full remount), so the cap is a backstop\n// against unbounded dynamic-path churn, never a working-set limit.\nconst MAX_ID_PATHS = 4096;\nconst sharedIdEntries = new WeakMap<object, StoreIdEntries>();\n\nconst sharedIdEntry = (store: object, path: string): SharedIdEntry => {\n const existingStore = sharedIdEntries.get(store);\n const forStore = existingStore ?? { byPath: new Map(), seq: 1 };\n if (existingStore === undefined) sharedIdEntries.set(store, forStore);\n const existing = forStore.byPath.get(path);\n if (existing !== undefined) {\n // Re-insert to refresh recency, so eviction takes the longest-unused\n // path, not merely the oldest-created.\n forStore.byPath.delete(path);\n forStore.byPath.set(path, existing);\n return existing;\n }\n // Prefix from a PER-STORE sequence (deterministic per form, unlike a\n // module-global counter whose value depends on app-wide first-touch\n // order), so ids from different arrays — or a hook whose dynamic path\n // switches — can never collide as React keys.\n const created: SharedIdEntry = {\n state: {\n items: EMPTY_ITEMS,\n ids: [],\n counter: 0,\n prefix: `__zfa_${forStore.seq}_`,\n },\n };\n forStore.seq += 1;\n forStore.byPath.set(path, created);\n if (forStore.byPath.size > MAX_ID_PATHS) {\n const oldest = forStore.byPath.keys().next().value;\n if (oldest !== undefined) forStore.byPath.delete(oldest);\n }\n return created;\n};\n\n// Walk EVERY record in order, applying its exact mapping. A gap before a\n// record (a chain-breaking write between ops — though the core now clears\n// records at such writes, so gaps are rare) bridges by value to the\n// record's `from` first, so an op keeps its exactness no matter which side\n// of a whole-array write it fell on. The final hop to the live items — when\n// the last record didn't land there — reconciles by value too.\nconst walkOps = (\n start: IdState,\n items: readonly unknown[],\n ops: readonly ArrayOpRecord[],\n): IdState => {\n const walked = ops.reduce<IdState>((acc, op) => {\n const base = acc.items === op.from ? acc : reconcileIds(acc, op.from);\n return mappedIdState(base, op.mapping, op.to) ?? base;\n }, start);\n return walked.items === items ? walked : reconcileIds(walked, items);\n};\n\nconst deriveIds = (\n store: object,\n path: string,\n items: readonly unknown[],\n): IdState => {\n const entry = sharedIdEntry(store, path);\n if (entry.state.items === items) return entry.state;\n const ops = arrayOpsFor(store, path);\n // The walk consumes every record, so the log is spent bookkeeping\n // afterwards — clear it, which also keeps ring composition from ever\n // merging a record a consumer is still anchored at. (The one residual:\n // a render discarded between clear and commit re-derives the final hop\n // by value — sound ids, possibly reminted where reuse was possible.)\n if (ops.length > 0) clearArrayOps(store, path);\n const next = walkOps(entry.state, items, ops);\n entry.state = next;\n return next;\n};\n\n// The element type at an array-valued path. FieldValue re-adds `| undefined`\n// for arrays reached through optional ancestors, so strip that before\n// extracting; a non-array path yields `never`, which makes every write\n// (`push(never)`) an immediate error instead of a silently-`unknown` bind.\nexport type ArrayItemOf<T> = [NonNullable<T>] extends [readonly (infer U)[]]\n ? U\n : never;\n\n// The readable-error trap-guard, mirroring useField's: an explicit type\n// argument (`useFieldArray<Item>(typedForm, \"users\")`) arity-matches ONLY\n// the one-type-parameter overloads, and the structural one's brand then\n// rejects the Form with a baffling \"... not assignable to type\n// 'undefined'\". The error overload below intercepts that shape — TItem\n// defaults to this unexported sentinel, which inferred calls can never\n// escape (TItem has no inference site), collapsing `path` to `never`; an\n// explicit TItem on a schema-carrying form instead types `path` as a\n// string-literal instruction the compiler blames the path argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the\n// typed-path overload sits last so a typo'd path on a Form<TSchema> is\n// blamed on the path argument against the full FieldPath union, and the\n// `schema?: undefined` brand forces a real Form past the widened structural\n// overload — without it, `useFieldArray(form, \"users\")` would bind there\n// and return UseFieldArrayReturn<unknown> instead of inferring the item\n// type from the path. Schema-less FieldFormApi forms keep the explicit\n// TItem parameter (there is nothing to infer from).\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useFieldArray<Schema,\n// \"tags\">`) — TS applies explicit type args to every arity-compatible\n// overload, so a second parameter here would check \"tags\" against it.\nexport function useFieldArray<TSchema extends z.ZodType>(\n form: FieldArrayFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n): UseFieldArrayReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): explicit type argument on a\n// schema-carrying form → readable error on the path argument; inferred\n// calls fall through (path collapses to never).\nexport function useFieldArray<TItem = InferredTypeArg>(\n form: FieldArrayFormApi & Readonly<{ schema: z.ZodType }>,\n path: TItem extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the item type from the path\",\n): UseFieldArrayReturn<TItem>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem>;\n// D last with a default (P's constraint forward-references it), preserving\n// the arity of explicit instantiations like\n// `useFieldArray<typeof schema, \"tags\">`.\nexport function useFieldArray<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi,\n pathArg: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem> {\n const path = useStore(form.store, (state) =>\n typeof pathArg === \"function\" ? pathArg(state) : pathArg,\n );\n const slice = useStore(\n form.store,\n useShallow((state) => {\n const value = getAtPath(state.values, path);\n return {\n items: (Array.isArray(value) ? value : EMPTY_ITEMS) as readonly TItem[],\n error: state.errors[path],\n };\n }),\n );\n const items = slice.items;\n const error = slice.error;\n\n // Ids derive from the shared per-(store, path) entry: the core's op log\n // replays each array op's exact index mapping (hook-issued or imperative\n // — both go through applyArrayOp, which records them), and value\n // reconciliation covers everything else (setValue of a whole array,\n // restore, resets). Deriving during render is safe because the entry is\n // a convergent cache — every commit is a pure function of a real store\n // state — and cheap because it early-exits on the same items reference.\n // All hook instances on the same path read the same entry, so their ids\n // can never disagree.\n const ids = deriveIds(form.store, path, items).ids;\n\n // After every op, revalidate the ARRAY path under the exact change-trigger\n // gate useField.setValue applies (same shouldValidateOn call), so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. The result is deliberately unhandled — the core self-routes async\n // schemas (validateField returns { kind: \"pending\" } having already started\n // the async pass). validateField is probed: a hand-rolled FieldArrayFormApi\n // without it skips revalidation instead of crashing. The IMPERATIVE\n // form.arrayPush/arrayRemove stay non-revalidating on purpose — the same\n // layering as form.setValue (raw write) vs useField.setValue (write + gate).\n const revalidate = useCallback(() => {\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n state.touched[path] ?? false,\n )\n ) {\n form.validateField?.(path);\n }\n }, [form, path]);\n\n const push = useCallback(\n (item: TItem) => {\n form.arrayPush(path, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const remove = useCallback(\n (index: number) => {\n form.arrayRemove(path, index);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const insert = useCallback(\n (index: number, item: TItem) => {\n form.arrayInsert(path, index, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const move = useCallback(\n (from: number, to: number) => {\n form.arrayMove(path, from, to);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const swap = useCallback(\n (a: number, b: number) => {\n form.arraySwap(path, a, b);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const fields = useMemo<readonly FieldArrayEntry<TItem>[]>(\n () =>\n items.map((value, index) => ({\n id: ids[index] ?? `__zfa_fallback_${index}`,\n value,\n })),\n [items, ids],\n );\n\n const setError = useCallback(\n // Same string-shorthand normalization as useField.setError, so custom\n // implementations typed for readonly string[] never receive a bare\n // string.\n (errors: string | readonly string[]) =>\n form.setError?.(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(() => form.clearErrors?.(path), [form, path]);\n\n return useMemo(\n () => ({\n path,\n fields,\n items,\n length: items.length,\n error,\n firstError: error?.[0],\n setError,\n clearError,\n push,\n remove,\n insert,\n move,\n swap,\n }),\n [path, fields, items, error, setError, clearError, push, remove, insert, move, swap],\n );\n}\n","import { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\nexport const useFormError = (\n form: FormStateApi,\n): readonly string[] | undefined =>\n useStore(\n form.store,\n useShallow((state) => state.errors[\"\"]),\n );\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Whole-values subscription in render — sugar for\n// useFormSelector(form, (s) => s.values), the render-side sibling of\n// form.watchValues. The classic use is derived rendering driven by live\n// form values (a map re-rendering as coordinates are edited).\n//\n// Deliberately NOT shallow-compared: the store replaces the values object\n// immutably on every value change, so reference equality (useStore's\n// default Object.is) is exactly right — one comparison, re-render if and\n// only if some value changed. Unrelated state changes (touched, errors,\n// isSubmitting) leave the values reference alone and cause no re-render.\n\nexport function useFormValues<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>): z.input<TSchema>;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above — same rule as\n// useFormSelector. Structural forms have nothing to infer from and read\n// `unknown`.\nexport function useFormValues(\n form: FormStateApi & { readonly schema?: undefined },\n): unknown;\nexport function useFormValues(form: FormStateApi): unknown {\n return useStore(form.store, (state) => state.values);\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// Composite fields: ONE control backed by SEVERAL schema paths — a\n// coordinate pair behind a single map-driven input, a range's min/max, a\n// date span. Binding each path with its own useField works, but the\n// coordination (a combined error line, one blur, one touched/dirty answer)\n// is the same hand-written boilerplate every time. useFields binds the\n// paths together:\n//\n// const location = useFields(form, [\"latitude\", \"longitude\"]);\n// const [latitude, longitude] = location.fields; // full UseFieldReturns\n// <span>{location.firstError}</span> // combined error line\n//\n// Each element of `fields` is a REAL UseFieldReturn — it spreads into the\n// same prop builders and Bound components a solo binding would — and the\n// wrapper adds the combined view: errors merged in path order (deduped, so\n// a cross-field superRefine that stamps both paths reads once), touched /\n// dirty / isValidating as \"any of them\", and one onBlur that blurs every\n// path (each under the form's own validation mode gate).\n//\n// THE PATHS TUPLE IS PART OF THE HOOK CONTRACT: its length and order must\n// be stable across renders, because it expands to exactly that many hook\n// calls. React enforces this itself — a tuple that changes length throws\n// the \"Rendered fewer/more hooks than expected\" dev error at the very\n// render that broke the contract (pinned by the test suite), so pass a\n// literal or a module-level constant, never a filtered array.\n\nexport type UseFieldsReturn<TFields extends readonly unknown[]> = Readonly<{\n fields: TFields;\n // Every bound path's messages, merged in path order and deduped.\n error: readonly string[] | undefined;\n firstError: string | undefined;\n // \"Any of them\": one answer for the composite control's chrome.\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n // Blurs every bound path — each under the form's validation mode gate,\n // so the composite behaves like one control losing focus.\n onBlur: () => void;\n}>;\n\n// Schema-less forms keep the caller-typed shape (the `schema?: undefined`\n// brand forces a real Form past this overload, mirroring useField).\nexport function useFields(\n form: FieldFormApi & { readonly schema?: undefined },\n paths: readonly string[],\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]>;\n// The typed overload: `paths` is a const-inferred tuple and `fields` maps\n// it position-for-position, so destructuring keeps each path's exact value\n// type. D is recovered from the form (the \"~pathDepth\" marker), like the\n// sibling hooks.\nexport function useFields<\n TSchema extends z.ZodType,\n const P extends readonly FieldPath<z.input<TSchema>, D>[],\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n paths: P,\n): UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\nexport function useFields(\n form: FieldFormApi,\n paths: readonly string[],\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> {\n const fields = paths.map((path) =>\n // eslint-disable-next-line react-hooks/rules-of-hooks -- a fixed hook count by the stable-arity contract above; each element must be a REAL UseFieldReturn so it spreads into the prop builders\n useField(form as FieldFormApi & { readonly schema?: undefined }, path),\n );\n const merged = [...new Set(fields.flatMap((field) => field.error ?? []))];\n return {\n fields,\n error: merged.length > 0 ? merged : undefined,\n firstError: merged[0],\n touched: fields.some((field) => field.touched),\n dirty: fields.some((field) => field.dirty),\n isValidating: fields.some((field) => field.isValidating),\n onBlur: () => {\n fields.forEach((field) => {\n field.onBlur();\n });\n },\n };\n}\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type { DefaultPathDepth, FieldPath, PathDepth } from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport { isPathOrChild } from \"../core/validation\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Both flag hooks take an optional path and scope to it with the same\n// prefix semantics as the rest of the library (isPathOrChild): \"shipping\"\n// covers \"shipping.city\". Omitted path = whole form. Overload order mirrors\n// useField: the typed-path overload sits last so a typo'd path on a\n// Form<TSchema> is blamed against the full FieldPath union, and the\n// `schema?: undefined` brand keeps real Forms off the widened string\n// overload. Subscriptions are boolean-only — the component re-renders when\n// the flag flips, not on every keystroke (unlike useField(...).dirty).\n\n// Derived from the values (memoized per values reference), so it always\n// agrees with per-field dirty reads. The scoped form compares just the\n// subtree at `path` — a missing path on both sides reads as clean.\nexport function useIsDirty(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsDirty<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsDirty(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) =>\n path === undefined || path === \"\"\n ? isFieldDirty(state.values, state.initialValues)\n : isFieldDirty(\n getAtPath(state.values, path),\n getAtPath(state.initialValues, path),\n ),\n );\n}\n\n// \"No errors currently in the merged map\" (not a fresh validation pass);\n// the scoped form only looks at errors at or under `path`, including the\n// path's own key (array-level errors like `items` count for path \"items\").\nexport function useIsValid(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValid<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValid(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n // A loop rather than Object.entries().some(): this selector re-runs on\n // EVERY store change, and the loop exits at the first error without\n // materializing an entries array for a map that is usually empty.\n for (const k in state.errors) {\n const errs = state.errors[k];\n if (\n errs !== undefined &&\n errs.length > 0 &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return false;\n }\n }\n return true;\n });\n}\n\n// Whether async validation is in flight — form-level (a whole-form pass,\n// or any field's own pass) or scoped to a path subtree, boolean-only like\n// the sibling flags. The form-level read was previously reachable only\n// through a selector, asymmetric with useIsSubmitting.\nexport function useIsValidating(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValidating<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValidating(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n if (path === undefined || path === \"\") {\n if (state.isValidatingForm) return true;\n }\n // Same first-hit loop rationale as useIsValid: this selector re-runs\n // on every store change over a usually-empty map.\n for (const k in state.isValidating) {\n if (\n state.isValidating[k] === true &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return true;\n }\n }\n return false;\n });\n}\n\nexport const useIsSubmitting = (form: FormStateApi): boolean =>\n useStore(form.store, (state) => state.isSubmitting);\n\nexport const useSubmitCount = (form: FormStateApi): number =>\n useStore(form.store, (state) => state.submitCount);\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldFormApi,\n type UseFieldOptions,\n type UseFieldReturn,\n useField,\n} from \"./useField\";\nimport {\n type UnionValueAt,\n type VariantFieldValue,\n type VariantFieldPath,\n useVariantField,\n} from \"./useVariantField\";\nimport {\n type ArrayItemOf,\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport { useFormError } from \"./useFormError\";\nimport { useFormValues } from \"./useFormValues\";\nimport {\n type FormStep,\n type UseFormStepsReturn,\n useFormSteps,\n} from \"./useFormSteps\";\nimport { type UseFieldsReturn, useFields } from \"./useFields\";\nimport {\n useIsDirty,\n useIsSubmitting,\n useIsValid,\n useIsValidating,\n useSubmitCount,\n} from \"./useFormFlags\";\nimport {\n type FormStateApi,\n useFormSelector,\n useFormSelectorShallow,\n} from \"./useFormSelector\";\n\n// createFormHooks(form, name?) — every hook, pre-wired to one form. The\n// context-free way to share a form: create it at module scope, export the\n// returned hooks, and no component ever passes `form` through props or a\n// provider. The optional name is baked into the hook names (both at the\n// type level and at runtime), so a module reads like a domain API:\n//\n// const form = createForm(invoiceSchema, { initialValues });\n// export const { useInvoiceField, useInvoiceFieldArray, useInvoiceIsDirty } =\n// createFormHooks(form, \"invoice\");\n//\n// Typed paths survive the binding: useInvoiceField(\"customer\") infers the\n// value type from the schema, and a typo'd path is a compile error.\n//\n// Reach for this when the form is a genuine module-level singleton (one\n// instance for the app's lifetime — settings, a global compose box). For a\n// form that mounts per page/dialog with its own lifecycle, use useForm and\n// createFormContext instead: a module singleton never unmounts, so state\n// persists across navigations until you reset() it.\n\n// The bound signatures mirror the unbound hooks minus the form parameter;\n// the typed-path call signature sits last for the same error-blame reason\n// as the originals.\nexport type BoundUseField<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n options?: UseFieldOptions,\n ): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\n};\n\n// The variant-field accessor bound to the form: the type math (variant\n// paths, value across resolving variants) lives in useVariantField; the\n// bound signature just drops the form parameter.\nexport type BoundUseVariantField<TSchema extends z.ZodType> = <\n P extends string,\n // Default depth, matching the unbound hook (see its comment on why the\n // constraint cannot ride the form's D).\n TField extends VariantFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n>(\n unionPath: P,\n field: TField,\n) => UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\n\nexport type BoundUseFieldArray<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n ): UseFieldArrayReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\n};\n\nexport type BoundUseSelector<TSchema extends z.ZodType> = <U>(\n selector: (state: FormState<z.input<TSchema>>) => U,\n) => U;\n\nexport type BoundUseFlag<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = (\n path?: FieldPath<z.input<TSchema>, D>,\n) => boolean;\n\n// One single-key mapped type per hook, intersected: template-literal keys\n// carry the capitalized name, so the destructured names are typo-checked\n// ({ useInvoceField } fails to compile against createFormHooks(f, \"invoice\")).\nexport type FormHooks<\n TSchema extends z.ZodType,\n N extends string,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<\n { [K in `use${Capitalize<N>}Field`]: BoundUseField<TSchema, D> } & {\n [K in `use${Capitalize<N>}VariantField`]: BoundUseVariantField<TSchema>;\n } & {\n [K in `use${Capitalize<N>}FieldArray`]: BoundUseFieldArray<TSchema, D>;\n } & { [K in `use${Capitalize<N>}Selector`]: BoundUseSelector<TSchema> } & {\n [K in `use${Capitalize<N>}SelectorShallow`]: BoundUseSelector<TSchema>;\n } & {\n [K in `use${Capitalize<N>}Error`]: () => readonly string[] | undefined;\n } & { [K in `use${Capitalize<N>}IsDirty`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsValid`]: BoundUseFlag<TSchema, D>;\n } & { [K in `use${Capitalize<N>}IsValidating`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsSubmitting`]: () => boolean;\n } & {\n [K in `use${Capitalize<N>}SubmitCount`]: () => number;\n } & { [K in `use${Capitalize<N>}Values`]: () => z.input<TSchema> } & {\n [K in `use${Capitalize<N>}Fields`]: BoundUseFields<TSchema, D>;\n } & {\n [K in `use${Capitalize<N>}Steps`]: (\n steps: readonly FormStep<z.input<TSchema>, D>[],\n ) => UseFormStepsReturn;\n }\n>;\n\n// The bound composite-fields hook: same const-inferred tuple and\n// position-typed fields as the plain useFields.\nexport type BoundUseFields<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = <const P extends readonly FieldPath<z.input<TSchema>, D>[]>(\n paths: P,\n) => UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\n\n// Runtime twin of TypeScript's Capitalize<N> (ASCII names; a leading\n// non-letter passes through unchanged in both).\nconst capitalize = (name: string): string =>\n name.length === 0 ? name : name.charAt(0).toUpperCase() + name.slice(1);\n\n// D (the form's typed-path depth budget) sits LAST so existing explicit\n// instantiations — createFormHooks<Schema, \"invoice\"> — keep compiling; it\n// is inferred from the form argument anyway.\nexport const createFormHooks = <\n TSchema extends z.ZodType,\n N extends string = \"\",\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n name?: N,\n): FormHooks<TSchema, N, D> => {\n // Calling the unbound hooks through a structural view (no `schema`\n // property) binds their widened overloads — the precise typing is\n // re-established by the Bound* signatures above, which the type tests pin.\n const structural: FieldFormApi & FieldArrayFormApi & FormStateApi = form;\n\n const useBoundField = (\n path: string | ((state: FormState<unknown>) => string),\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown> => useField(structural, path, options);\n\n const useBoundVariantField = (\n unionPath: string,\n field: string,\n ): UseFieldReturn<unknown> =>\n useVariantField(\n structural as FieldFormApi & { readonly schema?: undefined },\n unionPath,\n field,\n );\n\n const useBoundFieldArray = (\n path: string | ((state: FormState<unknown>) => string),\n ): UseFieldArrayReturn<unknown> => useFieldArray(structural, path);\n\n const useBoundSelector = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelector(structural, selector);\n\n const useBoundSelectorShallow = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelectorShallow(structural, selector);\n\n const useBoundError = (): readonly string[] | undefined =>\n useFormError(structural);\n\n const useBoundIsDirty = (path?: string): boolean =>\n useIsDirty(structural, path);\n\n const useBoundIsValid = (path?: string): boolean =>\n useIsValid(structural, path);\n\n const useBoundIsValidating = (path?: string): boolean =>\n useIsValidating(structural, path);\n\n const useBoundIsSubmitting = (): boolean => useIsSubmitting(structural);\n\n const useBoundValues = (): unknown => useFormValues(structural);\n\n const useBoundFields = (\n paths: readonly string[],\n ): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> =>\n useFields(\n structural as FieldFormApi & { readonly schema?: undefined },\n paths,\n );\n\n const useBoundSubmitCount = (): number => useSubmitCount(structural);\n\n const useBoundSteps = (\n steps: readonly FormStep<z.input<TSchema>, D>[],\n ): UseFormStepsReturn => useFormSteps(form, steps);\n\n const prefix = capitalize(name ?? \"\");\n // Computed keys erase to an index signature, so the literal is asserted\n // to the mapped FormHooks type — the real contract, verified by type\n // tests on both the key names and the bound signatures.\n return {\n [`use${prefix}Field`]: useBoundField,\n [`use${prefix}VariantField`]: useBoundVariantField,\n [`use${prefix}FieldArray`]: useBoundFieldArray,\n [`use${prefix}Selector`]: useBoundSelector,\n [`use${prefix}SelectorShallow`]: useBoundSelectorShallow,\n [`use${prefix}Error`]: useBoundError,\n [`use${prefix}IsDirty`]: useBoundIsDirty,\n [`use${prefix}IsValid`]: useBoundIsValid,\n [`use${prefix}IsValidating`]: useBoundIsValidating,\n [`use${prefix}IsSubmitting`]: useBoundIsSubmitting,\n [`use${prefix}SubmitCount`]: useBoundSubmitCount,\n [`use${prefix}Values`]: useBoundValues,\n [`use${prefix}Fields`]: useBoundFields,\n [`use${prefix}Steps`]: useBoundSteps,\n } as FormHooks<TSchema, N, D>;\n};\n","import { type ChangeEvent, type ReactNode, useId, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { FieldPath, PathDepth } from \"../core/fieldPath\";\nimport {\n checkboxProps,\n dateInputProps,\n hasFieldError,\n numberToInputText,\n parseNumberText,\n selectProps,\n textInputProps,\n} from \"./inputProps\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// The paths a bound component accepts for a given `form` prop: when the form\n// carries its schema (a real Form<TSchema>), `path` narrows to the schema's\n// FieldPath union — a typo'd path is a compile error, matching useField's\n// typed overloads. Template-literal paths with a numeric hole\n// (`users.${index}.email`) are part of that union, so dynamic array rows\n// still typecheck. A bare structural FieldFormApi keeps plain string paths.\n// The form's own depth budget (createForm's `pathDepth`, default 9) is\n// recovered alongside the schema, so a widened form widens its bound\n// components' paths too.\nexport type PathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? FieldPath<z.input<TSchema>, D>\n : string;\n\n// Structural stand-in for React.Ref<T>: accepts useRef objects and callback\n// refs (including React 19 cleanup-returning ones — any return type is\n// assignable to a void-returning signature). Declared structurally instead of\n// as React.Ref so it unifies even when the consumer resolves a different\n// @types/react copy than the library.\nexport type FieldRef<T> =\n | ((instance: T | null) => void)\n | Readonly<{ current: T | null }>\n | null;\n\n// The chrome every bound field renders: wrapper, optional label, the\n// control, and the error line. `wrapLabel` puts the control INSIDE the\n// label (the checkbox layout: box, then text) instead of after a preceding\n// sibling label. One component so an a11y change lands everywhere at once.\ntype FieldShellProps = Readonly<{\n id: string;\n errorId: string;\n label: ReactNode | undefined;\n error: readonly string[] | undefined;\n wrapLabel?: boolean;\n children: ReactNode;\n}>;\n\n// Shared id wiring for every bound field: a stable control id, the error\n// line's id derived from it, and the aria-describedby value — set only\n// while an error shows, so assistive tech is never pointed at a node that\n// isn't rendered.\nconst useFieldA11y = (\n error: readonly string[] | undefined,\n): Readonly<{ id: string; errorId: string; describedBy: string | undefined }> => {\n const id = useId();\n const errorId = `${id}-error`;\n return {\n id,\n errorId,\n describedBy: hasFieldError(error) ? errorId : undefined,\n };\n};\n\n// role=\"alert\" announces the message to assistive tech when it appears; the\n// id lets the input point at it via aria-describedby.\nconst ErrorText = ({\n id,\n error,\n}: Readonly<{ id: string; error: readonly string[] | undefined }>) =>\n hasFieldError(error) ? (\n <span className=\"zf-error\" id={id} role=\"alert\">\n {error?.[0]}\n </span>\n ) : null;\n\nconst FieldShell = ({\n id,\n errorId,\n label,\n error,\n wrapLabel,\n children,\n}: FieldShellProps) => (\n <div className=\"zf-field\">\n {wrapLabel === true ? (\n <label htmlFor={id} className=\"zf-label\">\n {children} {label}\n </label>\n ) : (\n <>\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n {children}\n </>\n )}\n <ErrorText id={errorId} error={error} />\n </div>\n);\n\nexport type TextFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n placeholder?: string;\n type?: \"text\" | \"password\" | \"email\" | \"url\" | \"tel\";\n autoComplete?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\nexport const TextField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n type = \"text\",\n autoComplete,\n ref,\n}: TextFieldProps<F>) => {\n const field = useField<string | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...textInputProps(field)}\n type={type}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type DateFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n min?: string;\n max?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\n// <input type=\"date\"> holds Date-typed state: display and parsing go\n// through the shared dateInputProps rules (local calendar-date semantics —\n// see inputProps.ts), so a nullable date clears back to null and an\n// invalid/partial entry writes the field's emptyValue. No raw-text state:\n// unlike number inputs, the date control has no partial entries to\n// preserve — the browser only fires change with \"\" or a complete date.\nexport const DateField = <F extends FieldFormApi>({\n form,\n path,\n label,\n min,\n max,\n ref,\n}: DateFieldProps<F>) => {\n const field = useField<Date | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...dateInputProps(field)}\n min={min}\n max={max}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type NumberFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n placeholder?: string;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport type NumberInputBinding = Readonly<{\n name: string;\n value: string;\n inputMode: \"decimal\";\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype NumberEditState = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a partial\n // entry). When field.value diverges, an external writer (reset/adoptValues/\n // another field) changed it — drop the raw text so the input shows it.\n pushed: number | null | undefined;\n}>;\n\nconst IDLE_EDIT: NumberEditState = { raw: null, pushed: undefined };\n\n// Holds the raw text while editing so intermediate, not-yet-valid numbers\n// (\"-\", \"1.\", \"1e\") stay visible instead of being coerced to \"\". Keystrokes\n// that parse to a number (via the shared parseNumberText rules) are pushed to\n// the form; partial input is kept locally. On blur the display snaps back to\n// the form's canonical value, and an external value change while editing wins\n// over the local text (render-phase derived-state reset).\n// Exported for custom number inputs (and the CLI's kit adapters mirror its\n// semantics): spread the binding onto an <input type=\"text\"> — a naive\n// value={String(field.value)} controlled input eats the \".\" of \"85000.50\"\n// and the \"-\" of \"-5\" as they're typed.\nexport const useNumberInput = (\n field: UseFieldReturn<number | null | undefined>,\n): NumberInputBinding => {\n const [edit, setEdit] = useState<NumberEditState>(IDLE_EDIT);\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit(IDLE_EDIT);\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value: raw ?? numberToInputText(field.value),\n inputMode: \"decimal\",\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = parseNumberText(text);\n switch (parsed.kind) {\n case \"empty\": {\n const empty = field.emptyValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"number\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form value\n // so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n setEdit(IDLE_EDIT);\n field.onBlur();\n },\n };\n};\n\nexport const NumberField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n ref,\n}: NumberFieldProps<F>) => {\n const field = useField<number | null | undefined>(form, path);\n const binding = useNumberInput(field);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n type=\"text\"\n {...binding}\n placeholder={placeholder}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type CheckboxFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport const CheckboxField = <F extends FieldFormApi>({\n form,\n path,\n label,\n ref,\n}: CheckboxFieldProps<F>) => {\n const field = useField<boolean | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n wrapLabel\n >\n <input\n id={a11y.id}\n ref={ref}\n {...checkboxProps(field)}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type SelectFieldOption<T extends string> = Readonly<{\n value: T;\n label: ReactNode;\n}>;\n\nexport type SelectFieldProps<\n T extends string,\n F extends FieldFormApi = FieldFormApi,\n> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n options: readonly SelectFieldOption<T>[];\n // Shown as a disabled first option while the field has no value, so the\n // select stays controlled and the blank state is visible instead of\n // silently displaying the first option. Ignored when `options` itself\n // contains a \"\"-valued entry — that explicit, labelled option IS the\n // blank state and renders instead.\n placeholder?: string;\n ref?: FieldRef<HTMLSelectElement>;\n}>;\n\nexport const SelectField = <T extends string, F extends FieldFormApi>({\n form,\n path,\n label,\n options,\n placeholder,\n ref,\n}: SelectFieldProps<T, F>) => {\n // null included: a nullable enum's \"not chosen yet\" must render the empty\n // option, or the browser shows the first real option while state stays null.\n const field = useField<T | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n const select = selectProps(field);\n // A clearable field (nullable, optional, or defaulted) must be clearable\n // BACK to its emptyValue through the UI, so its empty option stays\n // visible after a choice and stays selectable — selectProps writes the\n // emptyValue for it. Everywhere else the empty option is only a\n // placeholder: visible while nothing is chosen, never selectable.\n // The value condition derives from selectProps' own coercion (undefined,\n // null, and \"\" all render as value \"\"), so any blank the select displays\n // has a matching option by construction. When the options list supplies\n // its OWN \"\"-valued entry, that explicit option IS the blank state —\n // rendering the implicit one too would duplicate the value, and the\n // browser would select the first (unlabelled) match instead.\n const clearable = field.clearable;\n const hasExplicitEmptyOption = options.some((opt) => opt.value === \"\");\n const showEmptyOption =\n !hasExplicitEmptyOption &&\n (clearable || select.value === \"\" || placeholder !== undefined);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <select\n id={a11y.id}\n ref={ref}\n {...select}\n aria-describedby={a11y.describedBy}\n >\n {showEmptyOption ? (\n <option value=\"\" disabled={!clearable}>\n {placeholder ?? \"\"}\n </option>\n ) : null}\n {options.map((opt, index) => (\n // Index-qualified: option lists may legitimately repeat a value\n // (e.g. differently-labelled aliases), and bare value keys would\n // collide.\n <option key={`${index}-${opt.value}`} value={opt.value}>\n {opt.label}\n </option>\n ))}\n </select>\n </FieldShell>\n );\n};\n","import type { ErrorMap } from \"../core/types\";\nimport { isPathOrChild } from \"../core/validation\";\n\n// The shared candidate walk for focusFirstError/focusField: form controls\n// with a `name`, in DOM order. Focusability is a SEPARATE, later filter —\n// matches()/closest() are ancestor walks, so they run on the few\n// name-matched candidates instead of every named control in the document\n// (a failed submit on a page with hundreds of controls shouldn't pay\n// hundreds of DOM traversals to focus one input).\nconst namedControls = (scope: ParentNode): readonly HTMLElement[] => [\n ...scope.querySelectorAll<HTMLElement>(\n \"input[name], select[name], textarea[name]\",\n ),\n];\n\n// Hidden and disabled controls, and controls inside a closed <dialog>,\n// can't take focus — without the filter, a leading <input type=\"hidden\"\n// name=\"csrf\"> would swallow focusFirstError's root fallback, and a name\n// match inside a not-yet-opened dialog would shadow the visible one.\nconst isFocusCandidate = (el: HTMLElement): boolean =>\n !el.matches(':disabled, [type=\"hidden\"]') &&\n el.closest(\"dialog:not([open])\") === null;\n\n// Does `el` actually hold focus? Ask the element's OWN root (document or\n// shadow root): document.activeElement retargets to the shadow HOST for a\n// focused control inside a shadow root, so it would read a successfully\n// focused shadow-DOM control as unfocused. A root that is neither (a\n// detached fragment) has no activeElement — fall back to the document,\n// where a detached element can never be the active one.\nconst holdsFocus = (el: HTMLElement): boolean => {\n const rootNode = el.getRootNode();\n const active =\n rootNode instanceof Document || rootNode instanceof ShadowRoot\n ? rootNode.activeElement\n : document.activeElement;\n return active === el;\n};\n\n// focus() can silently no-op (display:none ancestors and other unfocusable\n// states the cheap filters above can't see) — verify it took, and fall\n// through to the next candidate in DOM order. True only when a control\n// actually holds focus.\nconst focusFirstOf = (candidates: readonly HTMLElement[]): boolean =>\n candidates.some((el) => {\n el.focus();\n return holdsFocus(el);\n });\n\nconst nameMatchesAny = (\n el: HTMLElement,\n paths: readonly string[],\n): boolean => {\n const name = el.getAttribute(\"name\");\n return name !== null && paths.some((p) => isPathOrChild(name, p));\n};\n\n// CSS attribute-selector value for an arbitrary path: quoted, with the two\n// characters that are active inside a double-quoted CSS string escaped —\n// so paths with dots (\"address.region\") and hostile names select literally.\n// Control characters (a stray \"\\n\" in a computed path, DEL) are additionally\n// hex-escaped (`\\a `, with CSS's required trailing space): a raw newline\n// inside a quoted CSS string is a parse error, and querySelectorAll on an\n// invalid selector THROWS instead of matching nothing.\nconst cssQuoted = (value: string): string =>\n `\"${value\n .replace(/[\\\\\"]/g, (ch) => `\\\\${ch}`)\n .replace(\n /[\\x00-\\x1f\\x7f]/g,\n (ch) => `\\\\${ch.codePointAt(0)!.toString(16)} `,\n )}\"`;\n\n// The id fallback for composite widgets that render no `name` at all (e.g.\n// antd's Select — no form-posting input exists in it) but DO forward\n// `id={path}` to their real focusable control, the way the CLI's antd\n// adapter emits it. EXACT id match only, by design: descendant semantics\n// (\"address\" covering \"address.city\") belong to the name walk — an id names\n// one element, and inventing prefix matching over ids would guess. Runs\n// through the same focusability filter and post-focus verification as name\n// matches.\nconst idMatches = (\n scope: ParentNode,\n path: string,\n): readonly HTMLElement[] =>\n path === \"\"\n ? []\n : [...scope.querySelectorAll<HTMLElement>(`[id=${cssQuoted(path)}]`)];\n\n// Document order for a merged candidate list (name matches + id fallbacks\n// come from separate queries, but \"first error\" means first in the DOM).\nconst inDomOrder = (\n els: readonly HTMLElement[],\n): readonly HTMLElement[] =>\n [...els].sort((a, b) =>\n a === b\n ? 0\n : (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n ? -1\n : 1,\n );\n\n// The candidate walk shared by focusFirstError and focusField: name-matched\n// form controls for every path, plus — per path that matched NO named\n// control — the element whose `id` is exactly that path. Paths with a named\n// match never consult ids, so the name walk's semantics (descendants\n// included) stay authoritative wherever a `name` exists.\nconst pathCandidates = (\n scope: ParentNode,\n paths: readonly string[],\n): readonly HTMLElement[] => {\n const controls = namedControls(scope);\n const named = controls.filter((el) => nameMatchesAny(el, paths));\n // \"Has a named match\" is judged against focus-CANDIDATE controls only: a\n // hidden name-carrier (react-select's <input type=\"hidden\" name={path}>\n // value input, notably) can never take focus, so letting it claim the\n // path would suppress the id fallback and leave the real, id={path}\n // focusable control unreachable. The `named` list itself stays\n // pre-filter — callers apply isFocusCandidate to the merged result.\n const focusableControls = controls.filter(isFocusCandidate);\n const unnamedPaths = paths.filter(\n (p) => !focusableControls.some((el) => nameMatchesAny(el, [p])),\n );\n const byId = unnamedPaths.flatMap((p) => idMatches(scope, p));\n return inDomOrder([...new Set([...named, ...byId])]);\n};\n\n// Focus the first form control (in DOM order) whose `name` attribute matches\n// an entry in the error map — either exactly, or as a descendant of an\n// errored container path, so array-level errors (\"lineItems\" from\n// z.array().min()) and object-level refines (\"address\") land on their first\n// rendered field. Most specific wins: the root \"\" key (a form-wide refine)\n// falls back to the first control only when no field-keyed error matches\n// anything — otherwise a root error would steal focus from the actually\n// errored field. A path that matches NO named control at all additionally\n// tries the element whose `id` is exactly that path (see pathCandidates) —\n// how composite widgets with no `name` anywhere, like antd's Select with\n// id={path}, still get focused. The bound components and prop builders set\n// name={path}, so this works out of the box:\n//\n// form.handleSubmit(onValid, (errors) => focusFirstError(errors))\n//\n// Pass `root` to scope the search (e.g. the <form> element via a ref) — on a\n// page with several forms this is the way to keep focus inside YOUR form:\n// without it the search spans the whole document, and the root-\"\" fallback\n// refuses to guess between forms (it returns false when the document holds\n// more than one <form>). Returns whether a control actually received focus —\n// candidates that can't take it (disabled, hidden, inside a closed <dialog>,\n// display:none, ...) are passed over for the next match in DOM order. Safe to\n// import during SSR — it only touches the DOM when called.\nexport const focusFirstError = (\n errors: ErrorMap,\n root?: ParentNode,\n): boolean => {\n const scope = root ?? document;\n const erroredPaths = Object.keys(errors).filter(\n (k) => k !== \"\" && (errors[k]?.length ?? 0) > 0,\n );\n const hasRootError = (errors[\"\"]?.length ?? 0) > 0;\n const controls = namedControls(scope);\n const fieldMatches = pathCandidates(scope, erroredPaths).filter(\n isFocusCandidate,\n );\n // The root-\"\" fallback (\"focus the first control\") is only meaningful when\n // \"first control\" is unambiguous. With the default document scope on a\n // page holding several <form>s, the first control could belong to a form\n // that had nothing to do with this submit — refuse to guess and report\n // false; pass the form element as `root` to disambiguate.\n const rootFallbackApplies =\n hasRootError &&\n (root !== undefined || document.querySelectorAll(\"form\").length <= 1);\n const candidates =\n fieldMatches.length > 0\n ? fieldMatches\n : rootFallbackApplies\n ? controls.filter(isFocusCandidate)\n : [];\n return focusFirstOf(candidates);\n};\n\n// Imperative sibling of focusFirstError, keyed by a path instead of an error\n// map: focus the first control (in DOM order) whose `name` is `path` itself\n// or a descendant of it — focusField(\"address\") lands on the first rendered\n// address field. Same candidate walk (unfocusable controls are passed over,\n// focus is verified to have taken, a name-less path falls back to the\n// element whose `id` is exactly the path) and the same `root` scoping.\n// This is the \"setFocus\" of the library — reach for it after opening a\n// dialog or appending an array row:\n//\n// items.push(emptyItem);\n// requestAnimationFrame(() =>\n// focusField(`items.${items.length}.name`, formRef.current ?? undefined),\n// );\n//\n// The root \"\" path is whole-form scope, consistent with the imperative\n// surface (validateField(\"\") / resetField(\"\")): focus the first focusable\n// control in scope. Like focusFirstError's root-\"\" fallback, \"first control\"\n// under the default document scope is a guess when the page holds several\n// <form>s — focusField refuses to guess and returns false; pass the form\n// element as `root` to disambiguate.\n//\n// Returns whether a control actually received focus. Safe to import during\n// SSR — it only touches the DOM when called.\nexport const focusField = (path: string, root?: ParentNode): boolean => {\n const scope = root ?? document;\n return path === \"\"\n ? (root !== undefined ||\n document.querySelectorAll(\"form\").length <= 1) &&\n focusFirstOf(namedControls(scope).filter(isFocusCandidate))\n : focusFirstOf(pathCandidates(scope, [path]).filter(isFocusCandidate));\n};\n"]}
|