attaform 0.16.4 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +4 -2
  2. package/dist/chunks/devtools.cjs +19 -12
  3. package/dist/chunks/devtools.cjs.map +1 -1
  4. package/dist/chunks/devtools.mjs +19 -12
  5. package/dist/chunks/devtools.mjs.map +1 -1
  6. package/dist/chunks/indexeddb.cjs +1 -1
  7. package/dist/chunks/indexeddb.mjs +1 -1
  8. package/dist/chunks/local-storage.cjs +1 -1
  9. package/dist/chunks/local-storage.mjs +1 -1
  10. package/dist/chunks/session-storage.cjs +1 -1
  11. package/dist/chunks/session-storage.mjs +1 -1
  12. package/dist/index.cjs +26 -7
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +51 -8
  15. package/dist/index.d.mts +51 -8
  16. package/dist/index.d.ts +51 -8
  17. package/dist/index.mjs +28 -9
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/nuxt.d.cts +1 -1
  20. package/dist/nuxt.d.mts +1 -1
  21. package/dist/nuxt.d.ts +1 -1
  22. package/dist/runtime/plugins/attaform.cjs +3 -3
  23. package/dist/runtime/plugins/attaform.cjs.map +1 -1
  24. package/dist/runtime/plugins/attaform.mjs +3 -3
  25. package/dist/runtime/plugins/attaform.mjs.map +1 -1
  26. package/dist/shared/{attaform.Dd_pWnmn.cjs → attaform.0Wg7UEeX.cjs} +51 -10
  27. package/dist/shared/attaform.0Wg7UEeX.cjs.map +1 -0
  28. package/dist/shared/attaform.AOgGyRoI.d.cts +65 -0
  29. package/dist/shared/{attaform.CCQkY4Ta.d.ts → attaform.B0zue7zt.d.ts} +1 -1
  30. package/dist/shared/{attaform.CIwZtbGV.cjs → attaform.BBM2muQ9.cjs} +2 -2
  31. package/dist/shared/{attaform.CIwZtbGV.cjs.map → attaform.BBM2muQ9.cjs.map} +1 -1
  32. package/dist/shared/{attaform.fegmBJaq.cjs → attaform.BFumZXY2.cjs} +1422 -389
  33. package/dist/shared/attaform.BFumZXY2.cjs.map +1 -0
  34. package/dist/shared/attaform.BQ-iGGWd.d.mts +65 -0
  35. package/dist/shared/{attaform.DyV1O4tI.mjs → attaform.BT55rDNN.mjs} +1423 -391
  36. package/dist/shared/attaform.BT55rDNN.mjs.map +1 -0
  37. package/dist/shared/{attaform.CU3JperC.d.cts → attaform.BYbsV2Wv.d.cts} +574 -132
  38. package/dist/shared/{attaform.CU3JperC.d.mts → attaform.BYbsV2Wv.d.mts} +574 -132
  39. package/dist/shared/{attaform.CU3JperC.d.ts → attaform.BYbsV2Wv.d.ts} +574 -132
  40. package/dist/shared/{attaform.keLBaHB6.cjs → attaform.C6_zOf8x.cjs} +228 -113
  41. package/dist/shared/attaform.C6_zOf8x.cjs.map +1 -0
  42. package/dist/shared/{attaform.CJttVxRj.cjs → attaform.C8LVFVVe.cjs} +2 -2
  43. package/dist/shared/{attaform.CJttVxRj.cjs.map → attaform.C8LVFVVe.cjs.map} +1 -1
  44. package/dist/shared/{attaform.BfMxsfmE.mjs → attaform.CIEQgJnM.mjs} +143 -78
  45. package/dist/shared/attaform.CIEQgJnM.mjs.map +1 -0
  46. package/dist/shared/attaform.CX9v2M8k.d.ts +65 -0
  47. package/dist/shared/{attaform.g7rfuXdz.mjs → attaform.Cj0pCNVn.mjs} +228 -113
  48. package/dist/shared/attaform.Cj0pCNVn.mjs.map +1 -0
  49. package/dist/shared/{attaform.CMRmwGDt.d.cts → attaform.ClfCi1i2.d.mts} +1 -1
  50. package/dist/shared/{attaform.UA19EF3J.mjs → attaform.D6Q5ZP8L.mjs} +51 -10
  51. package/dist/shared/attaform.D6Q5ZP8L.mjs.map +1 -0
  52. package/dist/shared/{attaform.CXMOheyZ.d.mts → attaform.D7lomopc.d.cts} +1 -1
  53. package/dist/shared/{attaform.rIRYSUI1.cjs → attaform.Dee2rU1P.cjs} +145 -77
  54. package/dist/shared/attaform.Dee2rU1P.cjs.map +1 -0
  55. package/dist/shared/{attaform.CINUMjPq.mjs → attaform.Vo-Kft0t.mjs} +2 -2
  56. package/dist/shared/{attaform.CINUMjPq.mjs.map → attaform.Vo-Kft0t.mjs.map} +1 -1
  57. package/dist/shared/{attaform.DZRj9s0s.mjs → attaform.h1sq3BFu.mjs} +2 -2
  58. package/dist/shared/{attaform.DZRj9s0s.mjs.map → attaform.h1sq3BFu.mjs.map} +1 -1
  59. package/dist/zod-v3.cjs +3 -3
  60. package/dist/zod-v3.d.cts +5 -5
  61. package/dist/zod-v3.d.mts +5 -5
  62. package/dist/zod-v3.d.ts +5 -5
  63. package/dist/zod-v3.mjs +3 -3
  64. package/dist/zod-v4.cjs +3 -3
  65. package/dist/zod-v4.d.cts +16 -42
  66. package/dist/zod-v4.d.mts +16 -42
  67. package/dist/zod-v4.d.ts +16 -42
  68. package/dist/zod-v4.mjs +3 -3
  69. package/dist/zod.cjs +4 -4
  70. package/dist/zod.cjs.map +1 -1
  71. package/dist/zod.d.cts +6 -5
  72. package/dist/zod.d.mts +6 -5
  73. package/dist/zod.d.ts +6 -5
  74. package/dist/zod.mjs +5 -5
  75. package/dist/zod.mjs.map +1 -1
  76. package/package.json +3 -8
  77. package/dist/shared/attaform.BfMxsfmE.mjs.map +0 -1
  78. package/dist/shared/attaform.Dd_pWnmn.cjs.map +0 -1
  79. package/dist/shared/attaform.DyV1O4tI.mjs.map +0 -1
  80. package/dist/shared/attaform.UA19EF3J.mjs.map +0 -1
  81. package/dist/shared/attaform.fegmBJaq.cjs.map +0 -1
  82. package/dist/shared/attaform.g7rfuXdz.mjs.map +0 -1
  83. package/dist/shared/attaform.keLBaHB6.cjs.map +0 -1
  84. package/dist/shared/attaform.rIRYSUI1.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attaform.BT55rDNN.mjs","sources":["../../src/runtime/core/path-walker.ts","../../src/runtime/core/diff-apply.ts","../../src/runtime/core/field-meta.ts","../../src/runtime/core/humanize.ts","../../src/runtime/core/field-state-api.ts","../../src/runtime/core/surface-proxy.ts","../../src/runtime/core/errors-proxy.ts","../../src/runtime/core/field-arrays.ts","../../src/runtime/core/field-state-proxy.ts","../../src/runtime/core/defaults.ts","../../src/runtime/core/persistence/index.ts","../../src/runtime/core/error-codes.ts","../../src/runtime/core/process-form.ts","../../src/runtime/core/extract-schema-fields.ts","../../src/runtime/core/slim-primitive-gate.ts","../../src/runtime/core/schema-coerce.ts","../../src/runtime/core/register-api.ts","../../src/runtime/core/unset.ts","../../src/runtime/core/unset-walker.ts","../../src/runtime/core/values-proxy.ts","../../src/runtime/core/build-form-api.ts","../../src/runtime/core/should-show-errors.ts","../../src/runtime/core/create-form-store.ts","../../src/runtime/core/get-computed-schema.ts","../../src/runtime/core/history.ts","../../src/runtime/core/hash.ts","../../src/runtime/core/multi-tab-sync.ts","../../src/runtime/core/insecure-context-warn.ts","../../src/runtime/composables/use-abstract-form.ts","../../src/runtime/composables/use-form-context.ts"],"sourcesContent":["import type { Path, Segment } from './paths'\n\n/**\n * The minimal slice of `AbstractSchema` the structural-completeness\n * helpers need. Declared inline (not imported from types-api) so this\n * file stays free of cyclic imports — types-api imports types-core,\n * types-core does not import types-api, and this file is consumed by\n * core/create-form-store.ts which sits between the two.\n */\nexport type SchemaForFill = {\n getDefaultAtPath(path: Path): unknown\n /**\n * Distinguish tuple (number — structural length) from unbounded\n * array (null) at `path`. `undefined` signals \"fall back to the\n * runtime's index-probe loop\" for adapters that can't introspect.\n * See `AbstractSchema.arrayShapeAtPath` for the full contract.\n */\n arrayShapeAtPath(path: Path): number | null | undefined\n}\n\n/**\n * Structured-path get/set primitives. Replace `lodash-es/get` and\n * `lodash-es/set` for internal callers that speak `Path` rather than\n * dotted strings.\n *\n * Semantics:\n * - `getAtPath` returns `undefined` for any path that traverses through\n * a non-descendable value (null, primitive, function). This preserves\n * distinctions: `null` at the exact target is returned as `null`, not\n * as `undefined`; only missing / non-descendable intermediates collapse.\n * - `setAtPath` is copy-on-write at every level from root to target. New\n * intermediate containers are created according to the segment type:\n * numeric segments produce arrays, string segments produce plain objects.\n * Sibling values at each level are preserved by reference (structural\n * sharing), so the non-touched subtrees stay reference-equal for\n * downstream `Object.is` checks in `diffAndApply`.\n */\n\nconst NOT_FOUND: unique symbol = Symbol('NOT_FOUND')\n\nfunction descendStep(value: unknown, segment: Segment): unknown | typeof NOT_FOUND {\n if (value === null || value === undefined) return NOT_FOUND\n if (typeof value !== 'object') return NOT_FOUND\n if (Array.isArray(value)) {\n if (typeof segment !== 'number') return NOT_FOUND\n if (segment < 0 || segment >= value.length) return NOT_FOUND\n return value[segment]\n }\n const record = value as Record<string, unknown>\n const key = typeof segment === 'number' ? String(segment) : segment\n if (!(key in record)) return NOT_FOUND\n return record[key]\n}\n\nexport function getAtPath(root: unknown, path: Path): unknown {\n if (path.length === 0) return root\n let current: unknown = root\n for (const segment of path) {\n const next = descendStep(current, segment)\n if (next === NOT_FOUND) return undefined\n current = next\n }\n return current\n}\n\n/**\n * Returns true iff `path` exists in `root` as a descendable chain to a leaf\n * or to a defined value. Distinguishes \"exists and is undefined\" (rare but\n * possible with explicit assignment) from \"missing\".\n */\nexport function hasAtPath(root: unknown, path: Path): boolean {\n if (path.length === 0) return true\n let current: unknown = root\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i] as Segment\n const next = descendStep(current, segment)\n if (next === NOT_FOUND) return false\n current = next\n }\n const last = path[path.length - 1] as Segment\n if (current === null || current === undefined) return false\n if (typeof current !== 'object') return false\n if (Array.isArray(current)) {\n return typeof last === 'number' && last >= 0 && last < current.length\n }\n const key = typeof last === 'number' ? String(last) : last\n return key in (current as Record<string, unknown>)\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false\n if (Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value) as object | null\n return proto === null || proto === Object.prototype\n}\n\nexport function setAtPath(root: unknown, path: Path, value: unknown): unknown {\n return setAtPathOffset(root, path, value, 0)\n}\n\nfunction setAtPathOffset(root: unknown, path: Path, value: unknown, offset: number): unknown {\n if (offset >= path.length) return value\n\n const head = path[offset] as Segment\n const nextOffset = offset + 1\n\n if (typeof head === 'number') {\n const arr = Array.isArray(root) ? [...root] : []\n // Extend sparse arrays with undefined slots up to the target index.\n while (arr.length <= head) arr.push(undefined)\n arr[head] = setAtPathOffset(arr[head], path, value, nextOffset)\n return arr\n }\n\n const rec: Record<string, unknown> = isPlainRecord(root) ? { ...root } : {}\n rec[head] = setAtPathOffset(rec[head], path, value, nextOffset)\n return rec\n}\n\n/**\n * Copy-on-write deletion of `path` from `root`. Returns a fresh root\n * with the targeted leaf (or container) removed; siblings stay\n * reference-equal. Missing intermediates short-circuit and return\n * `root` unchanged.\n *\n * Array semantics: deleting a numeric index splices the array (length\n * shrinks by one). Object semantics: deleting a string key removes the\n * own-property and shrinks the key set by one.\n *\n * Used by the persistence layer's `clearPersistedDraft(path)` to wipe\n * a single subpath from the persisted entry without disturbing other\n * paths the user might have opted in.\n */\nexport function deleteAtPath(root: unknown, path: Path): unknown {\n return deleteAtPathOffset(root, path, 0)\n}\n\nfunction deleteAtPathOffset(root: unknown, path: Path, offset: number): unknown {\n if (offset >= path.length) return undefined\n\n const head = path[offset] as Segment\n const isLeafStep = offset === path.length - 1\n const nextOffset = offset + 1\n\n if (typeof head === 'number') {\n if (!Array.isArray(root)) return root\n if (head < 0 || head >= root.length) return root\n if (isLeafStep) {\n const arr = [...root]\n arr.splice(head, 1)\n return arr\n }\n const arr = [...root]\n arr[head] = deleteAtPathOffset(arr[head], path, nextOffset)\n return arr\n }\n\n if (!isPlainRecord(root)) return root\n if (isLeafStep) {\n const rec: Record<string, unknown> = { ...root }\n delete rec[head]\n return rec\n }\n if (!(head in root)) return root\n const rec: Record<string, unknown> = { ...root }\n rec[head] = deleteAtPathOffset(rec[head], path, nextOffset)\n return rec\n}\n\n/**\n * Recursive merge that fills consumer-supplied gaps with the schema's\n * prescribed defaults. The runtime calls this on every `setValueAtPath`\n * write (and on whole-form callback returns) so the form remains\n * structurally complete after the write.\n *\n * Semantics:\n * - Plain object: every schema-default key not present in `consumer`\n * is filled with the schema default's value at that key. Schema-only\n * keys recurse into structural completeness; consumer-only keys (not\n * in the schema) survive untouched (validation flags them).\n * - Array: each consumer element is merged with the SCHEMA element\n * default (looked up via `schema.getDefaultAtPath([...path, i])`).\n * Length follows the consumer — padding past the consumer's length\n * is `setAtPathWithSchemaFill`'s job, not this function's.\n * - `null` consumer wins (a deliberate \"clear\" signal — validation\n * catches misuse against non-nullable shapes).\n * - `undefined` consumer falls back to the schema default (treats\n * undefined as \"missing\"). When the schema default is also\n * undefined the result is undefined — schema and consumer agree.\n * - Primitives, Date, RegExp, Map, Set, class instances: consumer\n * wins; no recursion (these are leaves under `isPlainRecord`).\n *\n * Idempotent short-circuit: when consumer is structurally complete\n * relative to defaults the function returns `consumer` by reference,\n * so common-case writes (consumer already complete) allocate nothing.\n */\n/**\n * Resolve the array shape at `scratch`. Returns the tuple's\n * structural length, `null` for unbounded arrays, or `undefined`\n * if the adapter doesn't support `arrayShapeAtPath` (signalling\n * the fallback probe loop).\n *\n * The fallback probes at index `1_000_000` (tuple → `undefined`;\n * array → element default), then probes sequentially up to the cap\n * to discover the tuple length. Built-in zod adapters return a\n * definitive shape so this never fires for them; the fallback\n * exists for third-party adapters that haven't implemented the\n * method.\n */\nfunction resolveArrayShape(schema: SchemaForFill, scratch: Segment[]): number | null | undefined {\n const shape = schema.arrayShapeAtPath(scratch)\n if (shape !== undefined) return shape\n // Legacy probe: high-index lookup distinguishes tuple from array.\n const TUPLE_PROBE_INDEX = 1_000_000\n scratch.push(TUPLE_PROBE_INDEX)\n const probe = schema.getDefaultAtPath(scratch)\n scratch.pop()\n if (probe !== undefined) return null // unbounded array\n // Tuple-like: walk forward to find the structural length. Cap at\n // 1024 to protect against pathological recursive lazies.\n let n = 0\n while (n < 1024) {\n scratch.push(n)\n const v = schema.getDefaultAtPath(scratch)\n scratch.pop()\n if (v === undefined) break\n n++\n }\n return n\n}\n\nexport function mergeStructural(\n schema: SchemaForFill,\n path: Path,\n consumer: unknown,\n defaultValue: unknown = schema.getDefaultAtPath(path)\n): unknown {\n // Internal recursion uses a single mutable scratch path: each level\n // pushes its segment before descending and pops on return. Eliminates\n // the per-recursion `[...path, key]` / `[...path, i]` allocation\n // that previously fired on every object key + every array element.\n // Schema adapters (zod / standard-schema) read `getDefaultAtPath`\n // synchronously and don't retain the path, so passing the live\n // scratch is safe; if a future adapter needed retention, snapshot\n // inside that adapter rather than allocating per-call here.\n const scratch: Segment[] = path.slice()\n return mergeStructuralImpl(schema, scratch, consumer, defaultValue)\n}\n\nfunction mergeStructuralImpl(\n schema: SchemaForFill,\n scratch: Segment[],\n consumer: unknown,\n defaultValue: unknown\n): unknown {\n // Consumer is missing — fall back to the schema default. When the\n // schema default itself is `undefined` (path doesn't exist in the\n // schema), the result is `undefined` and we don't fight it.\n if (consumer === undefined) return defaultValue\n\n // Null wins: deliberate consumer signal. Schema-validation catches\n // null-vs-non-nullable; runtime doesn't override consumer intent.\n if (consumer === null) return null\n\n // Array branch: distinguish tuple-like (fixed length) from array\n // (unbounded) via `arrayShapeAtPath`. Tuples pad consumer to the\n // structural length; unbounded arrays follow the consumer's length\n // and reuse one element default across positions.\n if (Array.isArray(consumer)) {\n const shape = resolveArrayShape(schema, scratch)\n const isTuple = typeof shape === 'number'\n const targetLen = isTuple ? shape : consumer.length\n // Unbounded array: every position resolves to the same element\n // default — query once and reuse. Tuples query per-position\n // since each slot carries its own default.\n let cachedElementDefault: unknown\n let cachedElementDefaultRead = false\n let mutated = targetLen > consumer.length\n const out = consumer.slice() as unknown[]\n while (out.length < targetLen) out.push(undefined)\n for (let i = 0; i < targetLen; i++) {\n scratch.push(i)\n let elemDefault: unknown\n if (isTuple) {\n elemDefault = schema.getDefaultAtPath(scratch)\n } else {\n if (!cachedElementDefaultRead) {\n cachedElementDefault = schema.getDefaultAtPath(scratch)\n cachedElementDefaultRead = true\n }\n elemDefault = cachedElementDefault\n }\n const consumerElem = i < consumer.length ? consumer[i] : undefined\n const merged = mergeStructuralImpl(schema, scratch, consumerElem, elemDefault)\n scratch.pop()\n if (merged !== consumerElem) {\n out[i] = merged\n mutated = true\n }\n }\n return mutated ? out : consumer\n }\n\n // Plain object: fill missing keys from default, recurse on present\n // keys. Consumer-only keys pass through.\n if (isPlainRecord(consumer)) {\n if (!isPlainRecord(defaultValue)) {\n // Default is non-record (or undefined / leaf) — nothing to fill;\n // consumer wins as-is. Recurse just in case consumer holds nested\n // keys that the schema knows about at deeper paths (rare).\n return consumer\n }\n let mutated = false\n const out: Record<string, unknown> = { ...consumer }\n // Fill schema-default keys missing from consumer.\n for (const key of Object.keys(defaultValue)) {\n if (!(key in consumer) || consumer[key] === undefined) {\n const defAtKey = defaultValue[key]\n // Recurse so that filling produces a structurally-complete\n // sub-tree (covers nested-object defaults that themselves\n // contain wrappers / unions).\n scratch.push(key)\n const filled = mergeStructuralImpl(schema, scratch, undefined, defAtKey)\n scratch.pop()\n if (filled !== undefined) {\n out[key] = filled\n mutated = true\n }\n }\n }\n // Recurse into consumer-supplied keys to catch nested gaps.\n for (const key of Object.keys(consumer)) {\n scratch.push(key)\n const merged = mergeStructuralImpl(schema, scratch, consumer[key], defaultValue[key])\n scratch.pop()\n if (merged !== consumer[key]) {\n out[key] = merged\n mutated = true\n }\n }\n return mutated ? out : consumer\n }\n\n // Leaf-ish (primitives, Date, RegExp, Map, Set, class instances) —\n // consumer wins, no recursion.\n return consumer\n}\n\n/**\n * Schema-aware variant of `setAtPath`. When extending past array\n * length, pads new positions with the schema's element default\n * instead of `undefined`. When descending into an object whose\n * intermediate property is missing, fills the intermediate with\n * the schema's default at that sub-path.\n *\n * `value` is the already-mergeStructural'd target value — this\n * function only handles INTERMEDIATE fill. The caller (typically\n * `setValueAtPath` on the form store) is responsible for completing\n * the leaf.\n *\n * Performance: schema lookups happen only at gap sites. The common\n * case (write to existing slot) does a copy-on-write spread without\n * touching the schema. Misuse (`setValue('posts.21', x)` against an\n * empty array) costs `getDefaultAtPath` once for the array element\n * default (cached via `lastArrayDefault`/`lastArrayPathPrefix` for\n * the duration of the call) and N pad inserts.\n */\nexport function setAtPathWithSchemaFill(\n root: unknown,\n schema: SchemaForFill,\n fullPath: Path,\n value: unknown\n): unknown {\n if (fullPath.length === 0) return value\n return setAtPathWithSchemaFillImpl(root, schema, fullPath, value, 0)\n}\n\nfunction setAtPathWithSchemaFillImpl(\n root: unknown,\n schema: SchemaForFill,\n fullPath: Path,\n value: unknown,\n startIdx: number\n): unknown {\n if (startIdx >= fullPath.length) return value\n\n const head = fullPath[startIdx] as Segment\n const isLeafStep = startIdx === fullPath.length - 1\n\n if (typeof head === 'number') {\n const arr = Array.isArray(root) ? [...root] : []\n const prefix = fullPath.slice(0, startIdx)\n // Pad with element defaults if extending past length. Tuple-vs-\n // array detection mirrors mergeStructural: probe at a high index\n // — tuples return `undefined` (out of range), unbounded arrays\n // return the element default. The previous heuristic (compare two\n // adjacent defaults via Object.is) gave wrong answers for arrays\n // of objects (each call yields a fresh object, identity differs)\n // AND for tuples of identical primitives (Object.is(0, 0) === true).\n if (arr.length < head) {\n const scratch: Segment[] = prefix.slice() as Segment[]\n const shape = resolveArrayShape(schema, scratch)\n const tupleLike = typeof shape === 'number'\n // For unbounded arrays, every position resolves to the same\n // element default — cache the lookup once. For tuples, query\n // per-position so each slot's default lands at its own index.\n let cachedArrayDefault: unknown\n if (!tupleLike) {\n scratch.push(0)\n cachedArrayDefault = schema.getDefaultAtPath(scratch)\n scratch.pop()\n }\n while (arr.length < head) {\n const idx = arr.length\n if (tupleLike) {\n scratch.push(idx)\n arr.push(schema.getDefaultAtPath(scratch))\n scratch.pop()\n } else {\n arr.push(cachedArrayDefault)\n }\n }\n }\n\n if (isLeafStep) {\n arr[head] = value\n return arr\n }\n\n // Intermediate step: ensure the slot at `head` is structurally\n // complete BEFORE recursing into the rest of the path. Without\n // this fill, recursion starts from `undefined` and the next level\n // builds a fresh `{}` populated only by the keys the path\n // actually touches — sibling fields (other Person keys, other\n // Address keys) get silently dropped. Same intermediate-fill\n // semantic the object branch applies a few lines below.\n let childRoot = arr[head]\n if (childRoot === undefined || (childRoot !== null && typeof childRoot !== 'object')) {\n childRoot = schema.getDefaultAtPath([...prefix, head])\n }\n arr[head] = setAtPathWithSchemaFillImpl(childRoot, schema, fullPath, value, startIdx + 1)\n return arr\n }\n\n // Object key.\n const rec: Record<string, unknown> = isPlainRecord(root) ? { ...root } : {}\n if (isLeafStep) {\n rec[head] = value\n return rec\n }\n\n // Intermediate: ensure the child exists, filling from the schema\n // default if missing or non-descendable.\n const existing = rec[head]\n let childRoot: unknown\n if (existing === undefined || (existing !== null && typeof existing !== 'object')) {\n const intermPath: Segment[] = [...fullPath.slice(0, startIdx + 1)]\n const intermDefault = schema.getDefaultAtPath(intermPath)\n childRoot = intermDefault\n } else {\n childRoot = existing\n }\n rec[head] = setAtPathWithSchemaFillImpl(childRoot, schema, fullPath, value, startIdx + 1)\n return rec\n}\n","import { deleteAtPath, setAtPath } from './path-walker'\nimport type { Path, Segment } from './paths'\n\n/**\n * Structural diff/apply walker. Used by the state layer to emit per-leaf\n * patches when `setValue` replaces a subtree. Cost scales with the\n * size of the changed subtree, not the full form's leaf count.\n *\n * \"Leaves\" are anything that's not a plain object or array: strings, numbers,\n * booleans, null, undefined, Date, Map, Set, class instances, functions, etc.\n * For forms, this is the right boundary — we don't want to walk into a `Date`\n * or a `File` value.\n */\n\nexport type Patch =\n | { readonly kind: 'added'; readonly path: Path; readonly newValue: unknown }\n | { readonly kind: 'removed'; readonly path: Path; readonly oldValue: unknown }\n | {\n readonly kind: 'changed'\n readonly path: Path\n readonly oldValue: unknown\n readonly newValue: unknown\n }\n\n/**\n * True for plain objects (own prototype === Object.prototype or null) and\n * arrays. Deliberately rejects Map, Set, Date, class instances, functions —\n * those are treated as opaque leaf values.\n */\nfunction isDescendable(value: unknown): value is Record<string, unknown> | readonly unknown[] {\n if (value === null || typeof value !== 'object') return false\n if (Array.isArray(value)) return true\n const proto = Object.getPrototypeOf(value) as object | null\n return proto === null || proto === Object.prototype\n}\n\nfunction appendSegment(prefix: Path, segment: Segment): Path {\n const next: Segment[] = new Array<Segment>(prefix.length + 1)\n for (let i = 0; i < prefix.length; i++) {\n const s = prefix[i]\n // prefix indices are always in-range by construction; the nullish fallback\n // placates noUncheckedIndexedAccess without adding runtime overhead.\n next[i] = s as Segment\n }\n next[prefix.length] = segment\n return next\n}\n\n/**\n * Walk `oldValue` and `newValue` in lockstep, calling `visit(patch)` for every\n * leaf that differs. Identical values (by `Object.is`) produce no patches.\n *\n * Root replacement (when `prefix` is empty and both values are descendable\n * but of different shapes, e.g. object → array) emits a single `'changed'`\n * patch with `path: []`. Callers handling root patches should clear all\n * dependent state.\n */\nexport function diffAndApply(\n oldValue: unknown,\n newValue: unknown,\n prefix: Path,\n visit: (patch: Patch) => void\n): void {\n if (Object.is(oldValue, newValue)) return\n\n const oldIsDescendable = isDescendable(oldValue)\n const newIsDescendable = isDescendable(newValue)\n\n // Missing (undefined) <-> descendable: recurse into the descendable side so\n // every leaf emits an atomic 'added' / 'removed' patch. Populating\n // per-field metadata during form init / dynamic field additions relies on\n // this granularity. Other shape mismatches (primitive <-> object, array <->\n // object) are treated as atomic replacements.\n if (oldValue === undefined && newIsDescendable) {\n if (Array.isArray(newValue)) {\n for (let i = 0; i < newValue.length; i++) {\n diffAndApply(undefined, newValue[i], appendSegment(prefix, i), visit)\n }\n } else {\n const rec = newValue as Record<string, unknown>\n for (const k of Object.keys(rec)) {\n diffAndApply(undefined, rec[k], appendSegment(prefix, k), visit)\n }\n }\n return\n }\n\n if (oldIsDescendable && newValue === undefined) {\n if (Array.isArray(oldValue)) {\n for (let i = 0; i < oldValue.length; i++) {\n diffAndApply(oldValue[i], undefined, appendSegment(prefix, i), visit)\n }\n } else {\n const rec = oldValue as Record<string, unknown>\n for (const k of Object.keys(rec)) {\n diffAndApply(rec[k], undefined, appendSegment(prefix, k), visit)\n }\n }\n return\n }\n\n if (oldIsDescendable && newIsDescendable) {\n const oldIsArray = Array.isArray(oldValue)\n const newIsArray = Array.isArray(newValue)\n\n if (oldIsArray && newIsArray) {\n const oldArr = oldValue\n const newArr = newValue\n const max = Math.max(oldArr.length, newArr.length)\n for (let i = 0; i < max; i++) {\n diffAndApply(oldArr[i], newArr[i], appendSegment(prefix, i), visit)\n }\n return\n }\n\n if (!oldIsArray && !newIsArray) {\n const oldRec = oldValue as Record<string, unknown>\n const newRec = newValue as Record<string, unknown>\n const seen = new Set<string>()\n for (const k of Object.keys(oldRec)) {\n seen.add(k)\n diffAndApply(oldRec[k], newRec[k], appendSegment(prefix, k), visit)\n }\n for (const k of Object.keys(newRec)) {\n if (seen.has(k)) continue\n diffAndApply(oldRec[k], newRec[k], appendSegment(prefix, k), visit)\n }\n return\n }\n\n // object <-> array mismatch at this node. Treat as a full replacement.\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n return\n }\n\n if (oldIsDescendable && !newIsDescendable) {\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n return\n }\n\n if (!oldIsDescendable && newIsDescendable) {\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n return\n }\n\n // Both leaves; they differ (Object.is returned false above).\n if (oldValue === undefined) {\n visit({ kind: 'added', path: prefix, newValue })\n return\n }\n if (newValue === undefined) {\n visit({ kind: 'removed', path: prefix, oldValue })\n return\n }\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n}\n\n/**\n * Apply `source`'s changes to `target` by reassigning only the\n * top-level keys whose subtrees CONTENT-differ. Uses `diffAndApply`'s\n * structural walk (not `Object.is`) to decide which keys changed,\n * because reactive proxies and copy-on-write spreads routinely produce\n * reference-different but content-equal subtrees that we don't want\n * to reassign — reassigning fires Vue's property dep and re-triggers\n * deep watches on that subtree.\n *\n * Returns `true` on success. Returns `false` when `target` and\n * `source` have incompatible shapes (e.g. object ↔ array, or one\n * side isn't a descendable container) — the caller must fall back\n * to wholesale replacement.\n *\n * **Why** (subtle but load-bearing):\n *\n * Vue's reactive proxy for an object-typed Ref gets re-created every\n * time the Ref's value is reassigned wholesale (`form.value = next`).\n * That re-creation fires every deep watch transitively bound to the\n * Ref — even watches whose underlying sub-tree is identity-equal\n * across the swap. When one of those watches reacts by writing back\n * to the form (the canonical \"same as pickup address\" mirror\n * pattern), the watch re-fires synchronously on its own write and\n * the browser tab freezes.\n *\n * The cure is to keep `form.value`'s identity stable across writes\n * and update only the children whose CONTENT actually changed. Deep\n * watches on sibling subtrees see no dep change and stay quiet; the\n * touched child gets a new reference, so reactive consumers tracking\n * THAT path (computeds, directive bindings, etc.) re-evaluate\n * correctly.\n *\n * Old subtree references that get reassigned are orphaned but\n * unmutated — exactly what consumers (history snapshots, captured\n * `prev` callback args) need.\n */\nexport function applyChangedKeys(target: unknown, source: unknown): boolean {\n if (!isDescendable(target) || !isDescendable(source)) return false\n const targetIsArray = Array.isArray(target)\n const sourceIsArray = Array.isArray(source)\n if (targetIsArray !== sourceIsArray) return false\n\n // Find the unique first segments where target and source differ in\n // CONTENT. A root-level patch (path.length === 0) signals an\n // un-recoverable shape mismatch: tell the caller to wholesale-replace.\n // Tracking a sentinel inside `changedFirstSegments` itself rather\n // than a separate flag — keeps eslint's narrowing from declaring\n // the flag dead code (the visitor callback is opaque to its flow\n // analysis).\n const ROOT_SENTINEL = Symbol.for('attaform.applyChangedKeys.rootMismatch')\n const changedFirstSegments = new Set<string | number | symbol>()\n diffAndApply(target, source, [], (patch) => {\n if (patch.path.length === 0) {\n changedFirstSegments.add(ROOT_SENTINEL)\n return\n }\n changedFirstSegments.add(patch.path[0] as string | number)\n })\n if (changedFirstSegments.has(ROOT_SENTINEL)) return false\n\n if (targetIsArray) {\n const t = target as unknown[]\n const s = source as readonly unknown[]\n if (t.length > s.length) t.length = s.length\n for (const idx of changedFirstSegments) {\n if (typeof idx === 'symbol') continue\n const i = typeof idx === 'number' ? idx : Number(idx)\n t[i] = s[i]\n }\n } else {\n const t = target as Record<string, unknown>\n const s = source as Record<string, unknown>\n const sourceKeys = new Set(Object.keys(s))\n for (const k of Object.keys(t)) {\n if (!sourceKeys.has(k)) delete t[k]\n }\n for (const k of changedFirstSegments) {\n if (typeof k === 'symbol') continue\n t[String(k)] = s[String(k)]\n }\n }\n return true\n}\n\n/**\n * Apply a `Patch[]` forward to `root`, returning a fresh root with each\n * patch's `newValue` (or `path` deletion) realised. Uses `setAtPath` /\n * `deleteAtPath` from `path-walker.ts`, which are copy-on-write — each\n * step rebuilds only the spine from root to the touched path, leaving\n * sibling subtrees reference-equal with the input. The result is a\n * structurally-shared successor suitable for use as a history snapshot.\n *\n * Patch semantics:\n * - `added` — set the path to `newValue`. Intermediate containers are\n * created on demand (`setAtPath` handles this).\n * - `removed` — delete the path (array splice / object key deletion).\n * - `changed` — set the path to `newValue`. A root-level `changed`\n * (path: []) replaces `root` wholesale; this matches `diffAndApply`'s\n * \"object ↔ array mismatch at root\" emission.\n *\n * Patches are applied in their emitted order. `diffAndApply` emits\n * array patches in index order, so a sequence like\n * `[changed@1, removed@2]` collapses to the correct final array shape\n * (set then splice).\n */\nexport function applyPatchesForward(root: unknown, patches: readonly Patch[]): unknown {\n let current = root\n for (const patch of patches) {\n if (patch.path.length === 0) {\n current = patch.kind === 'removed' ? undefined : patch.newValue\n continue\n }\n if (patch.kind === 'removed') {\n current = deleteAtPath(current, patch.path)\n } else {\n current = setAtPath(current, patch.path, patch.newValue)\n }\n }\n return current\n}\n\n/**\n * Apply a `Patch[]` in reverse, restoring `root` to its pre-patch state.\n * Walks patches back-to-front and inverts each one's direction:\n * - `added` (forward set) → `deleteAtPath` (remove what was added).\n * - `removed` (forward delete) → `setAtPath` with `oldValue`.\n * - `changed` (forward set newValue) → `setAtPath` with `oldValue`.\n *\n * Reverse traversal matters because `diffAndApply` emits array patches\n * in index order. A forward sequence `[changed@1, removed@2]` applied\n * forward yields the new array; to invert, the splice at index 2 must\n * un-splice FIRST (extending the array back to length 3 by setting\n * index 2 to its `oldValue`), then the `changed@1` patch restores\n * index 1 to its `oldValue`. Going the other direction would leave a\n * hole.\n */\nexport function applyPatchesInverse(root: unknown, patches: readonly Patch[]): unknown {\n let current = root\n for (let i = patches.length - 1; i >= 0; i--) {\n const patch = patches[i] as Patch\n if (patch.path.length === 0) {\n if (patch.kind === 'added') {\n current = undefined\n } else {\n current = patch.oldValue\n }\n continue\n }\n if (patch.kind === 'added') {\n current = deleteAtPath(current, patch.path)\n } else {\n current = setAtPath(current, patch.path, patch.oldValue)\n }\n }\n return current\n}\n\n/**\n * Stable structural snapshot of a value. Walks plain objects + arrays\n * recursively; non-recursable values (primitives, Date, RegExp, Map,\n * Set, functions, class instances) pass through unchanged.\n *\n * Used by setValue's callback path so the `prev` arg passed to a\n * consumer's `(prev) => next` lambda is a frozen-in-time snapshot —\n * not a live reference into `form.value` that would silently mutate\n * once the surrounding setValue commits its in-place merge. Consumers\n * routinely cache `prev` in a closure or a test variable; without this\n * clone, those caches would silently drift to the post-setValue state.\n */\nexport function structuralSnapshot<T>(value: T): T {\n if (!isDescendable(value)) return value\n if (Array.isArray(value)) {\n const out = new Array(value.length)\n for (let i = 0; i < value.length; i++) {\n out[i] = structuralSnapshot(value[i])\n }\n return out as unknown as T\n }\n const src = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const k of Object.keys(src)) {\n out[k] = structuralSnapshot(src[k])\n }\n return out as unknown as T\n}\n","/**\n * Schema-attached field metadata — the shared types used by both Zod\n * adapters and the unified `attaform/zod` entry so a consumer's data\n * flow reads the same shape regardless of which path runs at lookup.\n *\n * Storage lives in the cross-adapter `field-meta-store` core: a pair\n * of WeakMaps (single-payload for last-write-wins reads, list-of-\n * payloads for shared-schema disambiguation). Every entry's\n * `fieldMeta` re-exports the same registry-shaped object, so\n * `withMeta`/`fieldMeta.add` writes from one entry surface at lookup\n * through any other.\n *\n * `withMeta(schema, payload)` clones the schema before registering,\n * so each call gets fresh identity (the WeakMap keys on reference).\n * The cloning strategy depends on the major: Zod 4 schemas use the\n * native `.clone()`, Zod 3 schemas reconstruct via constructor +\n * `_def`. The unified entry's `withMeta` runtime-branches on which\n * one is in play.\n *\n * Reads are unified through `AbstractSchema.getFieldMetaAtPath(path)`,\n * which returns a fully-resolved `ResolvedFieldMeta` (label /\n * description / placeholder / meta) so the per-leaf and per-container\n * `FieldState` producers in core never see the version split.\n */\n\n/**\n * The metadata a consumer attaches to a schema node — short label\n * (presentational), longer description (helper text), placeholder\n * (input affordance). Declared as `interface` (not `type`) so\n * downstream apps can extend the shape via TypeScript declaration\n * merging when they want to register richer payloads (tooltips,\n * icons, badge counts, etc.):\n *\n * declare module 'attaform/zod' {\n * interface FieldMetaPayload {\n * tooltip?: string\n * }\n * }\n *\n * After augmentation, `withMeta(schema, { tooltip: '…' })` is typed\n * and `state.meta.tooltip` reads back as `string | undefined`.\n *\n * Every key is optional. Empty payloads (no keys registered) are\n * indistinguishable from \"not registered at all\" — both surface as\n * fallbacks (humanize for label, undefined for the rest).\n */\nexport interface FieldMetaPayload {\n label?: string\n description?: string\n placeholder?: string\n}\n\n/**\n * The fully-resolved metadata returned by\n * `AbstractSchema.getFieldMetaAtPath(path)`. Adapters apply the\n * precedence rules:\n *\n * - `label`: registry payload → `humanize(lastSegment)`\n * - `description`: registry payload → schema's `.describe()` value → `undefined`\n * - `placeholder`: registry payload → `undefined`\n * - `meta`: full registered payload, frozen — empty object if nothing registered\n *\n * `label` is always a non-empty string at leaves (humanize fallback\n * guarantees this for any non-numeric segment). For containers it\n * may collapse to the empty string when the path is empty (root) or\n * the segment is a numeric index — callers display \"\" or substitute\n * a context-appropriate fallback.\n */\nexport type ResolvedFieldMeta = {\n readonly label: string\n readonly description: string | undefined\n readonly placeholder: string | undefined\n readonly meta: Readonly<FieldMetaPayload>\n}\n\n/**\n * Empty resolved metadata for paths that don't exist in the schema\n * (or for adapters that don't yet implement `getFieldMetaAtPath`).\n * Callers can compare against this sentinel via referential equality\n * to detect \"no metadata available.\"\n */\nexport const EMPTY_RESOLVED_FIELD_META: ResolvedFieldMeta = Object.freeze({\n label: '',\n description: undefined,\n placeholder: undefined,\n meta: Object.freeze({}),\n})\n","/**\n * Convert a path segment into a presentable label. Used as the\n * fallback for `FieldState.label` when no explicit label is\n * registered with the schema. Splits camelCase, snake_case, and\n * kebab-case into separate words and title-cases each word.\n *\n * Numeric segments (array indices) collapse to an empty string —\n * `items[3]` should not present as `'3'`. Callers can substitute\n * their own fallback (e.g. `'Item 3'`) when this returns empty.\n *\n * Pure function, no I/O. Safe to call eagerly.\n */\nexport function humanize(segment: string | number): string {\n if (typeof segment === 'number') return ''\n const str = String(segment)\n if (str.length === 0) return ''\n // Numeric-string segments (array indices like '3'): treat as\n // empty so `items.3` doesn't surface as 'Item 3'.\n if (/^\\d+$/.test(str)) return ''\n // Split camelCase boundaries, snake_case, kebab-case, and\n // collapse runs of whitespace.\n const tokens = str\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .split(' ')\n .filter((part) => part.length > 0)\n if (tokens.length === 0) return ''\n return tokens\n .map((part) => {\n const head = part[0]\n return head === undefined ? part : head.toUpperCase() + part.slice(1).toLowerCase()\n })\n .join(' ')\n}\n","import { computed, type ComputedRef } from 'vue'\nimport type { FieldState, FormMeta, ShouldShowErrors, ValidationError } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { EMPTY_RESOLVED_FIELD_META } from './field-meta'\nimport { humanize } from './humanize'\nimport { getAtPath, hasAtPath } from './path-walker'\nimport {\n canonicalizePath,\n FORM_ERRORS_PATH_KEY,\n isPathPrefix,\n segmentsForPathKey,\n type Path,\n type PathKey,\n} from './paths'\n\nfunction isUnderStubAncestor<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n segments: Path\n): boolean {\n for (let i = 0; i < segments.length; i++) {\n const ancestorPath = segments.slice(0, i)\n const du = state.schema.getUnionDiscriminatorAtPath(ancestorPath)\n if (du === undefined) continue\n const ancestorValue = getAtPath(state.form.value, ancestorPath)\n if (ancestorValue === null || typeof ancestorValue !== 'object') continue\n const discValue = (ancestorValue as Record<string, unknown>)[du.discriminatorKey]\n if (discValue === undefined) return true\n if (!du.isVariantSelected(discValue)) return true\n }\n return false\n}\n\n/**\n * Reactive field-state accessor. Combines per-field records, DOM\n * focus/blur state, validation errors, and adapter-resolved metadata\n * into a single `FieldState` object suitable for templates:\n *\n * const emailState = getFieldState('email')\n * emailState.value.dirty, .errors, .focused, .label, ...\n *\n * All reads go through Vue computeds so consumers get fine-grained\n * reactivity — a change to one field's focus does not invalidate\n * computeds watching another field.\n *\n * The accessor returns one shape — `FieldState<unknown>` — at every\n * path. At leaf paths, fields read from per-leaf primitives. At\n * container paths, the same fields aggregate over descendant leaves\n * (disjunction for event-presence: dirty/focused/touched/validating;\n * conjunction for absence/uniformity: pristine/valid/blank). DU\n * containers traverse only the active variant via `hasAtPath` on\n * the live form value.\n *\n * Memoised per canonical path key — repeated calls with the same\n * path return the same `ComputedRef` so consumers don't accumulate\n * duplicate Vue subscriptions.\n */\nexport type { FieldState }\n\n/**\n * Internal shape of a field's reactive state minus the two derived\n * predicate-fed properties (`showErrors`, `firstError`). The\n * predicate `state.shouldShowErrors(field, formMeta)` is invoked\n * with this exact shape on the field side: the keys literally are\n * not present, so a vanilla-JS adopter (or `as`-cast caller) cannot\n * read `field.showErrors` from inside their predicate and form a\n * cycle. Pair with `FormMetaBase` for the matching guard on the\n * form-level argument.\n */\nexport type FieldStateBase = Omit<FieldState<unknown>, 'showErrors' | 'firstError'>\n\n/**\n * Internal shape of the form's reactive meta minus the two derived\n * predicate-fed properties. Same defense-in-depth role as\n * `FieldStateBase` for the second predicate argument. Built in\n * `build-form-api.ts` once per form (where the history options are\n * in scope) and threaded through to the field-state computeds via\n * the `getFormMetaBase` thunk.\n */\nexport type FormMetaBase = Omit<FormMeta<unknown>, 'showErrors' | 'firstError'>\n\n/**\n * Thunk shape passed to `buildFieldStateAccessor`. Each call to the\n * accessor's returned `computed` invokes this thunk to materialise\n * a fresh `FormMetaBase` snapshot — Vue's reactivity tracks every\n * `Ref.value` read inside, so the field-state computed re-evaluates\n * when (e.g.) `submitCount` changes. Stateless function, not a Ref:\n * we never need to swap predicates at runtime, and a plain function\n * keeps the dependency graph shallow.\n */\nexport type FormMetaBaseGetter = () => FormMetaBase\n\nexport function buildFieldStateAccessor<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n getFormMetaBase: FormMetaBaseGetter,\n options?: { readonly shouldShowErrors?: ShouldShowErrors }\n) {\n // Per-path memoisation so `getFieldStateAt(p)` returns the same\n // `ComputedRef` reference on repeated reads with the same canonical\n // path. The Map's lifetime equals the form-store's; cleared\n // implicitly when the store is GC'd.\n const cache = new Map<PathKey, ComputedRef<FieldState<unknown>>>()\n const predicate = options?.shouldShowErrors\n\n return function getFieldState(pathInput: string | Path): ComputedRef<FieldState<unknown>> {\n const { segments, key } = canonicalizePath(pathInput)\n const cached = cache.get(key)\n if (cached !== undefined) return cached\n const c = computed<FieldState<unknown>>(() =>\n state.schema.isLeafAtPath(segments)\n ? buildLeafFieldState(state, segments, key, getFormMetaBase, predicate)\n : buildContainerFieldState(state, segments, key, getFormMetaBase, predicate)\n )\n cache.set(key, c)\n return c\n }\n}\n\n/**\n * Per-leaf computation of the predicate-safe base shape. Reads the\n * leaf-specific reactive sources only; does NOT compute\n * `showErrors` / `firstError` (those are layered on by\n * `buildLeafFieldState`).\n */\nfunction buildLeafFieldStateBase<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n segments: Path,\n key: PathKey\n): FieldStateBase {\n const record = state.fields.get(key)\n const value = state.getValueAtPath(segments)\n const original = state.originals.get(key)?.value\n const pristine = state.isPristineAtPath(segments)\n const schemaForKey = state.schemaErrors.get(key)\n const blankForKey = state.derivedBlankErrors.value.get(key)\n const userForKey = state.userErrors.get(key)\n const errors: ValidationError[] = []\n if (schemaForKey !== undefined) errors.push(...schemaForKey)\n if (blankForKey !== undefined) errors.push(...blankForKey)\n if (userForKey !== undefined) errors.push(...userForKey)\n const validating = (state.fieldValidationCounts.get(key) ?? 0) > 0\n // `valid` mirrors `meta.valid` per-path: when the sub-schema at\n // this path declares async work, gate the answer on the form-wide\n // `firstValidationDone` so the surface doesn't lie about a\n // yet-to-arrive verdict. Sync-only sub-schemas (e.g. a bare\n // `z.string()` leaf) skip the gate — there's nothing to wait on,\n // and clamping every such field to `false` at mount would defeat\n // the green-checkmark UX pattern that `field.valid` is built for.\n const gated = state.pathHasAsyncValidation(segments) && !state.firstValidationDone.value\n // Stub-state orphan gate: when a leaf is structurally absent from\n // `form.value` AND any DU ancestor is in stub state (its disc value\n // isn't a known variant), the surface MUST NOT report `valid: true`.\n // The parent is broken; pretending the descendant is fine hides\n // it from error-summary UIs. Inactive-variant siblings under a\n // VALID disc are a different case — they read as stable stubs\n // (`valid: true`, errors: []) so unconditional template bindings\n // keep working across variants.\n const isOrphan =\n segments.length > 0 &&\n !hasAtPath(state.form.value, segments) &&\n isUnderStubAncestor(state, segments)\n const valid = !gated && errors.length === 0 && !validating && !isOrphan\n const elementRecord = state.elements.get(key)\n const elementsArr: readonly HTMLElement[] = elementRecord\n ? Object.freeze([...elementRecord.elements])\n : EMPTY_ELEMENTS\n const firstElement: HTMLElement | null = elementsArr[0] ?? null\n const resolved = state.schema.getFieldMetaAtPath\n ? state.schema.getFieldMetaAtPath(segments)\n : EMPTY_RESOLVED_FIELD_META\n const lastSegment = segments.length === 0 ? '' : (segments[segments.length - 1] ?? '')\n const label = resolved.label || humanize(lastSegment)\n return {\n value,\n original,\n pristine,\n dirty: !pristine,\n focused: record?.focused ?? null,\n blurred: record?.blurred ?? null,\n touched: record?.touched ?? null,\n connected: record?.connected ?? false,\n element: firstElement,\n elements: elementsArr,\n updatedAt: record?.updatedAt ?? null,\n errors,\n validating,\n valid,\n path: segments,\n blank: state.blankPaths.has(key),\n label,\n description: resolved.description,\n placeholder: resolved.placeholder,\n meta: resolved.meta,\n }\n}\n\n/**\n * Per-leaf full computation: builds the base, then layers on\n * `showErrors` / `firstError` via `state.shouldShowErrors`. The\n * base object passed to the predicate has NO `showErrors` /\n * `firstError` keys at runtime (it's the literal `FieldStateBase`\n * we just constructed) — recursion is impossible regardless of TS\n * vs vanilla-JS.\n */\nfunction buildLeafFieldState<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n segments: Path,\n key: PathKey,\n getFormMetaBase: FormMetaBaseGetter,\n shouldShowErrors?: ShouldShowErrors\n): FieldState<unknown> {\n const base = buildLeafFieldStateBase(state, segments, key)\n return decorateWithDerivedProps(base, state, getFormMetaBase, shouldShowErrors)\n}\n\n/**\n * Per-container aggregation for the predicate-safe base shape.\n * Rolls up descendant-leaf state per the rule sheet; does NOT\n * compute `showErrors` / `firstError`.\n *\n * Aggregation rules (matches `docs/api/use-form-return.md`):\n * - pristine / valid / blank: conjunction (all descendants)\n * - dirty: !pristine\n * - focused / blurred / touched / connected / validating: disjunction (any descendant)\n * - errors: concat + sort by `pathOrdinal` (schema-declaration order)\n * - updatedAt: max ISO timestamp (lex-compared) over descendants\n * - value / original: live subtree at the path\n * - element / elements: nothing bound at containers — null / empty\n * - label / description / placeholder / meta: from `getFieldMetaAtPath`\n *\n * Exported so `build-form-api.ts` can build a `FormMetaBase` (the\n * predicate's second arg) without going through the cached\n * field-state accessor — that route would recurse through the\n * root path's own `showErrors` computation.\n */\nexport function buildContainerFieldStateBase<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n segments: Path,\n _key: PathKey\n): FieldStateBase {\n // Read live form value first so the access participates in dep\n // tracking; the discriminator key write that switches a DU variant\n // shows up here and re-runs the computed.\n const formValue = state.form.value\n const value = state.getValueAtPath(segments)\n const original = state.originals.get(canonicalizePath(segments).key)?.value\n // Enumerate active descendant leaves under the container path.\n // The `originals` Map tracks every leaf the form has ever seen;\n // filter via `isPathPrefix` for descendant-membership and via\n // `hasAtPath(formValue, leafSeg)` to keep only the active-variant\n // leaves (DU switches reshape `formValue` wholesale, so this is\n // the live ground truth).\n let pristine = true\n let blank = true\n let dirty = false\n let focused = false\n let blurred = false\n let touched = false\n let connected = false\n let validating = false\n let updatedAt: string | null = null\n let asyncPending = false\n for (const [, entry] of state.originals) {\n if (!isPathPrefix(segments, entry.segments)) continue\n if (segments.length === entry.segments.length) continue // self isn't a descendant\n if (!hasAtPath(formValue, entry.segments)) continue\n const leafKey = canonicalizePath(entry.segments).key\n const leafRecord = state.fields.get(leafKey)\n if (!state.isPristineAtPath(entry.segments)) {\n pristine = false\n dirty = true\n }\n if (!state.blankPaths.has(leafKey)) blank = false\n if (leafRecord?.focused === true) focused = true\n if (leafRecord?.blurred === true) blurred = true\n if (leafRecord?.touched === true) touched = true\n if (leafRecord?.connected === true) connected = true\n if ((state.fieldValidationCounts.get(leafKey) ?? 0) > 0) validating = true\n if (state.pathHasAsyncValidation(entry.segments)) asyncPending = true\n const ts = leafRecord?.updatedAt\n if (ts !== undefined && ts !== null) {\n // ISO 8601 timestamps sort lexicographically; max-string is\n // the most-recent write.\n if (updatedAt === null || ts > updatedAt) updatedAt = ts\n }\n }\n // Aggregate errors at this prefix. Drives `form.fields(p).errors`,\n // `form.errors(p)`, and `form.meta.errors` through one helper so\n // the three surfaces read identically. Active-variant filter\n // applied via the same `hasAtPath` gate the descendant walk used.\n // `valid` derives from this single source so the two fields can\n // never disagree.\n const errors = aggregateErrorsAt(state, segments)\n // A container's own sub-schema can also declare async work — a\n // top-level `.refine(async ...)` on the root, or a cross-field\n // refine on a sub-object — and those don't show up in any per-\n // leaf `pathHasAsyncValidation` reading. Check the container's\n // OWN path too, so the firstValidationDone gate fires until that\n // pass lands.\n if (!asyncPending && state.pathHasAsyncValidation(segments)) asyncPending = true\n const gated = asyncPending && !state.firstValidationDone.value\n const valid = !gated && errors.length === 0 && !validating\n const resolved = state.schema.getFieldMetaAtPath\n ? state.schema.getFieldMetaAtPath(segments)\n : EMPTY_RESOLVED_FIELD_META\n const lastSegment = segments.length === 0 ? '' : (segments[segments.length - 1] ?? '')\n const label = resolved.label || humanize(lastSegment)\n return {\n value,\n original,\n pristine,\n dirty,\n focused,\n blurred,\n touched,\n connected,\n element: null,\n elements: EMPTY_ELEMENTS,\n updatedAt,\n errors,\n validating,\n valid,\n path: segments,\n blank,\n label,\n description: resolved.description,\n placeholder: resolved.placeholder,\n meta: resolved.meta,\n }\n}\n\n/**\n * Per-container full computation: builds the base, layers on the\n * derived predicate-fed props.\n */\nfunction buildContainerFieldState<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n segments: Path,\n key: PathKey,\n getFormMetaBase: FormMetaBaseGetter,\n shouldShowErrors?: ShouldShowErrors\n): FieldState<unknown> {\n const base = buildContainerFieldStateBase(state, segments, key)\n return decorateWithDerivedProps(base, state, getFormMetaBase, shouldShowErrors)\n}\n\n/**\n * Layer `showErrors` + `firstError` onto a freshly-computed base.\n * Shared by leaf and container paths so the gate runs identically\n * at every depth.\n *\n * `firstError` is `errors[0]` — deterministic because errors are\n * already sorted by schema-declaration order (within a leaf: schema\n * → blank → user concat; across a container: `pathOrdinal` bucket\n * sort).\n *\n * `showErrors` short-circuits when there are no errors, so the\n * predicate only fires when the heuristic actually has something to\n * decide.\n */\nfunction decorateWithDerivedProps<F extends GenericForm>(\n base: FieldStateBase,\n state: FormStore<F, GenericForm>,\n getFormMetaBase: FormMetaBaseGetter,\n shouldShowErrors?: ShouldShowErrors\n): FieldState<unknown> {\n const firstError = base.errors[0]\n const predicate = shouldShowErrors ?? state.shouldShowErrors\n const showErrors = base.errors.length > 0 && predicate(base, getFormMetaBase())\n return { ...base, showErrors, firstError }\n}\n\n/**\n * Walk the merged error stores at every leaf descendant of `prefix`,\n * filter inactive variants via `hasAtPath`, and return the\n * concatenated errors sorted by schema-declaration order\n * (`pathOrdinals` — same ordering metaErrors uses today).\n *\n * Shared by container `errors` aggregation here and by the top-level\n * `metaErrors` / `form.errors(path)` aggregation in `build-form-api.ts`\n * — one helper, three call sites, no drift.\n */\nexport function aggregateErrorsAt<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n prefix: Path\n): ValidationError[] {\n const formValue = state.form.value\n const buckets = new Map<number, ValidationError[]>()\n const collect = (errs: ReadonlyMap<PathKey, ValidationError[]>): void => {\n for (const [pathKey, list] of errs) {\n if (list.length === 0) continue\n // Resolve the path's segments via the canonical PathKey ↔\n // Segment[] inverse cache (`segmentsForPathKey`). Covers\n // every shape the error stores can hold — leaf paths,\n // container paths (cross-field refines), and the form-level\n // `[]` key — without depending on `originals` (which only\n // tracks leaves).\n const segs = segmentsForPathKey(pathKey)\n if (segs === null) continue\n if (!isPathPrefix(prefix, segs)) continue\n // Skip inactive variants. Form-level errors are always retained\n // — they're not variant-bound. Two flavours qualify:\n // - the empty path `[]` (kept for parity with any legacy\n // entries / cross-adapter paths);\n // - the empty-string bucket `['']`, which is the conventional\n // home for root `.refine()` errors and `setFormErrors()`\n // entries.\n // Container-level errors (cross-field refines on a container\n // path) are filtered when their CONTAINER path is reachable;\n // the refine pinned the error at the container, not at any\n // particular leaf.\n if (pathKey === FORM_ERRORS_PATH_KEY) {\n // Always retain — form-level bucket.\n } else if (segs.length > 0 && !hasAtPath(formValue, segs)) continue\n const ordinal = state.ensurePathOrdinal(pathKey)\n const existing = buckets.get(ordinal)\n if (existing === undefined) buckets.set(ordinal, [...list])\n else existing.push(...list)\n }\n }\n collect(state.schemaErrors)\n collect(state.derivedBlankErrors.value)\n collect(state.userErrors)\n if (buckets.size === 0) return []\n return [...buckets.entries()].sort(([a], [b]) => a - b).flatMap(([, errs]) => errs)\n}\n\n// Frozen empty array shared across \"no elements bound\" reads so\n// consumers can `===`-compare against a stable reference and the\n// computed doesn't allocate a new array on every re-evaluation when\n// the path has no registered elements.\nconst EMPTY_ELEMENTS: readonly HTMLElement[] = Object.freeze([])\n","import type { AbstractSchema } from '../types/types-api'\nimport { canonicalizePath, type Path, type Segment } from './paths'\n\n/**\n * Leaf-aware callable Proxy machinery shared by `form.values`,\n * `form.errors`, and `form.fields`. One generic builder; per-surface\n * specialisation lives in the surface's own factory file (see\n * `field-state-proxy.ts` for fields).\n *\n * Two-level contract:\n *\n * - At a **container path** (`schema.isLeafAtPath(segments) === false`)\n * the `get` trap descends to a sub-proxy. No leaf-key injection — a\n * schema field literally named `dirty` at depth 2+ stays reachable.\n * - At a **leaf path** (`schema.isLeafAtPath(segments) === true`)\n * the `get` trap terminates. Two flavours:\n * - `leafKeys` undefined (errors/values): returns\n * `resolveLeaf(segments)` directly. The terminal IS the value.\n * - `leafKeys` provided (fields): returns a leaf-VIEW proxy that\n * exposes only `leafKeys` as terminal reads off `resolveLeaf`'s\n * return. FIELD_STATE_KEYS injection happens HERE only.\n *\n * Both proxies are callable (function-target with `apply` trap):\n * - `proxy()` → root proxy (same as no-paren)\n * - `proxy('a.b.c')` / `proxy(['a', 'b', 'c'])` → walks to that path,\n * returns whatever the dotted form would (leaf or container proxy).\n *\n * Symbol keys pass through to the function target so Vue's reactivity\n * sigils (`Symbol(__v_isRef)`, `Symbol(__v_isReadonly)`, etc.) and\n * iteration symbols don't accidentally route through the schema-aware\n * branch.\n *\n * Per-path proxy memoisation: each surface keeps its own\n * `Map<PathKey, CallableSurface>` so repeated reads of the same path\n * return the same Proxy object — referential equality matters for\n * downstream effect tracking and Vue's render diff.\n */\n\n/**\n * Tests an integer-like string without leading zeros. Mirrors the\n * `INTEGER_SEGMENT` regex in paths.ts. Inlined here to avoid exporting\n * an internal helper across the module boundary.\n */\nconst INTEGER_SEGMENT = /^(?:0|[1-9]\\d*)$/\n\n/**\n * Convert a string property key to the canonical Segment form. Integer-\n * looking strings (`'0'`, `'1'`, `'42'`) become numbers so that paths\n * accumulated through proxy descent match what `canonicalizePath`\n * produces from a dotted-string call (e.g. `proxy('users.0.name')`).\n */\nfunction keyToSegment(key: string): Segment {\n return INTEGER_SEGMENT.test(key) ? Number(key) : key\n}\n\nexport type SurfaceOptions<TLeaf> = {\n /** Schema instance; queried via `isLeafAtPath` at every descent. */\n readonly schema: AbstractSchema<unknown, unknown>\n /**\n * Resolve the surface's terminal value at a leaf path. Called at every\n * leaf-path read; consumers should memoise inside `resolveLeaf` if the\n * resolution is expensive (the field-state surface uses\n * `buildFieldStateAccessor` which returns a memoised `ComputedRef`).\n */\n readonly resolveLeaf: (path: Path) => TLeaf\n /**\n * If provided: at a leaf path, the surface proxy returns a leaf-VIEW\n * proxy exposing only these keys as terminal reads off the resolved\n * leaf. `readLeafKey` performs the extraction.\n *\n * If undefined: at a leaf path, the surface proxy returns\n * `resolveLeaf(path)` directly. No further proxy wrap.\n */\n readonly leafKeys?: ReadonlySet<string>\n /**\n * Extracts a leaf-key value from the resolved leaf. Required when\n * `leafKeys` is provided. The `key` arg is guaranteed to be in\n * `leafKeys`. Reads inside this function happen during a Vue effect's\n * run, so dependency tracking propagates from `resolveLeaf`'s return.\n */\n readonly readLeafKey?: (leaf: TLeaf, key: string) => unknown\n /**\n * Materialise the container at `segments` into a plain JSON-friendly\n * object. Called by the container proxy's `toJSON` / `toString` /\n * `Symbol.toPrimitive('default')` traps every time a consumer\n * stringifies the proxy. Reads inside this callback happen at call\n * time inside the consumer's active effect, so Vue's dependency\n * tracking captures every reactive read (error stores, the form\n * Ref, computed maps) — `JSON.stringify(form.errors)` in a render\n * function or `{{ form.errors }}` in a template re-runs whenever\n * the underlying state changes.\n *\n * If undefined: containers serialise to `{}`. Provided so each\n * surface controls its own materialisation strategy:\n * - `errors`: sparse — only paths that actually have errors,\n * active-path-filtered.\n * - `fields`: dense — every schema-leaf descendant snapshotted as\n * a `FieldState`.\n * - `values`: not built on this generic; its own proxy serialises\n * the inner readonly proxy directly.\n */\n readonly materializeContainer?: (segments: readonly Segment[]) => unknown\n /**\n * Terminal for the `apply` trap (call-form). `proxy('a.b.c')` and\n * `proxy()` route here, separate from the dot/bracket `get` trap\n * (which continues to descend at containers). This is what lets\n * `form.fields.pickup` navigate while `form.fields('pickup')`\n * returns the aggregated container `FieldState`; same dual-mode\n * applies to `form.errors(path)`.\n *\n * `proxy()` (no-arg) calls `resolveCallTarget([])` so consumers\n * grab the root state with one call (`form.fields()` aggregates\n * over the whole form).\n */\n readonly resolveCallTarget: (path: Path) => unknown\n}\n\n/**\n * The public shape of a built surface. Drill (dot/bracket) OR call\n * (apply trap with a path arg). The TypeScript shape stays loose at\n * the runtime layer; per-surface types in `types-api.ts` narrow the\n * descent.\n */\nexport type SurfaceProxy = ((path?: string | Path) => unknown) & Record<string, unknown>\n\nexport function buildSurfaceProxy<TLeaf>(opts: SurfaceOptions<TLeaf>): SurfaceProxy {\n // Per-path container Proxy cache. Key = canonical PathKey\n // (`JSON.stringify(segments)`). Lifetime = one buildSurfaceProxy call.\n const containerCache = new Map<string, SurfaceProxy>()\n // Per-path leaf-VIEW Proxy cache. Only populated when `leafKeys` is\n // configured. Same key shape, separate Map so a path with the same\n // canonical key but different leaf-ness (impossible in practice) wouldn't\n // collide.\n const leafViewCache = new Map<string, SurfaceProxy>()\n // Per-path \"schema has a field here\" cache. Used by the\n // schema-authority check that resolves collisions between built-in\n // method names (`toString`, `valueOf`) and schema fields literally\n // sharing those names. Same lifetime as the leaf/container caches.\n const existsCache = new Map<string, boolean>()\n\n /** True iff the schema has a field at `segs` (leaf OR container). */\n function schemaHasPath(segs: readonly Segment[]): boolean {\n const cacheKey = JSON.stringify(segs)\n const cached = existsCache.get(cacheKey)\n if (cached !== undefined) return cached\n const result = opts.schema.getSlimPrimitiveTypesAtPath(segs).size > 0\n existsCache.set(cacheKey, result)\n return result\n }\n\n /** Resolve a path to its leaf terminal or container sub-proxy. */\n function descendOrTerminate(segs: readonly Segment[]): unknown {\n const isLeaf = opts.schema.isLeafAtPath(segs)\n if (isLeaf) {\n if (opts.leafKeys !== undefined) return leafViewProxyAt(segs)\n return opts.resolveLeaf(segs)\n }\n return containerProxyAt(segs)\n }\n\n function containerProxyAt(segments: readonly Segment[]): SurfaceProxy {\n const cacheKey = JSON.stringify(segments)\n const existing = containerCache.get(cacheKey)\n if (existing !== undefined) return existing\n\n // Container-shaped primitive coercion. The materialiser (when set)\n // is invoked on every call so reactive reads (error stores, the\n // form Ref) are tracked inside the consumer's active effect — the\n // proxy itself is cached per-path, but its serialised form is\n // computed fresh on every stringify, so there is no staleness.\n //\n // - `valueOf` follows `Object.prototype.valueOf` semantics: return\n // the receiver (the proxy itself, via dynamic `this`). Returning\n // a non-primitive keeps OrdinaryToPrimitive's `valueOf` →\n // `toString` fallback well-formed for any code path that\n // bypasses our `Symbol.toPrimitive` shortcut.\n // - `toString` returns `JSON.stringify(materialised)` so direct\n // method calls produce the same string as operator coercion.\n // - `Symbol.toPrimitive('number')` always returns `NaN` — a\n // container has no meaningful number coercion.\n const snapshotContainer = (): unknown =>\n opts.materializeContainer === undefined ? {} : opts.materializeContainer(segments)\n const containerToJSON = (): unknown => snapshotContainer()\n const containerToString = (): string => JSON.stringify(snapshotContainer())\n function containerValueOf(this: unknown): unknown {\n return this\n }\n const containerToPrimitive = (hint: string): string | number =>\n hint === 'number' ? NaN : containerToString()\n\n // Arrow-function target (so `typeof proxy === 'function'` and `apply`\n // fires). Arrow functions have no `prototype` property, which avoids\n // the \"ownKeys trap must include 'prototype'\" Proxy invariant — `length`\n // and `name` ARE present but configurable=true, so we can omit them\n // from ownKeys safely.\n const target = (() => {}) as unknown as SurfaceProxy\n const proxy = new Proxy(target, {\n apply(_, __, args: unknown[]): unknown {\n // proxy() returns the call-target at THIS path (so\n // `form.fields()` resolves the root aggregation). proxy(arg)\n // walks the absolutised arg path through the call-target.\n const arg = args[0] as string | Path | undefined\n if (arg === undefined) return opts.resolveCallTarget(segments as Path)\n const { segments: argSegs } = canonicalizePath(arg)\n return opts.resolveCallTarget(argSegs)\n },\n get(_, key: string | symbol): unknown {\n // Symbol passthrough: Vue's reactivity sigils + iteration symbols\n // resolve against the function target, not the schema-aware branch.\n if (typeof key === 'symbol') {\n // `Symbol.toPrimitive`: handles `String(proxy)` / `Number(proxy)`\n // / template-literal coercion in one shot, bypassing\n // OrdinaryToPrimitive's `toString` → `valueOf` walk (both of\n // which would otherwise route through schema descent below and\n // return sub-proxies — non-primitives — making the coercion\n // throw `TypeError(\"Cannot convert object to primitive value\")`).\n if (key === Symbol.toPrimitive) return containerToPrimitive\n return Reflect.get(target, key)\n }\n if (typeof key !== 'string') return undefined\n // `toJSON`: containers serialise to `{}`. The function-target\n // Proxy is `typeof === 'function'`, which JSON.stringify normally\n // omits — `toJSON` short-circuits that path. Consumers who want\n // structural data use `form.values.<container>` instead.\n if (key === 'toJSON') return containerToJSON\n const childSegs = [...segments, keyToSegment(key)]\n // Direct method-call coercion (`proxy.toString()` /\n // `proxy.valueOf()`): without intercepting these names, the\n // schema-aware descent below would return a sub-proxy and the\n // caller would get back another callable, not a primitive. We\n // resolve the collision with **schema authority**: if the\n // schema has a field literally named `toString` / `valueOf` at\n // this depth, that field wins (descent proceeds). Otherwise the\n // primitive-coercion handler wins. This keeps the Symbol.toPrimitive\n // shortcut consistent with direct method calls AND avoids the\n // FIELD_STATE_KEYS-style shadowing that 0.14 explicitly killed.\n if (key === 'toString' || key === 'valueOf') {\n if (!schemaHasPath(childSegs)) {\n return key === 'toString' ? containerToString : containerValueOf\n }\n // Schema has it — fall through to descent.\n }\n return descendOrTerminate(childSegs)\n },\n has(_, key: string | symbol): boolean {\n if (typeof key === 'symbol') return Reflect.has(target, key)\n // Conservatively true — the proxy navigates any path; whether\n // the path resolves to a schema-defined slot is the consumer's\n // concern (read returns the deep proxy or terminal as usual).\n return true\n },\n // Containers are descend-only — `JSON.stringify(form.fields.address)`\n // returns `{}` (no leaf keys to enumerate). Consumers who want\n // structural data use `form.values.<container>` instead.\n ownKeys: () => [],\n getOwnPropertyDescriptor: () => undefined,\n // Block writes at the proxy boundary. Mutations go through\n // `setValue`, the directive, or the field-array helpers.\n set: () => false,\n deleteProperty: () => false,\n defineProperty: () => false,\n })\n containerCache.set(cacheKey, proxy)\n return proxy\n }\n\n function leafViewProxyAt(segments: readonly Segment[]): SurfaceProxy {\n const cacheKey = JSON.stringify(segments)\n const existing = leafViewCache.get(cacheKey)\n if (existing !== undefined) return existing\n\n const leafKeys = opts.leafKeys\n const readLeafKey = opts.readLeafKey\n if (leafKeys === undefined || readLeafKey === undefined) {\n // Defensive: leaf-VIEW proxy is only constructed via the `get`\n // trap's `descendOrTerminate` branch in `containerProxyAt`,\n // which guards on `opts.leafKeys`. Throw rather than silently\n // misroute if a future caller skips the guard.\n throw new Error('leafViewProxyAt called without leafKeys/readLeafKey configured')\n }\n\n // Snapshot builder shared by `toJSON` and the primitive-coercion\n // handlers. Reads through `resolveLeaf` and `readLeafKey` happen at\n // call time inside the consumer's active effect, so Vue's dependency\n // tracking captures the leaf's reactive deps (the\n // `ComputedRef<FieldState>` for fields).\n const snapshotLeaf = (): Record<string, unknown> => {\n const leaf = opts.resolveLeaf(segments)\n const snapshot: Record<string, unknown> = {}\n for (const leafKey of leafKeys) {\n snapshot[leafKey] = readLeafKey(leaf, leafKey)\n }\n return snapshot\n }\n const leafToString = (): string => JSON.stringify(snapshotLeaf())\n function leafValueOf(this: unknown): unknown {\n return this\n }\n const leafToPrimitive = (hint: string): string | number =>\n hint === 'number' ? NaN : leafToString()\n\n const target = (() => {}) as unknown as SurfaceProxy\n const proxy = new Proxy(target, {\n apply(_, __, args: unknown[]): unknown {\n // Same call-target dispatch as `containerProxyAt` so\n // `form.fields.email(somePath)` reads identically to\n // `form.fields(somePath)` — the call-form always lands on\n // the FieldState terminal.\n const arg = args[0] as string | Path | undefined\n if (arg === undefined) return opts.resolveCallTarget(segments as Path)\n const { segments: argSegs } = canonicalizePath(arg)\n return opts.resolveCallTarget(argSegs)\n },\n get(_, key: string | symbol): unknown {\n if (typeof key === 'symbol') {\n // See containerProxyAt for the rationale. Leaf-views return\n // the JSON-stringified snapshot so primitive coercion produces\n // a useful display (e.g. `String(form.fields.email)` shows the\n // FieldState shape rather than throwing).\n if (key === Symbol.toPrimitive) return leafToPrimitive\n return Reflect.get(target, key)\n }\n if (typeof key !== 'string') return undefined\n // Direct method-call path for primitive coercion. `toString`\n // returns the same JSON snapshot as `Symbol.toPrimitive`;\n // `valueOf` returns the receiver (non-primitive) so\n // OrdinaryToPrimitive's `valueOf` → `toString` walk falls through\n // for any code path that bypasses `Symbol.toPrimitive`. No schema\n // collision is possible at this depth: leaves are primitives, so\n // they have no schema children. Collisions at higher container\n // depths (a schema field literally named `toString`) are\n // resolved by `containerProxyAt`'s schema-authority check.\n if (key === 'toString') return leafToString\n if (key === 'valueOf') return leafValueOf\n // `toJSON`: leaf-views serialise to a snapshot object containing\n // every leaf-key value at the moment of the call. Lets SSR\n // templates stringify `form.fields.<leaf>` straight into the\n // hydration payload.\n if (key === 'toJSON') return snapshotLeaf\n // Reads inside the trap stay inside the consumer's active effect —\n // `resolveLeaf` returns a `ComputedRef` (for fields) and `.value`\n // is read inside `readLeafKey`, so Vue's dep tracking captures\n // the dependency at access time.\n if (leafKeys.has(key)) {\n const leaf = opts.resolveLeaf(segments)\n return readLeafKey(leaf, key)\n }\n // Schema field at a leaf-prop name: descend further. The leaf-prop\n // and the schema field name occupy DIFFERENT proxy depths because\n // the schema's leaf-aware structure puts them on different paths.\n // Example: schema `{ address: { valid: boolean } }`:\n // form.fields.address → container proxy\n // form.fields.address.valid → leaf-view (here)\n // form.fields.address.valid.valid → THIS read; 'valid'\n // IS in leafKeys → returns\n // the FieldState's\n // valid prop.\n // For non-leafKeys reads, descend by appending the key to segments\n // and re-checking leaf-ness. This handles container-shaped\n // schema fields hanging off a leaf-named ancestor (rare but\n // possible).\n return descendOrTerminate([...segments, keyToSegment(key)])\n },\n has(_, key: string | symbol): boolean {\n if (typeof key === 'symbol') return Reflect.has(target, key)\n if (typeof key === 'string' && leafKeys.has(key)) return true\n return true\n },\n // Iteration: leaf-views expose the leaf-key set so\n // `JSON.stringify(form.fields.email)` produces a FieldState\n // snapshot rather than the function-target placeholder.\n ownKeys: () => Array.from(leafKeys),\n getOwnPropertyDescriptor(_, key: string | symbol): PropertyDescriptor | undefined {\n if (typeof key !== 'string') return undefined\n if (!leafKeys.has(key)) return undefined\n const leaf = opts.resolveLeaf(segments)\n return {\n configurable: true,\n enumerable: true,\n value: readLeafKey(leaf, key),\n writable: false,\n }\n },\n set: () => false,\n deleteProperty: () => false,\n defineProperty: () => false,\n })\n leafViewCache.set(cacheKey, proxy)\n return proxy\n }\n\n // Root proxy. Constructed via `containerProxyAt([])` — root is always\n // a container (every form has at least one field). The cache holds\n // a stable reference; `proxy()` returns the root for the no-arg case.\n const rootProxy = containerProxyAt([])\n return rootProxy\n}\n","import type { ValidationError } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { aggregateErrorsAt } from './field-state-api'\nimport { getAtPath, hasAtPath } from './path-walker'\nimport {\n canonicalizePath,\n segmentsForPathKey,\n type PathKey,\n type Path,\n type Segment,\n} from './paths'\nimport { buildSurfaceProxy, type SurfaceProxy } from './surface-proxy'\n\n/**\n * Build the leaf-aware `form.errors` callable Proxy. Drill via dot /\n * bracket OR call dynamically:\n *\n * form.errors.email // ValidationError[] | undefined (leaf)\n * form.errors.address.city // ValidationError[] | undefined (leaf)\n * form.errors.address // proxy for descent only (container)\n * form.errors('address.city') // function-call (dynamic / programmatic)\n * form.errors(['address', 'city']) // path-array form\n * form.errors() // root proxy\n *\n * Specialises `buildSurfaceProxy` (see surface-proxy.ts) with:\n * - `resolveLeaf`: merges schemaErrors + derivedBlankErrors + userErrors\n * at the canonical PathKey, FILTERED by `hasAtPath` (the active-path\n * filter from commit 1fbb8bb stays). Returns `undefined` when no\n * errors at the path OR the path isn't reachable through the live\n * form value (e.g. inactive variant of a discriminated union after\n * a switch). The store-side entries STAY — `form.meta.errors`\n * exposes the unfiltered aggregate.\n * - `leafKeys`: undefined. The leaf IS the terminal — an array or\n * undefined. No further proxy wrap.\n *\n * Path / value contract preserved: errors at unknown paths return a\n * sub-proxy (descend permissively). `form.errors.bogus` is a proxy,\n * not undefined — readers who want existence checks should use the\n * leaf form (`form.errors.bogus.somePath`) which terminates only at\n * schema-leaves.\n */\nexport function buildErrorsProxy<F extends GenericForm>(\n state: FormStore<F, GenericForm>\n): SurfaceProxy {\n return buildSurfaceProxy<ValidationError[] | undefined>({\n schema: state.schema as unknown as Parameters<typeof buildSurfaceProxy>[0]['schema'],\n resolveLeaf: (path) => {\n // Active-path filter applies to SCHEMA + DERIVED-BLANK errors\n // only: paths whose value is no longer reachable through the\n // live form (e.g. the inactive variant of a DU after a switch)\n // are hidden because they're library-produced verdicts against\n // state that's been replaced. USER errors (set via\n // `setFieldErrors` / `setFormErrors`) are the consumer's data\n // — server replies, programmatic warnings, manual marks — and\n // we never silently drop them, even at paths the schema\n // doesn't know about. Per-field reads\n // (`form.fields.<path>.errors`, `state.getErrorsForPath`) and\n // the `form.meta.errors` aggregate are unaffected by this\n // filter.\n const { key } = canonicalizePath(path as Path)\n const userForKey = state.userErrors.get(key)\n const isActive = hasAtPath(state.form.value, path as ReadonlyArray<Segment>)\n const merged: ValidationError[] = []\n if (isActive) {\n const schemaForKey = state.schemaErrors.get(key)\n const blankForKey = state.derivedBlankErrors.value.get(key)\n if (schemaForKey !== undefined) merged.push(...schemaForKey)\n if (blankForKey !== undefined) merged.push(...blankForKey)\n }\n if (userForKey !== undefined) merged.push(...userForKey)\n return merged.length === 0 ? undefined : merged\n },\n // No leafKeys — at a leaf, the resolved value (the merged array or\n // undefined) IS the terminal.\n materializeContainer: (segments) => materializeErrors(state, segments),\n // Call-form aggregates: `form.errors(path)` returns a single\n // `ValidationError[]` for any depth (leaf or container) — same\n // shared `aggregateErrorsAt` helper that `form.meta.errors` and\n // `form.fields(path).errors` use, so the three surfaces never\n // drift. Empty results return `undefined`, matching the leaf\n // proxy's pre-existing semantic (`form.errors.email === undefined`\n // when valid) so consumer code that branches on truthiness keeps\n // working — the call-form just extends that semantic to\n // containers and dynamic paths.\n resolveCallTarget: (path) => {\n const errs = aggregateErrorsAt(state, path)\n return errs.length === 0 ? undefined : errs\n },\n })\n}\n\n/**\n * Build a sparse, nested error tree under `containerSegments` for\n * `JSON.stringify(form.errors.<container>)`. Includes every leaf-keyed\n * descendant whose path is reachable in the live form value (the same\n * active-path filter `resolveLeaf` applies), excludes paths that\n * resolve to the container itself (cross-field refines and form-level\n * errors live in `form.meta.errors`, which is the unfiltered flat\n * aggregate). Sparse: containers with no error-bearing descendants\n * don't appear in the tree.\n *\n * Reactivity contract: every read in this function (the three error\n * stores, the form Ref) happens at call time. JSON.stringify invokes\n * `toJSON` once per stringify call inside the consumer's active\n * effect, so dependency tracking captures every store on every render\n * and re-runs on mutation. The per-path proxy memoisation in\n * `surface-proxy.ts` caches the proxy itself, NOT the materialised\n * object — there is no staleness.\n */\nfunction materializeErrors<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n containerSegments: readonly Segment[]\n): Record<string, unknown> | unknown[] {\n // Mirror the live-data shape at the container: array container →\n // array root (array indices place into integer slots, holes\n // serialise as `null`); object container → object root. Without\n // this the placement code would route numeric segments through a\n // string-keyed object, producing `{ \"0\": {…} }` for an array path\n // and breaking shape parity with `form.values`.\n const liveContainer = getAtPath(state.form.value, containerSegments)\n const tree: Record<string, unknown> | unknown[] = Array.isArray(liveContainer) ? [] : {}\n\n // Two store classes with different visibility rules. Schema +\n // derived-blank: library-produced verdicts; filter out paths the\n // current form value can't reach (inactive DU variants). User:\n // consumer-supplied data (server replies, manual marks); surface\n // every entry regardless of `hasAtPath`, otherwise unknown server\n // keys / form-level messages get silently swallowed.\n const collect = (\n store: ReadonlyMap<PathKey, ValidationError[]>,\n applyActivePathFilter: boolean\n ): void => {\n entries: for (const [pathKey, errors] of store) {\n if (errors.length === 0) continue\n // Cache hit on every keystroke — the store's PathKeys are\n // produced through `canonicalizePath`, which warms the inverse\n // cache. Cold path (corrupt key) returns null and we skip.\n const fullPath = segmentsForPathKey(pathKey)\n if (fullPath === null) continue\n // Skip paths that aren't strict descendants of the container.\n // Exception at the ROOT container (`containerSegments.length === 0`):\n // form-level user entries live at the empty-string path `['']`\n // (length 1), which IS a strict descendant of the root by length,\n // but with a `''` first segment that placeAt routes under an\n // empty-string key — letting consumers debug-print form-level\n // messages without a separate API call.\n if (fullPath.length <= containerSegments.length) continue\n for (let i = 0; i < containerSegments.length; i++) {\n if (fullPath[i] !== containerSegments[i]) continue entries\n }\n // Active-path filter matches `resolveLeaf` semantics so a leaf\n // read and a container materialisation never disagree. Only\n // schema-class stores apply it — user errors stay visible\n // whether or not their path is reachable.\n if (applyActivePathFilter && !hasAtPath(state.form.value, fullPath)) continue\n placeAt(tree, fullPath.slice(containerSegments.length), errors)\n }\n }\n\n collect(state.schemaErrors, true)\n collect(state.derivedBlankErrors.value, true)\n collect(state.userErrors, false)\n return tree\n}\n\n/**\n * Place `errors` at the relative `path` inside `tree`, allocating\n * intermediate object/array containers as needed (numeric segments\n * produce arrays). When `tree` already has an array at `path`,\n * concatenate so multiple stores' contributions to the same path\n * merge into one array — matches `resolveLeaf`'s\n * `[...schemaErrors, ...blankErrors, ...userErrors]` ordering.\n */\nfunction placeAt(\n tree: Record<string, unknown> | unknown[],\n path: readonly Segment[],\n errors: ValidationError[]\n): void {\n if (path.length === 0) return\n let cursor: Record<string, unknown> | unknown[] = tree\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i] as Segment\n const nextSeg = path[i + 1] as Segment\n const key = typeof seg === 'number' ? String(seg) : seg\n const cursorRecord = cursor as Record<string, unknown>\n let child = cursorRecord[key]\n if (child === null || child === undefined || typeof child !== 'object') {\n child = typeof nextSeg === 'number' ? [] : {}\n cursorRecord[key] = child\n }\n cursor = child as Record<string, unknown> | unknown[]\n }\n const lastSeg = path[path.length - 1] as Segment\n const lastKey = typeof lastSeg === 'number' ? String(lastSeg) : lastSeg\n const cursorRecord = cursor as Record<string, unknown>\n const existing = cursorRecord[lastKey]\n cursorRecord[lastKey] = Array.isArray(existing) ? [...existing, ...errors] : errors\n}\n","import type { GenericForm } from '../types/types-core'\nimport type { WriteMeta } from '../types/types-api'\nimport type { FormStore } from './create-form-store'\nimport { canonicalizePath } from './paths'\n\n/**\n * Typed array helpers on top of FormStore. Each helper reads the current\n * array at the given path, produces a new copy (immutable, so that the\n * `form` ref's reactive notification goes out), and writes it back via\n * `setValueAtPath`. All downstream bookkeeping — diffAndApply patches,\n * field-record `updatedAt` stamps, error-store preservation — comes for\n * free through the normal setValueAtPath pipeline.\n *\n * Out-of-range index semantics:\n * - `remove` / `swap` / `replace`: no-op on invalid indices. Never grow\n * the array. Matches react-hook-form / VeeValidate precedent.\n * - `insert`: the target index is clamped via `Array.prototype.splice`\n * (values past `length` are treated as `length`).\n * - `move`: invalid `from` is a no-op; `to` is clamped to `[0, length]`.\n *\n * None of the helpers mutate the existing array — every write is a fresh\n * array literal, so Vue's identity-based change detection fires. Callers\n * that need to compose mutations should batch them at the schema level\n * (build the replacement shape, call `setValue(path, shape)` once).\n */\n\nexport type FieldArrayApi = {\n append(path: string, value: unknown): boolean\n prepend(path: string, value: unknown): boolean\n insert(path: string, index: number, value: unknown): boolean\n remove(path: string, index: number): boolean\n swap(path: string, a: number, b: number): boolean\n move(path: string, from: number, to: number): boolean\n replace(path: string, index: number, value: unknown): boolean\n}\n\nexport function buildFieldArrayApi<F extends GenericForm>(\n state: FormStore<F, GenericForm>\n): FieldArrayApi {\n function readArray(path: string): unknown[] {\n const segments = canonicalizePath(path).segments\n const current = state.getValueAtPath(segments)\n // If the path is missing or points at a non-array (e.g. the schema\n // default was undefined), treat as an empty array. This lets\n // `append` work for arrays that haven't been initialised by the\n // schema; the alternative of throwing surfaces programmer errors\n // earlier but blocks a common consumer pattern.\n return Array.isArray(current) ? current.slice() : []\n }\n\n function writeArray(path: string, next: unknown[], arrayOp?: WriteMeta['arrayOp']): boolean {\n const { segments, key } = canonicalizePath(path)\n // Persist iff some element has opted into this exact array path. If\n // the consumer opted into specific leaves (e.g. 'contacts.0.name')\n // an `append('contacts', row)` falls through — the array root has\n // no opt-in, so it doesn't persist. Coherent: \"you opted to persist\n // a leaf, not the array structure.\"\n const meta: WriteMeta = {\n persist: state.persistOptIns.hasAnyOptInForPath(key),\n ...(arrayOp !== undefined ? { arrayOp } : {}),\n }\n return state.setValueAtPath(segments, next, meta)\n }\n\n return {\n append(path, value) {\n // Pure length-grow at the tail — existing indices keep their\n // identities, so no variant-memory key is invalidated. Skip the\n // arrayOp hint; nothing to clear.\n const next = readArray(path)\n next.push(value)\n return writeArray(path, next)\n },\n prepend(path, value) {\n const next = readArray(path)\n next.unshift(value)\n // Every existing index shifted by 1; memory at every index now\n // refers to a different element. Clear all under the array.\n return writeArray(path, next, { kind: 'shift-from', index: 0 })\n },\n insert(path, index, value) {\n const next = readArray(path)\n // splice clamps `index` to `[0, length]`; negative values count from\n // the end. We pass through untouched — Array semantics are the\n // consumer's expected behaviour here.\n next.splice(index, 0, value)\n const clampedIndex = Math.max(0, Math.min(index, next.length))\n return writeArray(path, next, { kind: 'shift-from', index: clampedIndex })\n },\n remove(path, index) {\n const next = readArray(path)\n if (index < 0 || index >= next.length) return false\n next.splice(index, 1)\n return writeArray(path, next, { kind: 'shift-from', index })\n },\n swap(path, a, b) {\n const next = readArray(path)\n if (a < 0 || a >= next.length) return false\n if (b < 0 || b >= next.length) return false\n if (a === b) return false\n const tmp = next[a]\n next[a] = next[b]\n next[b] = tmp\n return writeArray(path, next, { kind: 'swap', a, b })\n },\n move(path, from, to) {\n const next = readArray(path)\n if (from < 0 || from >= next.length) return false\n const [item] = next.splice(from, 1)\n const clampedTo = Math.max(0, Math.min(to, next.length))\n next.splice(clampedTo, 0, item)\n return writeArray(path, next, {\n kind: 'shift-range',\n fromIndex: Math.min(from, clampedTo),\n toIndex: Math.max(from, clampedTo),\n })\n },\n replace(path, index, value) {\n const next = readArray(path)\n if (index < 0 || index >= next.length) return false\n next[index] = value\n return writeArray(path, next, { kind: 'replace-at', index })\n },\n }\n}\n","import type { ShouldShowErrors } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport {\n buildFieldStateAccessor,\n type FieldState,\n type FormMetaBaseGetter,\n} from './field-state-api'\nimport { getAtPath } from './path-walker'\nimport type { Path, Segment } from './paths'\nimport { buildSurfaceProxy, type SurfaceProxy } from './surface-proxy'\n\n/**\n * The leaf-prop set of a `FieldState`. At a leaf path, reads of\n * any of these keys terminate against the FieldState's reactive\n * prop. Reads of OTHER keys descend (e.g. a schema field literally\n * named `dirty` AT the leaf — which can happen when the shape is\n * `{ outer: { dirty: boolean } }`, making `outer.dirty` a leaf in\n * its own right; that case resolves via the leaf-aware proxy in\n * surface-proxy.ts where `outer.dirty` becomes a leaf-VIEW proxy and\n * `.dirty` on it reads the FieldState's `dirty` boolean).\n *\n * Container paths do NOT inject these keys via dot-access —\n * `form.fields.address.dirty` (where `address` is a container with\n * no `dirty` field) descends to a sub-proxy at `address.dirty` so\n * schema fields literally named `dirty` at depth 2+ stay\n * reachable. The container aggregation is reached via call-form:\n * `form.fields('address').dirty` returns the disjunction over\n * descendants.\n */\nconst FIELD_STATE_KEYS: ReadonlySet<string> = new Set<keyof FieldState<unknown>>([\n 'value',\n 'original',\n 'pristine',\n 'dirty',\n 'focused',\n 'blurred',\n 'touched',\n 'connected',\n 'element',\n 'elements',\n 'updatedAt',\n 'errors',\n 'validating',\n 'valid',\n 'showErrors',\n 'firstError',\n 'path',\n 'blank',\n 'label',\n 'description',\n 'placeholder',\n 'meta',\n])\n\n/**\n * Build the leaf-aware `form.fields` callable Proxy. Drill via dot /\n * bracket access OR call dynamically:\n *\n * form.fields.email.errors // dot/bracket descent\n * form.fields('email').errors // function-call (dynamic / programmatic)\n * form.fields(['users', 0, 'name']) // path-array form\n * form.fields() // root proxy\n *\n * Specialises `buildSurfaceProxy` (see surface-proxy.ts) with:\n * - `resolveLeaf`: returns the per-path `ComputedRef<FieldState>`\n * produced by `buildFieldStateAccessor`. The accessor allocates one\n * computed per path; the per-path memoisation in `buildSurfaceProxy`\n * ensures repeated reads of the same path return the same proxy.\n * - `leafKeys`: `FIELD_STATE_KEYS`. At a leaf path, reads off these\n * keys return the FieldState's reactive prop. Reads inside the\n * trap stay inside the consumer's active effect, so Vue's dep\n * tracking captures the dependency at access time.\n * - `readLeafKey`: extracts `view.value[key]` — the `view.value` access\n * triggers the computed's evaluation; the bracket lookup is a plain\n * object read against the resulting `FieldState`.\n */\nexport function buildFieldStateProxy<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n getFormMetaBase: FormMetaBaseGetter,\n options?: { readonly shouldShowErrors?: ShouldShowErrors }\n): SurfaceProxy {\n const getFieldStateAt = buildFieldStateAccessor(\n state,\n getFormMetaBase,\n options?.shouldShowErrors !== undefined\n ? { shouldShowErrors: options.shouldShowErrors }\n : undefined\n )\n const snapshotFieldStateAt = (path: Path): Record<string, unknown> => {\n const view = getFieldStateAt(path as Parameters<typeof getFieldStateAt>[0]).value\n const snapshot: Record<string, unknown> = {}\n for (const k of FIELD_STATE_KEYS) snapshot[k] = (view as Record<string, unknown>)[k]\n return snapshot\n }\n // Per-path cache for the FieldState terminal proxy — stable\n // referential identity across repeated `form.fields(p)` reads with\n // the same canonical key.\n const terminalCache = new Map<string, SurfaceProxy>()\n /**\n * Build the third proxy shape (distinct from `containerProxyAt` and\n * `leafViewProxyAt` in surface-proxy.ts). Returned by `apply`-trap\n * call-form at any depth — leaf or container — so\n * `form.fields(path)` always lands on a `FieldState` surface.\n *\n * - `get`: `FIELD_STATE_KEYS` reads return the resolved leaf\n * prop (delegates to the per-path computed); other keys return\n * `undefined`. No descent.\n * - No `apply`. No further callable behavior.\n */\n function fieldStateTerminalAt(segments: Path): SurfaceProxy {\n const cacheKey = JSON.stringify(segments)\n const existing = terminalCache.get(cacheKey)\n if (existing !== undefined) return existing\n const target = (() => {}) as unknown as SurfaceProxy\n const proxy = new Proxy(target, {\n get(_, key: string | symbol): unknown {\n if (typeof key === 'symbol') {\n if (key === Symbol.toPrimitive) {\n return (hint: string): string | number =>\n hint === 'number' ? NaN : JSON.stringify(snapshotFieldStateAt(segments))\n }\n return Reflect.get(target, key)\n }\n if (typeof key !== 'string') return undefined\n if (key === 'toJSON') return () => snapshotFieldStateAt(segments)\n if (key === 'toString') return () => JSON.stringify(snapshotFieldStateAt(segments))\n if (key === 'valueOf')\n return function (this: unknown): unknown {\n return this\n }\n if (FIELD_STATE_KEYS.has(key)) {\n const computed = getFieldStateAt(segments as Parameters<typeof getFieldStateAt>[0])\n return (computed.value as Record<string, unknown>)[key]\n }\n return undefined\n },\n has: (_, key: string | symbol): boolean =>\n typeof key === 'string' && FIELD_STATE_KEYS.has(key),\n ownKeys: () => Array.from(FIELD_STATE_KEYS),\n getOwnPropertyDescriptor(_, key: string | symbol): PropertyDescriptor | undefined {\n if (typeof key !== 'string') return undefined\n if (!FIELD_STATE_KEYS.has(key)) return undefined\n const computed = getFieldStateAt(segments as Parameters<typeof getFieldStateAt>[0])\n return {\n configurable: true,\n enumerable: true,\n value: (computed.value as Record<string, unknown>)[key],\n writable: false,\n }\n },\n set: () => false,\n deleteProperty: () => false,\n defineProperty: () => false,\n })\n terminalCache.set(cacheKey, proxy)\n return proxy\n }\n return buildSurfaceProxy<ReturnType<typeof getFieldStateAt>>({\n schema: state.schema as unknown as Parameters<typeof buildSurfaceProxy>[0]['schema'],\n resolveLeaf: (path) => getFieldStateAt(path as Parameters<typeof getFieldStateAt>[0]),\n leafKeys: FIELD_STATE_KEYS,\n readLeafKey: (computed, key) => (computed.value as Record<string, unknown>)[key],\n materializeContainer: (segments) => materializeFields(state, segments, snapshotFieldStateAt),\n resolveCallTarget: (path) => fieldStateTerminalAt(path),\n })\n}\n\n/**\n * Build a dense, nested `FieldState`-snapshot tree at\n * `containerSegments` for `JSON.stringify(form.fields.<container>)`.\n * Walks the live form value at the container path and snapshots the\n * `FieldState` for every schema-leaf descendant. Containers\n * recurse; leaves terminate with the snapshot. Arrays produce arrays;\n * records / objects produce objects whose key set matches the live\n * data (so a discriminated union exposes only the active variant's\n * keys, and a record exposes the keys actually present).\n *\n * Reactivity contract identical to `materializeErrors`: every read in\n * this function happens at call time inside the consumer's active\n * effect, so dependency tracking captures `state.form.value` and the\n * field-state computeds — `JSON.stringify(form.fields)` re-runs\n * whenever the form data or any per-leaf field state changes.\n */\nfunction materializeFields<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n containerSegments: readonly Segment[],\n snapshotFieldStateAt: (path: Path) => Record<string, unknown>\n): unknown {\n const liveValue = getAtPath(state.form.value, containerSegments)\n return walk(liveValue, containerSegments, state.schema, snapshotFieldStateAt)\n}\n\nfunction walk(\n value: unknown,\n basePath: readonly Segment[],\n schema: { isLeafAtPath(path: Path): boolean },\n snapshotFieldStateAt: (path: Path) => Record<string, unknown>\n): unknown {\n // Schema-leaf takes precedence over data shape: a leaf path with\n // `null` or a primitive in storage still surfaces the FieldState\n // (which is the field-state authority — `value` lives inside the view).\n if (schema.isLeafAtPath(basePath)) return snapshotFieldStateAt(basePath)\n // Container with no live value (e.g. an absent record key, or a\n // missing optional object): expose null so consumers can distinguish\n // \"schema container that hasn't been populated\" from \"container with\n // empty state\" (`{}` / `[]`).\n if (value === null || value === undefined) return value\n if (typeof value !== 'object') {\n // Defensive: schema reports container but data is a primitive. Surface\n // the primitive so the JSON shape reflects reality without throwing.\n return value\n }\n if (Array.isArray(value)) {\n return value.map((_, i) => walk(value[i], [...basePath, i], schema, snapshotFieldStateAt))\n }\n const result: Record<string, unknown> = {}\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = walk(\n (value as Record<string, unknown>)[key],\n [...basePath, key],\n schema,\n snapshotFieldStateAt\n )\n }\n return result\n}\n","/**\n * Library-level default constants. All consumer-facing fallbacks for\n * the bundled options (`debounceMs`, `persist.debounceMs`,\n * `history.max`, etc.) resolve to one of these — extracting them here\n * keeps the JSDoc on the public option type and the runtime fallback\n * in lockstep, and gives reviewers a single file to scan when tuning\n * timing/policy defaults.\n *\n * Per-form `useForm({ ... })` options always win over these. App-level\n * `createAttaform({ defaults: ... })` options sit between the\n * two: per-form > app-level > library default.\n */\n\nimport { __DEV__ } from './dev'\n\n/**\n * Validation debounce (`useForm({ debounceMs })`) — ms to wait after\n * the LAST input event before running validation. Default `0`\n * (debounce disabled): every committed write fires a validation pass\n * synchronously, no `setTimeout`. Matches the obvious mental model\n * and avoids the \"why is my error 125 ms behind my keystroke?\"\n * footgun for new consumers.\n *\n * NOTE: this is purely the VALIDATION debounce. Form storage\n * (`form.values`) commits on every write the directive forwards;\n * `setValueWithInternalPath` writes immediately and triggers a\n * validation schedule. WHEN the directive actually forwards a write\n * is a separate concern controlled by input modifiers — `<input\n * v-register>` commits on every keystroke (`input` event), but\n * `<input v-register.lazy>` defers to the `change` event so storage\n * only commits on blur. The validation debounce is independent of\n * either path: it always counts ms since the last committed write.\n *\n * Devs who need validation coalescing — slow async adapters,\n * validation that runs heavy work — opt in with `debounceMs: 200`\n * (or any positive number). The off-by-default posture trades CPU\n * cycles for UX latency wins, and the cycles only matter for\n * adapters that are actually expensive.\n */\nexport const DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS = 0\n\n/**\n * Persistence write debounce (`persist.debounceMs`). 300 ms is\n * generous on purpose — the goal is \"draft survives accidental\n * navigation,\" not \"every keystroke hits storage.\" Lower if your\n * storage adapter is in-memory; raise for slow IndexedDB or remote\n * adapters.\n */\nexport const DEFAULT_PERSISTENCE_DEBOUNCE_MS = 300\n\n/**\n * Undo/redo stack ceiling (`history.max`). 128 covers an extended\n * editing session — long-form text inputs, multi-page wizard flows,\n * heavy iteration on a complex form — without unbounded memory\n * growth from long-lived forms. History is stored as one base\n * snapshot plus per-mutation forward deltas; each delta typically\n * carries only the leaves that changed, so the per-mutation cost\n * is `O(changed-leaf-count)` rather than `O(form-leaf-count)`.\n * The cap exists more for predictability than memory pressure.\n */\nexport const DEFAULT_HISTORY_MAX_SNAPSHOTS = 128\n\n/**\n * Storage-key namespace for persistence. Resolved once at\n * `resolveStorageKey` to `${PERSISTENCE_KEY_PREFIX}${formKey}` unless\n * the consumer passes an explicit `persist.key`. Kept as a separate\n * constant so multi-tenant deployments can audit or reserve their\n * own prefix without grepping for the literal.\n */\nexport const PERSISTENCE_KEY_PREFIX = 'attaform:'\n\n/**\n * Reserved namespace for the library's internal synthetic keys\n * (anonymous forms today, plus any future internal-key uses).\n * `useAbstractForm` rejects any consumer-supplied key starting with\n * this prefix at construction time, throwing `ReservedFormKeyError` —\n * so collisions with the synthetic-key namespace are impossible by\n * construction. The double-underscore convention reads as \"internal\"\n * universally, lowering the chance a consumer would naturally pick\n * a key from this space anyway.\n */\nexport const RESERVED_KEY_PREFIX = '__atta:'\n\n/**\n * Synthetic-key prefix for `useForm()` calls without an explicit\n * `key`. Lives inside the reserved `__atta:` namespace so the entry-\n * level reject in `resolveFormKey` covers it automatically — see\n * `RESERVED_KEY_PREFIX` for the enforcement story.\n */\nexport const ANONYMOUS_FORM_KEY_PREFIX = `${RESERVED_KEY_PREFIX}anon:`\n\n/**\n * Recursion ceiling for schema walks that descend through recursive\n * schemas (Zod's `z.lazy(...)` today, equivalent constructs in any\n * future adapter). Adapter walks that follow a recursive boundary —\n * default derivation, slim-primitive type gates, path resolution,\n * refinement stripping — track their descent depth and bail with a\n * permissive fallback once `depth > maxRecursionDepth`.\n *\n * Default `64`. Tunable per-form via `useForm({ maxRecursionDepth })`\n * and app-wide via `createAttaform({ defaults: { maxRecursionDepth } })`;\n * per-form > app-level > this library default. `Infinity` disables\n * the cap entirely — see `AttaformDefaults.maxRecursionDepth`.\n *\n * \"Permissive fallback\" means the gate stops type-checking past the\n * cap (storage accepts the consumer's value; runtime validation\n * still runs against the real schema). Practical effect: forms with\n * trees deeper than the cap still work, but writes at deeper nodes\n * skip the slim-primitive type-gate. Raise the cap if you regularly\n * edit beyond it.\n */\nexport const DEFAULT_MAX_RECURSION_DEPTH = 64\n\n/**\n * Normalise a consumer-supplied numeric option before threading it\n * into runtime logic. Library options typed as `number` (recursion\n * caps, debounce intervals, history ceiling, parse-error caps) all\n * share the same input-sanitisation problem: invalid values reach\n * the runtime and produce silent footguns.\n *\n * Categories the runtime mishandles without sanitisation:\n *\n * - `NaN` — comparison-based gates (`>=`, `>`) yield `false` against\n * `NaN`, so caps never trip and pathological inputs run unbounded.\n * `setTimeout(fn, NaN)` fires synchronously, defeating debounce.\n * - Negative numbers — comparison gates trip too eagerly; the\n * visible value doesn't match consumer intent.\n * - Non-integers — `>=` against `5.7` works but is imprecise and\n * surprising at the call site.\n * - Non-numbers (JS callers defying TS) — undefined behaviour at\n * every comparison and arithmetic site.\n *\n * Sanitisation:\n *\n * - `Infinity` passes through when `allowInfinity` is `true`\n * (e.g. `maxRecursionDepth` disables the cap by design). When\n * `allowInfinity` is `false` (e.g. `debounceMs`, where `Infinity`\n * stalls the event loop), it falls back to the default with a\n * dev-warn.\n * - `NaN`, `-Infinity`, non-numbers → fall back to `defaultValue`\n * with a dev-warn naming the source.\n * - Negative finite numbers → clamped to `min`.\n * - Non-integer positives → floored.\n *\n * The fallback path never throws — a bad option shouldn't be fatal\n * at construction. The dev-warn surfaces the misuse without\n * breaking production.\n */\nexport interface NormalizeNumericOptionConfig {\n /** The consumer-supplied value to validate. */\n value: number\n /**\n * Human-readable identifier for the dev warning. Format like\n * `useForm.debounceMs` or `parseApiErrors.maxEntries` so the warning\n * tells the consumer which option carried the bad value.\n */\n source: string\n /**\n * Whether `Infinity` is a semantically valid input. `true` for\n * options whose \"no cap\" sentinel is sensible (recursion depth);\n * `false` for options where unbounded values cause real problems\n * (debounce intervals, history caps, parse-error caps).\n */\n allowInfinity: boolean\n /** Lower bound applied via `Math.max(min, ...)` after `Math.floor`. */\n min: number\n /**\n * Library default returned when the input is invalid (`NaN`,\n * `-Infinity`, non-number, or `Infinity` under `allowInfinity:\n * false`).\n */\n defaultValue: number\n}\n\nexport function normalizeNumericOption(config: NormalizeNumericOptionConfig): number {\n const { value, source, allowInfinity, min, defaultValue } = config\n if (allowInfinity && value === Infinity) return Infinity\n if (\n typeof value !== 'number' ||\n Number.isNaN(value) ||\n value === Infinity ||\n value === -Infinity\n ) {\n if (__DEV__) {\n const acceptedDescription = allowInfinity\n ? 'a non-negative integer or Infinity'\n : 'a non-negative finite integer'\n console.warn(\n `[attaform] ${source} must be ${acceptedDescription}; ` +\n `got ${String(value)}. Falling back to ${String(defaultValue)}.`\n )\n }\n return defaultValue\n }\n return Math.max(min, Math.floor(value))\n}\n","import type {\n AbstractSchema,\n FormStorage,\n FormStorageKind,\n PersistConfig,\n PersistConfigOptions,\n ValidationError,\n} from '../../types/types-api'\nimport { PERSISTENCE_KEY_PREFIX } from '../defaults'\nimport { __DEV__ } from '../dev'\nimport { isPlainRecord, setAtPath, getAtPath } from '../path-walker'\nimport { segmentsForPathKey, type Path, type PathKey, type Segment } from '../paths'\n\n/**\n * Public-ish handle returned by `wirePersistence`. Lives on\n * `state.modules.get('persistence')` so `buildFormApi` can plug\n * `form.persist(path)` and `form.clearPersistedDraft(path?)` into\n * the consumer-facing API. Internal — consumers go through the API.\n */\nexport type PersistenceModule = {\n /**\n * The normalized persist config that wired this module. Held so a\n * second `useForm({ key, persist: ... })` call sharing the\n * FormStore can detect divergence (e.g., the modal-team dev passed\n * `'session'` but the main-form dev wired `'local'`) and emit a\n * dev-warn. First call wins; subsequent values are dropped silently\n * absent this readback.\n */\n readonly wiredConfig: PersistConfigOptions\n /**\n * Read-merge-write a single path's current value. Flushes any pending\n * debounced write first so the imperative checkpoint can't be\n * overwritten by a stale-data write that fires immediately after.\n * No-op if the FormStore is disposed.\n */\n writePathImmediately(path: Path): Promise<void>\n /**\n * Wipe the persisted entry. With `path` provided, removes that\n * subpath only (and any matching error entries) and writes back; the\n * entry is removed entirely if the resulting form value is empty.\n * Without `path`, calls the adapter's `removeItem` directly.\n */\n clearPersistedDraft(path?: Path): Promise<void>\n /**\n * Drains any pending debounced or in-flight write. Resolves once\n * storage has the latest opted-in form value. Called by the registry\n * before evicting a FormStore so the last keystroke isn't lost when\n * a component unmounts mid-debounce.\n *\n * Safe to call after `dispose()` — resolves immediately as a no-op.\n */\n awaitPendingWrites(): Promise<void>\n /** Disposer — called from FormStore.dispose. */\n dispose(): void\n}\n\n/**\n * Cache key for `state.modules.get(...)`. Only the persistence layer\n * itself + buildFormApi read this — exporting keeps the literal in one\n * place rather than scattering 'persistence' across files.\n */\nexport const PERSISTENCE_MODULE_KEY = 'persistence'\n\n/**\n * Resolve a `FormStorage` adapter for the given storage kind. Built-in\n * kinds are dynamically imported so a consumer who picks `'local'`\n * never pulls the IndexedDB adapter code. Rollup's\n * side-effect-free graph tree-shakes the unused adapters cleanly.\n *\n * Passing a custom `FormStorage` object bypasses the dispatch and is\n * returned as-is — no dynamic import happens. This is the escape hatch\n * for encrypted stores, cookie-backed stores, native-mobile bridges.\n */\nexport async function getStorageAdapter(\n storage: FormStorageKind | FormStorage\n): Promise<FormStorage> {\n if (typeof storage === 'object') return storage\n switch (storage) {\n case 'local': {\n const { createLocalStorageAdapter } = await import('./local-storage')\n return createLocalStorageAdapter()\n }\n case 'session': {\n const { createSessionStorageAdapter } = await import('./session-storage')\n return createSessionStorageAdapter()\n }\n case 'indexeddb': {\n const { createIndexedDbAdapter } = await import('./indexeddb')\n return createIndexedDbAdapter()\n }\n }\n}\n\n/**\n * Persisted payload envelope.\n *\n * `v` is a attaform-INTERNAL storage-format version — bumped only when the\n * library's persisted payload schema itself changes (e.g. adding a new\n * field, restructuring `data`). It is NOT consumer-controlled.\n * Schema-driven invalidation uses the storage key's `:${fingerprint}`\n * suffix instead, so consumers don't need to manage versioning at all.\n *\n * `data` mirrors the SSR `SerializedFormData` shape so one deserialiser\n * handles both.\n *\n * Errors are stored source-segregated (matching FormStore's split):\n * - `schemaErrors` is validation-owned; cleared by reset / submit-success.\n * - `userErrors` is consumer-owned (written via setFieldErrors* APIs);\n * persists across schema revalidation and successful submits.\n */\nexport type PersistedPayload<Form> = {\n readonly v: number\n readonly data: {\n readonly form: Form\n readonly schemaErrors?: ReadonlyArray<readonly [string, ValidationError[]]>\n readonly userErrors?: ReadonlyArray<readonly [string, ValidationError[]]>\n /**\n * Path keys that were in the form's `blankPaths` set at\n * serialisation time. Optional — older v=2 envelopes don't carry it,\n * and forms with no blank paths skip the field too.\n * Replayed into the reactive Set on the next mount so an accidental\n * refresh preserves the user's \"displayed empty\" state across\n * sessions. Introduced in envelope v=3.\n */\n readonly blankPaths?: ReadonlyArray<string>\n }\n}\n\n/**\n * Current attaform-internal envelope version. Bumped only when the library\n * changes the persisted payload's structural shape — readers reject\n * envelopes with a different `v`. Schema-content invalidation is\n * handled at the storage key level (the `:${fingerprint}` suffix), so\n * consumers shouldn't see this number.\n *\n * v=3: adds `data.blankPaths` for round-tripping the\n * blank UI state across persistence + SSR. v=2 envelopes\n * are dropped with a one-time dev-warn (commit 6 of the unset feature).\n *\n * v=4: `ValidationError` gained a required `code` field. Persisted\n * `schemaErrors` / `userErrors` now include `code`; v=3 payloads are\n * dropped with a one-time dev-warn.\n */\nexport const PERSISTED_ENVELOPE_VERSION = 4\n\n/**\n * `value` is expected to be a raw `PersistedPayload` (parsed JSON or\n * structured-cloned object). Returns `null` if the shape doesn't match\n * — the caller falls back to schema defaults.\n *\n * The attaform-internal envelope `v` must match `PERSISTED_ENVELOPE_VERSION`;\n * mismatches (older library versions' payloads) are dropped. Schema\n * change detection lives at the storage-key level via the fingerprint\n * suffix.\n */\nexport function readPersistedPayload<Form>(value: unknown): PersistedPayload<Form> | null {\n if (value === null || value === undefined || typeof value !== 'object') return null\n const envelope = value as Partial<PersistedPayload<Form>>\n if (typeof envelope.v !== 'number') return null\n if (envelope.v !== PERSISTED_ENVELOPE_VERSION) {\n warnVersionMismatch(envelope.v)\n return null\n }\n if (envelope.data === undefined || typeof envelope.data !== 'object') return null\n return envelope as PersistedPayload<Form>\n}\n\n/**\n * Tracks envelope versions we've already warned about during this\n * session. The reader hits this for every form mount that finds\n * stale persisted state, so a page with N saved drafts at an old\n * version would otherwise produce N warnings of the same content.\n * Module-scoped Set survives the test-suite hot-reload cycle but\n * resets on each fresh page load — exactly the dedup window we want.\n *\n * `null` in production so the Set allocation tree-shakes out.\n */\nconst warnedVersions: Set<number> | null = __DEV__ ? new Set<number>() : null\n\nfunction warnVersionMismatch(observedVersion: number): void {\n if (warnedVersions === null) return\n if (warnedVersions.has(observedVersion)) return\n warnedVersions.add(observedVersion)\n console.warn(\n `[attaform] Dropping persisted draft — envelope v=${observedVersion}, ` +\n `but this version of the library expects v=${PERSISTED_ENVELOPE_VERSION}. ` +\n `The persisted shape changed across releases; older drafts can't be restored. ` +\n `New drafts saved this session will use the current envelope.`\n )\n}\n\nexport function buildPersistedPayload<Form>(\n form: Form,\n include: 'form' | 'form+errors',\n schemaErrors: ReadonlyMap<string, ValidationError[]>,\n userErrors: ReadonlyMap<string, ValidationError[]>,\n blankPaths?: ReadonlySet<string>\n): PersistedPayload<Form> {\n // The blank list is part of the form's restorable UI\n // state — its visibility doesn't depend on the `include` mode\n // (which only governs whether errors come along for the ride).\n // Skip the field when the set is empty so v=3 round-trips with\n // unchanged minimal payload size for forms that never go empty.\n const transientList: ReadonlyArray<string> | undefined =\n blankPaths !== undefined && blankPaths.size > 0 ? [...blankPaths] : undefined\n\n if (include === 'form') {\n if (transientList === undefined) return { v: PERSISTED_ENVELOPE_VERSION, data: { form } }\n return {\n v: PERSISTED_ENVELOPE_VERSION,\n data: { form, blankPaths: transientList },\n }\n }\n return {\n v: PERSISTED_ENVELOPE_VERSION,\n data: {\n form,\n schemaErrors: [...schemaErrors.entries()].map(([k, v]) => [k, [...v]] as const),\n userErrors: [...userErrors.entries()].map(([k, v]) => [k, [...v]] as const),\n ...(transientList !== undefined ? { blankPaths: transientList } : {}),\n },\n }\n}\n\n/**\n * Tiny debounce utility. Returns a `{ schedule, flush, cancel }`\n * triple — `schedule` delays a single pending write, `flush` runs it\n * immediately, `cancel` drops it. Unlike a library `debounce`, this\n * one awaits the underlying async write inside `flush` so callers\n * can await full completion on consumer teardown.\n *\n * `debounceMs: 0` is the off switch — `schedule()` fires the write\n * synchronously rather than queueing through `setTimeout(fn, 0)`\n * (which is a macrotask the browser clamps to ~4 ms anyway).\n */\nexport function createDebouncedWriter(\n write: () => Promise<void>,\n debounceMs: number\n): {\n schedule(): void\n flush(): Promise<void>\n cancel(): void\n} {\n let timer: ReturnType<typeof setTimeout> | null = null\n let pending: Promise<void> | null = null\n\n function schedule(): void {\n if (timer !== null) clearTimeout(timer)\n // `debounceMs: 0` is the off switch — fire the write synchronously\n // rather than punting through `setTimeout(fn, 0)` (which queues a\n // macrotask and the browser clamps to ~4 ms anyway).\n if (debounceMs === 0) {\n pending = write().finally(() => {\n pending = null\n })\n return\n }\n timer = setTimeout(() => {\n timer = null\n pending = write().finally(() => {\n pending = null\n })\n }, debounceMs)\n }\n\n async function flush(): Promise<void> {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n pending = write().finally(() => {\n pending = null\n })\n }\n if (pending !== null) await pending\n }\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n return { schedule, flush, cancel }\n}\n\n/**\n * Resolve the per-form storage KEY BASE. Default is\n * `attaform:${formKey}` — consumers who want a different\n * namespace (multi-tenant app, per-user prefix) pass `persist.key`.\n *\n * The full storage key is `${base}:${fingerprint}` (see\n * `resolveStorageKey`). The base is exposed separately so the\n * orphan-cleanup pass can `listKeys(base)` and prune any entry under\n * an old fingerprint.\n */\nexport function resolveStorageKeyBase(config: PersistConfigOptions, formKey: string): string {\n return config.key ?? `${PERSISTENCE_KEY_PREFIX}${formKey}`\n}\n\n/**\n * Resolve the full per-form storage key, composed of the base and the\n * schema's structural fingerprint. The fingerprint suffix gives free\n * automatic invalidation: any structural schema change produces a new\n * fingerprint, so the new mount looks up a fresh key and the old\n * draft becomes an orphan (cleaned up on the same mount via\n * `cleanupOrphanKeys`).\n */\nexport function resolveStorageKey(\n config: PersistConfigOptions,\n formKey: string,\n fingerprint: string\n): string {\n return `${resolveStorageKeyBase(config, formKey)}:${fingerprint}`\n}\n\n/**\n * Delete every attaform-managed key under `base` that's not the current\n * fingerprint key. Sweeps two shapes:\n * - Unfingerprinted keys (no `:` suffix at all) — defensive cover\n * for hand-written or migration-written entries that skipped the\n * fingerprint suffix.\n * - Fingerprint-suffixed keys whose suffix doesn't match the\n * current schema.\n *\n * Exact-or-`:`-prefix match prevents collision with sibling forms\n * whose `config.key` shares a string prefix (e.g. `'my-form'` vs\n * `'my-form-2'`).\n *\n * Fire-and-forget; never throws. SSR-guarded by the caller (cleanup\n * runs inside `wirePersistence`, which is itself client-only).\n */\nexport async function cleanupOrphanKeys(\n adapter: FormStorage,\n base: string,\n currentKey: string\n): Promise<void> {\n let keys: string[]\n try {\n keys = await adapter.listKeys(base)\n } catch {\n return\n }\n for (const key of keys) {\n if (key === currentKey) continue\n // Match either the exact base (unfingerprinted key) or an\n // explicit `:` continuation (stale-fingerprint key).\n if (key === base || key.startsWith(`${base}:`)) {\n void adapter.removeItem(key).catch(() => undefined)\n }\n }\n}\n\n/**\n * The canonical list of built-in backends. Used by the cross-store\n * cleanup sweep — any standard backend not matching the configured\n * one gets a `removeItem(key)` at mount.\n */\nexport const STANDARD_STORAGE_KINDS = ['local', 'session', 'indexeddb'] as const\n\n/**\n * Coerce the consumer-facing `PersistConfig` (which accepts shorthand\n * forms — a string backend name, or a custom `FormStorage` adapter) into\n * the resolved options bag the rest of the persistence layer expects.\n *\n * Discrimination rules (in order):\n *\n * 1. `typeof input === 'string'` — `FormStorageKind` shorthand.\n * 2. `'storage' in input` — already the full options bag.\n * 3. otherwise — custom `FormStorage` adapter.\n *\n * Step 3 trusts the caller's type: a `FormStorage` is a duck-typed\n * `{ getItem, setItem, removeItem }` object, and we don't validate\n * the shape — TypeScript already covers that path on the call site.\n *\n * Returning `PersistConfigOptions` (not `PersistConfig`) means the\n * normalized form is referentially distinct from the input — callers\n * can be confident `result.storage` is always present.\n */\nexport function normalizePersistConfig(input: PersistConfig): PersistConfigOptions {\n if (typeof input === 'string') return { storage: input }\n if ('storage' in input) return input\n return { storage: input }\n}\n\n/**\n * Wipe every attaform-managed key under `base` from every standard backend.\n * Fire-and-forget. Used when no `persist:` is configured on the form:\n * a previous deployment may have written entries under this base\n * (any fingerprint), and the dev removing persistence should mean the\n * on-disk artifact is gone too — for every fingerprint that ever ran.\n *\n * Sweeps unfingerprinted keys (no `:` suffix) and fingerprint-\n * suffixed keys equally. Errors per backend are swallowed.\n */\nexport async function sweepAllOrphansAcrossStandardStores(base: string): Promise<void> {\n for (const kind of STANDARD_STORAGE_KINDS) {\n try {\n const adapter = await getStorageAdapter(kind)\n const keys = await adapter.listKeys(base)\n for (const key of keys) {\n if (key === base || key.startsWith(`${base}:`)) {\n void adapter.removeItem(key).catch(() => undefined)\n }\n }\n } catch {\n // Backend unavailable (Node, Safari private mode, IDB blocked).\n }\n }\n}\n\n/**\n * Cross-store cleanup. Calls `removeItem(key)` on every standard\n * backend that's NOT the configured one — fire-and-forget. Runs once\n * at form mount.\n *\n * Why this matters: if a form was persisting to `'local'` and the dev\n * later switches to `'session'` (or a custom encrypted adapter), the\n * stale entry in `'local'` would otherwise sit there indefinitely,\n * potentially holding sensitive data the dev thought they had moved\n * to a safer store. The configured `storage` option is the source of\n * truth for \"where the draft lives now\"; everything else is hysteresis\n * from past app states and should be wiped.\n *\n * Implementation note: deletion is inlined per-backend rather than going\n * through `getStorageAdapter`. Inlining avoids dynamic-importing the\n * adapter chunks the consumer specifically chose NOT to use — a form\n * configured for `'local'` shouldn't pull the IndexedDB chunk just to\n * sweep it.\n *\n * If `configured` is a custom `FormStorage` adapter, all three standard\n * backends are swept (we don't know which built-in the dev migrated\n * away from, and we can't reach custom adapters by enumeration).\n *\n * Errors are swallowed — cleanup is best-effort. Backend unavailable\n * (Node, Safari private mode, IDB blocked) is also a silent skip.\n */\n/**\n * Cross-store orphan cleanup: wipe every attaform-managed key under `base`\n * from each standard backend that's NOT the configured one. Symmetric\n * with `cleanupOrphanKeys` on the configured store: ensures stale\n * drafts don't survive in stores the dev migrated AWAY from. Sweeps\n * unfingerprinted and stale-fingerprint keys equally.\n *\n * If `configured` is a custom `FormStorage` adapter, all three\n * standard backends are swept (we don't know which built-in the dev\n * migrated away from, and we can't reach custom adapters by\n * enumeration).\n *\n * Fire-and-forget. Per-backend errors swallowed.\n */\nexport async function sweepNonConfiguredStandardStoresForOrphans(\n configured: FormStorageKind | FormStorage,\n base: string\n): Promise<void> {\n const configuredKind = typeof configured === 'string' ? configured : null\n for (const kind of STANDARD_STORAGE_KINDS) {\n if (kind === configuredKind) continue\n try {\n const adapter = await getStorageAdapter(kind)\n const keys = await adapter.listKeys(base)\n for (const key of keys) {\n if (key === base || key.startsWith(`${base}:`)) {\n void adapter.removeItem(key).catch(() => undefined)\n }\n }\n } catch {\n // Backend unavailable.\n }\n }\n}\n\n/**\n * Build a sparse object containing only the values at `pathKeys` from\n * `form`. Each PathKey is the canonical JSON-array form\n * (`'[\"profile\",\"name\"]'`) emitted by `canonicalizePath`. Paths whose\n * value is `undefined` in the source (e.g. an optional schema field\n * the user never touched) are skipped — the caller's\n * `mergeSparseHydration` re-fills from schema defaults on read.\n *\n * The returned object structurally-shares with the source: a path that\n * names a container (e.g. `'contacts'` resolving to a whole array) is\n * copied by reference into the sparse output. Per-leaf opt-ins\n * (`'contacts.0.name'`) construct intermediate containers via\n * `setAtPath`.\n */\nexport function pluckPaths(form: unknown, pathKeys: Iterable<PathKey>): unknown {\n let sparse: unknown = undefined\n for (const pathKey of pathKeys) {\n // PathKeys arrive from the opt-in registry (canonical) — cache hit\n // every iteration. The null branch covers persistence payloads\n // round-tripped from disk that were corrupted before reaching the\n // restoration code.\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n const value = getAtPath(form, segments)\n if (value === undefined) continue\n sparse = setAtPath(sparse ?? {}, segments, value)\n }\n return sparse ?? {}\n}\n\n/**\n * Restrict a `(PathKey → ValidationError[])` map to entries whose key\n * appears in `pathKeys`. Used by the persistence writer to drop errors\n * on non-opted-in paths from the persisted envelope — a persisted\n * error without a persisted value would dangle on rehydration (the\n * form would resurrect with no value but a complaint about it).\n */\nexport function filterErrorsByPaths(\n errors: ReadonlyMap<string, ValidationError[]>,\n pathKeys: ReadonlySet<PathKey>\n): Map<string, ValidationError[]> {\n const out = new Map<string, ValidationError[]>()\n for (const [key, value] of errors) {\n if (pathKeys.has(key as PathKey)) out.set(key, value)\n }\n return out\n}\n\n/**\n * Merge a sparse persisted form over schema defaults. Returns a new\n * object — neither input is mutated. Used by hydration replay when\n * the persisted payload only contains opted-in paths.\n *\n * Object keys are merged recursively (sparse keys override defaults).\n * Arrays are REPLACED wholesale: if a path resolves to an array in the\n * sparse persisted form, it overrides the schema's array entirely. This\n * is the simpler rule for the common cases (whole-array opt-in via\n * `'contacts'` works; per-leaf opt-in implicitly accepts that schema\n * defaults for sibling leaves at the same array index won't be filled).\n *\n * Primitives in the sparse form override defaults. `null` and explicit\n * primitive values pass through (a persisted `null` is meaningful).\n *\n * **Discriminated unions:** when a path resolves to a DU in the\n * schema AND the sparse value's discriminator differs from the\n * defaults' discriminator (i.e. the persisted draft was written\n * against a different active variant than the schema's first-variant\n * default), the merge REBASES on the matching variant's slim default\n * rather than deep-merging across variants. Without this, deep merge\n * would produce an inconsistent shape carrying BOTH variants' keys\n * (e.g. `{channel: 'sms', number: '...', address: ''}`) — violates\n * the DU's per-variant shape contract and surfaces ghost fields in\n * `form.values`.\n */\nexport function mergeSparseHydration<F>(\n schemaDefaults: F,\n sparse: unknown,\n schema?: AbstractSchema<unknown, unknown>\n): F {\n return mergeDeep(schemaDefaults, sparse, [], schema) as F\n}\n\nfunction mergeDeep(\n target: unknown,\n source: unknown,\n path: readonly Segment[],\n schema: AbstractSchema<unknown, unknown> | undefined\n): unknown {\n if (source === undefined) return target\n if (source === null || typeof source !== 'object') return source\n if (Array.isArray(source)) return source\n if (!isPlainRecord(source)) return source\n // DU-aware merge at a discriminated-union path. Three sub-cases the\n // plain deep-merge below can't get right on its own:\n // 1. source's disc selects a different variant than target's →\n // rebase target onto the matched variant's slim default so the\n // prior variant's keys don't bleed alongside the new ones.\n // 2. source's disc is unknown to the schema → collapse to a\n // disc-only stub `{ [discKey]: discValue }` (mirrors the\n // runtime stub-state contract; validation surfaces the\n // mismatch on first validateAsync).\n // 3. source carries foreign keys (sibling-variant fields the\n // active variant doesn't declare) → drop them; the merge only\n // keeps source keys that exist in the matched variant default.\n // Skipped when no schema is provided (callers without an adapter\n // handle, including older tests) — those fall through to plain\n // deep-merge.\n if (schema !== undefined) {\n const du = schema.getUnionDiscriminatorAtPath(path as Segment[])\n if (du !== undefined) {\n const sourceRecord = source as Record<string, unknown>\n const sourceDisc = sourceRecord[du.discriminatorKey]\n if (sourceDisc !== undefined && !du.isVariantSelected(sourceDisc)) {\n return { [du.discriminatorKey]: sourceDisc }\n }\n if (sourceDisc !== undefined) {\n const variantDefault = du.getVariantDefault(sourceDisc)\n if (isPlainRecord(variantDefault)) {\n const out: Record<string, unknown> = { ...variantDefault }\n for (const key of Object.keys(sourceRecord)) {\n if (!(key in variantDefault) && key !== du.discriminatorKey) continue\n out[key] = mergeDeep(out[key], sourceRecord[key], [...path, key], schema)\n }\n return out\n }\n }\n // No disc in source — empty stub keeps the slot in a \"between\n // selections\" state so a subsequent disc write reshapes cleanly.\n return {}\n }\n }\n const mergeTarget = target\n const out: Record<string, unknown> = isPlainRecord(mergeTarget) ? { ...mergeTarget } : {}\n for (const key of Object.keys(source)) {\n out[key] = mergeDeep(out[key], (source as Record<string, unknown>)[key], [...path, key], schema)\n }\n return out\n}\n","/**\n * Stable identifiers for library-emitted `ValidationError` codes.\n *\n * Convention: `<scope>:<kebab-case-identifier>`. Three scopes are\n * recognised by the library:\n *\n * - `atta:` — emitted by the framework-agnostic core (this map).\n * - `zod:` — emitted by the Zod adapter; computed inline from\n * `issue.code` (e.g. `zod:too_small`). No enum here because\n * Zod's code list evolves.\n * - consumer-defined — anything the consumer's backend / app stamps\n * onto a `ValidationError` (via the `parseApiErrors` wire payload\n * or `setFieldErrors` directly). Pick a scope (`api:`, `auth:`,\n * etc.) and stay consistent.\n *\n * Use these constants in tests and error-routing UI:\n *\n * ```ts\n * if (error.code === AttaformErrorCode.NoValueSupplied) {\n * // user hasn't filled this field\n * }\n * ```\n */\nexport const AttaformErrorCode = {\n /** A required field is in the blank set — user hasn't supplied a value. */\n NoValueSupplied: 'atta:no-value-supplied',\n /** The schema adapter's `validateAtPath` threw synchronously. */\n AdapterThrew: 'atta:adapter-threw',\n /** The supplied path didn't resolve to any node in the schema. */\n PathNotFound: 'atta:path-not-found',\n} as const\n\nexport type AttaformErrorCode = (typeof AttaformErrorCode)[keyof typeof AttaformErrorCode]\n","import { getCurrentScope, onScopeDispose, ref, watchEffect, type Ref } from 'vue'\nimport type {\n HandleSubmit,\n OnError,\n OnInvalidSubmitPolicy,\n OnSubmit,\n ReactiveValidationStatus,\n SubmitHandler,\n ValidationError,\n ValidationResponse,\n ValidationResponseWithoutValue,\n} from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { __DEV__ } from './dev'\nimport { AttaformErrorCode } from './error-codes'\nimport { SubmitErrorHandlerError } from './errors'\nimport { canonicalizePath, segmentsForPathKey, type Path } from './paths'\n\n/**\n * Tracks FormStores for which we've already emitted the\n * \"validate() called outside an effect scope\" warning. One warn per\n * store keeps the diagnostic loud the first time and silent for the\n * rest of the run — important for hot-loop callers that would\n * otherwise spam the console (a tight test loop calling validate()\n * 1000 times shouldn't produce 1000 warnings).\n */\nconst warnedNoScopeStores: WeakSet<FormStore<GenericForm>> | null = __DEV__\n ? new WeakSet<FormStore<GenericForm>>()\n : null\n\n/**\n * validate + handleSubmit, both built against a FormStore<F>. Replaces\n * use-form-store's validation factory + the submit wrapper in\n * use-abstract-form.ts.\n *\n * Phase 5.6: validation is async end-to-end. `AbstractSchema.validateAtPath`\n * returns `Promise<ValidationResponse<F>>`, so every caller here awaits.\n * The reactive `validate()` ref carries a `pending` flag to distinguish\n * \"in-flight\" from \"settled\"; stale results are dropped via a per-call\n * generation counter.\n */\n\nexport type BuildProcessFormOptions = {\n /**\n * Policy applied inside handleSubmit when validation fails. Invoked\n * after the error store is populated and before the user's `onError`\n * callback. Default `'none'`.\n */\n onInvalidSubmit?: OnInvalidSubmitPolicy\n}\n\nexport function buildProcessForm<F extends GenericForm, Out extends GenericForm = F>(\n state: FormStore<F, Out>,\n formInstanceId: string,\n options: BuildProcessFormOptions = {}\n) {\n const invalidPolicy: OnInvalidSubmitPolicy = options.onInvalidSubmit ?? 'none'\n\n function validate(pathInput?: string | Path): Readonly<Ref<ReactiveValidationStatus<F>>> {\n // Start in a pending state — the first async run has not settled yet.\n // When validation fires, this ref writes `{ pending: false, ... }`\n // with the resolved status; stale writes (older generation) are\n // dropped so a slow earlier run can't overwrite a newer result.\n const result = ref<ReactiveValidationStatus<F>>({\n pending: true,\n errors: undefined,\n success: false,\n formKey: state.formKey,\n }) as Ref<ReactiveValidationStatus<F>>\n\n let gen = 0\n\n async function kickoff(data: unknown, path: Path | undefined, captured: number): Promise<void> {\n // Runs on a microtask outside the watchEffect's sync frame. Reads\n // and writes to reactive state inside this function DO NOT track\n // against the effect — the activeEffect stack is empty here —\n // so writing to `activeValidations` / `result` can't re-trigger\n // the watchEffect below.\n //\n // The lifecycle setup (counter increment + `pending: true` write)\n // lives INSIDE the try block so a sync watcher on\n // `meta.validating` or on the returned `result` ref that throws\n // can't leak the counter — the finally still decrements (Math.max\n // clamps the partial-increment underflow case at zero).\n try {\n state.activeValidations.value += 1\n result.value = {\n pending: true,\n errors: undefined,\n success: false,\n formKey: state.formKey,\n }\n const refinement = await runRefinementValidation(data, path)\n if (captured !== gen) return\n result.value = settled(composeWithDerivedBlank(refinement, path))\n } catch (err) {\n if (captured !== gen) return\n // Adapters are contractually \"return errors, don't throw\"; if\n // one does throw we don't want the validate() ref to hang in\n // `pending: true` forever. Wrap the throw as a single\n // adapter-level error so the form surfaces something.\n result.value = {\n pending: false,\n errors: [\n {\n message: adapterThrowMessage(err),\n path: [],\n formKey: state.formKey,\n code: AttaformErrorCode.AdapterThrew,\n },\n ],\n success: false,\n formKey: state.formKey,\n }\n } finally {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n }\n\n const stop = watchEffect(() => {\n // Read form.value (or the subtree at path) so the effect re-runs\n // on any mutation. We must NOT touch any other reactive state\n // here — the writes in `kickoff` would otherwise re-trigger the\n // effect in a hot loop. Deferring via `queueMicrotask` puts the\n // writes on a clean task where `activeEffect` is null.\n const segments = pathInput === undefined ? undefined : toSegments(pathInput)\n const dataAtPath = segments === undefined ? state.form.value : state.getValueAtPath(segments)\n const localGen = ++gen\n queueMicrotask(() => {\n void kickoff(dataAtPath, segments, localGen)\n })\n })\n // Tie the watcher's lifetime to the caller's effect scope so\n // components that call validate() in setup release the watcher on\n // unmount. Tests calling validate() in a raw context simply leak\n // the watcher for the test's duration — acceptable given tests\n // tear down the module context per run.\n if (getCurrentScope() !== undefined) {\n onScopeDispose(stop)\n } else if (\n __DEV__ &&\n warnedNoScopeStores !== null &&\n !warnedNoScopeStores.has(state as FormStore<GenericForm>)\n ) {\n warnedNoScopeStores.add(state as FormStore<GenericForm>)\n console.warn(\n '[attaform] validate() called outside a Vue effect scope; ' +\n 'its reactive watcher will leak until the form is garbage-collected. ' +\n 'Fix: call validate() inside setup() / a child component, ' +\n 'or wrap the call in `effectScope().run(...)`.'\n )\n }\n return result as Readonly<Ref<ReactiveValidationStatus<F>>>\n }\n\n /**\n * Imperative one-shot validation. Doesn't subscribe to form reactivity;\n * each call runs validation once against the current form snapshot.\n * Used by consumers who want to `await` a single validation run — the\n * debounced field-level path in 5.7, server-side round-trips, tests.\n */\n async function validateAsync(\n pathInput?: string | Path\n ): Promise<ValidationResponseWithoutValue<F>> {\n const segments = pathInput === undefined ? undefined : toSegments(pathInput)\n const dataAtPath = segments === undefined ? state.form.value : state.getValueAtPath(segments)\n // Increment lives INSIDE the try so a sync watcher on\n // `meta.validating` that throws can't leak `activeValidations`. The\n // finally still decrements (Math.max guards the partial-increment\n // underflow case). Adapter throws (or any throw inside the\n // pipeline — sync watcher boom, malformed schema) get translated\n // into a structured failure response with the `AdapterThrew` code\n // instead of rejecting the promise. A misbehaving adapter must not\n // be allowed to wreck the consumer's await chain or leak a raw\n // exception into UI code.\n try {\n state.activeValidations.value += 1\n const refinement = await runRefinementValidation(dataAtPath, segments)\n return stripData(composeWithDerivedBlank(refinement, segments))\n } catch (err) {\n return adapterThrowResponse(err)\n } finally {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n }\n\n /**\n * Imperative one-shot parse — same pipeline as `validateAsync` but\n * RETAINS the parsed data. Returns what `form.values` WOULD be if\n * every refinement passed and every transform fired. Useful when\n * the form's storage holds the pre-transform input view (the\n * \"honest input view\" — Attaform doesn't run `.transform()` at\n * write time, only preprocess) and the consumer wants the\n * post-transform output on demand.\n *\n * For a schema like `z.object({ email: z.string().transform(v =>\n * v.length > 10) })`, `form.values.email` is the string the user\n * wrote, while `(await form.process()).data?.email` is the boolean\n * the transform produces. handleSubmit's callback already receives\n * this same shape (it's what the parse pipeline emits before\n * onSubmit runs); `process()` is the standalone read-only form.\n *\n * Async because refinements may be async (`.refine(async ...)`).\n * The path-scoped variant mirrors `validateAsync(path?)` —\n * `process('email')` returns the parsed value at that path only.\n *\n * Like `validateAsync`, this never rejects on adapter misbehavior:\n * a throwing adapter (or any pipeline failure) lands in the\n * response as a `success: false, errors: [{ code: AdapterThrew }]`\n * shape so the library stays robust against a bad adapter.\n */\n async function process(pathInput?: string | Path): Promise<ValidationResponse<Out>> {\n const segments = pathInput === undefined ? undefined : toSegments(pathInput)\n const dataAtPath = segments === undefined ? state.form.value : state.getValueAtPath(segments)\n try {\n state.activeValidations.value += 1\n const refinement = await runRefinementValidation(dataAtPath, segments)\n return composeWithDerivedBlank(refinement, segments)\n } catch (err) {\n return adapterThrowResponse(err)\n } finally {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n }\n\n /**\n * Build an adapter-threw failure response. Shared between\n * `validateAsync`, `process`, and the reactive `validate()`'s\n * kickoff so every imperative validation surface presents the same\n * shape on adapter misbehavior: `{ success: false, errors: [{ code\n * AdapterThrew, message: adapterThrowMessage(err), path: [],\n * formKey }] }`. The `data` field is `undefined` so the\n * ValidationResponse union resolves to ErrorWithoutData.\n */\n function adapterThrowResponse(err: unknown): ValidationResponse<Out> {\n return {\n success: false,\n data: undefined,\n errors: [\n {\n message: adapterThrowMessage(err),\n path: [],\n formKey: state.formKey,\n code: AttaformErrorCode.AdapterThrew,\n },\n ],\n formKey: state.formKey,\n }\n }\n\n /**\n * Refinement-only adapter pass-through. Returns the schema's\n * refinement-class result without touching the blank-required class\n * — that lives reactively on `state.derivedBlankErrors`. Callers\n * compose the consumer-facing response via `composeWithDerivedBlank`\n * so `setAllSchemaErrors` only ever sees refinement errors and the\n * blank class never gets double-counted (once in `schemaErrors`, once\n * in `derivedBlankErrors`).\n */\n async function runRefinementValidation(\n data: unknown,\n path: Path | undefined\n ): Promise<ValidationResponse<Out>> {\n return await state.schema.validateAtPath(data, path)\n }\n\n /**\n * Fold the reactively-derived blank-required errors into a refinement\n * response. The derived class always reflects current state, so this\n * snapshot at call time matches what `form.errors` shows in the same\n * tick.\n */\n function composeWithDerivedBlank(\n refinement: ValidationResponse<Out>,\n scope: Path | undefined\n ): ValidationResponse<Out> {\n const blankErrors = collectScopedBlankErrors(state, scope)\n if (blankErrors.length === 0) return refinement\n if (refinement.success) {\n return {\n data: undefined,\n errors: blankErrors,\n success: false,\n formKey: state.formKey,\n }\n }\n return { ...refinement, errors: [...refinement.errors, ...blankErrors] }\n }\n\n /**\n * handleSubmit(onSubmit, onError?) builds a submit handler. On success:\n * clear errors, call onSubmit. On failure: populate errors via\n * setAllErrors, then call onError if provided.\n *\n * If the user's onError throws/rejects, the thrown value is re-thrown\n * wrapped in SubmitErrorHandlerError — prior versions swallowed this\n * into a console.error, which masked real bugs.\n *\n * Drives the submission-lifecycle refs on FormStore:\n * - `submitting` flips true at entry, false in `finally`.\n * - `submitCount` increments once per call, regardless of outcome —\n * \"how many times did the user click submit\" is the consumer-facing\n * question, independent of whether anything awaited.\n * - `submitError` clears at entry and captures anything thrown from\n * the user callback (or the wrapped error-handler error). Re-throws\n * after capturing so imperative callers (`await handler(event)`)\n * still see the rejection; template `@submit=\"...\"` callers read\n * `submitError` instead.\n *\n * Phase 5.6: the pre-dispatch validation is now async, so the handler\n * awaits `runValidation` before branching on success/failure. The\n * `validating` ref (backed by `state.activeValidations`) is true\n * for the validation window.\n */\n const handleSubmit: HandleSubmit<Out> = (onSubmit: OnSubmit<Out>, onError?: OnError) => {\n const submitHandler: SubmitHandler = async (event?: Event): Promise<void> => {\n if (\n event !== undefined &&\n 'preventDefault' in event &&\n typeof event.preventDefault === 'function'\n ) {\n event.preventDefault()\n }\n // Re-entry guard: a submission is already in flight. The classic\n // double-click case — `submit()` fires while a prior call is still\n // awaiting validation or the consumer's onSuccess — would otherwise\n // drive `onSuccess` twice and duplicate side-effects (POSTs, etc).\n // `preventDefault` already ran above, so a duplicate browser submit\n // is suppressed even when this branch returns early.\n if (state.activeSubmissions.value > 0) {\n return\n }\n // Track in-flight via a counter (not a flag) so that a generation\n // bump during the run can still distinguish \"I'm the live submission\"\n // from \"a stale prior submission winding down\" via the early\n // generation snapshot. submitError is shared with the prior call's\n // capture only when a `reset()` hasn't fired between entry and\n // throw (see the catch block).\n const genAtEntry = state.submissionGeneration.value\n let validationSettled = false\n try {\n // All lifecycle setup happens inside the try so a throw from\n // any of the setters (e.g. a sync `watch` on `meta.submitting`\n // that rejects, or a defensive throw from\n // `cancelFieldValidation`) still lands in the finally block.\n // Without this, an early-setup throw would leak\n // `activeSubmissions` at 1 forever and silently block every\n // subsequent submit. Math.max in the finally already clamps\n // partial-increment underflow at zero.\n state.activeSubmissions.value += 1\n state.submitting.value = true\n state.submitError.value = null\n // Abort any in-flight per-field validation runs so their late\n // writes can't clobber the authoritative submit result. Also\n // clears debounce timers that never fired.\n state.cancelFieldValidation()\n state.activeValidations.value += 1\n const refinement = await runRefinementValidation(state.form.value, undefined)\n const merged = composeWithDerivedBlank(refinement, undefined)\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n validationSettled = true\n // Generation guard: if `reset()` fired while we were awaiting\n // validation, the consumer just zeroed the submission surface\n // — the validation result is for state that's been replaced.\n // Skip the schema-error write so reset's empty store stays\n // empty; still run the user's onError so they get the result\n // (it's their data, not ours, to discard).\n const generationStillValid = state.submissionGeneration.value === genAtEntry\n if (!merged.success) {\n // Source-segregated writer: only refinement-class errors land\n // in `schemaErrors`. The blank-required class is already in\n // `derivedBlankErrors` (reactively derived from `blankPaths`),\n // so writing it here would double-count. User-injected errors\n // live in their own store and are NOT clobbered by validation.\n if (generationStillValid) {\n if (refinement.success) {\n state.clearSchemaErrors()\n } else {\n state.setAllSchemaErrors(refinement.errors)\n }\n }\n // Apply the invalid-submit focus/scroll policy AFTER populating\n // the error store (so getFirstErrorElement walks the fresh\n // entries) and BEFORE the user's onError callback (so consumer\n // logic can override by calling .focus on something else).\n // Skip the policy too on a stale generation — the post-reset\n // form has no errors to focus.\n if (generationStillValid) {\n applyInvalidSubmitPolicy(state, formInstanceId, invalidPolicy)\n }\n if (onError !== undefined) {\n try {\n await onError(merged.errors)\n } catch (cause) {\n throw new SubmitErrorHandlerError('User-provided onError threw', { cause })\n }\n }\n return\n }\n // Schema-only clear: a successful submit means refinement\n // validation passed AND no required-blank errors exist, so the\n // schema-error store goes empty. User-injected errors persist —\n // consumers managing their own warning/info state via\n // setFieldErrors keep ownership of that lifecycle. Skip the\n // clear when reset already cleared (and bumped gen) — any\n // errors injected by post-reset user mutations would be wrongly\n // wiped otherwise.\n if (generationStillValid) {\n state.clearSchemaErrors()\n }\n await onSubmit(merged.data)\n // Notify subscribers (persistence's clear-on-success handler,\n // future hooks). Fires only when the user callback resolved —\n // validation-failure and callback-throw skip it.\n state.emitSubmitSuccess()\n } catch (err) {\n // Only publish the error if `reset()` hasn't fired since this\n // submission began. Otherwise the consumer just zeroed the\n // submission surface and we'd undo their intent by re-raising\n // into `submitError`. We still re-throw so imperative callers\n // (`await handler(event)`) observe the rejection.\n if (state.submissionGeneration.value === genAtEntry) {\n state.submitError.value = err\n }\n throw err\n } finally {\n // If validation threw before we decremented, drop the counter now\n // so `validating` doesn't hang true after a failed submit.\n if (!validationSettled) {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n state.activeSubmissions.value = Math.max(0, state.activeSubmissions.value - 1)\n // `activeSubmissions` always decrements (the submission is done),\n // but the *visible* lifecycle counters — `submitting` and\n // `submitCount` — only update when the submission's generation\n // still matches. A post-reset completion is a no-op from the\n // consumer's point of view: reset already flipped `submitting`\n // to false and zeroed `submitCount`, and the finished submission\n // belongs to the prior generation.\n if (state.submissionGeneration.value === genAtEntry) {\n state.submitting.value = state.activeSubmissions.value > 0\n state.submitCount.value += 1\n }\n }\n }\n return submitHandler\n }\n\n return { validate, validateAsync, process, handleSubmit }\n}\n\nfunction toSegments(pathInput: string | Path): Path {\n return canonicalizePath(pathInput).segments\n}\n\nfunction settled<F extends GenericForm>(\n response: ValidationResponse<F>\n): ReactiveValidationStatus<F> {\n if (response.success) {\n return { pending: false, errors: undefined, success: true, formKey: response.formKey }\n }\n return { pending: false, errors: response.errors, success: false, formKey: response.formKey }\n}\n\nfunction stripData<F extends GenericForm>(\n response: ValidationResponse<F>\n): ValidationResponseWithoutValue<F> {\n if (response.success) {\n return { errors: undefined, success: true, formKey: response.formKey }\n }\n return { errors: response.errors, success: false, formKey: response.formKey }\n}\n\nfunction adapterThrowMessage(err: unknown): string {\n if (err instanceof Error) return `Adapter validateAtPath threw: ${err.message}`\n return 'Adapter validateAtPath threw a non-Error value'\n}\n\n/**\n * Read the reactively-derived blank-required errors out of the store,\n * filtered to paths inside `scope` (or all paths when `scope` is\n * `undefined`). The errors themselves are computed on the FormStore via\n * `derivedBlankErrors` — this helper just snapshots a scoped slice for\n * the validation/submit response. Mutating the returned array is safe;\n * the store's computed builds a fresh map per recompute.\n */\nfunction collectScopedBlankErrors<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n scope: Path | undefined\n): ValidationError[] {\n const derived = state.derivedBlankErrors.value\n if (derived.size === 0) return []\n const errors: ValidationError[] = []\n for (const [pathKey, entries] of derived) {\n if (scope !== undefined) {\n // Cache hit on canonical PathKeys; cold (corrupt) keys return\n // null and we skip. Don't round-trip through\n // `canonicalizePath(pathKey)` — that would treat the JSON-encoded\n // string as a NEW dotted path and produce a single segment\n // containing the literal JSON.\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n if (!pathStartsWith(segments, scope)) continue\n }\n errors.push(...entries)\n }\n return errors\n}\n\n/**\n * `true` if `target`'s segments start with `prefix`. Used to honour the\n * per-path scope of `validate(path)` / `validateAsync(path)` — only\n * blank paths inside the validated subtree contribute. An empty prefix\n * matches every path.\n */\nfunction pathStartsWith(target: Path, prefix: Path): boolean {\n if (prefix.length > target.length) return false\n for (let i = 0; i < prefix.length; i++) {\n if (!Object.is(target[i], prefix[i])) return false\n }\n return true\n}\n\nfunction applyInvalidSubmitPolicy<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n formInstanceId: string,\n policy: OnInvalidSubmitPolicy\n): void {\n if (policy === 'none') return\n const target = state.getFirstErrorElement(formInstanceId)\n if (target === null) return\n if (policy === 'scroll-to-first-error') {\n target.element.scrollIntoView()\n return\n }\n if (policy === 'focus-first-error') {\n target.element.focus()\n return\n }\n // 'both' — scroll first, then focus with preventScroll so the\n // browser doesn't undo the explicit scroll.\n target.element.scrollIntoView()\n target.element.focus({ preventScroll: true })\n}\n","import type { AbstractSchema } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\n\n/**\n * Best-effort top-level field hint for diagnostic error messages.\n * Walks the schema's slim default at the root and returns its keys\n * — sufficient for object-rooted schemas (the overwhelming majority).\n * Non-object roots return `[]`; the message degrades by omitting the\n * fields clause rather than throwing.\n *\n * No adapter contract change: every adapter already implements\n * `getDefaultAtPath([])` for the structural-fill pipeline, so this\n * helper is free.\n */\nexport function extractSchemaFields(\n schema: AbstractSchema<GenericForm, GenericForm>\n): readonly string[] {\n try {\n const root = schema.getDefaultAtPath([])\n if (root !== null && typeof root === 'object' && !Array.isArray(root)) {\n return Object.keys(root as object)\n }\n } catch {\n // Adapter threw — degrade gracefully so the diagnostic still fires.\n }\n return []\n}\n","/**\n * Slim-primitive write gate.\n *\n * Walks a value tree from a write path, validating that each leaf's\n * primitive type matches the schema's slim primitive set at the\n * corresponding sub-path. Used by `setValueAtPath` to reject writes\n * whose primitive shape can't possibly satisfy the slim schema —\n * regardless of refinement-level conformance.\n *\n * Refinement-level constraints (format checks, length / range bounds,\n * enum membership, literal equality) are NOT enforced here; they're\n * a validation-time concern. This gate exists purely to keep the\n * runtime store's primitive shape honest.\n */\nimport type { AbstractSchema, SlimPrimitiveKind } from '../types/types-api'\nimport type { Path, Segment } from './paths'\nimport { isPlainRecord } from './path-walker'\nimport { __DEV__ } from './dev'\n\n/**\n * Per-store one-shot dev-warn dedupe. Keyed by (FormStore identity,\n * dotted path + offending kind) so the same misuse during a v-for\n * re-render doesn't flood the console.\n *\n * In production, `__DEV__` is `false` and the WeakMap allocation\n * tree-shakes out — `recordRejection` returns `false` (don't warn).\n */\nconst warnedRejections: WeakMap<object, Set<string>> | null = __DEV__\n ? new WeakMap<object, Set<string>>()\n : null\n\nfunction shouldWarnOnce(store: object, key: string): boolean {\n if (warnedRejections === null) return false\n let set = warnedRejections.get(store)\n if (set === undefined) {\n set = new Set()\n warnedRejections.set(store, set)\n }\n if (set.has(key)) return false\n set.add(key)\n return true\n}\n\n/**\n * Map a value to its slim primitive kind. Mirrors the adapter walker's\n * leaf-level mapping so the same kind names compare across the\n * accept-set boundary.\n *\n * Exported so the default-values pipelines can reuse the same\n * primitive-vs-refinement classification logic the runtime gate uses.\n */\nexport function slimKindOf(value: unknown): SlimPrimitiveKind {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n if (Array.isArray(value)) return 'array'\n if (value instanceof Date) return 'date'\n if (value instanceof Map) return 'map'\n if (value instanceof Set) return 'set'\n const t = typeof value\n switch (t) {\n case 'string':\n return 'string'\n case 'number':\n return 'number'\n case 'boolean':\n return 'boolean'\n case 'bigint':\n return 'bigint'\n case 'symbol':\n return 'symbol'\n case 'function':\n return 'function'\n case 'undefined':\n return 'undefined'\n case 'object':\n return 'object'\n }\n}\n\nfunction isLeafValue(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (Array.isArray(value)) return false\n if (isPlainRecord(value)) return false\n return true\n}\n\n/**\n * Validate `value` against the schema's slim shape, descending into\n * plain records and arrays so every leaf is checked at its sub-path.\n *\n * Returns `true` if every leaf's primitive matches the schema's\n * accept set at its path; `false` otherwise (and emits a one-shot\n * dev-warn naming the bad path + offending kind + accepted kinds).\n *\n * Conventions:\n * - Empty accept set → REJECT every kind. This covers a `never`-typed\n * path (intentionally accepts nothing) AND unresolvable paths (typo\n * in `register('addr.zipp')` against a schema that doesn't have\n * that field — silently accepting the write would create a phantom\n * slot in storage). The \"permissive\" cases (`any` / `unknown` /\n * `void` and the lazy-peel-failure case) return the FULL accept set\n * instead, so they accept anything via the membership check below\n * — they don't go through this branch.\n * - The value AT the write path is also checked: writing `'oops'`\n * to a path expecting `'object'` is rejected at the top-level.\n * - For wrappers like `.optional()` / `.nullable()`, the adapter's\n * accept set already includes `'undefined'` / `'null'` — no\n * special-casing here.\n */\nexport function isSlimPrimitiveValid(\n schema: AbstractSchema<unknown, unknown>,\n store: object,\n path: Path,\n value: unknown\n): boolean {\n return walk(schema, store, path, value)\n}\n\nfunction walk(\n schema: AbstractSchema<unknown, unknown>,\n store: object,\n path: Path,\n value: unknown\n): boolean {\n // Top-of-tree check: does the value at THIS path satisfy the\n // schema's slim kinds at this path? Recurse into containers\n // afterwards — the recursion checks the elements' kinds at\n // the sub-paths.\n //\n // An empty accept set means the schema rejects every kind at this\n // path: either the path doesn't resolve (typo / unknown leaf) or\n // the path resolves to a `never`-typed schema. Either way, the\n // membership check below rejects, blocking the write. `any` /\n // `unknown` / `void` and the lazy-peel-failure case return the\n // full permissive set — those still accept any kind.\n const accepted = schema.getSlimPrimitiveTypesAtPath(path)\n const kind = isLeafValue(value) ? slimKindOf(value) : Array.isArray(value) ? 'array' : 'object'\n if (!accepted.has(kind)) {\n reportRejection(store, path, kind, accepted)\n return false\n }\n\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (!walk(schema, store, [...path, i], value[i])) return false\n }\n return true\n }\n\n if (isPlainRecord(value)) {\n for (const key of Object.keys(value)) {\n if (!walk(schema, store, [...path, key], (value as Record<string, unknown>)[key])) {\n return false\n }\n }\n return true\n }\n\n return true\n}\n\nfunction reportRejection(\n store: object,\n path: Path,\n kind: SlimPrimitiveKind,\n accepted: Set<SlimPrimitiveKind>\n): void {\n if (!__DEV__) return\n const dotted = path.map((s: Segment) => String(s)).join('.') || '(root)'\n const key = `${dotted}::${kind}`\n if (!shouldWarnOnce(store, key)) return\n\n // KISS rule: state the problem in one sentence, then list the fix.\n // Devs scan the first line; everything after is the recipe.\n\n // Path doesn't resolve (or resolves to a `never`-typed schema). The\n // headline names the actual cause; `never`-typed paths are rare\n // enough that they don't deserve top billing.\n if (accepted.size === 0) {\n console.warn(\n `[attaform] Cannot write to '${dotted}' — this path is not in your schema.\\n` +\n ` Fix: check for a typo in register('${dotted}'); it should match a leaf key in your schema.\\n` +\n ` (If the path resolves to a never-typed schema, it explicitly admits no values — relax the schema if intentional.)\\n` +\n ` The write was a no-op.`\n )\n return\n }\n\n const expected = formatExpectedKinds(accepted)\n\n // String-to-number is the most common gate rejection in real apps:\n // a plain `<input v-register>` against a numeric leaf reads\n // `el.value` as a string. Show both v-register fix paths verbatim\n // so the dev can copy-paste rather than parse \"slim primitive set\".\n if (kind === 'string' && accepted.has('number')) {\n console.warn(\n `[attaform] Cannot write a string to '${dotted}' — the schema expects ${expected}.\\n` +\n ` Fix: add type=\"number\" to the input, OR use the .number modifier on v-register:\\n` +\n ` <input type=\"number\" v-register=\"register('${dotted}')\" />\\n` +\n ` <input v-register.number=\"register('${dotted}')\" />\\n` +\n ` The write was a no-op.`\n )\n return\n }\n\n // Generic kind mismatch — no built-in DOM coercion path to suggest.\n console.warn(\n `[attaform] Cannot write a ${kind} to '${dotted}' — the schema expects ${expected}.\\n` +\n ` The write was a no-op.`\n )\n}\n\nfunction formatExpectedKinds(accepted: Set<SlimPrimitiveKind>): string {\n const list = [...accepted].sort()\n if (list.length === 1) return list[0] as string\n if (list.length === 2) return `${list[0]} or ${list[1]}`\n return `one of: ${list.join(', ')}`\n}\n","/**\n * Schema-driven coercion of user-typed DOM values at the v-register\n * directive layer. When the slim schema declares a numeric or\n * boolean type at a path, the directive coerces incoming string\n * values (`'25'` → `25`, `'true'` → `true`) before the slim-primitive\n * gate sees the write — making the schema authoritative for storage\n * shape and freeing consumers from sprinkling `.number` modifiers\n * across templates.\n *\n * Coercion is consumer-extensible: a `CoercionRegistry` is just an\n * `Array<CoercionEntry>` keyed at config time by `(input, output)`\n * `SlimPrimitiveKind` literals. The library ships\n * `defaultCoercionRules` (string→number, string→boolean) and\n * `defineCoercion` for type-narrowed authoring; consumers spread the\n * defaults to extend or supply their own array to replace.\n *\n * Coercion applies ONLY to user-typed DOM values flowing through\n * the directive's assigner. Programmatic writes (`form.setValue`,\n * `setValueWithInternalPath`) bypass coercion — they're authoritative\n * writes whose strict typing is on the caller. This mirrors the\n * `transforms` pipeline's user-input-only contract.\n */\nimport type {\n AbstractSchema,\n CoercionEntry,\n CoercionRegistry,\n CoercionResult,\n SlimPrimitiveKind,\n} from '../types/types-api'\nimport type { Path } from './paths'\nimport { slimKindOf } from './slim-primitive-gate'\nimport { __DEV__ } from './dev'\n\n/**\n * Type-narrowing helper for authoring entries. At runtime it's\n * identity; at compile time it preserves the `input` / `output`\n * literal types so `transform`'s parameter is narrowed to the\n * runtime type instead of widening to `SlimRuntimeOf<SlimPrimitiveKind>`.\n *\n * Without this helper, authoring `{ input: 'string', output:\n * 'number', transform: (s) => ... }` against the broader\n * `CoercionEntry` widens `s` to `string | number | boolean | ...`,\n * forcing a cast in every transform body. `defineCoercion` is the\n * opaque-free idiom.\n */\nexport function defineCoercion<I extends SlimPrimitiveKind, O extends SlimPrimitiveKind>(\n entry: CoercionEntry<I, O>\n): CoercionEntry<I, O> {\n return entry\n}\n\n/**\n * Internal index built from a `CoercionRegistry` at config-resolve\n * time. Keyed by `${input}->${output}` for O(1) per-keystroke\n * dispatch. The authoring shape (array, ergonomic, type-narrowing-\n * friendly) and the dispatch shape (Map, fast) decouple cleanly.\n */\nexport type CoercionIndex = ReadonlyMap<`${SlimPrimitiveKind}->${SlimPrimitiveKind}`, CoercionEntry>\n\n/** Identity function reused by `buildCoerceFn` when coercion is\n * disabled or the path admits no coercion target. */\nexport const IDENTITY: (v: unknown) => unknown = (v) => v\n\n/** Frozen empty index — reference-equal sentinel that lets\n * `buildCoerceFn` short-circuit to `IDENTITY` without allocation. */\nconst EMPTY_INDEX: CoercionIndex = new Map()\n\n/**\n * The library's built-in registry. Two cells: string→number and\n * string→boolean. Re-exported so consumers can spread it when\n * supplying a custom registry that extends defaults.\n */\nexport const defaultCoercionRules: CoercionRegistry = [\n defineCoercion({\n input: 'string',\n output: 'number',\n transform: (s) => {\n // Trim first so whitespace-only inputs don't slip past the\n // empty-string guard via `Number(' ') === 0`. The blank-paths\n // machinery owns the empty-input shape; coerce only fires when\n // there's a non-blank token to consider.\n const trimmed = s.trim()\n if (trimmed === '') return { coerced: false }\n const n = Number(trimmed)\n if (!Number.isFinite(n)) return { coerced: false }\n return { coerced: true, value: n }\n },\n }),\n defineCoercion({\n input: 'string',\n output: 'boolean',\n transform: (s) => {\n // Case-insensitive + whitespace-tolerant. Aligns with the\n // aria-style boolean-token convention (`aria-checked` accepts\n // \"true\"/\"True\"/\"TRUE\"). DOM `value=` attributes preserve\n // whatever case the dev wrote, and `value=\"True\"` is common\n // enough that strict-lowercase-only would be a footgun.\n const normalized = s.trim().toLowerCase()\n if (normalized === 'true') return { coerced: true, value: true }\n if (normalized === 'false') return { coerced: true, value: false }\n return { coerced: false }\n },\n }),\n]\n\n/**\n * Resolve the consumer's `coerce` config slot to a concrete index.\n * `true` / `undefined` → indexed defaults; `false` → empty index;\n * custom registry → indexed (with duplicate-pair dev-warn).\n *\n * Called once per FormStore in `createFormStore`.\n */\nexport function resolveCoercionIndex(\n config: boolean | CoercionRegistry | undefined\n): CoercionIndex {\n if (config === false) return EMPTY_INDEX\n const rules = config === undefined || config === true ? defaultCoercionRules : config\n return indexRules(rules)\n}\n\nfunction indexRules(rules: CoercionRegistry): CoercionIndex {\n const idx = new Map<`${SlimPrimitiveKind}->${SlimPrimitiveKind}`, CoercionEntry>()\n for (const entry of rules) {\n // The static type says `entry: CoercionEntry`, but consumers can\n // pass in registries assembled at runtime (parsed JSON, plugin\n // config) where individual entries may be malformed. Cast through\n // `unknown` to inspect runtime shape without lint complaining about\n // an \"always true\" type-narrowing branch.\n const candidate = entry as unknown\n if (\n candidate === null ||\n typeof candidate !== 'object' ||\n typeof (candidate as { transform?: unknown }).transform !== 'function'\n ) {\n if (__DEV__) {\n console.warn('[attaform] coercion entry missing or invalid `transform` — skipped.')\n }\n continue\n }\n const key = `${entry.input}->${entry.output}` as const\n if (idx.has(key) && __DEV__) {\n console.warn(`[attaform] duplicate coercion rule for '${key}' — last entry wins.`)\n }\n idx.set(key, entry)\n }\n return idx\n}\n\n/**\n * Build the per-register coerce closure. The closure captures the\n * resolved `accepted` set + the index, so the per-event hot path\n * doesn't re-walk the schema on every keystroke. Returns `IDENTITY`\n * when coerce is disabled — zero allocation for the common case.\n */\nexport function buildCoerceFn(\n schema: AbstractSchema<unknown, unknown>,\n segments: Path,\n index: CoercionIndex\n): (value: unknown) => unknown {\n if (index === EMPTY_INDEX) return IDENTITY\n if (index.size === 0) return IDENTITY\n const accepted = schema.getSlimPrimitiveTypesAtPath(segments)\n const elementAccepted =\n accepted.has('array') || accepted.has('set')\n ? schema.getSlimPrimitiveTypesAtPath([...segments, 0])\n : undefined\n return (value) => coerceValue(value, accepted, elementAccepted, index)\n}\n\n/**\n * Element-level coerce closure. Returns `undefined` when the path\n * isn't a container (scalar paths use `buildCoerceFn` exclusively).\n *\n * Why this is separate from `buildCoerceFn`: the path-level closure\n * handles the WRITE path correctly — given a container value, it\n * iterates and coerces each element internally. But the directive's\n * READ-side comparisons (`setChecked` array/Set branches,\n * `setSelected` multi-select) compare a SCALAR DOM-side value (the\n * option's `value` attribute) against the post-coerce container\n * elements. The path-level closure can't help here because it would\n * see a scalar and look up the path's accept set (`{ array }`),\n * which has no scalar coercion target. The element-level closure\n * skips ahead to the element-type accept set.\n */\nexport function buildElementCoerceFn(\n schema: AbstractSchema<unknown, unknown>,\n segments: Path,\n index: CoercionIndex\n): ((value: unknown) => unknown) | undefined {\n if (index === EMPTY_INDEX) return undefined\n if (index.size === 0) return undefined\n const accepted = schema.getSlimPrimitiveTypesAtPath(segments)\n if (!accepted.has('array') && !accepted.has('set')) return undefined\n const elementAccepted = schema.getSlimPrimitiveTypesAtPath([...segments, 0])\n return (value) => coerceScalar(value, elementAccepted, index)\n}\n\n/**\n * Pick the unambiguous coercion target for an accept set. Returns\n * the target kind only when it's the SOLE coercible kind — if the\n * path admits both `string` and `number`, the schema explicitly\n * accepts either, so silent retyping is wrong (passthrough).\n */\nfunction pickScalarTarget(accepted: ReadonlySet<SlimPrimitiveKind>): SlimPrimitiveKind | null {\n if (accepted.has('string')) return null\n if (accepted.has('number')) return 'number'\n if (accepted.has('boolean')) return 'boolean'\n if (accepted.has('bigint')) return 'bigint'\n return null\n}\n\n/**\n * Per-store WeakMap dedupe of dev-warns from coercion. Mirrors the\n * slim-gate's pattern (`slim-primitive-gate.ts:28-42`) so the same\n * (rule, error) pair doesn't flood the console during a v-for re-\n * render. Key shape: `<input>-><output>::<reason>`.\n */\nconst warnedCoerce: WeakMap<object, Set<string>> | null = __DEV__\n ? new WeakMap<object, Set<string>>()\n : null\nconst sharedWarnStore: object = {}\n\nfunction shouldWarnOnce(key: string): boolean {\n if (warnedCoerce === null) return false\n let set = warnedCoerce.get(sharedWarnStore)\n if (set === undefined) {\n set = new Set()\n warnedCoerce.set(sharedWarnStore, set)\n }\n if (set.has(key)) return false\n set.add(key)\n return true\n}\n\nfunction coerceScalar(\n value: unknown,\n accepted: ReadonlySet<SlimPrimitiveKind>,\n index: CoercionIndex\n): unknown {\n if (accepted.size === 0) return value\n const sourceKind = slimKindOf(value)\n if (accepted.has(sourceKind)) return value\n const target = pickScalarTarget(accepted)\n if (target === null) return value\n const entry = index.get(`${sourceKind}->${target}`)\n if (entry === undefined) return value\n let result: CoercionResult<unknown>\n try {\n result = entry.transform(value as never) as CoercionResult<unknown>\n } catch (err) {\n if (__DEV__ && shouldWarnOnce(`${entry.input}->${entry.output}::throw`)) {\n console.warn(\n `[attaform] coercion '${entry.input}->${entry.output}' threw — write passes through.`,\n err\n )\n }\n return value\n }\n if (!result.coerced) return value\n // Post-validate: the rule claimed it coerced, but did it actually\n // produce a value matching the declared `output`? Defends against\n // buggy consumer rules without forcing them to validate themselves.\n const returnedKind = slimKindOf(result.value)\n if (returnedKind !== entry.output) {\n if (__DEV__ && shouldWarnOnce(`${entry.input}->${entry.output}::wrong-kind:${returnedKind}`)) {\n console.warn(\n `[attaform] coercion '${entry.input}->${entry.output}' produced a ${returnedKind} — write passes through.`\n )\n }\n return value\n }\n if (entry.output === 'number' && !Number.isFinite(result.value as number)) {\n if (__DEV__ && shouldWarnOnce(`${entry.input}->${entry.output}::nan`)) {\n console.warn(\n `[attaform] coercion '${entry.input}->${entry.output}' produced a non-finite number — write passes through.`\n )\n }\n return value\n }\n return result.value\n}\n\nfunction coerceArrayMembers(\n arr: readonly unknown[],\n elementAccepted: ReadonlySet<SlimPrimitiveKind>,\n index: CoercionIndex\n): readonly unknown[] {\n let changed = false\n const out: unknown[] = []\n for (const el of arr) {\n const next = coerceScalar(el, elementAccepted, index)\n if (next !== el) changed = true\n out.push(next)\n }\n return changed ? out : arr\n}\n\nfunction coerceSetMembers(\n set: ReadonlySet<unknown>,\n elementAccepted: ReadonlySet<SlimPrimitiveKind>,\n index: CoercionIndex\n): ReadonlySet<unknown> {\n let changed = false\n const out: unknown[] = []\n for (const el of set) {\n const next = coerceScalar(el, elementAccepted, index)\n if (next !== el) changed = true\n out.push(next)\n }\n return changed ? new Set(out) : set\n}\n\nfunction coerceValue(\n value: unknown,\n accepted: ReadonlySet<SlimPrimitiveKind>,\n elementAccepted: ReadonlySet<SlimPrimitiveKind> | undefined,\n index: CoercionIndex\n): unknown {\n if (Array.isArray(value)) {\n if (!accepted.has('array') || elementAccepted === undefined) return value\n return coerceArrayMembers(value, elementAccepted, index)\n }\n if (value instanceof Set) {\n if (!accepted.has('set') || elementAccepted === undefined) return value\n return coerceSetMembers(value, elementAccepted, index)\n }\n return coerceScalar(value, accepted, index)\n}\n","import { computed, ref, shallowReadonly, type Ref } from 'vue'\nimport type {\n CoercionRegistry,\n InternalRegisterValue,\n RegisterOptions,\n RegisterTransform,\n RegisterValue,\n WriteMeta,\n} from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { captureUserCallSite } from './dev-stack-trace'\nimport { AnonPersistError } from './errors'\nimport { extractSchemaFields } from './extract-schema-fields'\nimport { canonicalizePath, type Path, type PathKey } from './paths'\nimport { PERSISTENCE_MODULE_KEY } from './persistence'\nimport { buildCoerceFn, buildElementCoerceFn, resolveCoercionIndex } from './schema-coerce'\n\n/**\n * Per-`useForm()`-instance config that the API layer threads through\n * register so each instance honors its own `validateOn` / `debounceMs`\n * / `coerce` / `rememberVariants` even when sharing a FormStore with\n * sibling instances. Anything omitted falls back to the store's\n * construction-time captured values.\n */\nexport type InstanceRegisterConfig = {\n readonly instanceMeta?: WriteMeta['instance']\n readonly coerce?: boolean | CoercionRegistry\n}\n\n// Module-level frozen empty array — re-used as the transforms default\n// across every register() call that doesn't opt in. Avoids a per-call\n// allocation on the 99% of fields that don't declare normalization,\n// while keeping the directive's `for (const t of rv.transforms)`\n// iteration uniform (no null-check needed).\nconst EMPTY_TRANSFORMS: ReadonlyArray<RegisterTransform> = Object.freeze([])\n\n/**\n * Register API factory. Given a FormStore, returns a `register(path)` that\n * produces a RegisterValue suitable for the v-register directive.\n *\n * Design points:\n *\n * - Focus/blur listeners are attached per-element-registration and stored\n * on the element itself via a symbol, then removed on deregistration.\n * No registration-time helper cache.\n * - `innerRef` reads `form.value` directly via `getValueAtPath`; there's\n * no separate raw-vs-form tracking. The synchronous diff-apply writer\n * keeps the two values in lock-step.\n * - Cross-form isolation is by construction: every call to `buildRegister`\n * closes over a FormStore<F> unique to one form.\n */\n\nconst INTERACTIVE_TAG_NAMES = new Set(['INPUT', 'SELECT', 'TEXTAREA'])\n\n// `Symbol.for(...)` so duplicate copies of attaform agree on the\n// element-property key for stashed focus/blur handlers — see\n// `assignKey` in core/directive.ts for the same reasoning.\nconst attaformListenersSymbol: unique symbol = Symbol.for('attaform:focus-listeners')\n\ntype ElementWithListeners = HTMLElement & {\n [attaformListenersSymbol]?: {\n handleFocus: (event: FocusEvent) => void\n handleBlur: (event: FocusEvent) => void\n }\n}\n\nfunction attachFocusListeners<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n segments: Path,\n element: HTMLElement,\n instanceMeta: WriteMeta['instance'] | undefined\n): void {\n const target = element as ElementWithListeners\n if (target[attaformListenersSymbol] !== undefined) return\n const focusMeta = instanceMeta !== undefined ? { instance: instanceMeta } : undefined\n const handleFocus = (): void => state.markFocused(segments, true, focusMeta)\n const handleBlur = (): void => state.markFocused(segments, false, focusMeta)\n element.addEventListener('focus', handleFocus)\n element.addEventListener('blur', handleBlur)\n target[attaformListenersSymbol] = { handleFocus, handleBlur }\n}\n\nfunction detachFocusListeners(element: HTMLElement): void {\n const target = element as ElementWithListeners\n const listeners = target[attaformListenersSymbol]\n if (listeners === undefined) return\n element.removeEventListener('focus', listeners.handleFocus)\n element.removeEventListener('blur', listeners.handleBlur)\n delete target[attaformListenersSymbol]\n}\n\nexport function buildRegister<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n formInstanceId: string,\n instanceConfig?: InstanceRegisterConfig\n) {\n // Per-instance coerce resolution: when a `useForm()` callsite passes\n // its own `coerce` config, resolve to a fresh CoercionIndex local to\n // this register factory. Sibling instances sharing the FormStore\n // (modal + main) keep their own input-side coerce semantics — one's\n // `'1' → 1` doesn't infect the other's. Falls through to the store's\n // captured index when the per-call config is absent.\n const coerceIndex =\n instanceConfig?.coerce !== undefined\n ? resolveCoercionIndex(instanceConfig.coerce)\n : state.coerceIndex\n const instanceMeta = instanceConfig?.instanceMeta\n // `meta.instance` is forwarded into every store write below so the\n // store's reads of `validateOn` / `debounceMs` / `rememberVariants`\n // honor THIS instance's config. Composed with caller-supplied\n // `meta` so the persist / blank flags ride through unchanged.\n const withInstanceMeta = (meta?: WriteMeta): WriteMeta | undefined => {\n if (instanceMeta === undefined) return meta\n return meta === undefined ? { instance: instanceMeta } : { ...meta, instance: instanceMeta }\n }\n // Path-keyed cache of typed-form refs. Lifted out of the per-call\n // closure so multiple `register(path)` invocations for the same\n // path — e.g. two `<input v-register>` bindings to `'numberText'`,\n // or repeated calls inside a render function — share the same ref.\n // Without sharing, the directive's keystroke listener writes to\n // RegisterValue A's `lastTypedForm` while RegisterValue B's\n // `displayValue` reads its own (always-null) ref, and Vue patches\n // B's DOM to the canonical `String(storage)` mid-typing — yanking\n // the user's caret on a sibling input.\n const lastTypedFormByPath = new Map<PathKey, Ref<string | null>>()\n\n return function register(\n pathInput: string | Path,\n options?: RegisterOptions\n ): RegisterValue<unknown> {\n const { segments, key: pathKey } = canonicalizePath(pathInput)\n\n const innerRef = computed(() => state.getValueAtPath(segments)) as Readonly<Ref<unknown>>\n\n // The user's currently-typed string form for numeric fields,\n // populated by the directive on every keystroke and cleared on\n // blur. Lets `displayValue` surface the typed form (e.g. `'1e2'`)\n // mid-typing instead of the canonical `String(storage)` (`'100'`),\n // which Vue would otherwise patch into the DOM and yank the\n // cursor away from the user's caret. After blur the typed form\n // is cleared so `displayValue` falls back to the honest canonical\n // form — what the user sees matches what's in storage. Shared\n // across all RegisterValues for the same path so paired inputs\n // stay in sync mid-typing.\n let lastTypedForm = lastTypedFormByPath.get(pathKey)\n if (lastTypedForm === undefined) {\n lastTypedForm = ref<string | null>(null)\n lastTypedFormByPath.set(pathKey, lastTypedForm)\n }\n\n // String-form view of the path's storage value, with `''` returned\n // for blank membership and for null/undefined storage.\n // The blank branch is what lets a user clear a numeric\n // field: even though storage holds 0, the `:value` binding reads\n // displayValue and writes `''` to el.value, so Vue's next render\n // doesn't undo the user's clear.\n //\n // Typed-form preference (numeric only): when `lastTypedForm` is\n // set AND `parseFloat(lastTypedForm)` equals the current numeric\n // storage, return the typed form. Storage commits live (typing\n // `1e2` writes 100 to storage immediately), but the DOM keeps\n // showing `1e2` until blur — at which point the directive clears\n // `lastTypedForm` and Vue patches the DOM to `String(100)` =\n // `'100'`. The check naturally invalidates on programmatic\n // setValue / hydration / reset (different storage value → fall\n // back to `String(...)`).\n const displayValue = computed(() => {\n if (state.blankPaths.has(pathKey)) return ''\n const raw = state.getValueAtPath(segments)\n if (raw === null || raw === undefined) return ''\n const typed = lastTypedForm.value\n if (typed !== null && typeof raw === 'number' && parseFloat(typed) === raw) {\n return typed\n }\n return String(raw)\n }) as Readonly<Ref<string>>\n\n // Slim default precomputed at register-time. The schema is fixed\n // for the form's lifetime, so this is safe to cache; downstream\n // `markBlank` calls reuse it without re-walking the\n // schema tree.\n const slimDefault = state.schema.getDefaultAtPath(segments)\n\n const persist = options?.persist === true\n const acknowledgeSensitive = options?.acknowledgeSensitive === true\n const multiTab = options?.multiTab !== false\n const transforms = options?.transforms ?? EMPTY_TRANSFORMS\n // Pre-bound mount/unmount hooks for the directive — only present\n // when this binding explicitly opted OUT of multi-tab sync.\n // `undefined` for the common case (multiTab !== false) so the\n // directive does no extra work on the hot path.\n const markNoSync = !multiTab\n ? () => {\n state.incrementNoSyncOptOut(pathKey)\n }\n : undefined\n const unmarkNoSync = !multiTab\n ? () => {\n state.decrementNoSyncOptOut(pathKey)\n }\n : undefined\n\n // Schema-driven coerce closure. Captures the path's slim accept set\n // and the form's resolved coercion index so the per-event hot path\n // is a single function call. Identity when the form has coercion\n // disabled (`useForm({ coerce: false })`) or the path admits no\n // coercion target. Cached on RegisterValue so the directive doesn't\n // re-walk the schema per keystroke.\n const coerce = buildCoerceFn(\n state.schema as Parameters<typeof buildCoerceFn>[0],\n segments,\n coerceIndex\n )\n const coerceElement = buildElementCoerceFn(\n state.schema as Parameters<typeof buildElementCoerceFn>[0],\n segments,\n coerceIndex\n )\n\n // Eager throw: opt-in declared but the form has no persistence wired.\n // Without the throw the directive silently records the opt-in, no\n // writes ever land, and the dev concludes \"persistence is broken\"\n // when the actual issue is a missing `persist:` option on useForm().\n // Throws in dev and prod — contradictions are bugs, not rate-limited\n // drift. The error body carries the schema's top-level fields and a\n // captured call-site frame so the offending form is identifiable\n // from the message alone (script-setup stacks collapse misleadingly).\n //\n // Skipped during SSR: `wirePersistence` is intentionally not run on\n // the server (persistence is a client-only concern), so\n // `state.modules.has(PERSISTENCE_MODULE_KEY)` is always false during\n // SSR — even for forms that DID configure `persist:`. Without this\n // gate the throw would falsely fire on every server-rendered\n // `register({ persist: true })`. The client-side hydration pass\n // re-checks against a freshly-wired module and throws correctly if\n // the misuse is real.\n if (persist && !state.ssr && !state.modules.has(PERSISTENCE_MODULE_KEY)) {\n throw new AnonPersistError({\n cause: 'register-without-config',\n schemaFields: extractSchemaFields(state.schema),\n callSite: captureUserCallSite(),\n })\n }\n\n // `shallowReadonly` is what makes `rv.path`, `rv.formKey`, and the\n // other top-level string fields feel like reactive state in\n // wrapper components: property reads track in computeds /\n // watchEffects, mutations are blocked at runtime + type level, and\n // inner refs (`innerRef`, `displayValue`, `lastTypedForm`) keep\n // their `Ref` shape so the directive's `.value` reads/writes\n // continue to work unchanged.\n const internalRv: InternalRegisterValue = {\n innerRef,\n displayValue,\n lastTypedForm,\n\n markBlank: (): boolean => {\n // Mirror the binding's persist meta so the blank\n // mark rides the same persistence channel as user-typed\n // writes — without this, refresh after a clear silently loses\n // the empty state. The slim default keeps storage well-typed\n // (the schema's getDefaultAtPath returns 0 for z.number(), ''\n // for z.string(), false for z.boolean(), etc.).\n return state.setValueAtPath(\n segments,\n slimDefault,\n withInstanceMeta({\n blank: true,\n persist,\n })\n )\n },\n\n registerElement: (element: HTMLElement): void => {\n // Skip non-form elements. Prevents accidental registration of\n // component wrapper divs when fallthrough attributes carry the\n // directive past the intended `<input>` / `<select>` / `<textarea>`.\n if (!INTERACTIVE_TAG_NAMES.has(element.tagName)) return\n const added = state.registerElement(segments, element, formInstanceId)\n if (added) attachFocusListeners(state, segments, element, instanceMeta)\n },\n\n deregisterElement: (element: HTMLElement): void => {\n detachFocusListeners(element)\n state.deregisterElement(segments, element)\n },\n\n setValueWithInternalPath: (value: unknown, meta?: WriteMeta): boolean => {\n return state.setValueAtPath(segments, value, withInstanceMeta(meta))\n },\n\n // Called by the `vRegisterHint` compile-time transform's wrapping\n // IIFE on every server-side render of `<element v-register=\"…\">`.\n // Without it, every SSR'd FieldState serialises `connected: false`\n // (because Vue skips directive lifecycle during SSR) and the client\n // briefly shows that stale flag until hydration runs the directive's\n // `created` hook. The mark only takes effect when `state.ssr` is\n // true; on the client this is a no-op so the directive lifecycle\n // remains the source of truth.\n markConnectedOptimistically: (): void => {\n state.markConnectedOptimistically(segments)\n },\n\n path: pathKey,\n // Frozen so a wrapper component can pass `rv.segments` directly\n // to `form.fields(...)` without defensive copying — and so test\n // fixtures or downstream code can't mutate the canonical\n // segment list out from under the directive.\n segments: Object.freeze(segments.slice()),\n formKey: state.formKey,\n formInstanceId,\n\n // --- Persistence opt-in (internal; the directive is the only\n // legitimate consumer) ---\n persist,\n acknowledgeSensitive,\n persistOptIns: state.persistOptIns,\n isSensitivePath: state.isSensitivePath,\n multiTab,\n ...(markNoSync !== undefined ? { markNoSync } : {}),\n ...(unmarkNoSync !== undefined ? { unmarkNoSync } : {}),\n transforms,\n coerce,\n ...(coerceElement !== undefined ? { coerceElement } : {}),\n }\n return shallowReadonly(internalRv) as RegisterValue\n }\n}\n","/** Internal brand for the `Unset` type. Never exposed at runtime. */\ndeclare const _unsetBrand: unique symbol\n\n/**\n * Brand-typed sentinel admitted at every primitive leaf of\n * `DefaultValuesShape<T>`, `setValue`, and `reset`. The runtime value\n * is exported as {@link unset} under the same name.\n */\nexport type Unset = typeof _unsetBrand\n\n/**\n * The `unset` sentinel — pass it as a primitive leaf's value to mark\n * the field **displayed-empty** while storage holds the schema's slim\n * default (`0` / `''` / `false` / `0n`).\n *\n * Use it wherever a primitive leaf value is expected:\n *\n * ```ts\n * const form = useForm({\n * schema: z.object({ income: z.number() }),\n * defaultValues: { income: unset }, // UI starts blank, storage holds 0\n * key: 'housing',\n * })\n *\n * form.setValue('income', unset) // re-blank a field after a write\n * form.reset({ income: unset }) // reset to the blank state\n * ```\n *\n * Accepted at any `string` / `number` / `boolean` / `bigint` leaf in\n * `defaultValues`, `setValue(path, unset)`, and `form.reset({ … })`.\n *\n * The path joins the form's `blankPaths` set as long as it stays\n * unset. Required schemas (no `.optional()` / `.nullable()` /\n * `.default(N)`) raise `\"No value supplied\"` on submit while a leaf\n * is in `blankPaths`; optional / nullable / has-default schemas\n * accept the empty case as their wrapper allows.\n *\n * Storage never holds the symbol — the runtime translates it at the\n * API boundary, so reads through `form.values` always see the slim\n * default. Cross-bundle / SSR-safe: backed by `Symbol.for(...)` so\n * every realm gets the same sentinel.\n *\n * @see {@link isUnset} — type guard that narrows a value back to {@link Unset}.\n * @see `docs/recipes/blank-inputs.md` — the conceptual model behind blank-aware fields.\n */\nexport const unset: Unset = Symbol.for('attaform/unset') as Unset\n\n/**\n * Type guard — `true` when `value` is the `unset` sentinel.\n *\n * ```ts\n * if (isUnset(payload.income)) {\n * // payload.income is the sentinel; the field will display empty\n * }\n * ```\n */\nexport function isUnset(value: unknown): value is Unset {\n return value === unset\n}\n","import type { AbstractSchema } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport { __DEV__ } from './dev'\nimport { canonicalizePath, type Path, type PathKey, type Segment } from './paths'\nimport { isUnset } from './unset'\n\n/**\n * Walk a defaults / setValue / reset payload depth-first and produce\n * the cleaned-up storage tree plus the set of paths to mark as blank.\n * Used at three boundaries:\n *\n * - `useAbstractForm` construction (defaultValues pre-pass)\n * - `setValue(path, unset)` translation\n * - `reset(nextDefaultValues)` translation\n *\n * `blank` is the runtime's bookkeeping for **storage / display\n * divergence** — see `docs/recipes/blank-inputs.md` for the concept. Two sources of\n * marks, gated by that purpose:\n *\n * 1. **Explicit `unset` (any primitive leaf)** — the consumer wrote\n * `unset` at a primitive leaf (`defaultValues: { count: unset }` /\n * `setValue('count', unset)` / `reset({ count: unset })`). The\n * sentinel is replaced with the schema's slim default and the\n * path is added to the result. Explicit user intent applies\n * across every primitive type (string / number / boolean /\n * bigint), so the mark records \"the consumer asked for blank\n * here\" regardless of whether storage and display would otherwise\n * diverge.\n *\n * 2. **Unspecified numeric leaf (auto-mark)** — the consumer's\n * payload is partial (or omitted entirely) and the schema has a\n * `number` / `bigint` leaf the consumer did not cover. The slim\n * default (`0` / `0n`) lands in storage and the path is\n * auto-marked. Rationale: numeric storage forces a value (`0`,\n * `0n`) that the DOM input represents as `''` — the runtime\n * can't tell \"user typed 0\" from \"user supplied nothing\" without\n * this side-channel. Strings and booleans are NOT auto-marked:\n * their slim defaults (`''` / `false`) match what the DOM shows\n * natively, so there's no divergence to record. Adding an\n * auto-mark for those types would be the library second-\n * guessing the schema's accepted-empty verdict, which is the\n * schema author's call to express via `.min(1)` /\n * `z.literal(true)` / refinements.\n *\n * Recurses into plain objects, arrays, and tuples; non-recursable\n * containers (`Date`, `RegExp`, `Map`, `Set`, functions) pass through\n * unchanged. Arrays are NOT auto-mark-recursed (their elements are\n * runtime-added; per-element opt-in via explicit `unset`).\n *\n * Runtime guard: if `unset` lands at a path whose slim default isn't\n * a primitive, emit a one-time dev-warn and recurse into the slim\n * subtree for auto-mark — the path itself is NOT marked.\n * `DefaultValuesShape<T>` blocks this at compile time; the runtime\n * check is a guardrail for plain-JS consumers and dynamic plumbing.\n */\nexport function walkUnsetSentinels<T>(\n values: T,\n schema: AbstractSchema<GenericForm, GenericForm>\n): { cleanedValues: T; paths: PathKey[] } {\n const paths: PathKey[] = []\n // No defaults supplied — auto-mark every primitive leaf reachable\n // from the schema's slim root default. cleanedValues stays `undefined`\n // to preserve createFormStore's existing \"no user defaults\" code path.\n if (values === undefined) {\n const rootSlim = schema.getDefaultAtPath([])\n walkUnspecified(rootSlim, [], paths)\n return { cleanedValues: undefined as unknown as T, paths }\n }\n const cleaned = walk(values as unknown, [], schema, paths)\n return { cleanedValues: cleaned as T, paths }\n}\n\nfunction walk(\n input: unknown,\n segments: Segment[],\n schema: AbstractSchema<GenericForm, GenericForm>,\n paths: PathKey[]\n): unknown {\n if (isUnset(input)) {\n const slim = schema.getDefaultAtPath(segments)\n if (!isPrimitiveOrEmpty(slim)) {\n warnNonPrimitiveLeaf(segments, slim)\n // Recurse into slim subtree so unspecified primitive leaves\n // below this misused `unset` still get auto-marked.\n return walkUnspecified(slim, segments, paths)\n }\n paths.push(canonicalizePath(segments).key)\n return slim\n }\n // User omitted this key — fall through to walkUnspecified on the\n // schema's slim default at this path so primitive leaves get marked.\n if (input === undefined) {\n const slim = schema.getDefaultAtPath(segments)\n return walkUnspecified(slim, segments, paths)\n }\n // Explicit null is the user's choice, not absence — pass through.\n if (input === null) return null\n if (\n input instanceof Date ||\n input instanceof RegExp ||\n input instanceof Map ||\n input instanceof Set ||\n typeof input === 'function'\n ) {\n return input\n }\n // Reference stability: when an array's elements all walk to themselves\n // (no unset substitutions, no schema-only keys synthesized), return the\n // ORIGINAL `input` reference. Without this, a whole-form setValue with\n // a structurally-unchanged subtree (e.g., the `pickup` half of\n // `({ ...prev, delivery: prev.pickup })`) still produces a new clone of\n // pickup, which then re-fires any deep watch on `form.values.pickup` —\n // and a watcher that reacts by writing back to the form loops forever.\n // Returning the original reference for unchanged subtrees keeps Vue's\n // reactivity quiet on identity-equal slots.\n if (Array.isArray(input)) {\n const out = new Array(input.length)\n let mutated = false\n for (let i = 0; i < input.length; i++) {\n const walked = walk(input[i], [...segments, i], schema, paths)\n out[i] = walked\n if (walked !== input[i]) mutated = true\n }\n return mutated ? out : input\n }\n if (typeof input === 'object') {\n // Walk both user-supplied keys AND schema-only keys so unspecified\n // primitive leaves get auto-marked even inside a partially-supplied\n // object (e.g., `defaultValues: { user: { name: 'a' } }` against a\n // schema with `user.{name, age}` marks `user.age`).\n const slim = schema.getDefaultAtPath(segments)\n const inputKeys = Object.keys(input as object)\n const allKeys = new Set<string>(inputKeys)\n if (\n slim !== null &&\n slim !== undefined &&\n typeof slim === 'object' &&\n !Array.isArray(slim) &&\n !(slim instanceof Date) &&\n !(slim instanceof RegExp) &&\n !(slim instanceof Map) &&\n !(slim instanceof Set)\n ) {\n for (const k of Object.keys(slim as object)) allKeys.add(k)\n }\n const out: Record<string, unknown> = {}\n let mutated = allKeys.size !== inputKeys.length\n for (const key of allKeys) {\n const orig = (input as Record<string, unknown>)[key]\n const walked = walk(orig, [...segments, key], schema, paths)\n out[key] = walked\n if (walked !== orig) mutated = true\n }\n return mutated ? out : input\n }\n return input\n}\n\n/**\n * Recurse into a schema slim-default subtree, auto-marking every\n * **numeric** primitive leaf encountered. Called from `walk` whenever\n * the user's payload is missing at a path, and from the top-level\n * walker entry point when no defaults are supplied at all. Strings,\n * booleans, and other non-numeric leaves are left unmarked — the\n * library only auto-marks where storage and display diverge, which\n * for slim primitives is exclusively `number` and `bigint`. See the\n * docblock on `walkUnsetSentinels` for the full rationale.\n *\n * Exported so the discriminated-union variant-switch reshape in\n * `create-form-store.ts` can re-mark numeric leaves of the newly\n * activated variant after replacing the union's parent storage.\n */\nexport function walkUnspecified(slim: unknown, segments: Segment[], paths: PathKey[]): unknown {\n if (isPrimitiveOrEmpty(slim)) {\n if (isNumericPrimitive(slim)) {\n paths.push(canonicalizePath(segments).key)\n }\n return slim\n }\n if (\n slim instanceof Date ||\n slim instanceof RegExp ||\n slim instanceof Map ||\n slim instanceof Set ||\n typeof slim === 'function'\n ) {\n return slim\n }\n // Arrays: pass through without recursion. Elements are runtime-added;\n // tuple-shaped fixed arrays opt-in via explicit per-element `unset`.\n if (Array.isArray(slim)) return slim\n if (slim !== null && typeof slim === 'object') {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(slim as object)) {\n out[key] = walkUnspecified((slim as Record<string, unknown>)[key], [...segments, key], paths)\n }\n return out\n }\n return slim\n}\n\n/**\n * Substitute every `unset` sentinel inside `value` with the schema's\n * slim default at its absolute path (rooted at `prefix`), returning\n * the cleaned value plus the absolute paths where substitutions\n * happened.\n *\n * Trust-the-caller cousin of `walkUnsetSentinels`. Differs in two\n * ways tuned for the `setValue(path, value)` runtime boundary:\n *\n * 1. No auto-marking of unspecified primitive leaves. The caller's\n * shape is authoritative — we don't synthesize blanks for keys\n * they didn't supply. (The discriminated-union variant reshape\n * in `create-form-store.ts` handles numeric auto-marks for the\n * activated variant separately.)\n * 2. No schema-only key synthesis at object paths. For Case B\n * whole-union writes (`setValue('cargo', { type: 'oversized', … })`),\n * `schema.getDefaultAtPath(['cargo'])` returns the FIRST union\n * variant's default — synthesizing those keys would smuggle the\n * FIRST variant's leaves into the activated variant. The variant\n * reshape clears them via the matched `getVariantDefault`; we\n * must not put them back.\n *\n * Reference-stable: subtrees with no substitutions return their\n * original input reference, so a watcher on `form.values.<peer>`\n * stays quiet when the consumer's write didn't touch that peer.\n */\nexport function substituteUnsetSentinels<T>(\n value: T,\n prefix: Path,\n schema: AbstractSchema<GenericForm, GenericForm>\n): { cleanedValues: T; paths: PathKey[] } {\n const paths: PathKey[] = []\n const cleaned = substitute(value as unknown, [...prefix], schema, paths)\n return { cleanedValues: cleaned as T, paths }\n}\n\nfunction substitute(\n input: unknown,\n segments: Segment[],\n schema: AbstractSchema<GenericForm, GenericForm>,\n paths: PathKey[]\n): unknown {\n if (isUnset(input)) {\n const slim = schema.getDefaultAtPath(segments)\n if (!isPrimitiveOrEmpty(slim)) {\n // unset misuse at non-primitive leaf — match the existing\n // walker's guardrail: warn once, write the slim default, do\n // NOT mark the offending path.\n warnNonPrimitiveLeaf(segments, slim)\n return slim\n }\n paths.push(canonicalizePath(segments).key)\n return slim\n }\n if (input === undefined || input === null) return input\n if (\n input instanceof Date ||\n input instanceof RegExp ||\n input instanceof Map ||\n input instanceof Set ||\n typeof input === 'function'\n ) {\n return input\n }\n if (Array.isArray(input)) {\n let mutated = false\n const out = new Array(input.length)\n for (let i = 0; i < input.length; i++) {\n const walked = substitute(input[i], [...segments, i], schema, paths)\n out[i] = walked\n if (walked !== input[i]) mutated = true\n }\n return mutated ? out : input\n }\n if (typeof input === 'object') {\n let mutated = false\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(input as object)) {\n const orig = (input as Record<string, unknown>)[key]\n const walked = substitute(orig, [...segments, key], schema, paths)\n out[key] = walked\n if (walked !== orig) mutated = true\n }\n return mutated ? out : input\n }\n return input\n}\n\nfunction isPrimitiveOrEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n const t = typeof value\n return t === 'string' || t === 'number' || t === 'boolean' || t === 'bigint'\n}\n\n/**\n * `true` when `value` is a numeric primitive — the only types where\n * storage and display diverge enough that the runtime needs the\n * `blank` side-channel to tell \"user typed 0\" from \"user supplied\n * nothing.\" Strings (`''` storage = `''` display), booleans (`false`\n * storage = unchecked display), null, and undefined never auto-mark.\n */\nfunction isNumericPrimitive(value: unknown): boolean {\n const t = typeof value\n return t === 'number' || t === 'bigint'\n}\n\nconst warnedNonPrimitivePaths: Set<string> | null = __DEV__ ? new Set<string>() : null\n\nfunction warnNonPrimitiveLeaf(segments: Segment[], slim: unknown): void {\n if (warnedNonPrimitivePaths === null) return\n const dotted = segments.map(String).join('.')\n if (warnedNonPrimitivePaths.has(dotted)) return\n warnedNonPrimitivePaths.add(dotted)\n const slimType = slim === null ? 'null' : slim instanceof Date ? 'Date' : typeof slim\n console.warn(\n `[attaform] \\`unset\\` at \"${dotted || '<root>'}\" is a no-op — ` +\n `unset only works at primitive leaves (string / number / boolean / bigint, ` +\n `plus their optional / nullable variants), got \"${slimType}\". ` +\n `The slim default was written but the path is NOT marked blank. ` +\n `(TypeScript catches this at compile time; this warn covers plain-JS callers.)`\n )\n}\n","import { computed, readonly, type Ref } from 'vue'\nimport { __DEV__ } from './dev'\nimport { canonicalizePath, type Path } from './paths'\nimport type { GenericForm } from '../types/types-core'\n\n/**\n * Public shape of `form.values` — a callable proxy that drills via\n * dot/bracket OR call dynamically:\n *\n * form.values.email // string (the value)\n * form.values.address.city // string (chained descent)\n * form.values.address // { city, … } — object, drillable further\n * form.values('address.city') // function-call (dynamic / programmatic)\n * form.values(['address', 'city']) // path-array form\n * form.values() // the whole form value (root)\n *\n * Asymmetry against `form.errors` / `form.fields`: containers in\n * `values` ARE useful (they are the structural objects), so they\n * terminate as well as descend. Errors and fields containers are\n * descend-only because their content at a container level is a\n * derivation (e.g. \"any descendant dirty\") rather than a real datum.\n */\nexport type ValuesProxy<F> = ((path?: string | Path) => unknown) & Readonly<F>\n\n/**\n * Build the callable readonly Proxy that powers `form.values`.\n *\n * Reactivity contract:\n *\n * - **Reads track dependencies normally.** The inner\n * `computed(() => readonly(form.value))` recomputes on every\n * whole-form swap (Ref reassignment via `reset()` / whole-form\n * `setValue`) and on every per-key write through Vue's reactive\n * tracking. Each read on the callable proxy delegates to\n * `inner.value.<key>`, which lands inside the consumer's active\n * effect — Vue tracks the dependency at access time.\n *\n * - **Writes are blocked.** Vue's `readonly()` traps `set` / `delete` /\n * `defineProperty` on the inner proxy. The callable wrapper\n * additionally rejects writes at its own boundary. The slim-\n * primitive write gate stays the only path into storage.\n *\n * - **Identity-stable on swap.** Vue's `readonly()` maps targets\n * to proxies by identity. A whole-form swap produces a fresh\n * readonly proxy; the wrapping computed invalidates and\n * re-evaluates. Consumers reading `form.values.<x>` always see\n * the current target's data.\n *\n * - **JSON.stringify works.** The callable proxy is `typeof ===\n * 'function'`, which JSON.stringify normally omits — `toJSON`\n * short-circuits that path and returns the inner readonly proxy\n * so consumers serialise the actual form data, not `undefined`.\n *\n * - **Symbol passthrough.** Vue's reactivity sigils\n * (`Symbol(__v_isRef)`, `Symbol(__v_isReadonly)`, etc.) and\n * iteration symbols resolve against the function target, not\n * the schema-aware branch.\n */\nexport function buildValuesProxy<F extends GenericForm>(form: Ref<F>): ValuesProxy<F> {\n const inner = computed(() => readonly(form.value))\n\n // Arrow-function target: callable (typeof === 'function', `apply`\n // trap fires) but no non-configurable `prototype` to satisfy the\n // ownKeys Proxy invariant.\n const target = (() => {}) as unknown as ValuesProxy<F>\n\n // Coerce-to-primitive: Vue's `toDisplayString` (powering `{{ expr }}`)\n // falls back to `String(val)` whenever `typeof val === 'function'`,\n // which is true for our callable-proxy target. Without this trap,\n // `{{ form.values }}` lands at `Function.prototype.toString` and\n // renders `\"() => {}\"`. JSON.stringify already works via `toJSON`\n // below; this trap reaches the SAME data through the template path\n // (and `String(form.values)`), so the two surfaces agree.\n const valuesToString = (): string => JSON.stringify(inner.value)\n const valuesToPrimitive = (hint: string): string | number =>\n hint === 'number' ? NaN : valuesToString()\n\n return new Proxy(target, {\n apply(_, __, args: unknown[]): unknown {\n const arg = args[0] as string | Path | undefined\n // No-arg: return the whole form value (the readonly root proxy).\n if (arg === undefined) return inner.value\n // Dynamic path: walk segments through the readonly proxy. Each\n // step reads through the proxy's own get traps so dependency\n // tracking propagates at every level.\n const { segments } = canonicalizePath(arg)\n let cursor: unknown = inner.value\n for (const seg of segments) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string | number, unknown>)[seg]\n }\n return cursor\n },\n get(_, key: string | symbol): unknown {\n // Symbol passthrough — Vue's reactivity sigils resolve here.\n // `Symbol.toPrimitive` is the one symbol we intercept: it's\n // what `String(proxy)` / template-literal coercion / Vue's\n // `toDisplayString` end up calling for callables.\n if (typeof key === 'symbol') {\n if (key === Symbol.toPrimitive) return valuesToPrimitive\n return Reflect.get(target, key)\n }\n // toJSON: serialise the inner readonly proxy. JSON.stringify\n // checks for toJSON before checking typeof, so the callable\n // proxy serialises to the actual form data.\n if (key === 'toJSON') return () => inner.value\n // toString / valueOf: direct method-call coercion. Mirrors the\n // Symbol.toPrimitive path so `form.values.toString()` and\n // `String(form.values)` produce the same JSON snapshot.\n if (key === 'toString') return valuesToString\n if (key === 'valueOf')\n return function (this: unknown): unknown {\n return this\n }\n // Property access: delegate to the readonly proxy. Vue's\n // dependency tracking captures the read inside the consumer's\n // active effect.\n return (inner.value as Record<string, unknown>)[key]\n },\n has(_, key: string | symbol): boolean {\n if (typeof key === 'symbol') return Reflect.has(target, key)\n return Reflect.has(inner.value as object, key)\n },\n ownKeys(): ArrayLike<string | symbol> {\n return Reflect.ownKeys(inner.value as object)\n },\n getOwnPropertyDescriptor(_, key: string | symbol): PropertyDescriptor | undefined {\n const desc = Reflect.getOwnPropertyDescriptor(inner.value as object, key)\n if (desc !== undefined) desc.configurable = true\n return desc\n },\n // Match Vue's `readonly()` semantics: writes warn (in dev) and\n // silently noop (return true). Returning false would throw\n // TypeError in strict-mode consumers, surprising users who\n // assigned through the proxy and expected it to be ignored.\n set(_, key) {\n if (__DEV__) {\n console.warn(\n `[attaform] form.values is read-only — write to \"${String(key)}\" was ignored. Use form.setValue / the directive / field-array helpers instead.`\n )\n }\n return true\n },\n deleteProperty(_, key) {\n if (__DEV__) {\n console.warn(\n `[attaform] form.values is read-only — delete of \"${String(key)}\" was ignored.`\n )\n }\n return true\n },\n defineProperty: () => true,\n })\n}\n","import { computed, reactive, readonly, type Ref } from 'vue'\nimport type {\n CoercionRegistry,\n FormErrorsSurface,\n FormHistoryNamespace,\n FormMeta,\n OnInvalidSubmitPolicy,\n ReactiveValidationStatus,\n RegisterValue,\n ShouldShowErrors,\n UseFormReturnType,\n ValidateOn,\n ValidationError,\n ValidationResponse,\n ValidationResponseWithoutValue,\n WriteMeta,\n} from '../types/types-api'\nimport type { DeepPartial, DefaultValuesShape, GenericForm } from '../types/types-core'\nimport { __DEV__ } from './dev'\nimport type { FormStore } from './create-form-store'\nimport { structuralSnapshot } from './diff-apply'\nimport { buildErrorsProxy } from './errors-proxy'\nimport { buildFieldArrayApi } from './field-arrays'\nimport {\n aggregateErrorsAt,\n buildContainerFieldStateBase,\n buildFieldStateAccessor,\n type FormMetaBase,\n} from './field-state-api'\nimport { buildFieldStateProxy } from './field-state-proxy'\nimport type { HistoryModule } from './history'\nimport { getAtPath } from './path-walker'\nimport {\n canonicalizePath,\n FORM_ERRORS_PATH,\n FORM_ERRORS_PATH_KEY,\n ROOT_PATH,\n ROOT_PATH_KEY,\n segmentsForPathKey,\n type Path,\n type PathKey,\n} from './paths'\nimport { PERSISTENCE_MODULE_KEY, type PersistenceModule } from './persistence'\nimport { enforceSensitiveCheck } from './persistence/sensitive-names'\nimport { buildProcessForm } from './process-form'\nimport { buildRegister } from './register-api'\nimport { isUnset } from './unset'\nimport { substituteUnsetSentinels, walkUnsetSentinels } from './unset-walker'\nimport { buildValuesProxy } from './values-proxy'\n\nexport type BuildFormApiOptions = {\n /** Forwarded to buildProcessForm. See `UseFormConfiguration.onInvalidSubmit`. */\n onInvalidSubmit?: OnInvalidSubmitPolicy\n /**\n * Pre-wired history module backing `form.history.{undo, redo, clear,\n * canUndo, canRedo, size}`. When omitted, the namespace's methods\n * are inert no-ops and its reactive flags read `false` / `0` —\n * consumers get a consistent API shape without opting into the feature.\n */\n history?: HistoryModule\n /**\n * Per-`useForm()`-instance config that the API layer threads through\n * writes / register / field-state so each callsite honors its own\n * `validateOn` / `debounceMs` / `shouldShowErrors` / `coerce` /\n * `rememberVariants` even when sharing a FormStore with sibling\n * instances (e.g., a modal and main form rendering the same logical\n * form). Anything omitted falls through to the store's\n * construction-time captured values.\n */\n validateOn?: ValidateOn\n debounceMs?: number\n shouldShowErrors?: ShouldShowErrors\n coerce?: boolean | CoercionRegistry\n rememberVariants?: boolean\n}\n\n/**\n * Wrap a Set in a read-only facade. `Object.freeze(new Set(...))` does\n * NOT prevent `add` / `delete` / `clear` mutations on the underlying\n * Set — those methods bypass the frozen state. The Proxy traps the\n * mutating methods and rebinds method/getter access to the underlying\n * Set so internal-slot accesses (e.g. `size`, `has`) keep working.\n */\nfunction blankForKind(slimDefault: unknown): unknown {\n if (typeof slimDefault === 'string') return ''\n if (typeof slimDefault === 'number') return 0\n if (typeof slimDefault === 'bigint') return 0n\n if (typeof slimDefault === 'boolean') return false\n if (slimDefault === null) return null\n return undefined\n}\n\nfunction readonlySetSnapshot<T>(source: Iterable<T>): ReadonlySet<T> {\n const snapshot = new Set(source)\n return new Proxy(snapshot, {\n get(target, prop) {\n if (prop === 'add' || prop === 'delete' || prop === 'clear') {\n return () => {\n throw new TypeError(`Cannot mutate readonly Set: '${String(prop)}' is not allowed.`)\n }\n }\n // Bind the result to `target` so Set's internal-slot accessors\n // (`size`, `has`, `forEach`, the iterator protocol) receive the\n // underlying Set as `this` instead of the Proxy.\n const value = Reflect.get(target, prop, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n }) as ReadonlySet<T>\n}\n\n/**\n * Build the public form API from a FormStore. Extracted from\n * `useAbstractForm` so that both the top-level form entry (which creates\n * a fresh state) and `injectForm` (which resolves state from an\n * ambient provide/inject) produce identical API shapes without\n * duplicating the wiring.\n *\n * `buildFormApi` does not interact with the registry, consumer ref-counts,\n * or the current Vue instance — those concerns belong to the caller. This\n * function is pure over (FormStore, options) → api.\n */\nexport function buildFormApi<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(\n state: FormStore<Form, GetValueFormType>,\n formInstanceId: string,\n options: BuildFormApiOptions = {}\n): UseFormReturnType<Form, GetValueFormType> {\n // Compose the per-instance write-meta bag once. Each public write\n // method below splices `instance: instanceMeta` into its forwarded\n // `meta` so the store's runtime reads of `validateOn` / `debounceMs`\n // / `rememberVariants` honor THIS instance's config. Sibling\n // instances sharing the same FormStore (modal + main) carry their\n // own instanceMeta in their own buildFormApi closure.\n const instanceMeta: WriteMeta['instance'] | undefined = (() => {\n const bag: {\n -readonly [K in keyof NonNullable<WriteMeta['instance']>]: NonNullable<\n WriteMeta['instance']\n >[K]\n } = {}\n if (options.validateOn !== undefined) bag.validateOn = options.validateOn\n if (options.debounceMs !== undefined) bag.debounceMs = options.debounceMs\n if (options.rememberVariants !== undefined) bag.rememberVariants = options.rememberVariants\n return Object.keys(bag).length > 0 ? bag : undefined\n })()\n // Helper used by every internal `state.setValueAtPath` call below to\n // splice the instance bag into the forwarded WriteMeta. Identity\n // when no instance overrides are active.\n const withInstanceMeta = (meta?: WriteMeta): WriteMeta | undefined => {\n if (instanceMeta === undefined) return meta\n return meta === undefined ? { instance: instanceMeta } : { ...meta, instance: instanceMeta }\n }\n\n const registerConfig = {\n ...(instanceMeta !== undefined ? { instanceMeta } : {}),\n ...(options.coerce !== undefined ? { coerce: options.coerce } : {}),\n }\n const register = buildRegister(\n state,\n formInstanceId,\n Object.keys(registerConfig).length > 0 ? registerConfig : undefined\n ) as (path: string | Path) => RegisterValue<unknown>\n // Don't set `onInvalidSubmit: undefined` — exactOptionalPropertyTypes\n // treats an explicit-undefined value differently from an omitted\n // property. Only pass the key when the consumer opted in.\n const processOptions =\n options.onInvalidSubmit !== undefined ? { onInvalidSubmit: options.onInvalidSubmit } : {}\n const {\n validate: validateBuilt,\n validateAsync: validateAsyncBuilt,\n process: processBuilt,\n handleSubmit,\n } = buildProcessForm<Form, GetValueFormType>(state, formInstanceId, processOptions)\n\n const validate = (pathInput?: string) =>\n validateBuilt(pathInput) as Ref<ReactiveValidationStatus<Form>>\n\n const validateAsync = (pathInput?: string) =>\n validateAsyncBuilt(pathInput) as Promise<ValidationResponseWithoutValue<Form>>\n\n const process = (pathInput?: string) =>\n processBuilt(pathInput) as Promise<ValidationResponse<GetValueFormType>>\n\n // --- toRef escape hatch — Readonly<Ref<...>> for the rare case\n // a consumer needs ref-shaped interop (external composables that\n // expect a Vue ref, watchers reading a single path). Writes still\n // funnel through `setValue`, never via the ref.\n function pathToRef(pathInput: string): Readonly<Ref<unknown>> {\n const segments = canonicalizePath(pathInput).segments\n return computed(() => getAtPath(state.form.value, segments)) as Readonly<Ref<unknown>>\n }\n\n function setValueImpl(pathOrValue: unknown, maybeValue?: unknown): boolean {\n if (arguments.length === 1) {\n // Whole-form: hand the consumer's callback a STABLE structural\n // snapshot of the form, not the live reactive value. The form\n // store mutates `form.value` in place on commit (so deep-watch\n // dependencies fire only for paths that actually changed), so\n // a callback that closes over `prev` would otherwise see its\n // `prev` reference silently follow the post-commit state. The\n // consumer's RETURN value passes through mergeStructural so any\n // gaps the consumer introduced (partial replacement) are filled\n // from defaults.\n const next =\n typeof pathOrValue === 'function'\n ? (pathOrValue as (prev: unknown) => unknown)(structuralSnapshot(state.form.value))\n : pathOrValue\n // Whole-form `unset` sentinels (consumer wrote `setValue(unset)`\n // or returned `unset` for some leaf in a function form) flow\n // through the walker — every leaf gets translated, the cleaned\n // value lands in storage, and the discovered paths are added to\n // `blankPaths` via direct setValueAtPath calls (the\n // gate hook handles the bookkeeping).\n const walked = walkUnsetSentinels(\n next,\n state.schema as unknown as Parameters<typeof walkUnsetSentinels>[1]\n )\n const ok = state.setValueAtPath([], walked.cleanedValues, withInstanceMeta())\n if (!ok) return false\n // Mark each blank path. `setValueAtPath` was just called\n // with cleaned values, so the gate hook's implicit-unmark would\n // have removed any prior blank entries for the paths\n // we just touched — re-add them now.\n for (const pathKey of walked.paths) {\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n state.setValueAtPath(\n segments,\n state.schema.getDefaultAtPath(segments),\n withInstanceMeta({ blank: true })\n )\n }\n return true\n }\n const segments = canonicalizePath(pathOrValue as string | Path).segments\n // `unset` at a specific path: resolve the slim default and route\n // through `setValueAtPath` with `blank: true`. Storage\n // gets the well-typed default; the path is marked for the\n // displayValue / required-empty machinery.\n if (isUnset(maybeValue)) {\n // Discriminator-path special case: the slim default at a disc\n // path is the first variant's literal (e.g. 'email'). Seeding\n // that here would silently activate a variant the consumer\n // didn't pick. Use a kind-appropriate primitive blank instead so\n // setValueAtPath's stub branch lands `{ [discKey]: blank }`\n // with no variant body.\n const last = segments.length > 0 ? segments[segments.length - 1] : undefined\n if (typeof last === 'string') {\n const parent = segments.slice(0, -1)\n const parentDU = state.schema.getUnionDiscriminatorAtPath(parent)\n if (parentDU?.discriminatorKey === last) {\n const slimDefault = state.schema.getDefaultAtPath(segments)\n const blank = blankForKind(slimDefault)\n return state.setValueAtPath(segments, blank, withInstanceMeta({ blank: true }))\n }\n }\n return state.setValueAtPath(\n segments,\n state.schema.getDefaultAtPath(segments),\n withInstanceMeta({ blank: true })\n )\n }\n // Path-form callback: when the slot at `segments` is unpopulated,\n // hand the consumer the schema's default at that path instead of\n // `undefined` so `(prev) => prev.first.toUpperCase()` is safe.\n // For populated slots, prev is the live value — and stable: the\n // form store reassigns the changed first-segment of `form.value`\n // on commit (so the OLD subtree, which `prev` may close over, is\n // orphaned but unmutated). Consumers caching `prev` see frozen\n // pre-commit state.\n let resolvedValue: unknown\n if (typeof maybeValue === 'function') {\n const current = state.getValueAtPath(segments)\n const prev = current === undefined ? state.schema.getDefaultAtPath(segments) : current\n resolvedValue = (maybeValue as (prev: unknown) => unknown)(prev)\n // Callback returned `unset` — translate the same way as the\n // direct case above.\n if (isUnset(resolvedValue)) {\n return state.setValueAtPath(\n segments,\n state.schema.getDefaultAtPath(segments),\n withInstanceMeta({ blank: true })\n )\n }\n } else {\n resolvedValue = maybeValue\n }\n // Nested-unset pass. The leaf-level cases above (`maybeValue ===\n // unset`, callback returned `unset`) are already done; what\n // remains is values like `{ type: 'oversized', lengthCm: unset, … }`\n // — the homepage REPL's discriminated-union Case B write. Without\n // this scrub, the symbols flow into the slim-primitive gate, fail\n // the kind check at the numeric leaf, and the whole write is\n // rejected — leaving the form on the prior variant.\n //\n // The walker is reference-stable on subtrees with no substitutions,\n // so the common case (no nested unsets) returns the same `resolvedValue`\n // identity and produces an empty `paths` list — no extra writes.\n const walked = substituteUnsetSentinels(\n resolvedValue,\n segments,\n state.schema as unknown as Parameters<typeof substituteUnsetSentinels>[2]\n )\n const ok = state.setValueAtPath(segments, walked.cleanedValues, withInstanceMeta())\n if (!ok) return false\n // Mark each substituted leaf blank. Re-write the slim default\n // explicitly with `blank: true` so the gate hook adds the path\n // to `blankPaths` (the variant reshape's `walkUnspecified` only\n // auto-marks numeric leaves; this loop catches the\n // string / boolean / bigint cases the consumer flagged blank).\n for (const pathKey of walked.paths) {\n const blankSegments = segmentsForPathKey(pathKey)\n if (blankSegments === null) continue\n state.setValueAtPath(\n blankSegments,\n state.schema.getDefaultAtPath(blankSegments),\n withInstanceMeta({ blank: true })\n )\n }\n return true\n }\n\n // --- Error store API — leaf-aware drillable callable Proxy ---\n // `form.errors` merges three reactive sources at every leaf path:\n // 1. `schemaErrors` — refinement-class errors written by the\n // validation pipeline (`scheduleFieldValidation`, `handleSubmit`,\n // construction-time seed, hydration).\n // 2. `derivedBlankErrors` — the reactively-derived \"No value supplied\"\n // class. Pure function of `(blankPaths, schema.isRequiredAtPath)`,\n // no writers.\n // 3. `userErrors` — API-injected errors written by `setFieldErrors*`\n // / `parseApiErrors`-fed entries.\n //\n // Iteration order at each leaf is schema → derived-blank → user, so\n // consumers reading `errors.email` see the structural / synthesised\n // errors first and any user-injected entries appended after. Mirrored\n // in `state.getErrorsForPath` and the per-field accessor.\n //\n // Active-path filter: errors whose `err.path` is no longer reachable\n // through the live form value (e.g. the inactive variant of a\n // discriminated union after a switch) are hidden from `form.errors`.\n // The store-side entries STAY — per-field accessors and the\n // `form.meta.errors` aggregate still expose them, so a programmatic\n // consumer reading errors at a specific path can see what's known\n // about it even when the path isn't currently in the active schema.\n //\n // Container paths are descend-only (no terminal). The \"give me every\n // error\" need is served by `form.meta.errors` (flat ValidationError[]).\n const errorsProxy = buildErrorsProxy(state)\n\n function filterToOwnFormKey(\n errors: ValidationError[],\n op: 'setFieldErrors' | 'addFieldErrors'\n ): ValidationError[] {\n const own: ValidationError[] = []\n let dropped = 0\n for (const e of errors) {\n if (e.formKey === state.formKey) own.push(e)\n else dropped++\n }\n if (__DEV__ && dropped > 0) {\n console.warn(\n `[attaform] ${op}: dropped ${dropped} error(s) with non-matching formKey ` +\n `(this form's key is \"${String(state.formKey)}\"). Errors are scoped to ` +\n `the form that produced them — pass them to the matching form instance.`\n )\n }\n return own\n }\n\n function setFieldErrors(errors: ValidationError[]): void {\n // `setAllUserErrors` clears the entire user-error map before\n // writing, which would also wipe the form-level bucket\n // (`FORM_ERRORS_PATH_KEY`). The form-level slot is owned by\n // `setFormErrors` / `clearFormErrors` and is logically separate\n // from field errors — replace-all field-error writes must not\n // touch it. Preserve the bucket across the call.\n const preserved = state.userErrors.get(FORM_ERRORS_PATH_KEY)\n state.setAllUserErrors(filterToOwnFormKey(errors, 'setFieldErrors'))\n if (preserved !== undefined && preserved.length > 0) {\n state.userErrors.set(FORM_ERRORS_PATH_KEY, preserved)\n }\n }\n\n function addFieldErrors(errors: ValidationError[]): void {\n state.addUserErrors(filterToOwnFormKey(errors, 'addFieldErrors'))\n }\n\n function clearFieldErrors(path?: string | (string | number)[]): void {\n // Pragmatic semantic: \"make the errors at this path go away\" —\n // clears both the schema-owned and user-owned stores. With always-on\n // validation the schema half re-populates on the next mutation if\n // the value is still invalid, so the inconsistency is short-lived\n // and confined to \"before the next keystroke / submit.\" See\n // docs/migration/0.11-to-0.12.md for the rationale.\n if (path === undefined) {\n // Same logical separation as `setFieldErrors`: a no-arg\n // `clearFieldErrors()` clears every FIELD error but must NOT\n // wipe the form-level bucket. Form-level lifecycle belongs to\n // `clearFormErrors()`.\n const preserved = state.userErrors.get(FORM_ERRORS_PATH_KEY)\n state.clearSchemaErrors()\n state.clearUserErrors()\n if (preserved !== undefined && preserved.length > 0) {\n state.userErrors.set(FORM_ERRORS_PATH_KEY, preserved)\n }\n return\n }\n const segments = canonicalizePath(path as string | Path).segments\n state.clearSchemaErrors(segments)\n state.clearUserErrors(segments)\n }\n\n function setFormErrors(\n errors: ReadonlyArray<Partial<ValidationError> & { message: string }>\n ): void {\n // Surgically replace just the form-level entry. Going through\n // `setAllUserErrors` / `setFieldErrors` would clobber every field\n // error too — wrong for \"set this top-of-form message without\n // disturbing field validation.\"\n //\n // Form-level errors live at the empty-string path bucket\n // (PathKey `'[\"\"]'`, segments `['']`). Distinct from the root\n // subtree address `[]`: aggregate reads like `errors([])` /\n // `errors()` still surface them, while `errors('')` returns ONLY\n // this bucket — the dedicated channel for `<FieldErrors path=\"\" />`.\n //\n // Caller-provided `path` and `formKey` are intentionally ignored:\n // this API is form-level-only by definition and the form knows\n // its own key. The lenient input shape lets callers pipe\n // `ValidationError[]` (e.g. from `parseApiErrors`) straight in\n // without having to map first.\n if (errors.length === 0) {\n state.userErrors.delete(FORM_ERRORS_PATH_KEY)\n return\n }\n state.userErrors.set(\n FORM_ERRORS_PATH_KEY,\n errors.map((e) => ({\n path: [...FORM_ERRORS_PATH],\n message: e.message,\n formKey: state.formKey,\n code: e.code ?? 'atta:form-error',\n }))\n )\n }\n\n function clearFormErrors(): void {\n state.userErrors.delete(FORM_ERRORS_PATH_KEY)\n }\n\n // --- Submission lifecycle ---\n const submitting = computed<boolean>(() => state.submitting.value)\n const submitCount = computed<number>(() => state.submitCount.value)\n const submitError = computed<unknown>(() => state.submitError.value)\n\n // --- Validation lifecycle ---\n const validating = computed<boolean>(() => state.activeValidations.value > 0)\n // `valid` is \"we've validated at least once AND no errors AND not\n // currently validating.\" The `firstValidationDone` gate closes the\n // brief flash window at mount time when the slim default-derivation\n // parse strips refinements (`.refine`, `.superRefine`, async\n // validators) and the queued construction-time microtask hasn't\n // run yet. Without it, frame 1 paints the form as \"valid\" before\n // the real verdict arrives. The `!validating.value` guard\n // distinguishes a genuinely-clean form from one in the window\n // between an async refinement starting and resolving (where errors\n // haven't been written yet, but the verdict is pending).\n // Submit-button gates and per-form clean indicators use this.\n const valid = computed<boolean>(\n () =>\n state.firstValidationDone.value &&\n state.schemaErrors.size === 0 &&\n state.userErrors.size === 0 &&\n state.derivedBlankErrors.value.size === 0 &&\n !validating.value\n )\n\n // --- History (undo/redo) ---\n // When the consumer doesn't configure history, fall back to inert\n // stubs so the `form.history.*` namespace shape stays consistent\n // whether or not the feature is enabled. Templates can read\n // `form.history.canUndo` etc. unconditionally.\n const history = options.history\n const formHistory = readonly(\n reactive({\n undo: history?.undo ?? (() => false),\n redo: history?.redo ?? (() => false),\n clear: history?.clear ?? (() => {}),\n canUndo: history?.canUndo ?? computed(() => false),\n canRedo: history?.canRedo ?? computed(() => false),\n size: history?.historySize ?? computed(() => 0),\n })\n ) as FormHistoryNamespace\n\n // --- Form-level meta aggregate ---\n // `metaErrors` flattens the three reactive error stores into a single\n // ValidationError[]. Unlike `form.errors.<path>` (per-leaf, active-\n // path filtered), this aggregate is UNFILTERED — inactive-variant\n // errors stay in. Consumers who want only addressable errors filter\n // the array themselves.\n //\n // Order is determined by the SET of errors currently present, not by\n // the temporal sequence of validations. Each path is bucketed at its\n // schema-declaration ordinal (`state.ensurePathOrdinal`); buckets sort\n // by ordinal and flatten in order. Within one ordinal slot the\n // per-store iteration order survives — schema → blank → user — so a\n // path with both a schema error and a userErrors entry surfaces both\n // at the same slot in their existing relative order. Resurrected\n // errors return to the slot they originally occupied: clearing\n // `email` then re-breaking it puts `email` back ahead of `password`,\n // not at the end of the aggregate.\n // The form-level error aggregate. Reads through the same shared\n // `aggregateErrorsAt` helper that `form.fields(path).errors` and\n // `form.errors(path)` use (with the empty-prefix path, which\n // collects every active-variant leaf). One source of truth — the\n // three surfaces never drift, and inactive-variant errors stay\n // hidden everywhere by default.\n const metaErrors = computed<readonly ValidationError[]>(() =>\n aggregateErrorsAt(state, [] as Path)\n )\n\n // --- Form-level meta bundle ---\n // Vue auto-unwraps refs that are top-level on a setup return, but not\n // refs nested in a return *object* — those render as their wrapper\n // (always truthy) and silently break bindings like `:disabled`. We\n // work around it by placing the scalars + computed array inside\n // `reactive()`, which unwraps ref values on property access at any\n // depth; `readonly()` layers a runtime write-guard on top.\n //\n // Named `formMeta` locally to avoid shadowing the `state: FormStore<F>`\n // param this function receives; exposed as `meta` on the public return.\n //\n // FormMeta = FieldState<F> at the root + lifecycle (submit / undo /\n // redo / instance identity). The FieldState fields are derived\n // through the shared `getFieldStateAt([])` accessor (memoised, same\n // reference returned by `form.fields()`) so `form.meta.dirty`,\n // `form.fields().dirty`, and `form.fields([]).dirty` all read\n // identical aggregated state.\n // Thunk producing a fresh `FormMetaBase` snapshot on each call —\n // the omit'd-shape second argument to `state.shouldShowErrors`.\n // Reads run inside the field-state computed, so every reactive\n // primitive touched here (submitCount, canUndo, ...) registers as\n // a dependency of that computed. Bypasses the cached field-state\n // accessor by calling `buildContainerFieldStateBase` directly —\n // going through the accessor would recurse through the root path's\n // own showErrors computation.\n const getFormMetaBase = (): FormMetaBase => {\n const rootBase = buildContainerFieldStateBase(state, ROOT_PATH, ROOT_PATH_KEY)\n return {\n ...rootBase,\n submitting: state.submitting.value,\n submitCount: state.submitCount.value,\n submitError: state.submitError.value,\n instanceId: formInstanceId,\n }\n }\n\n const fieldStateAccessorOptions =\n options.shouldShowErrors !== undefined\n ? { shouldShowErrors: options.shouldShowErrors }\n : undefined\n const getRootFieldStateAt = buildFieldStateAccessor(\n state,\n getFormMetaBase,\n fieldStateAccessorOptions\n )\n const rootFieldState = getRootFieldStateAt([] as Path)\n const formMeta = readonly(\n reactive({\n // FieldState fields — read through one shared root computed. Each\n // property accesses `rootFieldState.value[X]`, so any descendant\n // change re-evaluates the root computed once (Vue's reactive\n // graph dedupes the dependent re-renders).\n value: computed(() => rootFieldState.value.value),\n original: computed(() => rootFieldState.value.original),\n pristine: computed(() => rootFieldState.value.pristine),\n dirty: computed(() => rootFieldState.value.dirty),\n focused: computed(() => rootFieldState.value.focused),\n blurred: computed(() => rootFieldState.value.blurred),\n touched: computed(() => rootFieldState.value.touched),\n connected: computed(() => rootFieldState.value.connected),\n element: computed(() => rootFieldState.value.element),\n elements: computed(() => rootFieldState.value.elements),\n updatedAt: computed(() => rootFieldState.value.updatedAt),\n // Whole-form validating mirrors the LIFECYCLE counter\n // (`state.activeValidations`) ORed with any per-leaf validation\n // in flight (via `rootFieldState.validating`). A submit-time\n // validate run shows up as activeValidations; per-field\n // debounced validators show up as fieldValidationCounts. Either\n // flips the flag.\n validating: computed(\n () => state.activeValidations.value > 0 || rootFieldState.value.validating\n ),\n // Whole-form valid keeps the original `firstValidationDone`\n // mount gate so the surface doesn't lie about a yet-to-arrive\n // verdict at construction time. The shared `aggregateErrorsAt`\n // ensures `form.meta.errors` and `rootFieldState.errors` match,\n // so `errors.length === 0` here would agree with `valid` —\n // keep the explicit form-level computation for the gate.\n valid,\n errors: metaErrors,\n // `showErrors` / `firstError` flow through the same root\n // field-state computed as the rest of the FieldState surface,\n // so `form.meta.showErrors` matches `form.fields().showErrors`\n // exactly — the predicate runs once at the root and the result\n // is shared.\n showErrors: computed(() => rootFieldState.value.showErrors),\n firstError: computed(() => rootFieldState.value.firstError),\n path: computed(() => rootFieldState.value.path),\n blank: computed(() => rootFieldState.value.blank),\n label: computed(() => rootFieldState.value.label),\n description: computed(() => rootFieldState.value.description),\n placeholder: computed(() => rootFieldState.value.placeholder),\n meta: computed(() => rootFieldState.value.meta),\n // Lifecycle (form-level only — not on FieldState).\n submitting,\n submitCount,\n submitError,\n // Per-`useForm()`-call identity. Stable for one mount; new on\n // re-mount; orthogonal to `form.key` (which is the user-supplied\n // shared identifier). Useful for devtools panels disambiguating\n // shared-key instances, telemetry hooks tagging events with\n // \"which mount\", and E2E tests stamping `data-form-id`.\n instanceId: formInstanceId,\n })\n ) as FormMeta<Form>\n\n // --- Persistence handle (cached on FormStore by useAbstractForm\n // when persist: is configured). The persist + clearPersistedDraft\n // APIs below close over this; reset / resetField also poke it. ---\n const persistence = state.modules.get(PERSISTENCE_MODULE_KEY) as PersistenceModule | undefined\n\n // --- Reset ---\n // Reset semantics are \"fresh start across every layer\" — drafts are\n // transient, so a reset that left stale storage behind would surprise\n // on next mount (form would re-hydrate the discarded draft). The\n // opt-in registry is NOT touched: directives are still mounted and\n // the next user keystroke on an opted-in input re-populates the\n // entry naturally.\n const reset = (nextDefaultValues?: DeepPartial<DefaultValuesShape<Form>>): void => {\n if (nextDefaultValues === undefined) {\n state.reset()\n } else {\n // Walk the consumer's overrides for `unset` symbols, replacing\n // them with the schema's slim defaults and capturing the marked\n // paths. The cleaned values land in form storage via state.reset;\n // the marked paths get added back via direct setValueAtPath\n // calls AFTER the reset so the FormStore's own reset (which\n // clears the blank set in the args branch) doesn't\n // wipe them.\n const walked = walkUnsetSentinels(\n nextDefaultValues,\n state.schema as unknown as Parameters<typeof walkUnsetSentinels>[1]\n )\n // After the walker, `cleanedValues` has had every `unset` symbol\n // replaced with the schema's slim default — the result is\n // structurally compatible with `WriteShape<Form>`, so the cast\n // here is safe.\n state.reset(walked.cleanedValues as DeepPartial<unknown> as Parameters<typeof state.reset>[0])\n for (const pathKey of walked.paths) {\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n state.setValueAtPath(\n segments,\n state.schema.getDefaultAtPath(segments),\n withInstanceMeta({ blank: true })\n )\n // Mirror the new baseline into originalBlankPaths so the\n // post-reset state is the dirty=false reference.\n state.originalBlankPaths.add(pathKey as PathKey)\n }\n }\n if (persistence !== undefined) {\n // Fire-and-forget — reset is sync from the consumer's POV; the\n // wipe lands a moment later. Errors are absorbed by the adapter\n // contract (best-effort).\n void persistence.clearPersistedDraft().catch(() => undefined)\n }\n }\n\n const resetField = (pathInput: string): void => {\n const segments = canonicalizePath(pathInput).segments\n state.resetField(segments)\n if (persistence !== undefined) {\n void persistence.clearPersistedDraft(segments).catch(() => undefined)\n }\n }\n\n // --- Persistence (imperative APIs) ---\n\n const persist = async (\n pathInput: string | Path,\n options?: { acknowledgeSensitive?: boolean }\n ): Promise<void> => {\n const segments = canonicalizePath(pathInput).segments\n enforceSensitiveCheck(segments, options?.acknowledgeSensitive === true, state.isSensitivePath)\n if (persistence === undefined) return // persist: not configured → silent no-op\n await persistence.writePathImmediately(segments)\n }\n\n const clearPersistedDraft = async (pathInput?: string | Path): Promise<void> => {\n if (persistence === undefined) return\n if (pathInput === undefined) {\n await persistence.clearPersistedDraft()\n return\n }\n const segments = canonicalizePath(pathInput).segments\n await persistence.clearPersistedDraft(segments)\n }\n\n // --- Programmatic touch ---\n // Flip `touched: true` on a leaf, every leaf under a container, or\n // every leaf in the form (no arg). Closes the post-import / paste /\n // autofill gap where there's no DOM blur to drive the standard\n // gesture-based touched flow. Touched is the sticky-true flag the\n // standard \"show errors after interaction\" pattern reads.\n function touch(pathInput?: string | Path): void {\n const segments = pathInput === undefined ? ROOT_PATH : canonicalizePath(pathInput).segments\n state.touchAtPath(segments)\n }\n\n // --- Focus / scroll to first error ---\n // Both helpers scope to `formInstanceId` so two `useForm()` callsites\n // sharing a `key` (e.g. sidebar + main mounting the same form) only\n // focus / scroll within their own registered elements.\n const focusFirstError = (options?: { preventScroll?: boolean }): boolean => {\n const target = state.getFirstErrorElement(formInstanceId)\n if (target === null) return false\n target.element.focus(options)\n return true\n }\n\n const scrollToFirstError = (options?: ScrollIntoViewOptions): boolean => {\n const target = state.getFirstErrorElement(formInstanceId)\n if (target === null) return false\n target.element.scrollIntoView(options)\n return true\n }\n\n // --- Field arrays ---\n const fieldArrays = buildFieldArrayApi(state)\n\n // --- Bulk blank introspection ---\n // Read-only view of the form's blank path set. Vue 3.5\n // tracks `.has()` / `for..of` / size accesses on a reactive Set,\n // so the computed below is a lazy, dependency-tracked passthrough.\n // Wrapped in a Proxy that traps mutating methods so consumers can't\n // pollute the snapshot they receive (`Object.freeze` does NOT make\n // a Set readonly — `add` / `delete` / `clear` still work on frozen\n // Sets). Writes still go through `setValue(_, unset)` /\n // `markBlank()` / the directive's input listener.\n const blankPathsView = computed<ReadonlySet<string>>(() => {\n return readonlySetSnapshot(state.blankPaths)\n })\n\n // --- Pinia-style reactive readonly proxy over the form's value ---\n // `valuesProxyComputed.value` is a deeply-readonly Vue proxy. The\n // computed wrapping ensures `state.form.value` reassignments (the\n // `applyFormReplacement` path used by `reset()` and whole-form\n // `setValue`) invalidate the inner readonly proxy and produce a\n // fresh one keyed to the new target. The callable proxy itself is\n // identity-stable — consumers caching `form.values` get a stable\n // reference whose underlying data tracks the live form value.\n const valuesProxy = buildValuesProxy(state.form)\n\n // --- Pinia-style reactive per-field state proxy ---\n // Allocated once per buildFormApi call (one per consumer). Each Proxy\n // node memoizes its descendants and the per-path FieldState\n // computed it reads through, so repeated access to the same path\n // (`form.fields.email` twice) returns the same object — useful\n // for downstream `===` checks and Vue's render diff.\n const fieldStateProxy = buildFieldStateProxy(state, getFormMetaBase, fieldStateAccessorOptions)\n\n return {\n handleSubmit,\n // `values` is the callable readonly Proxy. Each `get` trap reads\n // through `inner.value` (a `computed(() => readonly(form.value))`)\n // so reactivity tracking propagates at the call site. Identity-\n // stable across whole-form swaps (the inner readonly proxy\n // re-keys; the outer callable proxy stays the same instance).\n values: valuesProxy as unknown as UseFormReturnType<Form, GetValueFormType>['values'],\n fields: fieldStateProxy as unknown as UseFormReturnType<Form, GetValueFormType>['fields'],\n setValue: setValueImpl as UseFormReturnType<Form, GetValueFormType>['setValue'],\n validate: validate as UseFormReturnType<Form, GetValueFormType>['validate'],\n validateAsync: validateAsync as UseFormReturnType<Form, GetValueFormType>['validateAsync'],\n process: process as UseFormReturnType<Form, GetValueFormType>['process'],\n register: register as UseFormReturnType<Form, GetValueFormType>['register'],\n key: state.formKey,\n errors: errorsProxy as unknown as FormErrorsSurface<Form>,\n toRef: pathToRef as UseFormReturnType<Form, GetValueFormType>['toRef'],\n setFieldErrors,\n addFieldErrors,\n clearFieldErrors,\n setFormErrors,\n clearFormErrors,\n meta: formMeta,\n reset: reset as UseFormReturnType<Form, GetValueFormType>['reset'],\n resetField: resetField as UseFormReturnType<Form, GetValueFormType>['resetField'],\n persist: persist as UseFormReturnType<Form, GetValueFormType>['persist'],\n clearPersistedDraft: clearPersistedDraft as UseFormReturnType<\n Form,\n GetValueFormType\n >['clearPersistedDraft'],\n focusFirstError,\n scrollToFirstError,\n touch: touch as UseFormReturnType<Form, GetValueFormType>['touch'],\n history: formHistory,\n append: fieldArrays.append as UseFormReturnType<Form, GetValueFormType>['append'],\n prepend: fieldArrays.prepend as UseFormReturnType<Form, GetValueFormType>['prepend'],\n insert: fieldArrays.insert as UseFormReturnType<Form, GetValueFormType>['insert'],\n remove: fieldArrays.remove as UseFormReturnType<Form, GetValueFormType>['remove'],\n swap: fieldArrays.swap as UseFormReturnType<Form, GetValueFormType>['swap'],\n move: fieldArrays.move as UseFormReturnType<Form, GetValueFormType>['move'],\n replace: fieldArrays.replace as UseFormReturnType<Form, GetValueFormType>['replace'],\n blankPaths: blankPathsView,\n }\n}\n","import type { ShouldShowErrors, ShouldShowErrorsConfig } from '../types/types-api'\n\n/**\n * Library-default heuristic for `shouldShowErrors`. Drives\n * `field.showErrors` and `form.meta.showErrors` whenever the consumer\n * has not configured an override at either the plugin or per-form\n * level.\n *\n * Reads \"show errors after the first submit attempt, OR after the\n * user has interacted (`touched`) and made a change (`dirty`).\" The\n * framework already gates on `errors.length > 0` before invoking the\n * predicate, so the body only decides *when* to surface existing\n * errors — not whether errors exist.\n *\n * Public re-export so adopters can compose with this without\n * copy-pasting the rule body. A layered predicate that adds a\n * special case but otherwise defers to the library default picks up\n * future heuristic refinements automatically:\n *\n * ```ts\n * import { defaultShouldShowErrors } from 'attaform'\n *\n * useForm({\n * schema,\n * shouldShowErrors: (field, formMeta) =>\n * field.path[0] === 'urgent' || defaultShouldShowErrors(field, formMeta),\n * })\n * ```\n */\nexport const defaultShouldShowErrors: ShouldShowErrors = (field, formMeta) =>\n formMeta.submitCount > 0 || (field.touched === true && field.dirty)\n\nconst SHOW_ALWAYS: ShouldShowErrors = () => true\nconst SHOW_NEVER: ShouldShowErrors = () => false\n\n/**\n * Resolve a `ShouldShowErrorsConfig` (function | boolean | undefined)\n * to a concrete `ShouldShowErrors` predicate. Boolean shorthand lifts\n * to a constant predicate; `undefined` falls back to the library\n * default. Called once at form construction; the resolved predicate\n * is then stored on `FormStore` for the field-state computeds.\n */\nexport function resolveShouldShowErrors(\n config: ShouldShowErrorsConfig | undefined\n): ShouldShowErrors {\n if (config === undefined) return defaultShouldShowErrors\n if (config === true) return SHOW_ALWAYS\n if (config === false) return SHOW_NEVER\n return config\n}\n","import { computed, markRaw, reactive, ref, toRaw, watch, type ComputedRef, type Ref } from 'vue'\nimport type {\n AbstractSchema,\n CoercionRegistry,\n FormKey,\n DefaultValuesResponse,\n ShouldShowErrors,\n ShouldShowErrorsConfig,\n ValidateOn,\n ValidationError,\n WriteMeta,\n} from '../types/types-api'\nimport { resolveShouldShowErrors } from './should-show-errors'\nimport type { DeepPartial, GenericForm, WriteShape } from '../types/types-core'\nimport { DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS, normalizeNumericOption } from './defaults'\nimport { applyChangedKeys, diffAndApply, structuralSnapshot, type Patch } from './diff-apply'\nimport { AttaformErrorCode } from './error-codes'\nimport {\n canonicalizePath,\n FORM_ERRORS_PATH,\n FORM_ERRORS_PATH_KEY,\n segmentsForPathKey,\n type Path,\n type PathKey,\n type Segment,\n} from './paths'\nimport {\n getAtPath,\n hasAtPath,\n isPlainRecord,\n mergeStructural,\n setAtPath,\n setAtPathWithSchemaFill,\n} from './path-walker'\nimport { __DEV__ } from './dev'\nimport { resolveCoercionIndex, type CoercionIndex } from './schema-coerce'\nimport { isSlimPrimitiveValid } from './slim-primitive-gate'\nimport { walkUnspecified } from './unset-walker'\nimport {\n createPersistOptInRegistry,\n type PersistOptInRegistry,\n} from './persistence/opt-in-registry'\nimport {\n isSensitivePath as defaultIsSensitivePath,\n segmentMatchesSensitive as defaultSegmentMatchesSensitive,\n} from './persistence/sensitive-names'\n\n/**\n * Per-form closure state — the single store owned by each `useForm` call.\n * Bundles the form value, the summary record, element references, field\n * state, the meta tracker, and the error stores under one keyed-by-\n * `(formKey, path)` instance so cross-form DOM state cannot collide.\n *\n * This is NOT a singleton. Each call to `useForm` creates its own FormStore\n * instance and holds onto it via closure. The registry provides SSR\n * hydration; otherwise the state is per-component-per-form.\n */\n\n/** Per-path field status. Replaced wholesale (not mutated in place) on every change. */\nexport type FieldRecord = {\n readonly path: Path\n readonly updatedAt: string | null\n readonly connected: boolean\n readonly focused: boolean | null\n readonly blurred: boolean | null\n readonly touched: boolean | null\n}\n\n// Hydration shape guards — defend against rolling deploys / stale cache\n// where the SSR bundle's record shape diverges from the client's. The\n// `as FieldRecord` / `as ValidationError[]` casts in the hydration loop\n// would otherwise silently admit malformed entries; downstream reads of\n// `.touched` / `.code` then crash with \"Cannot read properties of\n// undefined\" far away from the actual cause. Skip the malformed entries\n// and warn once per key in dev so the rolling-deploy diagnosis is loud.\nfunction isHydratedFieldRecord(value: unknown): value is FieldRecord {\n if (typeof value !== 'object' || value === null) return false\n const r = value as Partial<FieldRecord>\n return (\n Array.isArray(r.path) &&\n (typeof r.updatedAt === 'string' || r.updatedAt === null) &&\n typeof r.connected === 'boolean' &&\n (typeof r.focused === 'boolean' || r.focused === null) &&\n (typeof r.blurred === 'boolean' || r.blurred === null) &&\n (typeof r.touched === 'boolean' || r.touched === null)\n )\n}\n\nfunction isHydratedValidationErrorArray(value: unknown): value is ValidationError[] {\n if (!Array.isArray(value)) return false\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null) return false\n const e = entry as Partial<ValidationError>\n if (typeof e.message !== 'string') return false\n if (!Array.isArray(e.path)) return false\n if (typeof e.formKey !== 'string') return false\n if (typeof e.code !== 'string') return false\n }\n return true\n}\n\nfunction warnMalformedHydration(formKey: FormKey, kind: string, rawKey: string): void {\n if (!__DEV__) return\n console.warn(\n `[attaform] hydration: skipping malformed ${kind} entry at key '${rawKey}' on form '${formKey}'. ` +\n `This usually means the SSR bundle is on a different version than the client (rolling deploy / stale cache).`\n )\n}\n\nfunction applyDuStubs(\n schema: AbstractSchema<unknown, unknown>,\n data: unknown,\n options: { warn?: boolean; basePath?: Path } = {}\n): unknown {\n const warned = options.warn === true ? new Set<string>() : undefined\n return walkDuStubs(schema, data, options.basePath ?? [], warned)\n}\n\nfunction walkDuStubs(\n schema: AbstractSchema<unknown, unknown>,\n value: unknown,\n path: Path,\n warned: Set<string> | undefined\n): unknown {\n if (value === null || value === undefined || typeof value !== 'object') return value\n if (\n value instanceof Date ||\n value instanceof RegExp ||\n value instanceof Map ||\n value instanceof Set ||\n typeof value === 'function'\n ) {\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, i) => walkDuStubs(schema, item, [...path, i], warned))\n }\n const rec = value as Record<string, unknown>\n const du = schema.getUnionDiscriminatorAtPath(path)\n if (du !== undefined) {\n const discValue = rec[du.discriminatorKey]\n if (discValue !== undefined && !du.isVariantSelected(discValue)) {\n if (warned !== undefined && __DEV__) {\n const dotted = path.map((s) => String(s)).join('.') || '(root)'\n const key = `${dotted}::${String(discValue)}`\n if (!warned.has(key)) {\n warned.add(key)\n console.warn(\n `[attaform] defaultValues at '${dotted}' carries discriminator ` +\n `'${du.discriminatorKey}=${JSON.stringify(discValue)}' which isn't a known variant. ` +\n `Form mounts in a stub holding only the discriminator key. Validation will surface the mismatch.`\n )\n }\n }\n return { [du.discriminatorKey]: discValue }\n }\n }\n const out: Record<string, unknown> = {}\n for (const k of Object.keys(rec)) {\n out[k] = walkDuStubs(schema, rec[k], [...path, k], warned)\n }\n return out\n}\n\n/** Per-path DOM element tracking. Client-only. */\nexport type ElementRecord = {\n /**\n * Original Path captured at first registration. Stored alongside the\n * elements Set so the DOM-order sort cache can recover the structured\n * Path without round-tripping through `JSON.parse(pathKey)`.\n */\n readonly path: Path\n readonly elements: Set<HTMLElement>\n}\n\n/**\n * Per-path record stored in `originals`. Pairing `segments` with the tracked\n * value means `dirty` and `resetField`'s container loop don't have to\n * `JSON.parse(pathKey)` on every iteration — the canonical Path is already\n * sitting next to the value it belongs to. PathKey still keys the Map (the\n * stable string is the only collision-free identifier), but downstream\n * iteration reads `segments` directly.\n */\nexport type OriginalsRecord = {\n readonly segments: Path\n readonly value: unknown\n}\n\nexport type FormStore<F extends GenericForm, G extends GenericForm = F> = {\n readonly formKey: FormKey\n readonly form: Ref<F>\n readonly fields: Map<PathKey, FieldRecord>\n readonly elements: Map<PathKey, ElementRecord>\n /**\n * Schema-driven errors. Written ONLY by the schema validation pipeline:\n * `scheduleFieldValidation`, `handleSubmit`, the construction-time seed,\n * history restore, and hydration. Cleared by `reset` / `resetField` and by\n * a successful submit. `setFieldErrors*` APIs do NOT touch this Map.\n */\n readonly schemaErrors: Map<PathKey, ValidationError[]>\n /**\n * User-injected errors. Written ONLY by the `setFieldErrors*` API surfaces\n * (and history / hydration replay). Survives schema revalidation and\n * successful submits — the consumer owns its lifetime explicitly.\n */\n readonly userErrors: Map<PathKey, ValidationError[]>\n /**\n * Reactively-derived \"No value supplied\" errors. Pure function of\n * `(blankPaths, schema.isRequiredAtPath)` — no writers, no clears.\n * Membership tracks `blankPaths` automatically: typing a value into\n * a blank required numeric field removes the path from `blankPaths`\n * and the derived error vanishes; clearing the numeric input re-adds\n * the path and the error reappears. The `errors` proxy and\n * `getErrorsForPath` merge this map in alongside `schemaErrors` and\n * `userErrors`, so consumers see the \"this required field is empty\"\n * error the moment it's true — no `validate()` / `handleSubmit`\n * call required. Honors the founding principle that\n * `errors = f(schema, state)`.\n *\n * Most entries flow through this map for `number` / `bigint` leaves\n * (where the side-channel is needed to distinguish \"user typed 0\"\n * from \"user supplied nothing\"). String / boolean leaves only land\n * here when the consumer explicitly opted in via the `unset`\n * sentinel — see `docs/recipes/blank-inputs.md`.\n */\n readonly derivedBlankErrors: ComputedRef<ReadonlyMap<PathKey, ValidationError[]>>\n readonly originals: Map<PathKey, OriginalsRecord>\n /**\n * Reactive set of paths whose displayed state should be EMPTY even\n * though storage holds a real, schema-conformant value (the slim\n * default). It exists exclusively to record **storage / display\n * divergence** — the case where the runtime can't tell \"user typed\n * 0\" from \"user supplied nothing\" by looking at storage alone.\n *\n * The mechanism shines for `number` / `bigint`: storage holds the\n * slim default (`0` / `0n`) but the DOM input shows `''`, so the\n * directive's input listener marks the path here on clear. Strings\n * and booleans don't need it — `''` storage equals `''` display,\n * `false` storage equals unchecked display — so they're never\n * auto-marked. Consumers can still mark any primitive leaf\n * explicitly via the `unset` sentinel (`defaultValues: { x: unset }`,\n * `setValue('x', unset)`, `reset({ x: unset })`); the mark is then\n * a documented signal of consumer intent rather than runtime\n * inference.\n *\n * Reads (`displayValue` computed, `fields.<path>.blank`,\n * `derivedBlankErrors` computed) track via Vue 3.5's reactive Set\n * handlers. Writes happen inside `setValueAtPath` (gate-hook\n * bookkeeping: `blank: true` meta adds the path; any other write\n * removes it) and `reset`.\n *\n * Storage NEVER reflects this set — calculations and reads against\n * `form.value` see the slim default. The set is purely a UI/intent\n * channel that `derivedBlankErrors` consults to surface\n * \"No value supplied\" errors for required schemas.\n *\n * See `docs/recipes/blank-inputs.md` for the conceptual model.\n */\n readonly blankPaths: Set<PathKey>\n /**\n * Snapshot of `blankPaths` captured at construction (and\n * re-captured on `reset(args)`). Used by dirty calculation: a path\n * whose membership differs from the snapshot is dirty even if\n * storage matches the original. Eagerly populated to avoid a \"dirty\n * on first read\" race after construction.\n */\n readonly originalBlankPaths: Set<PathKey>\n readonly schema: AbstractSchema<F, G>\n\n /**\n * Server-side flag, plumbed in from `registry.ssr`. The\n * `register()`-returned `markConnectedOptimistically()` reads this\n * before flipping `connected: true`; on the client it's a no-op so\n * the eventual directive lifecycle remains the source of truth.\n */\n readonly ssr: boolean\n\n /**\n * Resolved `shouldShowErrors` predicate driving `field.showErrors`\n * and `form.meta.showErrors`. Resolved once at construction via\n * `resolveShouldShowErrors(options.shouldShowErrors)` so the\n * field-state computeds don't repeat the boolean-vs-function\n * branch on every read. Boolean shorthand has already been lifted\n * to a constant predicate by the time it lands here; `undefined`\n * config falls through to `defaultShouldShowErrors`.\n */\n readonly shouldShowErrors: ShouldShowErrors\n\n // --- submission lifecycle ---\n // Driven by buildProcessForm's handleSubmit wrapper. See use-abstract-form.ts\n // for the public readonly surface. Mutations happen in exactly one place\n // (the submit handler) so there's no \"source of truth\" ambiguity — these\n // refs live on FormStore so a `reset()` can clear them too.\n //\n // `activeSubmissions` is the source of truth for \"is anything in flight\".\n // `submitting` mirrors `activeSubmissions > 0` and is what consumers\n // read; tracking the counter separately means overlapping submissions\n // don't prematurely flip submitting to false when the first completes.\n readonly submitting: Ref<boolean>\n readonly activeSubmissions: Ref<number>\n readonly submitCount: Ref<number>\n readonly submitError: Ref<unknown>\n /**\n * Incremented by every `reset()` call. The submit wrapper captures\n * this at entry and skips writing `submitError` from a catch that\n * fires *after* a reset — otherwise a reset-during-submit would\n * visibly clear `submitError` and then have it reappear when the\n * in-flight promise rejects.\n */\n readonly submissionGeneration: Ref<number>\n /**\n * Counts in-flight validation calls across every `validate()` ref and\n * every `validateAsync(...)` / `handleSubmit` pre-check. `validating`\n * on the public API mirrors `activeValidations.value > 0`. Tracked\n * separately from submissions because a validate-while-submitting\n * (e.g. a debounced field check overlapping a submit) needs to show\n * the union of both surfaces.\n */\n readonly activeValidations: Ref<number>\n /**\n * `true` once the form has completed at least one validation pass\n * — flips when `activeValidations` returns to 0 from any positive\n * value. Until that happens, `meta.valid` and `field.valid` report\n * `false` even when `schemaErrors.size === 0`, because the absence\n * of errors at frame 1 is just \"we haven't checked yet,\" not \"we\n * checked and it's clean.\"\n *\n * This closes the brief flash window for schemas where the slim\n * default-derivation parse strips refinements (`.refine`,\n * `.superRefine`, async validators): the slim parse passes, no\n * construction-time errors land, and the queued microtask hasn't\n * run yet — so without the gate, frame 1 paints the form as\n * \"valid\" before the real verdict arrives a tick later.\n *\n * Initialized to `!strict`: non-strict consumers opt out of the\n * validation pipeline by design, so locking them on\n * `firstValidationDone === false` would defeat the opt-out.\n * Reset is left untouched — the post-reset validation flips it\n * back true on completion, same as the construction-time path.\n */\n readonly firstValidationDone: Ref<boolean>\n /**\n * `true` when the sub-schema rooted at `path` (or any of its\n * descendants) declares async work — composes\n * `schema.getSchemasAtPath(path)` with each candidate's\n * `needsAsyncValidation()`, memoised per canonical path key for\n * the lifetime of the FormStore. Used by `meta.valid` /\n * `field.valid` to skip the `firstValidationDone` gate on subtrees\n * that are fully synchronous: their verdict resolves at construction\n * (or on the next per-field run) without waiting on a microtask, so\n * honouring the form-wide gate would just play dumb about a known\n * answer.\n */\n pathHasAsyncValidation(path: Path): boolean\n /**\n * Per-path counter of in-flight field-level validation runs.\n * `field.validating` on `FieldState` mirrors\n * `(fieldValidationCounts.get(key) ?? 0) > 0`.\n *\n * Incremented at the same point as `activeValidations` inside\n * `scheduleFieldValidation`'s `run` closure (right before the schema\n * call) and decremented in the matching `.finally` — so the per-path\n * bookkeeping is exactly co-extensive with the form-wide counter for\n * the field-scheduled branch. Whole-form `validate()` /\n * `validateAsync()` runs touch `activeValidations` only; they don't\n * have a single field path and so don't contribute here.\n *\n * Counter (not Set) because two runs for the same path can briefly\n * overlap: when an in-flight run is aborted and a new run starts,\n * the new run increments before the aborted run's `.finally`\n * decrements. With `> 0` semantics the field stays \"validating\"\n * across the abort/restart boundary.\n *\n * Reactive Map: Vue 3's `reactive(new Map())` proxy makes `.get()`,\n * `.has()`, and `.size` track per-key, so the FieldState\n * computed only re-runs when the count for ITS key changes.\n */\n readonly fieldValidationCounts: Map<PathKey, number>\n\n // --- form mutations ---\n /**\n * Replace the form value wholesale. Optional `meta` is forwarded to\n * every `onFormChange` listener so they can decide whether THIS write\n * is one they care about — most importantly, the persistence layer\n * only writes when `meta?.persist === true`. Internal callers that\n * don't pass meta default to no-persist.\n */\n applyFormReplacement(next: F, meta?: WriteMeta): void\n /**\n * Set a single path's value. `meta` is forwarded to listeners via\n * `applyFormReplacement` (see above). The directive's input handler\n * computes `meta.persist` from the per-element opt-in registry; other\n * internal call sites pass `meta.persist = hasAnyOptInForPath(path)`.\n * Public `form.setValue` passes no meta.\n *\n * Returns `false` when the slim-primitive gate rejects the write\n * (the value's primitive shape doesn't match the schema's slim\n * shape at the path). The store is unchanged in that case.\n */\n setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean\n getValueAtPath(path: Path): unknown\n\n // --- reset ---\n reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void\n resetField(path: Path): void\n\n // --- errors ---\n // Schema-driven writers. Used by the validation pipeline + handleSubmit.\n setSchemaErrorsForPath(path: Path, errors: ValidationError[]): void\n setAllSchemaErrors(errors: readonly ValidationError[]): void\n clearSchemaErrors(path?: Path): void\n\n // User-driven writers. Used by build-form-api's setFieldErrors* surfaces.\n setAllUserErrors(errors: readonly ValidationError[]): void\n addUserErrors(errors: readonly ValidationError[]): void\n clearUserErrors(path?: Path): void\n\n /**\n * Merged read — returns `[...schemaErrors[path], ...userErrors[path]]`.\n * Schema errors come first (structural validation before business logic),\n * matching the iteration order for `getFirstErrorElement` and the\n * top-level `errors` drillable Proxy.\n */\n getErrorsForPath(path: Path): ValidationError[]\n\n /**\n * Returns a stable schema-declaration ordinal for `key`, assigning a\n * fresh one if the path hasn't been seen before. Drives\n * `form.meta.errors` sort order so the aggregate is a function of the\n * SET of errors currently present (not the temporal order their\n * Map keys were last `set`). Construction-time seed walks every leaf\n * in the schema's slim default; runtime callers (DU variant 2, dynamic\n * array indices, refines targeting cross-field paths) pick up\n * first-encounter ordinals and keep them for the form's lifetime.\n */\n ensurePathOrdinal(key: PathKey): number\n\n // --- DOM ---\n /**\n * Register `element` as a binding for `path`, tagged with the calling\n * `useForm()` instance's `formInstanceId`. The ID is the disambiguator\n * used by `getFirstErrorElement` to scope focus / scroll to elements\n * THIS form instance owns — important when two `useForm()` calls share\n * a `key` (e.g. sidebar + main rendering the same form), since both\n * write into one shared element store.\n */\n registerElement(path: Path, element: HTMLElement, formInstanceId: string): boolean\n deregisterElement(path: Path, element: HTMLElement): number\n /**\n * Optional `meta.instance` carries per-`useForm()`-instance overrides\n * for `validateOn` / `debounceMs` so the blur-trigger respects the\n * caller's config when sibling instances share a FormStore.\n */\n markFocused(\n path: Path,\n focused: boolean,\n meta?: { readonly instance?: WriteMeta['instance'] }\n ): void\n markTouched(path: Path): void\n /**\n * Walk every active-variant leaf under `segments` and flip\n * `touched: true`. Powers `form.touch(path?)`. Idempotent;\n * does not mutate value / focused / blurred or trigger validation.\n */\n touchAtPath(segments: Path): void\n /**\n * SSR-only optimistic mark: flip `connected: true` on the field\n * record without an actual DOM element. Called by the `vRegisterHint`\n * compile-time transform via `RegisterValue.markConnectedOptimistically()`\n * for every element rendered with `v-register`. Idempotent + no-op on\n * the client (the directive's `created` hook is the authoritative\n * source there).\n */\n markConnectedOptimistically(path: Path): void\n\n // --- derived ---\n /**\n * Leaf-only pristine check. `originals` is populated via\n * `diffAndApply`'s `added` patches, which fire only on primitive\n * leaves — a container path (e.g. `['profile']`) that isn't in\n * `originals` returns `true` here even when a descendant is dirty.\n * Callers that need container semantics should either loop over\n * leaves or walk `originals` manually. The public `getFieldState`\n * surface is typed to accept leaf paths only, so in practice this\n * isn't exposed to consumers.\n */\n isPristineAtPath(path: Path): boolean\n getFieldRecord(path: Path): FieldRecord | undefined\n getOriginalAtPath(path: Path): unknown\n /**\n * Returns the first errored field's first connected, visible DOM\n * element scoped to `formInstanceId` — the target that\n * `focusFirstError` / `scrollToFirstError` act on. \"First\" is\n * VISUAL-first (DOM-tree order via `compareDocumentPosition`), not\n * schema-declaration order, so a field rendered above another in the\n * template focuses first regardless of which one the schema declared\n * earlier. CSS `order:` flexbox/grid reordering is NOT respected\n * (DOM-tree order wins) — documented as a tradeoff against forcing\n * sync layout on every comparison.\n *\n * The `formInstanceId` filter scopes focus to elements registered\n * through THIS form instance. When two `useForm({ key })` calls share\n * a key, both register into the same element store; without the\n * filter, the sidebar form's submit could focus the main form's\n * input. With it, each `useForm()` callsite focuses only its own\n * elements.\n *\n * Returns `null` when every errored path has no currently-attached\n * element registered to this instance (fields behind `v-if=\"false\"`,\n * unmounted components, or a hidden `display:none` parent). Callers\n * get the choice of no-op or a dev-only warning.\n */\n getFirstErrorElement(formInstanceId: string): { path: Path; element: HTMLElement } | null\n\n /**\n * Cancel every in-flight field-level validation run — clears timers\n * for debounced 'change' runs that haven't fired, aborts controllers\n * for runs whose async parse is in flight. Called by `handleSubmit`\n * at entry (submit validation is authoritative) and by `reset()`.\n */\n cancelFieldValidation(): void\n\n /**\n * Kick off (or schedule) a field-level validation run for `path`. Pass\n * `path = []` to cover the whole form; `applySchemaErrorsForSubtree`\n * then wipes every `schemaErrors` entry and replaces them with the\n * adapter's full async response. Used by persistence's post-hydration\n * revalidation and by the construction-time async-refine seed.\n *\n * `immediate: true` skips the debounce window — the runtime kicks off\n * the adapter call on the next microtask. Internal callsites use this\n * for one-shot triggers; the per-keystroke writers pass `false` to\n * coalesce rapid mutations under the configured debounceMs.\n *\n * `override` carries per-`useForm()`-instance values: when provided,\n * the scheduler honors `override.mode` instead of the store's\n * captured `validateOn`, and `override.debounceMs` instead of the\n * store's captured `debounceMs`. Used so sibling instances sharing a\n * FormStore can each validate on their own cadence.\n */\n scheduleFieldValidation(\n path: Path,\n immediate: boolean,\n override?: { readonly mode?: ValidateOn; readonly debounceMs?: number }\n ): void\n\n /**\n * Subscribe to every `applyFormReplacement`. Fires synchronously\n * after `form.value` has been swapped to `next` and all field /\n * originals bookkeeping has run. Used by persistence + undo/redo\n * to hook the single mutation funnel. The optional `meta` carries\n * the originating call site's intent — the persistence subscription\n * filters on `meta?.persist === true`; subscribers that don't care\n * about meta can ignore the parameter. Returns an unsubscribe\n * function.\n */\n onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void\n\n /**\n * Subscribe to successful submissions. Fires after the consumer's\n * `onSubmit` callback has resolved — not on validation failure,\n * not on callback throw. Used by persistence's `clearOnSubmitSuccess`\n * to drop the stored payload once the form is safely through the\n * server round-trip. Returns an unsubscribe function.\n */\n onSubmitSuccess(listener: () => void): () => void\n\n /**\n * Subscribe to `reset()` calls. Fires AFTER reset has replaced\n * the form and cleared errors + lifecycle, so listeners see the\n * fresh post-reset state. Used by the history module to drop the\n * undo/redo stack on reset. Returns an unsubscribe function.\n */\n onReset(listener: () => void): () => void\n\n /**\n * Internal: notify submit-success subscribers. Called by\n * `handleSubmit` in `process-form.ts` once the user callback has\n * resolved. Consumers shouldn't call this directly.\n */\n emitSubmitSuccess(): void\n\n /**\n * Register a teardown function whose lifetime is bound to the\n * FormStore itself (not a consumer's Vue effect scope). Called by\n * `dispose()` when the last consumer unmounts. Used by persistence /\n * history wiring so their subscribers aren't detached prematurely\n * when only the first consumer unmounts but others remain.\n */\n registerCleanup(fn: () => void): void\n\n /**\n * Register an async drain function. Called by the registry before\n * `dispose()` so async background work — chiefly the persistence\n * layer's debounced storage writes — has a chance to settle without\n * losing the last keystroke. Each registered function is awaited in\n * parallel; failures are swallowed to keep eviction reliable.\n */\n registerDrain(fn: () => Promise<void>): void\n\n /**\n * Drain async work registered via `registerDrain`. Resolves once\n * every registered drain has settled (in parallel). Safe to call\n * repeatedly — registered drains decide their own idempotency.\n */\n awaitPendingWrites(): Promise<void>\n\n /**\n * Cache for per-state modules (history, persistence) that must\n * outlive any single consumer. Subsequent `useForm` / `injectForm`\n * calls for the same key read from this map so the public API shape\n * is identical regardless of mount order. Keyed by a string identifier\n * owned by the caller (e.g. `'history'`).\n */\n readonly modules: Map<string, unknown>\n\n /**\n * Per-element persistence opt-in tracker. Empty by default; the\n * `v-register` directive populates entries on `mount` for each binding\n * that passed `register('foo', { persist: true })` and clears them on\n * `beforeUnmount`. Two SFCs sharing a key share this registry — opt-ins\n * are per-DOM-element, not per-component. Internal to the persistence\n * subsystem; not part of the consumer API surface.\n */\n readonly persistOptIns: PersistOptInRegistry\n\n /**\n * Resolved sensitive-path predicate for THIS form. Honors the\n * cascade (`useForm({ sensitiveNames })` > global default >\n * library `DEFAULT_SENSITIVE_NAMES`). Used by:\n * - persistence enforcement (`enforceSensitiveCheck` at write time);\n * - the multi-tab sync module (outbound strip + inbound reject);\n * - DevTools edit rejection;\n * - any future surface that needs to flag \"this path holds\n * sensitive data.\"\n *\n * Frozen at FormStore construction. Two callsites sharing a key\n * share the predicate — consistent with the rest of the per-form\n * resolved-config surface.\n */\n readonly isSensitivePath: (path: Path | PathKey | string) => boolean\n\n /**\n * Single-segment variant of `isSensitivePath`. Used by the DevTools\n * redact walk to short-circuit whole subtrees the moment any\n * ancestor segment matches — saving an O(leaves × ancestors) regex\n * sweep per timeline event. Resolved from the same `sensitiveNames`\n * cascade as `isSensitivePath`.\n */\n readonly segmentMatchesSensitive: (segment: Segment) => boolean\n\n /**\n * Canonical path keys explicitly opted OUT of multi-tab sync by\n * `register(path, { multiTab: false })`. The sync module's outbound\n * broadcaster strips patches at these paths AND the inbound listener\n * rejects them — symmetric tab-local behaviour for selected fields.\n *\n * Read-only Set view; mutate via `incrementNoSyncOptOut` /\n * `decrementNoSyncOptOut` which maintain a per-path ref count so\n * multiple bindings on the same path balance correctly across\n * dynamic conditional renders. Empty by default.\n */\n readonly noSyncPaths: ReadonlySet<PathKey>\n\n /**\n * Ref-counted \"this path is tab-local\" registration. Called by\n * `v-register`'s `created` hook for any binding that declared\n * `register('x', { multiTab: false })`. The first call for a given\n * path adds it to `noSyncPaths`; subsequent calls just bump the\n * ref count. Pair with `decrementNoSyncOptOut`.\n */\n incrementNoSyncOptOut(path: PathKey): void\n\n /**\n * Symmetric companion to `incrementNoSyncOptOut`. Called by\n * `v-register`'s `beforeUnmount` hook. When the ref count for a\n * path drops to zero, the path is removed from `noSyncPaths` —\n * dynamic toggling (the binding rendered conditionally) restores\n * full sync to the path when the last opt-out unmounts.\n */\n decrementNoSyncOptOut(path: PathKey): void\n\n /**\n * Resolved schema-coercion index — the merged config from\n * `createAttaform({ defaults: { coerce } })` ∪ `useForm({ coerce })`,\n * keyed by `${input}->${output}` for O(1) per-keystroke dispatch.\n * Empty Map when coercion is disabled. Read at `register()` time\n * by `buildCoerceFn` to bake the per-path coerce closure on\n * `RegisterValue.coerce`.\n */\n readonly coerceIndex: CoercionIndex\n\n /**\n * Tear down non-reactive resources owned by this FormStore. Invoked\n * by the registry when the last consumer unmounts. Cancels pending\n * field-validation timers, drops every subscriber, and fires each\n * cleanup hook registered via `registerCleanup`.\n */\n dispose(): void\n}\n\n/**\n * Hydration payload shape accepted by `createFormStore`. When provided, the\n * initial form value comes from here rather than from `schema.getDefaultValues`.\n * Used to replay SSR state on the client; originals are reconstructed from\n * the schema because they're not serialised.\n */\nexport type FormStoreHydration = {\n readonly form: unknown\n /**\n * Schema-driven errors snapshot. Replayed into `schemaErrors` at\n * construction; takes precedence over the construction-time seed.\n */\n readonly schemaErrors: ReadonlyArray<readonly [string, unknown]>\n /**\n * User-injected errors snapshot. Replayed into `userErrors` at\n * construction. Allows server-side `setFieldErrors` /\n * `addFieldErrors` calls (typically fed from `parseApiErrors`) to\n * round-trip through hydration.\n */\n readonly userErrors: ReadonlyArray<readonly [string, unknown]>\n readonly fields: ReadonlyArray<readonly [string, unknown]>\n /**\n * Path keys that were in the form's `blankPaths` set at\n * SSR time. Replayed into the reactive Set on the client so the\n * \"displayed empty\" state survives the round-trip. Optional —\n * pre-v3 envelopes don't carry it; missing means \"no transient-\n * empty paths\".\n */\n readonly blankPaths?: ReadonlyArray<string>\n}\n\nexport type CreateFormStoreOptions<F extends GenericForm, G extends GenericForm = F> = {\n readonly formKey: FormKey\n readonly schema: AbstractSchema<F, G>\n readonly defaultValues?: DeepPartial<WriteShape<F>> | undefined\n readonly strict?: boolean | undefined\n readonly hydration?: FormStoreHydration | undefined\n /**\n * When per-field validation runs. Default `'change'`. See `ValidateOn`.\n * The discriminated union `ValidateOnConfig` lives at the public\n * `useForm` boundary; the internal store accepts the resolved\n * fields directly so the type-narrowing dance stays at the public\n * surface.\n */\n readonly validateOn?: ValidateOn | undefined\n /**\n * Per-field debounce when `validateOn === 'change'`. Default `0`\n * (disabled). Ignored under `'blur'` and `'submit'`.\n */\n readonly debounceMs?: number | undefined\n readonly ssr?: boolean | undefined\n /**\n * Path keys to seed the `blankPaths` set with at construction.\n * Only consulted when `hydration` is undefined — hydration data is\n * authoritative when present (its own `blankPaths` field\n * takes precedence). Used by `useAbstractForm`'s `unset`-symbol pre-\n * pass (commit 7 wires the producer); commit 2 plumbs the channel\n * through with no callers yet.\n */\n readonly initialBlankPaths?: ReadonlyArray<string> | undefined\n /**\n * Whether to remember per-variant typed state across discriminated-\n * union switches. Default `true`. See `UseFormConfiguration.rememberVariants`\n * for full semantics.\n */\n readonly rememberVariants?: boolean | undefined\n /**\n * Schema-driven coercion config. See\n * `UseFormConfiguration.coerce` for the full contract. Resolved\n * once via `resolveCoercionIndex(options.coerce)` and cached on\n * `FormStore.coerceIndex`.\n */\n readonly coerce?: boolean | CoercionRegistry | undefined\n /**\n * Configurable predicate driving `field.showErrors` and\n * `form.meta.showErrors`. Function | boolean | undefined; resolved\n * once at construction via `resolveShouldShowErrors`. See\n * `UseFormConfiguration.shouldShowErrors` and\n * `AttaformDefaults.shouldShowErrors` for the full contract and\n * three-tier resolution rules.\n */\n readonly shouldShowErrors?: ShouldShowErrorsConfig | undefined\n /**\n * Pre-resolved sensitive-path predicate. Built by the caller from\n * the `sensitiveNames` cascade (`useForm({ sensitiveNames })` >\n * global default > library `DEFAULT_SENSITIVE_NAMES`). Stored on\n * the FormStore for use by persistence enforcement, multi-tab sync,\n * DevTools, and the per-form variant of the heuristic. Optional;\n * when omitted, the library-default closure is used.\n */\n readonly isSensitivePath?: ((path: Path | PathKey | string) => boolean) | undefined\n /**\n * Pre-resolved single-segment variant of `isSensitivePath`. Paired\n * with `isSensitivePath` (built from the same resolved list) so the\n * DevTools redact walk can short-circuit whole subtrees. Optional;\n * when omitted, the library-default closure is used.\n */\n readonly segmentMatchesSensitive?: ((segment: Segment) => boolean) | undefined\n}\n\n/**\n * `true` when the JSON-encoded PathKey identifies a path strictly\n * nested under `parentPath` — i.e. shares every parent segment and\n * has at least one more. Used by the union-variant reshape to clear\n * blank-bookkeeping for paths that no longer exist in the new\n * variant's effective shape.\n */\nfunction isPathKeyUnder(existingKey: PathKey, parentPath: Path): boolean {\n const parsed = segmentsForPathKey(existingKey)\n if (parsed === null) return false\n if (parsed.length <= parentPath.length) return false\n for (let i = 0; i < parentPath.length; i++) {\n if (parsed[i] !== parentPath[i]) return false\n }\n return true\n}\n\n/**\n * Walk a consumer-supplied value and drop Symbol-keyed properties\n * recursively. Form values are string-keyed by schema design — symbols\n * at any level would trip JSON serialization (persistence adapters),\n * the variant-memory snapshot, and surface as\n * `Object.getOwnPropertySymbols(values.x).length > 0`.\n *\n * Fast path: returns the input unchanged when the tree contains no\n * symbols at any level. Only allocates a new object/array on the\n * spine that contains a stripped node, so the common no-symbol\n * case has zero allocation cost.\n */\nfunction stripSymbolsDeep(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value\n if (Array.isArray(value)) {\n let mutated = false\n const out: unknown[] = new Array(value.length)\n for (let i = 0; i < value.length; i++) {\n const cleaned = stripSymbolsDeep(value[i])\n out[i] = cleaned\n if (cleaned !== value[i]) mutated = true\n }\n return mutated ? out : value\n }\n // Skip non-plain objects (Date, Map, Set, RegExp, class instances) —\n // their semantics aren't \"key:value\" and stripping would corrupt\n // them. Symbol-keyed properties on these are a consumer concern.\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return value\n const symKeys = Object.getOwnPropertySymbols(value)\n const stringKeys = Object.keys(value)\n let mutated = symKeys.length > 0\n const out: Record<string, unknown> = {}\n const src = value as Record<string, unknown>\n for (const k of stringKeys) {\n const cleaned = stripSymbolsDeep(src[k])\n out[k] = cleaned\n if (cleaned !== src[k]) mutated = true\n }\n return mutated ? out : value\n}\n\n/**\n * Deep-clone a value read out of the live reactive form tree, for the\n * variant-memory snapshot. Calls `toRaw` at every level to bypass\n * Vue's on-demand reactivity wrapping, preserves `BigInt`, `Date`,\n * `Map`, `Set` natively (Zod can validate these at leaves), and\n * recurses through plain arrays + objects. Detached from the form's\n * reactive graph, so a later `form.value = nextForm` doesn't mutate\n * the snapshot.\n */\nfunction cloneVariantSnapshot(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value\n const raw = toRaw(value as object)\n if (raw instanceof Date) return new Date(raw.getTime())\n if (raw instanceof Map) {\n const out = new Map<unknown, unknown>()\n for (const [k, v] of raw.entries()) out.set(cloneVariantSnapshot(k), cloneVariantSnapshot(v))\n return out\n }\n if (raw instanceof Set) {\n const out = new Set<unknown>()\n for (const v of raw) out.add(cloneVariantSnapshot(v))\n return out\n }\n if (raw instanceof RegExp) return new RegExp(raw.source, raw.flags)\n if (Array.isArray(raw)) {\n const out: unknown[] = new Array(raw.length)\n for (let i = 0; i < raw.length; i++) out[i] = cloneVariantSnapshot(raw[i])\n return out\n }\n const src = raw as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const k of Object.keys(src)) out[k] = cloneVariantSnapshot(src[k])\n return out\n}\n\nexport function createFormStore<F extends GenericForm, G extends GenericForm = F>(\n options: CreateFormStoreOptions<F, G>\n): FormStore<F, G> {\n const { formKey, schema, defaultValues, strict = true, hydration } = options\n const ssr = options.ssr === true\n const rememberVariants: boolean = options.rememberVariants !== false\n const fieldValidationMode: ValidateOn = options.validateOn ?? 'change'\n // Sanitise the debounce value before threading it into `setTimeout`.\n // `NaN` would fire synchronously (defeating the debounce); negatives\n // clamp to 0 (consumer intent: \"no debounce\"); `Infinity` would stall\n // the event loop for ~24.8 days then wrap, so it falls back to the\n // library default.\n const fieldValidationDebounceMs = normalizeNumericOption({\n value: options.debounceMs ?? DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS,\n source: 'useForm.debounceMs',\n allowInfinity: false,\n min: 0,\n defaultValue: DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS,\n })\n\n type FieldValidationEntry = {\n controller: AbortController\n timer: ReturnType<typeof setTimeout> | null\n }\n const fieldValidationState = new Map<PathKey, FieldValidationEntry>()\n\n // Plain Sets (not reactive) — these fire imperative callbacks; no\n // template should ever depend on \"how many listeners are attached\".\n const formChangeListeners = new Set<(next: F, meta?: WriteMeta) => void>()\n const submitSuccessListeners = new Set<() => void>()\n const resetListeners = new Set<() => void>()\n\n // Per-element persistence opt-ins. Constructed up-front so the\n // directive can populate entries before the persistence module wires\n // its subscription (mount order between the directive and\n // wirePersistence isn't guaranteed).\n const persistOptIns = createPersistOptInRegistry()\n // Per-register `multiTab: false` opt-out tracker. Populated by the\n // directive's mount hook for bindings that pass `{ multiTab: false }`;\n // read by the multi-tab sync module to filter outbound + inbound\n // patches symmetrically. Ref-counted under the hood — the `Set`\n // view exposed to readers reflects \"any binding currently\n // declares this path as tab-local.\"\n const noSyncPaths = new Set<PathKey>()\n const noSyncPathCounts = new Map<PathKey, number>()\n\n function incrementNoSyncOptOut(path: PathKey): void {\n const next = (noSyncPathCounts.get(path) ?? 0) + 1\n noSyncPathCounts.set(path, next)\n if (next === 1) noSyncPaths.add(path)\n }\n\n function decrementNoSyncOptOut(path: PathKey): void {\n const current = noSyncPathCounts.get(path) ?? 0\n if (current <= 1) {\n noSyncPathCounts.delete(path)\n noSyncPaths.delete(path)\n return\n }\n noSyncPathCounts.set(path, current - 1)\n }\n\n // Resolve the coercion config to a concrete index ONCE per form.\n // The index is keyed by `${input}->${output}` for O(1) per-keystroke\n // dispatch. `register()` reads it via `state.coerceIndex` to bake\n // path-scoped coerce closures on each `RegisterValue`.\n const coerceIndex: CoercionIndex = resolveCoercionIndex(options.coerce)\n\n // Resolve `shouldShowErrors` once. Boolean shorthand lifts to a\n // constant predicate; `undefined` falls back to\n // `defaultShouldShowErrors`. The field-state computeds read the\n // resolved function directly without re-branching on type.\n const resolvedShouldShowErrors: ShouldShowErrors = resolveShouldShowErrors(\n options.shouldShowErrors\n )\n\n // Sensitive-path predicates: caller-provided (built from the\n // `sensitiveNames` cascade in `use-abstract-form.ts`) or the\n // library-default closure. Same predicate gates persistence,\n // multi-tab sync, DevTools.\n const resolvedIsSensitivePath = options.isSensitivePath ?? defaultIsSensitivePath\n const resolvedSegmentMatchesSensitive =\n options.segmentMatchesSensitive ?? defaultSegmentMatchesSensitive\n\n // State-scoped teardown hooks. Persistence / history / any other\n // per-state module registers its disposer here so the cleanup is\n // bound to the FormStore's own lifetime (`dispose()` call at\n // registry-eviction) and not the first consumer's effect scope.\n const cleanupHooks: (() => void)[] = []\n const modules = new Map<string, unknown>()\n\n // Schema is ALWAYS consulted: we need the schema-derived originals even\n // when hydrating, so pristine/dirty computation survives SSR round-trip.\n // The form's actual starting value, though, prefers hydration data.\n //\n // Run consumer-supplied `defaultValues` through `mergeStructural` first\n // so partial constraints against tuple shapes (e.g. `coords: [42]` for\n // `z.tuple([_, _, _])`) get padded with position defaults BEFORE the\n // adapter's validate-then-fix loop sees them. Without this, the\n // adapter's wholesale-replace fix-up would lose the consumer's data.\n const completedConstraints =\n defaultValues === undefined\n ? undefined\n : (mergeStructural(schema, [], defaultValues) as DeepPartial<WriteShape<F>>)\n const schemaResponse: DefaultValuesResponse<F> = schema.getDefaultValues({\n useDefaultSchemaValues: true,\n constraints: completedConstraints,\n strict,\n })\n const schemaInitialData = schemaResponse.data\n\n // Clone per instance so two forms sharing a schema (or one form\n // re-mounted from the same schema cache) don't alias the same\n // initial-data object. Without the clone, the in-place merge that\n // `applyFormReplacement` runs on every setValue would reach across\n // the alias and mutate sibling forms' state.\n const initialData: F =\n hydration !== undefined ? (hydration.form as F) : (structuralSnapshot(schemaInitialData) as F)\n\n // Construction-time DU stub walk: every DU path whose disc value\n // isn't a known variant literal collapses to a stub holding only\n // the discriminator key. Drops any first-variant fields that snuck\n // in via `mergeStructural` / `getDefaultValues` when the consumer's\n // `defaultValues` (or hydration payload) carried a bad discriminator.\n // Mirrors the runtime stub-state contract `setValueAtPath` uses for\n // bad-disc Case A/B writes; emits a one-shot dev warning per bad path.\n const stubbedInitialData = applyDuStubs(schema as AbstractSchema<unknown, unknown>, initialData, {\n warn: true,\n }) as F\n\n const form = ref(stubbedInitialData) as Ref<F>\n\n // Per-path state. `reactive(new Map())` uses Vue's collection handlers —\n // reads of specific keys track those keys only, so a change to one field\n // doesn't invalidate computeds watching another.\n const fields = reactive(new Map<PathKey, FieldRecord>()) as Map<PathKey, FieldRecord>\n const elements = reactive(new Map<PathKey, ElementRecord>()) as Map<PathKey, ElementRecord>\n\n // Per-element form-instance tag. WeakMap so detached elements GC\n // freely — `deregisterElement` does an explicit `.delete()` defensively\n // (in case the element is still strongly referenced elsewhere), but\n // the WeakMap keeps cleanup correct even when the consumer drops the\n // element without going through deregister.\n //\n // Read by `getFirstErrorElement` to scope focus/scroll targets to the\n // calling `useForm()` instance — load-bearing when two forms share a\n // `key` and both register into the same `elements` Map.\n const elementToFormInstance = new WeakMap<HTMLElement, string>()\n\n // Lazy DOM-order sort cache. Holds every registered element flattened\n // across paths, sorted by `compareDocumentPosition` (DOM-tree order).\n // Invalidated to `null` on any register/deregister; rebuilt on next\n // `getFirstErrorElement` read. The cache amortises the sort across\n // multiple submit failures between mutations — a 100-field form with\n // 5 failed submits and no DOM changes pays one O(n log n) sort, not\n // five.\n //\n // Note: `compareDocumentPosition` is DOM-tree order, NOT visual order.\n // CSS `order:` flexbox/grid reorders visually but not in tree, so a\n // child with `order: -1` will sort AFTER its tree-earlier siblings.\n // Real visual order would need `getBoundingClientRect`, which forces\n // sync layout per comparison and breaks under `display: none`. Tree-\n // order is the right tradeoff for a hot path; the 99% case (semantic\n // source-order rendering) works correctly.\n let sortedRegistrationsCache: Array<{ path: Path; element: HTMLElement }> | null = null\n // Errors are split by source so each writer touches exactly one slot.\n // Schema validation owns `schemaErrors`; the `setFieldErrors*` APIs own\n // `userErrors`. The two stores merge on read via `getErrorsForPath` and\n // the top-level `errors` drillable Proxy in build-form-api.\n const schemaErrors = reactive(new Map<PathKey, ValidationError[]>()) as Map<\n PathKey,\n ValidationError[]\n >\n const userErrors = reactive(new Map<PathKey, ValidationError[]>()) as Map<\n PathKey,\n ValidationError[]\n >\n\n // Originals are captured at init and on first appearance of a path; never\n // re-assigned. Not reactive — the set is append-only per form's lifetime.\n // Value is a {segments, value} record so consumers iterating this Map\n // (dirty, resetField's container loop) don't need to `JSON.parse(key)`\n // to recover the canonical Path.\n // Reactive: the dirty computed iterates this map AND accesses\n // `form.value` per entry. With `applyFormReplacement` mutating\n // `form.value` in place (so deep watches fire only for genuinely-\n // changed paths), the form Ref's value-setter dep no longer fires\n // for every write — so a plain Map here would leave the dirty\n // computed stuck on stale deps when new originals are added (e.g.\n // `append` introduces a new array index and seeds an originals\n // entry for it). Wrapping in `reactive(new Map(...))` makes the\n // Map's iteration / set / delete fire Vue's collection deps,\n // picking up exactly the change that prompted the originals\n // mutation.\n const originals = reactive(new Map<PathKey, OriginalsRecord>()) as Map<PathKey, OriginalsRecord>\n\n // Blank bookkeeping. The reactive Set tracks paths whose\n // displayed state should be EMPTY even though storage holds a real\n // slim default; the originals snapshot mirrors construction-time\n // membership so dirty calculation can detect the user's clear /\n // un-clear actions. Hydration takes precedence over `initialBlankPaths`\n // (the SSR snapshot wins when present), matching how the hydrated\n // `form` value overrides the schema's getDefaultValues result.\n const initialTransientList: ReadonlyArray<string> =\n hydration?.blankPaths ?? options.initialBlankPaths ?? []\n const blankPaths = reactive(new Set<PathKey>()) as Set<PathKey>\n const originalBlankPaths = new Set<PathKey>()\n for (const raw of initialTransientList) {\n blankPaths.add(raw as PathKey)\n originalBlankPaths.add(raw as PathKey)\n }\n\n // Per-form variant memory. On a discriminated-union switch the\n // outgoing variant's subtree (deep-cloned) and its blank-path\n // bookkeeping are stashed here keyed by `(unionPath, oldDiscValue)`;\n // on switch-in the entry for the incoming discriminator is\n // restored. Memory is in-memory only (never persisted, never on\n // form.value), and is cleared on `reset()` / whole-form replace /\n // `resetField` of an ancestor of the union path. Disabled when\n // `rememberVariants === false`.\n type VariantSnapshot = {\n readonly value: unknown\n readonly blankPaths: ReadonlyArray<PathKey>\n }\n const variantMemory = new Map<PathKey, Map<unknown, VariantSnapshot>>()\n\n function clearVariantMemoryUnderPath(arrayPath: Path): void {\n for (const memKey of [...variantMemory.keys()]) {\n const segs = segmentsForPathKey(memKey)\n if (segs === null) continue\n if (isPathPrefix(arrayPath, segs)) variantMemory.delete(memKey)\n }\n }\n\n function clearVariantMemoryAtArrayIndices(\n arrayPath: Path,\n indexFilter: (idx: number) => boolean\n ): void {\n for (const memKey of [...variantMemory.keys()]) {\n const segs = segmentsForPathKey(memKey)\n if (segs === null) continue\n if (!isPathPrefix(arrayPath, segs)) continue\n if (segs.length <= arrayPath.length) continue\n const idxSeg = segs[arrayPath.length]\n if (typeof idxSeg !== 'number') continue\n if (indexFilter(idxSeg)) variantMemory.delete(memKey)\n }\n }\n\n function applyArrayOpToMemory(arrayPath: Path, op: NonNullable<WriteMeta['arrayOp']>): void {\n switch (op.kind) {\n case 'shift-from':\n clearVariantMemoryAtArrayIndices(arrayPath, (i) => i >= op.index)\n return\n case 'shift-range':\n clearVariantMemoryAtArrayIndices(arrayPath, (i) => i >= op.fromIndex && i <= op.toIndex)\n return\n case 'swap':\n clearVariantMemoryAtArrayIndices(arrayPath, (i) => i === op.a || i === op.b)\n return\n case 'replace-at':\n clearVariantMemoryAtArrayIndices(arrayPath, (i) => i === op.index)\n return\n }\n }\n\n // Schema-declaration ordinal map for `form.meta.errors` sort order.\n // Plain (non-reactive) Map: it's mutated lazily from inside the\n // `metaErrors` computed when an unseen path appears, and a reactive\n // Map would retrigger that computed on every assignment. Plain\n // Map.set is invisible to Vue 3.5's reactivity tracking, so the\n // computed only re-runs when one of the error stores changes — not\n // when we extend the ordinal book during the same pass.\n //\n // Lifetime = FormStore lifetime. Never shrinks: an ordinal is\n // assigned once per path and survives `reset()`, undo/redo, and\n // hydration replay. Clearing then re-introducing an error at the\n // same path returns to the SAME slot, so `meta.errors` doesn't\n // shuffle when the user fixes a field and breaks it again.\n const pathOrdinals = new Map<PathKey, number>()\n let nextOrdinal = 0\n function ensurePathOrdinal(key: PathKey): number {\n let ordinal = pathOrdinals.get(key)\n if (ordinal === undefined) {\n ordinal = nextOrdinal\n pathOrdinals.set(key, ordinal)\n nextOrdinal += 1\n }\n return ordinal\n }\n\n // Reactively-derived blank-required errors. Recomputes whenever\n // `blankPaths` mutates (Vue 3.5 reactive Set handlers track size + has).\n // The schema's `isRequiredAtPath` is referentially stable for a given\n // form (schema is fixed at construction), so it doesn't need to be a\n // dep — only the membership of `blankPaths` drives invalidation.\n const derivedBlankErrors = computed<ReadonlyMap<PathKey, ValidationError[]>>(() => {\n const result = new Map<PathKey, ValidationError[]>()\n if (blankPaths.size === 0) return result\n for (const pathKey of blankPaths) {\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n if (!schema.isRequiredAtPath(segments)) continue\n result.set(pathKey, [\n {\n message: 'No value supplied',\n path: [...segments],\n formKey,\n code: AttaformErrorCode.NoValueSupplied,\n },\n ])\n }\n return result\n })\n\n // Submission lifecycle refs. Initial values encode \"no submission has\n // happened yet\": not in flight, zero attempts, no captured error.\n // `activeSubmissions` counts concurrent in-flight submissions so the\n // last completion (count → 0) is what flips `submitting` to false,\n // not just the first.\n const submitting = ref(false)\n const activeSubmissions = ref(0)\n const submitCount = ref(0)\n const submitError = ref<unknown>(null)\n const submissionGeneration = ref(0)\n const activeValidations = ref(0)\n // Initial-validity gate. See `FormStore.firstValidationDone` JSDoc.\n // Only ASYNC-validating strict schemas need the gate: sync schemas\n // either surface refinement errors at construction (slim parse\n // catches checks-style issues) or have nothing for the gate to\n // wait on, so locking them at `false` would just deadlock\n // `meta.valid` until the user touches a field. Async schemas are\n // the genuine flash case — slim parse strips the async refine,\n // construction sees no errors, the queued microtask runs a tick\n // later. The watch flips the gate when `activeValidations`\n // returns to 0 from a positive value (i.e. the construction-time\n // queued validation completes).\n const firstValidationDone = ref(!strict || schema.needsAsyncValidation?.() !== true)\n // `watch(source, cb)` only fires when the source CHANGES (no\n // immediate first-invocation), so `prev` is always the value\n // before the transition — typed as `number`, never `undefined`.\n watch(activeValidations, (now, prev) => {\n if (prev > 0 && now === 0) {\n firstValidationDone.value = true\n }\n })\n // Per-path async-need cache. Keyed by canonical PathKey;\n // populated lazily so a form whose consumers only ever ask about\n // a few prefixes doesn't pay for a full schema walk. The cache is\n // safe to grow unboundedly across the FormStore's lifetime — paths\n // are bounded by the schema, and the FormStore itself is GC'd\n // when its last consumer disposes.\n const pathAsyncCache = new Map<PathKey, boolean>()\n function pathHasAsyncValidation(path: Path): boolean {\n const { key } = canonicalizePath(path)\n const cached = pathAsyncCache.get(key)\n if (cached !== undefined) return cached\n // `getSchemasAtPath` returns every candidate sub-schema (DU\n // variants, intersections all surface here). Async work in any\n // candidate means the prefix is \"could be async\" — be\n // conservative and gate. Adapters that don't expose\n // `needsAsyncValidation` are treated as `false`, matching the\n // optional-method contract on AbstractSchema.\n const candidates = schema.getSchemasAtPath(path)\n const hasAsync = candidates.some((sub) => sub.needsAsyncValidation?.() === true)\n pathAsyncCache.set(key, hasAsync)\n return hasAsync\n }\n // Reactive per-path counter for `field.validating`. See JSDoc on\n // `FormStore.fieldValidationCounts` for semantics.\n const fieldValidationCounts: Map<PathKey, number> = reactive(new Map<PathKey, number>())\n function incFieldValidation(key: PathKey): void {\n fieldValidationCounts.set(key, (fieldValidationCounts.get(key) ?? 0) + 1)\n }\n function decFieldValidation(key: PathKey): void {\n const next = (fieldValidationCounts.get(key) ?? 0) - 1\n if (next <= 0) fieldValidationCounts.delete(key)\n else fieldValidationCounts.set(key, next)\n }\n\n // Populate originals by diffing from empty-form to schema-initial. This is\n // always the schema's shape regardless of hydration, so pristine/dirty\n // comparisons are against what the form was supposed to start as.\n // Same walk seeds `pathOrdinals` — `diffAndApply` visits every leaf in\n // declaration order, so the ordinal map gets schema-declaration order\n // for free with no extra traversal.\n const initStamp = new Date().toISOString()\n diffAndApply({}, schemaInitialData, [], (patch) => {\n if (patch.kind !== 'added') return\n const { key } = canonicalizePath(patch.path)\n originals.set(key, { segments: patch.path, value: patch.newValue })\n ensurePathOrdinal(key)\n })\n\n // Populate fields from either the hydration payload (preserves exact\n // server-side timestamps and flags) or by walking initialData for leaves.\n if (hydration !== undefined) {\n for (const [rawKey, record] of hydration.fields) {\n if (typeof rawKey !== 'string' || !isHydratedFieldRecord(record)) {\n warnMalformedHydration(formKey, 'FieldRecord', String(rawKey))\n continue\n }\n fields.set(rawKey as PathKey, record)\n }\n // Hydration takes precedence over the construction-time seed\n // below: the server already authored whatever error state the\n // client should mirror, including (deliberately) the empty case.\n // Each store replays from its own snapshot so the source-segregation\n // invariant is preserved across SSR round-trip.\n for (const [rawKey, errs] of hydration.schemaErrors) {\n if (typeof rawKey !== 'string' || !isHydratedValidationErrorArray(errs)) {\n warnMalformedHydration(formKey, 'schemaErrors', String(rawKey))\n continue\n }\n schemaErrors.set(rawKey as PathKey, errs)\n }\n for (const [rawKey, errs] of hydration.userErrors) {\n if (typeof rawKey !== 'string' || !isHydratedValidationErrorArray(errs)) {\n warnMalformedHydration(formKey, 'userErrors', String(rawKey))\n continue\n }\n userErrors.set(rawKey as PathKey, errs)\n }\n } else {\n diffAndApply({}, initialData, [], (patch) => {\n if (patch.kind !== 'added') return\n const { key } = canonicalizePath(patch.path)\n fields.set(key, {\n path: patch.path,\n updatedAt: initStamp,\n connected: false,\n focused: null,\n blurred: null,\n touched: null,\n })\n })\n // No hydration — seed schemaErrors from the construction-time\n // validation result IF the schema rejected the defaults AND the\n // form was constructed in strict mode. Non-strict mode treats\n // default values as \"best-effort,\" so populating errors there\n // would surprise consumers who explicitly opted out via\n // `strict: false`.\n if (strict && !schemaResponse.success) {\n setAllSchemaErrors(schemaResponse.errors)\n }\n }\n\n // Async-only verdicts (e.g. zod's `.refine(async (v) => …)`) can't\n // surface from `getDefaultValues` — that contract is sync, and the\n // adapter degrades to success when the schema's sync parse can't\n // resolve them. When the adapter signals via `needsAsyncValidation`\n // that there's verdicts only an async pass would surface, queue a\n // one-shot full-form validation so the errors land on a later\n // microtask instead of waiting for a user mutation.\n //\n // Two gates:\n // - SKIP on SSR. Microtasks don't get awaited before\n // `renderToString` serialises, so the async chain never\n // completes server-side; firing the schedule would only\n // increment `activeValidations` synchronously and stamp a\n // misleading `validating: true` into the SSR HTML, which\n // the client's hydration pass (taking the hydration branch\n // above) wouldn't reproduce — surface as a hydration\n // mismatch on the `validating…` indicator.\n // - `queueMicrotask` so the increment lands AFTER Vue's\n // synchronous hydration / first render. SSR HTML and the\n // client's first render both observe `activeValidations: 0`;\n // the validation kicks off only on the next microtask, by\n // which point hydration is done and Vue handles the reactive\n // re-render normally.\n //\n // Gated to strict mode AND to schemas that actually need async\n // work — sync-only schemas would otherwise pay a redundant\n // microtask + briefly flash `meta.validating: true` post-mount,\n // misrepresenting \"validation is running\" when nothing is.\n if (!ssr && strict && schema.needsAsyncValidation?.() === true) {\n queueMicrotask(() => scheduleFieldValidation([], true /* immediate */))\n }\n\n function touchFieldRecord(\n pathKey: PathKey,\n path: Path,\n patch: Partial<Omit<FieldRecord, 'path'>>\n ): void {\n const current = fields.get(pathKey)\n fields.set(pathKey, {\n path,\n updatedAt: patch.updatedAt ?? current?.updatedAt ?? null,\n connected: patch.connected ?? current?.connected ?? false,\n focused: patch.focused ?? current?.focused ?? null,\n blurred: patch.blurred ?? current?.blurred ?? null,\n touched: patch.touched ?? current?.touched ?? null,\n })\n }\n\n function applyFormReplacement(next: F, meta?: WriteMeta): void {\n const prev = form.value\n if (Object.is(prev, next)) return\n // Capture the diff before any mutation lands — bookkeeping below\n // needs the per-leaf patches against the OLD shape.\n const now = new Date().toISOString()\n const patches: Patch[] = []\n diffAndApply(prev, next, [], (patch) => {\n patches.push(patch)\n })\n // Mutate `form.value` in place so Vue's deep-reactivity dependencies\n // fire ONLY for paths that genuinely changed. A wholesale\n // `form.value = next` would fire every deep watch (including\n // watches on sub-trees that didn't change), which deadlocks the\n // browser when a watcher reacts by writing back to the form (the\n // canonical \"same as pickup address\" mirror pattern).\n //\n // On a top-level shape mismatch (object → array, etc.) fall back\n // to wholesale replacement — that's the only case where in-place\n // merging can't preserve existing reactive proxies anyway.\n if (!applyChangedKeys(prev, next)) {\n form.value = next\n }\n // Bookkeeping: per-leaf metadata bumped from the captured patches.\n // Runtime-added paths (e.g. `append('posts', {...})` introducing a\n // new array index) must compare against `undefined` for `dirty` —\n // appearing IS a mutation. Only `reset()` rebaselines the originals\n // map; this branch records absence-as-original so the first\n // appearance is correctly seen as dirty.\n for (const patch of patches) {\n const { key } = canonicalizePath(patch.path)\n if (patch.kind === 'added' && !originals.has(key)) {\n originals.set(key, { segments: patch.path, value: undefined })\n }\n touchFieldRecord(key, patch.path, { updatedAt: now })\n }\n // Notify any subscribed modules (persistence, undo/redo) — fire\n // after field bookkeeping so listeners see a fully-updated form.\n // Listener throws are isolated so one misbehaving subscriber\n // can't block the others. `meta` propagates the call-site's\n // intent (e.g. persist: true) to subscribers that filter on it.\n for (const listener of formChangeListeners) {\n try {\n listener(form.value, meta)\n } catch (err) {\n console.error('[attaform] onFormChange threw:', err)\n }\n }\n }\n\n function setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean {\n // Drop any Symbol-keyed properties before the value flows through\n // the gate, DU reshape, or storage. Form values are string-keyed\n // by schema design and the consumer-side leak would otherwise\n // surface in `Object.getOwnPropertySymbols(values.x)` and break\n // downstream JSON serialization (persistence) + variant memory.\n value = stripSymbolsDeep(value)\n // Give the schema a chance to normalize the consumer's input\n // before it hits the slim-primitive gate or storage. Zod expresses\n // this via `z.preprocess(fn, inner)`; other adapters expose\n // analogous constructs. Without this hook, a schema like `notify:\n // z.preprocess(v => v == null ? defaultVar : v, innerDU)` would\n // let the consumer write `null` and lock storage into `null` —\n // the preprocess wrapper accepts `unknown` at the input side, the\n // slim-gate has nothing to reject against, and the input lands\n // verbatim. Running the normalization at the write boundary means\n // storage holds the shape the user declared, and validation sees\n // a consistent value.\n value = schema.normalizeWriteValueAtPath(value, path)\n // Slim-primitive write gate: every leaf in the value must match\n // the schema's slim primitive set at its sub-path. Refinement-level\n // constraints (.email/.min/enum membership/etc.) are NOT enforced\n // here — they're a validation concern. See ./slim-primitive-gate.ts.\n if (!isSlimPrimitiveValid(schema, form, path, value)) {\n return false\n }\n // Cross-variant write guard: walking the path, if any ancestor is\n // a DU whose ACTIVE disc value resolves to a known variant that\n // doesn't contain the next path segment, the write targets an\n // inactive-variant key (e.g. `setValue('notify.number', ...)`\n // while the active channel is 'email'). Or the ancestor is in\n // stub state (disc isn't a known variant). Reject so foreign\n // sibling-variant fields can't leak into form.values.\n //\n // The DU's own disc key is always reachable — writes to it\n // recover the form from stub state by selecting a valid variant\n // — so the guard skips when the next path segment IS the disc.\n if (path.length >= 2) {\n for (let i = 0; i < path.length - 1; i++) {\n const ancestorPath = path.slice(0, i + 1)\n const du = schema.getUnionDiscriminatorAtPath(ancestorPath)\n if (du === undefined) continue\n const nextSeg = path[i + 1]\n if (nextSeg === du.discriminatorKey) continue\n const ancestorValue = getAtPath(form.value, ancestorPath)\n if (!isPlainRecord(ancestorValue)) continue\n const discValue = (ancestorValue as Record<string, unknown>)[du.discriminatorKey]\n if (discValue === undefined) {\n return false\n }\n if (!du.isVariantSelected(discValue)) {\n return false\n }\n const variantDefault = du.getVariantDefault(discValue)\n if (!isPlainRecord(variantDefault)) continue\n if (typeof nextSeg !== 'string') continue\n if (!(nextSeg in (variantDefault as Record<string, unknown>))) {\n return false\n }\n }\n }\n\n // Discriminated-union variant transitions. Writing a discriminator\n // — whether as a leaf write to the discriminator key or as a\n // wholesale write of the union value carrying a different\n // discriminator — changes the schema's effective shape at the\n // union's location. Old-variant keys (e.g. `address` on the email\n // branch) become foreign once `channel: 'sms'` lands; new-variant\n // required keys need their slim defaults populated so the\n // errors-as-state pipeline sees the new shape. Two flavours, both\n // routed through `reshapeUnionVariant`:\n //\n // Case A — leaf write to the discriminator key\n // (`setValue('notify.channel', 'sms')`). Parent path is the\n // union; the new value names a variant directly.\n //\n // Case B — wholesale write of the union itself\n // (`setValue('notify', { channel: 'sms', number: '...' })`).\n // Path is the union; the consumer's value carries the\n // discriminator. Layer the consumer's value on top of the\n // matched variant default so consumer-supplied keys win.\n if (meta?.skipDiscriminatorReshape !== true) {\n // Case A: discriminator-key write.\n if (path.length > 0) {\n const last = path[path.length - 1]\n if (typeof last === 'string') {\n const parentPath = path.slice(0, -1)\n const parentDU = schema.getUnionDiscriminatorAtPath(parentPath)\n if (parentDU?.discriminatorKey === last) {\n const oldValue = getAtPath(form.value, path)\n if (!Object.is(oldValue, value)) {\n const variantDefault = parentDU.getVariantDefault(value)\n if (variantDefault !== undefined) {\n return reshapeUnionVariant(\n parentPath,\n oldValue,\n value,\n variantDefault,\n undefined,\n meta\n )\n }\n // Disc value isn't a known variant literal. Storage at\n // the union path becomes a stub holding only the disc\n // key — prior variant body dropped, no first-variant-\n // default leak. Validation surfaces the issue via Zod's\n // natural invalid_union_discriminator at parentPath.\n return reshapeUnionVariant(\n parentPath,\n oldValue,\n value,\n { [last]: value },\n undefined,\n meta\n )\n }\n }\n }\n }\n // Case B: whole-union write.\n if (isPlainRecord(value)) {\n const selfDU = schema.getUnionDiscriminatorAtPath(path)\n if (selfDU !== undefined) {\n const valueRecord = value as Record<string, unknown>\n const discKey = selfDU.discriminatorKey\n const discValue = valueRecord[discKey]\n const currentUnionValue = getAtPath(form.value, path)\n const oldDiscValue = isPlainRecord(currentUnionValue)\n ? (currentUnionValue as Record<string, unknown>)[discKey]\n : undefined\n if (discValue !== undefined) {\n const variantDefault = selfDU.getVariantDefault(discValue)\n if (variantDefault !== undefined && isPlainRecord(variantDefault)) {\n return reshapeUnionVariant(\n path,\n oldDiscValue,\n discValue,\n variantDefault,\n valueRecord,\n meta\n )\n }\n // Consumer supplied a disc value that's not a known\n // variant. Stub holds only the disc key; non-disc consumer\n // keys are dropped (consumerOverrides = undefined) so\n // foreign fields don't leak into form.values.\n return reshapeUnionVariant(\n path,\n oldDiscValue,\n discValue,\n { [discKey]: discValue },\n undefined,\n meta\n )\n }\n // Consumer wrote a whole-union value with NO discriminator.\n // The form is \"between selections\" — empty stub {} ; every\n // consumer key is dropped (no auto-merge with the first-\n // variant default).\n return reshapeUnionVariant(path, oldDiscValue, undefined, {}, undefined, meta)\n }\n }\n }\n\n // Blank bookkeeping. `blank: true` adds the path\n // to the set (the call site declares \"this write represents an\n // empty intent\"); any other write removes it (the user typed a\n // real value or programmatically reassigned). The mark/unmark sit\n // BEFORE the identity short-circuit so transitions that don't\n // change storage value (e.g. typing 0 over slim-default 0) still\n // update the visual / blank state correctly.\n const pathKey = canonicalizePath(path).key\n if (meta?.blank === true) {\n blankPaths.add(pathKey)\n } else if (blankPaths.has(pathKey)) {\n blankPaths.delete(pathKey)\n }\n\n // Structural-completeness invariant: every write must leave the\n // form satisfying the slim schema. Two ingress points to fill:\n // 1. The target value (consumer may have passed a partial; the\n // schema's element default fills missing keys / array\n // elements via mergeStructural).\n // 2. Intermediate gaps along the path (missing object property,\n // array length below target index — setAtPathWithSchemaFill\n // asks the schema for defaults at each gap site).\n // The common case (write to existing slot with a complete value)\n // hits no schema lookups: mergeStructural short-circuits on\n // ref-equal sub-trees, and the fill walker only queries the\n // schema at gap sites.\n const completedValue = mergeStructural(schema, path, value)\n // Identity short-circuit: if the path's current value already\n // matches what we'd write, skip the replacement. Without this,\n // every keystroke that produces an unchanged trimmed/cast value\n // (e.g. typing a trailing space into a `.trim` input — trim → \"\"\n // → form already at \"\") would still replace `form.value` with a\n // new object identity, triggering Vue to re-render the input and\n // patch the `:value` binding (which compares against the live\n // DOM `el.value`, not the previous vnode prop). The patch\n // overwrites the user's transient whitespace and the spacebar\n // appears broken.\n const currentValue = getAtPath(form.value, path)\n if (Object.is(currentValue, completedValue)) {\n return true\n }\n const nextForm = setAtPathWithSchemaFill(form.value, schema, path, completedValue) as F\n applyFormReplacement(nextForm, meta)\n // Variant-memory bookkeeping for array structural mutations. The\n // field-array helpers tag each op with an `arrayOp` describing\n // which indices shifted; raw whole-array setValues (`setValue\n // ('events', [...])`) clear all memory under the array path\n // because identity bookkeeping was lost wholesale. Memory keyed\n // by absolute index would otherwise bleed onto new occupants of\n // those indices on a future variant switch.\n if (meta?.arrayOp !== undefined) {\n applyArrayOpToMemory(path, meta.arrayOp)\n } else if (Array.isArray(value) && Array.isArray(currentValue)) {\n clearVariantMemoryUnderPath(path)\n }\n const effectiveModeAfterWrite = meta?.instance?.validateOn ?? fieldValidationMode\n if (effectiveModeAfterWrite === 'change') {\n scheduleFieldValidation(path, false /* debounced */, {\n ...(meta?.instance?.validateOn !== undefined ? { mode: meta.instance.validateOn } : {}),\n ...(meta?.instance?.debounceMs !== undefined\n ? { debounceMs: meta.instance.debounceMs }\n : {}),\n })\n }\n return true\n }\n\n /**\n * Replace the union's parent storage with the activated variant's\n * value, atomically. Two flavours fold into one machine:\n *\n * - `oldDiscValue !== newDiscValue` is a TRUE switch. The\n * outgoing variant's subtree (deep-cloned) and its blank-path\n * bookkeeping under `parentPath` snapshot into `variantMemory`\n * keyed by the union's PathKey. Then memory is consulted for\n * `newDiscValue`: a hit restores the prior typed state; a miss\n * falls back to `variantDefault` (the adapter's slim default\n * for the matching `z.object`).\n * - `oldDiscValue === newDiscValue` is NOT a switch — the\n * reshape was entered via Case B with a partial whole-union\n * write. Skip memory I/O entirely (memory is for switches),\n * just merge `consumerOverrides` on top of `variantDefault`.\n *\n * `consumerOverrides` carries Case B's whole-union value (e.g.\n * `setValue('notify', { channel: 'email', address: 'x' })`).\n * Merge order: memory baseline (or `variantDefault`) first,\n * consumer overrides on top — so a memory-restored `address`\n * survives a partial write that doesn't override it. Case A\n * passes `undefined` for `consumerOverrides`.\n *\n * Direct write — the resolved value IS structurally complete\n * (from the adapter's `deriveDefault` or a matching prior\n * snapshot). Routing through `mergeStructural` would re-add\n * foreign keys from the FIRST variant (the union's\n * `getDefaultAtPath` falls back to the first option), which is\n * exactly what the reshape is meant to clear.\n */\n function reshapeUnionVariant(\n parentPath: Path,\n oldDiscValue: unknown,\n newDiscValue: unknown,\n variantDefault: unknown,\n consumerOverrides: Record<string, unknown> | undefined,\n meta?: WriteMeta\n ): boolean {\n const sameDisc = Object.is(oldDiscValue, newDiscValue)\n const parentKey = canonicalizePath(parentPath).key\n\n // Snapshot OUTGOING. Deep-clone the value: `getAtPath(form.value,\n // parentPath)` returns a Vue reactive proxy into the live tree\n // (form is `ref(initialData)`); after the upcoming `form.value =\n // nextForm` overwrites the union path, the proxy still points to\n // the orphaned raw target. `cloneVariantSnapshot` walks the\n // subtree, calling `toRaw` at each level to bypass Vue reactivity\n // and preserves `BigInt`, `Date`, `Map`, `Set` natively — types\n // Zod schemas can validate at leaves but the prior `JSON.parse(\n // JSON.stringify(...))` cycle either crashed on (BigInt) or\n // silently degraded (Date → ISO string, Map/Set → `{}`).\n // `structuredClone` won't work as a one-shot replacement: nested\n // reactive children stored as Proxies cause `DataCloneError`.\n // Skip when `oldDiscValue` is undefined (initial state had no\n // discriminator) — nothing meaningful to remember.\n let baseline: unknown = variantDefault\n let restoredBlanks: PathKey[] | undefined\n const effectiveRemember = meta?.instance?.rememberVariants ?? rememberVariants\n if (effectiveRemember && !sameDisc) {\n if (oldDiscValue !== undefined) {\n const currentValue: unknown = cloneVariantSnapshot(getAtPath(form.value, parentPath))\n const outgoingBlanks: PathKey[] = []\n for (const k of blankPaths) {\n if (isPathKeyUnder(k, parentPath)) outgoingBlanks.push(k)\n }\n let memoryForUnion = variantMemory.get(parentKey)\n if (memoryForUnion === undefined) {\n memoryForUnion = new Map<unknown, VariantSnapshot>()\n variantMemory.set(parentKey, memoryForUnion)\n }\n memoryForUnion.set(oldDiscValue, {\n value: currentValue,\n blankPaths: outgoingBlanks,\n })\n }\n // Look up INCOMING. Stored value is already a deep clone — safe\n // to use directly without re-cloning.\n const memoryForUnion = variantMemory.get(parentKey)\n const restored = memoryForUnion?.get(newDiscValue)\n if (restored !== undefined) {\n baseline = restored.value\n restoredBlanks = [...restored.blankPaths]\n }\n }\n\n // Layer consumer overrides on top of the baseline (Case B).\n // For Case A (`consumerOverrides === undefined`), the baseline\n // is the final value.\n const layered: unknown =\n consumerOverrides !== undefined\n ? { ...(baseline as Record<string, unknown>), ...consumerOverrides }\n : baseline\n // Stub-correct any nested DU paths inside `layered` whose disc\n // value isn't a known variant — the consumer's Case B payload may\n // carry a valid outer disc but a bad inner disc (e.g.\n // `{step:'choose', inner:{kind:'BAD_INNER', a:'x'}}`). Without\n // this, the inner mixed shape leaks through reshape; with it,\n // every level ends in either a real variant or a disc-only stub.\n const finalValue: unknown = applyDuStubs(schema as AbstractSchema<unknown, unknown>, layered, {\n basePath: parentPath,\n })\n\n // New blanks: restored from memory (preserves the user's prior\n // explicit blanks + numeric auto-marks together) or recomputed\n // from the resolved `finalValue` (mount-time rule: storage /\n // display divergence for `number` / `bigint` numeric leaves).\n // Compute BEFORE the drop loop so we know which old keys survive\n // — `Set.add` on a deleted-and-re-added key re-inserts at the END\n // of insertion order, which would shift `derivedBlankErrors` (and\n // therefore `form.meta.errors`) on every same-disc reshape even\n // when nothing about the post-reshape shape actually changed.\n let newBlankPaths: PathKey[]\n if (restoredBlanks !== undefined) {\n newBlankPaths = restoredBlanks\n } else {\n newBlankPaths = []\n walkUnspecified(finalValue, [...parentPath], newBlankPaths)\n }\n const survivingBlankKeys = new Set<PathKey>(newBlankPaths)\n // Drop blank-path bookkeeping under `parentPath` — those paths\n // belong to the OLD variant's leaves and don't exist in the new\n // effective shape. Skip keys present in `survivingBlankKeys`: the\n // `add` below is a no-op for an existing Set member (preserves the\n // original insertion slot).\n for (const existingKey of [...blankPaths]) {\n if (isPathKeyUnder(existingKey, parentPath) && !survivingBlankKeys.has(existingKey)) {\n blankPaths.delete(existingKey)\n }\n }\n\n const currentValue = getAtPath(form.value, parentPath)\n if (Object.is(currentValue, finalValue)) {\n // Apply the auto-marks even on no-op (the bookkeeping must\n // catch up even when storage identity matches by coincidence).\n for (const k of newBlankPaths) blankPaths.add(k)\n return true\n }\n // `setAtPathWithSchemaFill` (not the plain `setAtPath`) so that\n // writing to an array index past current length pads positions in\n // between with the schema's element default — otherwise a\n // `setValue('events.10', { type: 'text', value: 'far' })` on a\n // length-1 array would leave `events[1..9]` as `undefined` holes,\n // which break downstream iteration and validation.\n const nextForm =\n parentPath.length === 0\n ? (finalValue as F)\n : (setAtPathWithSchemaFill(form.value, schema, parentPath, finalValue) as F)\n // Sync-validate AHEAD of the form mutation when the schema\n // permits it. Both writes (schemaErrors + form.value) then land\n // in the same Vue reactive batch, so a single render emits the\n // fully-consistent post-reshape state. Without this, the render\n // queued by `applyFormReplacement` runs BEFORE the async\n // validation lands — the active-path filter hides the OLD\n // variant's schemaErrors (their leaves vanished from form.value)\n // and the NEW variant's haven't been written yet, producing a\n // visible `{}` flicker between the two meaningful states.\n //\n // We pass `{ sync: true }` to opt into the adapter's sync arm.\n // The adapter MAY still return a Promise (async refinements,\n // async transforms / pipes — schemas where sync isn't possible);\n // we detect that with `instanceof Promise` and fall through to\n // the existing debounced async pipeline in that case.\n let appliedSync = false\n const reshapeMode = meta?.instance?.validateOn ?? fieldValidationMode\n if (reshapeMode === 'change') {\n const syncOrPromise = schema.validateAtPath(finalValue, parentPath, { sync: true })\n if (!(syncOrPromise instanceof Promise)) {\n const reStamped = syncOrPromise.success\n ? []\n : syncOrPromise.errors.map((err) => ({\n ...err,\n path: [...parentPath, ...(err.path as Segment[])],\n }))\n applySchemaErrorsForSubtree(parentPath, reStamped)\n // Cancel any in-flight async validation at this path so a\n // late-arriving result can't clobber the sync write.\n const { key: parentKey } = canonicalizePath(parentPath)\n const prevValidation = fieldValidationState.get(parentKey)\n if (prevValidation !== undefined) {\n if (prevValidation.timer !== null) clearTimeout(prevValidation.timer)\n prevValidation.controller.abort()\n fieldValidationState.delete(parentKey)\n }\n appliedSync = true\n }\n }\n applyFormReplacement(nextForm, meta)\n for (const k of newBlankPaths) blankPaths.add(k)\n if (reshapeMode === 'change' && !appliedSync) {\n scheduleFieldValidation(parentPath, false /* debounced */, {\n ...(meta?.instance?.validateOn !== undefined ? { mode: meta.instance.validateOn } : {}),\n ...(meta?.instance?.debounceMs !== undefined\n ? { debounceMs: meta.instance.debounceMs }\n : {}),\n })\n }\n return true\n }\n\n /**\n * Schedule (or kick off immediately) a field-level validation run\n * for `path`. Per-path AbortController semantics: a new schedule\n * cancels any prior in-flight run for the same path, so rapid\n * successive writes don't pile up concurrent validations.\n *\n * The validation reads the current value at `path` from `form.value`\n * AT THE TIME THE TIMER FIRES, not at schedule time. That's the\n * correct semantics for a debounced change trigger: the user's\n * latest-keystroke value is what matters, not whichever value\n * tripped the timer scheduler N milliseconds ago.\n */\n function scheduleFieldValidation(\n path: Path,\n immediate: boolean,\n override?: { readonly mode?: ValidateOn; readonly debounceMs?: number }\n ): void {\n const effectiveMode = override?.mode ?? fieldValidationMode\n if (effectiveMode === 'submit') return\n const effectiveDebounce = override?.debounceMs ?? fieldValidationDebounceMs\n const { key } = canonicalizePath(path)\n const prev = fieldValidationState.get(key)\n if (prev !== undefined) {\n if (prev.timer !== null) clearTimeout(prev.timer)\n prev.controller.abort()\n }\n const controller = new AbortController()\n const fresh: FieldValidationEntry = { controller, timer: null }\n fieldValidationState.set(key, fresh)\n\n const run = () => {\n fresh.timer = null\n if (controller.signal.aborted) return\n const data = getAtPath(form.value, path)\n // Defense-in-depth: the increments below trigger reactive\n // subscribers (sync watchers on `api.meta.validating` or\n // `api.fields.X.validating`). If one of those subscribers throws,\n // the Promise chain whose `.finally` does the decrements never\n // starts, leaking the per-path counter — `validating` would\n // stay true forever, and the mount-gate's\n // `pathHasAsyncValidation` would report a permanently-pending\n // verdict. Roll back the increments that succeeded on a sync\n // throw before letting the error propagate.\n let activeIncremented = false\n try {\n activeValidations.value += 1\n activeIncremented = true\n incFieldValidation(key)\n } catch (err) {\n // `incFieldValidation` is the last statement above and is\n // structurally a `Map.set` — if it throws, it threw before the\n // map entry was written, so there's nothing to roll back on the\n // field counter. The only rollback that matters is the global\n // `activeValidations` increment that happened on the first line.\n if (activeIncremented) {\n activeValidations.value = Math.max(0, activeValidations.value - 1)\n }\n throw err\n }\n void Promise.resolve()\n .then(() => schema.validateAtPath(data, path))\n .then((response) => {\n if (controller.signal.aborted) return\n // The adapter emits issue paths relative to the sub-schema it\n // parsed (e.g. `[]` for a leaf string). Re-stamp each error\n // with the absolute field path so the schemaErrors store and\n // `form.errors.<dotted path>` reads agree on the canonical\n // key.\n const reStamped = response.success\n ? []\n : response.errors.map((err) => ({\n ...err,\n path: [...path, ...(err.path as Segment[])],\n }))\n // Apply at the LEAF level: when the scheduled path is a\n // container (e.g. `['notify']` after a DU reshape), the\n // adapter returns multiple issues at distinct leaf paths.\n // Storing them all under the scheduled key would (a) hide\n // them from the canonical-key lookup `form.errors.notify.X`\n // and (b) survive across variant switches as ghost entries\n // because `setSchemaErrorsForPath(parent, [])` only clears\n // the parent's own key, not the descendants written by a\n // previous run.\n applySchemaErrorsForSubtree(path, reStamped)\n })\n .catch(() => {\n // Adapter contract forbids throws — swallow here so a misbehaving\n // custom adapter doesn't surface as an uncaught rejection. The\n // silent drop matches the reactive `validate()` ref's catch\n // branch for adapter-level throws (see process-form.ts).\n })\n .finally(() => {\n activeValidations.value = Math.max(0, activeValidations.value - 1)\n decFieldValidation(key)\n })\n }\n\n // `debounceMs: 0` is the off switch — `setTimeout(fn, 0)` would\n // punt to the next macrotask (browsers also clamp to ~4 ms), and\n // the indirection serves no purpose when the consumer asked for\n // \"no debounce.\" Run synchronously like the `immediate` branch.\n if (immediate || effectiveDebounce === 0) {\n run()\n } else {\n fresh.timer = setTimeout(run, effectiveDebounce)\n }\n }\n\n function cancelFieldValidation(): void {\n for (const entry of fieldValidationState.values()) {\n if (entry.timer !== null) clearTimeout(entry.timer)\n entry.controller.abort()\n }\n fieldValidationState.clear()\n }\n\n function onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void {\n formChangeListeners.add(listener)\n return () => {\n formChangeListeners.delete(listener)\n }\n }\n\n function onSubmitSuccess(listener: () => void): () => void {\n submitSuccessListeners.add(listener)\n return () => {\n submitSuccessListeners.delete(listener)\n }\n }\n\n function onReset(listener: () => void): () => void {\n resetListeners.add(listener)\n return () => {\n resetListeners.delete(listener)\n }\n }\n\n function emitSubmitSuccess(): void {\n for (const listener of submitSuccessListeners) {\n try {\n listener()\n } catch (err) {\n console.error('[attaform] onSubmitSuccess threw:', err)\n }\n }\n }\n\n function registerCleanup(fn: () => void): void {\n cleanupHooks.push(fn)\n }\n\n const drainHooks: (() => Promise<void>)[] = []\n\n function registerDrain(fn: () => Promise<void>): void {\n drainHooks.push(fn)\n }\n\n async function awaitPendingWrites(): Promise<void> {\n if (drainHooks.length === 0) return\n // Run drains in parallel — each owns its own retry / failure\n // semantics; we just need to know when all have settled.\n await Promise.allSettled(drainHooks.map((fn) => fn()))\n }\n\n function dispose(): void {\n // Run state-scoped teardowns BEFORE clearing listener sets, so a\n // module that wants to flush something by emitting one last event\n // from its cleanup (unlikely but harmless) doesn't find the\n // listener set already empty. Each hook runs inside try/catch so\n // one misbehaving module can't block the others.\n for (const hook of cleanupHooks) {\n try {\n hook()\n } catch (err) {\n console.error('[attaform] cleanup threw:', err)\n }\n }\n cleanupHooks.length = 0\n drainHooks.length = 0\n modules.clear()\n cancelFieldValidation()\n formChangeListeners.clear()\n submitSuccessListeners.clear()\n resetListeners.clear()\n // Drop opt-ins so a directive that survives FormStore eviction\n // (it shouldn't, but defensive) doesn't keep the registry alive\n // through stale path entries on a disposed store.\n persistOptIns.clear()\n noSyncPaths.clear()\n noSyncPathCounts.clear()\n }\n\n function getValueAtPath(path: Path): unknown {\n return getAtPath(form.value, path)\n }\n\n // --- Errors ---\n // Two source-segregated stores: `schemaErrors` (validation-owned) and\n // `userErrors` (API-injected). Writers below are strict — each function\n // touches exactly one Map. The merged view is exposed via\n // `getErrorsForPath` and the top-level `errors` drillable Proxy.\n\n /**\n * Append every entry in `entries` to its target Map at the canonical\n * path key. Existing entries at that key are preserved (merge-append),\n * which matches the documented `addFieldErrors` semantics. Allocates a\n * fresh array per target key to keep the reactive trigger surface\n * obvious — Vue's collection handlers fire on `.set`, not on in-place\n * push.\n */\n /**\n * Form-level errors — entries whose absolute path is the empty\n * tuple `[]` — live in the empty-string bucket (`'[\"\"]'` PathKey,\n * segments `['']`). The convention lets `errors('')` return ONLY\n * the form-level bucket without sweeping every field error. Any\n * write that arrives with `err.path: []` (top-level handleSubmit\n * validation, root-scope `scheduleFieldValidation` re-stamping,\n * user APIs piping `parseApiErrors`-style entries) gets rerouted\n * here at the storage boundary.\n */\n function rerouteFormLevelEntry(err: ValidationError): ValidationError {\n if (err.path.length === 0) {\n return { ...err, path: [...FORM_ERRORS_PATH] }\n }\n return err\n }\n\n function pathKeyForEntry(err: ValidationError): PathKey {\n if (err.path.length === 0) return FORM_ERRORS_PATH_KEY\n return canonicalizePath(err.path as Path).key\n }\n\n function appendErrorsTo(\n map: Map<PathKey, ValidationError[]>,\n entries: readonly ValidationError[]\n ): void {\n for (const raw of entries) {\n const err = rerouteFormLevelEntry(raw)\n const key = pathKeyForEntry(err)\n const current = map.get(key)\n if (current === undefined) {\n map.set(key, [err])\n } else {\n map.set(key, [...current, err])\n }\n }\n }\n\n /**\n * Clear `map` and rebuild it from `entries`. Two reactive notifications\n * fire (one for `.clear`, one per `.set`), but Vue's microtask batching\n * collapses the burst so subscribers see one re-render. A diff-and-patch\n * variant is a deferred follow-up — profile first.\n */\n function replaceErrorsIn(\n map: Map<PathKey, ValidationError[]>,\n entries: readonly ValidationError[]\n ): void {\n map.clear()\n appendErrorsTo(map, entries)\n }\n\n function clearErrorsIn(map: Map<PathKey, ValidationError[]>, path: Path | undefined): void {\n if (path === undefined) {\n map.clear()\n return\n }\n const { key } = canonicalizePath(path)\n map.delete(key)\n }\n\n // --- Schema writers (validation pipeline + handleSubmit + history/hydration) ---\n\n function setSchemaErrorsForPath(path: Path, entries: ValidationError[]): void {\n const { key } = canonicalizePath(path)\n if (entries.length === 0) {\n schemaErrors.delete(key)\n return\n }\n schemaErrors.set(key, [...entries])\n }\n\n /**\n * Replace the schemaErrors subtree rooted at `path` with `entries`,\n * keying each entry by its OWN absolute path rather than `path`.\n * Used by `scheduleFieldValidation` so a re-validation of a\n * container (e.g. a DU parent after reshape) lands every leaf-keyed\n * issue at its canonical store key — `form.errors.<path>` reads\n * hit, and stale entries from a previous variant don't survive.\n *\n * Insertion-order stability: `Map.set` on an EXISTING key updates the\n * value in place and preserves the slot's position; `Map.delete`\n * followed by `Map.set` re-inserts at the END. `form.meta.errors`\n * iterates this Map in insertion order, so a per-field\n * re-validation that delete-then-sets the scheduled key flips the\n * aggregate's order on every keystroke. The grouped pass below\n * computes the surviving key set FIRST so we only delete keys that\n * genuinely drop out (an old DU-variant leaf that the new pass\n * doesn't write); keys that survive get an in-place `set` that keeps\n * their original slot.\n */\n function applySchemaErrorsForSubtree(path: Path, entries: ValidationError[]): void {\n // Root-scope re-validation (path === []) of a schema with a\n // top-level `.refine()` produces an absolute-path-empty entry.\n // Reroute those to the form-level bucket so the parent-key check\n // below reflects the storage convention; otherwise the dropped\n // parent (`'[]'`) and the surviving form-level entry (`'[\"\"]'`)\n // never reconcile and the refine error gets nuked on every\n // re-run.\n const parentKey = path.length === 0 ? FORM_ERRORS_PATH_KEY : canonicalizePath(path).key\n // Group by each error's own canonical storage key FIRST so we know\n // which keys survive this pass. Multiple issues at the same path\n // (e.g. two refinements failing the same leaf) merge into one\n // array — preserves adapter ordering within the leaf.\n const grouped = new Map<PathKey, ValidationError[]>()\n for (const raw of entries) {\n const err = rerouteFormLevelEntry(raw)\n const key = pathKeyForEntry(err)\n const list = grouped.get(key)\n if (list === undefined) grouped.set(key, [err])\n else list.push(err)\n }\n // Drop the parent key only if not in the new pass.\n if (!grouped.has(parentKey)) schemaErrors.delete(parentKey)\n // Drop stale descendants: existing keys under `path` that the new\n // pass doesn't write (DU-variant leaves that disappeared on\n // reshape). Keys that DO appear in `grouped` stay where they are\n // — the `set` below updates them in place. For root-scope passes\n // (`path === []`) the form-level bucket is treated as the\n // \"parent\" — `isPathKeyUnder('[\"\"]', [])` would otherwise sweep\n // it into the descendant set and clobber refine errors that the\n // new pass also writes.\n for (const existingKey of [...schemaErrors.keys()]) {\n if (existingKey === parentKey) continue\n if (isPathKeyUnder(existingKey, path) && !grouped.has(existingKey)) {\n schemaErrors.delete(existingKey)\n }\n }\n for (const [leafKey, group] of grouped) {\n schemaErrors.set(leafKey, group)\n }\n }\n\n function setAllSchemaErrors(entries: readonly ValidationError[]): void {\n replaceErrorsIn(schemaErrors, entries)\n }\n\n function clearSchemaErrors(path?: Path): void {\n clearErrorsIn(schemaErrors, path)\n }\n\n // --- User writers (setFieldErrors* surfaces + history/hydration) ---\n\n function setAllUserErrors(entries: readonly ValidationError[]): void {\n replaceErrorsIn(userErrors, entries)\n }\n\n function addUserErrors(entries: readonly ValidationError[]): void {\n appendErrorsTo(userErrors, entries)\n }\n\n function clearUserErrors(path?: Path): void {\n clearErrorsIn(userErrors, path)\n }\n\n // --- Merged read ---\n\n function getErrorsForPath(path: Path): ValidationError[] {\n const { key } = canonicalizePath(path)\n const schemaForKey = schemaErrors.get(key)\n const userForKey = userErrors.get(key)\n const blankForKey = derivedBlankErrors.value.get(key)\n if (schemaForKey === undefined && userForKey === undefined && blankForKey === undefined) {\n return []\n }\n const result: ValidationError[] = []\n if (schemaForKey !== undefined) result.push(...schemaForKey)\n if (blankForKey !== undefined) result.push(...blankForKey)\n if (userForKey !== undefined) result.push(...userForKey)\n return result\n }\n\n // --- DOM ---\n\n function registerElement(path: Path, element: HTMLElement, formInstanceId: string): boolean {\n const { key } = canonicalizePath(path)\n const record = elements.get(key)\n // `markRaw` keeps HTMLElement out of Vue's auto-proxy machinery\n // (DOM nodes have circular refs and external state that fight\n // reactivity, and consumers comparing `===` against the original\n // ref expect to get back what they registered). The Set itself\n // is reactive so add/delete on an existing record fires\n // FieldState's `element` / `elements` accessors.\n const raw = markRaw(element)\n if (record === undefined) {\n elements.set(key, { path, elements: reactive(new Set([raw])) })\n } else {\n if (record.elements.has(raw)) return false\n record.elements.add(raw)\n }\n elementToFormInstance.set(element, formInstanceId)\n sortedRegistrationsCache = null\n touchFieldRecord(key, path, { connected: true })\n return true\n }\n\n function deregisterElement(path: Path, element: HTMLElement): number {\n const { key } = canonicalizePath(path)\n const record = elements.get(key)\n if (record === undefined) return 0\n const removed = record.elements.delete(element)\n if (removed) {\n elementToFormInstance.delete(element)\n sortedRegistrationsCache = null\n }\n const remaining = record.elements.size\n if (remaining === 0) {\n elements.delete(key)\n touchFieldRecord(key, path, { connected: false })\n }\n return remaining\n }\n\n function markConnectedOptimistically(path: Path): void {\n // Client-side: the directive's `created` / `beforeUnmount` hooks are\n // authoritative for `connected`, so this is a no-op there. SSR is\n // the only environment where we can't observe the DOM and need an\n // upfront hint that the field WILL be wired up after hydration.\n if (!ssr) return\n const { key } = canonicalizePath(path)\n const current = fields.get(key)\n if (current?.connected === true) return\n touchFieldRecord(key, path, { connected: true })\n }\n\n function markFocused(\n path: Path,\n focused: boolean,\n meta?: { readonly instance?: WriteMeta['instance'] }\n ): void {\n const { key } = canonicalizePath(path)\n touchFieldRecord(key, path, {\n focused,\n blurred: !focused,\n // `touched` flips to true on blur and stays true thereafter; while\n // a field is currently focused we keep whatever value it held.\n touched: focused ? (fields.get(key)?.touched ?? null) : true,\n })\n // On blur (focused → false), `validateOn: 'blur'` fires an\n // immediate (no-debounce) validation for this path. Ignored for\n // change/submit modes so behaviour matches the declared config.\n const focusMode = meta?.instance?.validateOn ?? fieldValidationMode\n if (!focused && focusMode === 'blur') {\n scheduleFieldValidation(path, true /* immediate */, {\n ...(meta?.instance?.validateOn !== undefined ? { mode: meta.instance.validateOn } : {}),\n ...(meta?.instance?.debounceMs !== undefined\n ? { debounceMs: meta.instance.debounceMs }\n : {}),\n })\n }\n }\n\n function markTouched(path: Path): void {\n const { key } = canonicalizePath(path)\n touchFieldRecord(key, path, { touched: true })\n }\n\n /**\n * Walk every active-variant leaf under `segments` and flip its\n * `touched` flag to `true`. Powers the public `form.touch(path?)`\n * API: leaf path → exactly that leaf; container path → every\n * descendant leaf; root path `[]` → every leaf in the form.\n *\n * Idempotent: leaves already touched are skipped (no reactive\n * notification). Inactive DU-variant leaves are filtered via\n * `hasAtPath` against the live form value — same gate the\n * field-state aggregation walk uses, so touch never marks a leaf\n * the consumer can't see.\n *\n * Dev-warns when no leaves resolve under the path (typo'd input,\n * empty container, dead variant). Does NOT mutate value, focused,\n * blurred, or trigger validation — touched is the single sticky\n * flag this helper writes.\n */\n function touchAtPath(segments: Path): void {\n const formValue = form.value\n let touchedAny = false\n for (const [, entry] of originals) {\n if (!isPathPrefix(segments, entry.segments)) continue\n if (!hasAtPath(formValue, entry.segments)) continue\n touchedAny = true\n const leafKey = canonicalizePath(entry.segments).key\n const current = fields.get(leafKey)\n if (current?.touched === true) continue\n touchFieldRecord(leafKey, entry.segments, { touched: true })\n }\n if (!touchedAny && __DEV__) {\n console.warn(\n `[attaform] form.touch(): no fields resolved at path ${JSON.stringify(segments)}. ` +\n `Check the path matches an existing field or container.`\n )\n }\n }\n\n // --- Reset ---\n\n function reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void {\n // Fall back to construction-time `defaultValues` when the caller\n // doesn't provide a fresh override. Otherwise `reset()` produces\n // schema-only defaults — losing the consumer's initial state from\n // `useForm({ defaultValues: ... })`. The structural-completeness\n // invariant covers post-write correctness; preserving construction\n // defaults across reset is a separate semantic the consumer expects.\n //\n // Pre-merge sparse constraints through `mergeStructural` BEFORE\n // calling `getDefaultValues`, MIRRORING construction (line ~999).\n // Without this, a sparse `defaultValues` like `{ pickup: { country:\n // 'US' } }` reaches the adapter without its sibling-fill, and the\n // adapter's `useDefaultSchemaValues` branch returns\n // `success: true` even though the FILLED form\n // (`{ pickup: { country: 'US', line1: '', city: '', ... } }`)\n // violates `.min(1)` refinements on those siblings. Construction\n // pre-fills, so it sees `success: false` correctly. Reset must\n // do the same to keep the two responses byte-equivalent.\n const resetSource = nextDefaultValues ?? defaultValues\n const completedResetConstraints =\n resetSource === undefined\n ? undefined\n : (mergeStructural(schema, [], resetSource) as DeepPartial<WriteShape<F>>)\n const resetResponse = schema.getDefaultValues({\n useDefaultSchemaValues: true,\n constraints: completedResetConstraints,\n strict,\n })\n const next = resetResponse.data\n // Replace form in one shot — applyFormReplacement will emit diffAndApply\n // patches and touch field records for every changed leaf.\n applyFormReplacement(next)\n // Rebuild originals from the new baseline. The set becomes the\n // post-reset pristine reference — a subsequent dirty comparison\n // returns false until the consumer mutates again.\n originals.clear()\n diffAndApply({}, next, [], (patch) => {\n if (patch.kind !== 'added') return\n const { key } = canonicalizePath(patch.path)\n originals.set(key, { segments: patch.path, value: patch.newValue })\n })\n // Blank: with `nextDefaultValues` provided, both sets\n // adopt the new baseline (commit 7 plugs the `unset`-symbol walker\n // into this branch — for now the new defaults can't carry unset\n // symbols at the type level, so the post-reset baseline is empty).\n // With no args, restore `blankPaths` from the snapshot so\n // construction-time membership returns; originalBlankPaths is\n // preserved (the snapshot encodes the consumer's last declared\n // baseline, which `reset()` should honour).\n if (nextDefaultValues !== undefined) {\n blankPaths.clear()\n originalBlankPaths.clear()\n } else {\n blankPaths.clear()\n for (const key of originalBlankPaths) {\n blankPaths.add(key)\n }\n }\n // Drop every recorded error — the form is a fresh surface again.\n // Both stores clear: reset is \"fresh start\" semantics, so user-injected\n // errors are not preserved across a reset (different from submit-success,\n // which preserves them).\n schemaErrors.clear()\n userErrors.clear()\n // Re-derive schemaErrors from the post-reset state under strict mode,\n // mirroring construction-time validation (line ~1338). Without this,\n // reset clears the error store but never re-runs validation — so a\n // form mounted with invalid defaults (e.g. empty required strings)\n // would surface as `valid: true` immediately after reset even though\n // the values it landed back on are the same INVALID defaults it\n // mounted with. `field.valid` aggregates over schemaErrors and would\n // otherwise come up empty, flipping every leaf green.\n //\n // Gated on `strict` to honor the same opt-out construction uses:\n // a non-strict form opted out of construction-time validation\n // explicitly, and post-reset behaviour follows suit.\n if (strict && !resetResponse.success) {\n setAllSchemaErrors(resetResponse.errors)\n }\n // `getDefaultValues` strips refinements before parsing (see\n // `adapters/zod-v4/default-values.ts:290`) — it produces usable\n // starting data, not refinement-level verdicts. So `.min(1)` /\n // `.email()` / etc. failures on the post-reset defaults DON'T\n // surface via the sync re-derive above. Run a synchronous\n // full-schema parse against the post-reset form value to populate\n // refinement errors IMMEDIATELY (no flash where step titles flip\n // green between reset() returning and the async pass landing).\n // Async-only verdicts can't surface this way (adapter returns a\n // Promise) — they're handled by the queueMicrotask below.\n //\n // Construction has the same gap mount-side, but the flash is\n // invisible: the form mounts before the user is looking, errors\n // land within a microtask, and the UI never has time to render\n // the empty-errors state.\n if (strict) {\n const syncResult = schema.validateAtPath(form.value, undefined, { sync: true })\n if (!(syncResult instanceof Promise) && !syncResult.success) {\n applySchemaErrorsForSubtree([], syncResult.errors)\n }\n }\n // Restore the `firstValidationDone` gate to its construction-time\n // value (line ~1233). Async-validating schemas init this flag to\n // `false`, gating container `.valid` until the construction-time\n // async pass completes. After mount the flag flips `true` via the\n // watch on `activeValidations`. Across reset, leaving it `true`\n // removes the gate AND clears errors AND the sync re-derive\n // can't fill them (the zod-v4 adapter strips refinements in\n // `getDefaultValues`, returns `success: true`; sync\n // `validateAtPath` throws on schemas with always-running async\n // refines and falls through to async-only). The window between\n // `reset()` returning and the re-queued async pass landing reads\n // `valid: true` for every container — the docs-site stepper\n // demo's step titles turn green for ~600ms-1.5s. Restoring the\n // gate keeps containers `valid: false` throughout that window.\n firstValidationDone.value = !strict || schema.needsAsyncValidation?.() !== true\n // Re-queue the async validation pass on the same gate construction\n // uses (line ~1371). Picks up async-only verdicts the sync pass\n // above can't reach (`.refine(async ...)` on\n // `pickup.postalCode`, etc.). SSR skip mirrors construction —\n // microtasks don't await before `renderToString` and would stamp\n // `validating: true` into HTML the client won't reproduce.\n const needsAsync = !ssr && strict && schema.needsAsyncValidation?.() === true\n if (needsAsync) {\n queueMicrotask(() => scheduleFieldValidation([], true /* immediate */))\n }\n // Blow away touched/focused/blurred per field. connected stays as-is\n // (the DOM elements haven't detached — that's a separate concern from\n // form state) and updatedAt stamps to now.\n const now = new Date().toISOString()\n for (const [pathKey, record] of fields) {\n fields.set(pathKey, {\n path: record.path,\n updatedAt: now,\n connected: record.connected,\n focused: null,\n blurred: null,\n touched: null,\n })\n }\n // Clear submission lifecycle so a reset surface reports \"nothing has\n // been submitted yet\" rather than holding on to the prior run's\n // count. The generation counter is bumped first so any in-flight\n // submission's catch block knows its error write would land on the\n // post-reset state and skips it. `activeSubmissions` is zeroed\n // unconditionally — the finally-block's Math.max clamps the\n // decrement at zero, and `submitting` stays false afterwards\n // because the clamped value never exceeds zero.\n submissionGeneration.value += 1\n submitting.value = false\n activeSubmissions.value = 0\n submitCount.value = 0\n submitError.value = null\n // Drop any pending field-validation timers / in-flight runs. Writes\n // that reached the controller-aborted branch resolve to a no-op, so\n // the error store stays clean after the reset clears it above.\n cancelFieldValidation()\n // Variant memory is UX state — a fresh start drops the per-variant\n // typed-data cache too. Without this, a post-reset switch would\n // surface stale variant values from before the reset.\n variantMemory.clear()\n // Notify subscribers (history module clears its stack, persistence\n // sees the reset via onFormChange already). Listener throws are\n // isolated so one bad subscriber can't block the others.\n for (const listener of resetListeners) {\n try {\n listener()\n } catch (err) {\n console.error('[attaform] onReset threw:', err)\n }\n }\n }\n\n function resetField(path: Path): void {\n const { key: targetKey, segments: targetSegments } = canonicalizePath(path)\n\n // Variant memory: drop any union memory whose path equals or sits\n // under `targetSegments`. Memory under the reset subtree is\n // semantically \"user's prior typed state at a discriminator that\n // no longer corresponds to anything live\"; preserving it would\n // surface stale variants on a future switch. Memory ABOVE the\n // reset subtree (e.g. union at ['notify'] for resetField('notify.address'))\n // is intentionally preserved — the snapshot self-corrects on the\n // next switch-out.\n for (const memKey of [...variantMemory.keys()]) {\n const memSegments = segmentsForPathKey(memKey)\n if (memSegments === null) continue\n if (isPathPrefix(targetSegments, memSegments)) {\n variantMemory.delete(memKey)\n }\n }\n\n // Storage restore: leaf > container > nothing.\n //\n // Leaf shortcut: direct originals hit means one setValueAtPath does\n // it. A miss falls through to the container case, which assembles a\n // subtree from every original under the prefix. When neither\n // matches — e.g. `resetField('')` (the form-level error path, never\n // a storage slot) or `resetField('unknownPath')` — storage stays\n // untouched but the cleanup below still runs.\n const leafEntry = originals.get(targetKey)\n if (leafEntry !== undefined) {\n const wrote = setValueAtPath(targetSegments, leafEntry.value)\n if (!wrote) {\n // Originals come from the construction-time pipeline, which\n // guarantees primitive-correctness. A rejected reset write\n // signals an invariant violation upstream.\n console.error(\n `[attaform] resetField: leaf write rejected for path '${targetKey}' — ` +\n `originals contain a value that doesn't satisfy the slim primitive shape. ` +\n `This is a bug in the construction pipeline.`\n )\n }\n } else {\n // Container case — reconstruct the subtree by walking originals for\n // every leaf whose path is a descendant of `targetSegments`. We assemble\n // the subtree first, then apply it in one setValueAtPath so diffAndApply\n // sees a single coherent replacement (rather than N mutations).\n //\n // The iteration reads `entry.segments` directly; the alternative\n // (JSON.parse on the Map key) both allocates and pays a parse cost per\n // entry even on cold paths.\n let subtree: unknown = undefined\n let anyMatch = false\n for (const [, entry] of originals) {\n const leafSegments = entry.segments\n if (!isPathPrefix(targetSegments, leafSegments)) continue\n if (leafSegments.length === targetSegments.length) continue // would have hit the leaf shortcut\n anyMatch = true\n const relative = leafSegments.slice(targetSegments.length)\n if (subtree === undefined) {\n // Seed root container type from the first relative segment. Numeric\n // index → array; string key → plain object. setAtPath will stay\n // consistent with that choice for the rest of the walk.\n subtree = typeof relative[0] === 'number' ? [] : {}\n }\n subtree = setAtPath(subtree, relative, entry.value)\n }\n if (anyMatch) {\n const wroteSubtree = setValueAtPath(targetSegments, subtree)\n if (!wroteSubtree) {\n console.error(\n `[attaform] resetField: subtree write rejected at path '${targetKey}' — ` +\n `originals contain values that don't satisfy the slim primitive shape. ` +\n `This is a bug in the construction pipeline.`\n )\n }\n }\n }\n\n // Cleanup runs regardless of whether storage was restored. Clears\n // errors and field-record flags for the target path AND every\n // descendant. `deleteErrorsUnderPrefix` covers the exact-path entry\n // too (an array is a prefix of itself), so a leaf reset clears the\n // single matching entry and a container reset sweeps the subtree.\n // Crucially, this also makes `resetField('')` a usable form-level-\n // error wipe: there's no storage at `''`, but errors do live there,\n // and a consumer who calls resetField on that path expects them\n // cleared. Same reasoning applies to consumer-set errors at any\n // path the schema doesn't model.\n deleteErrorsUnderPrefix(schemaErrors, targetSegments)\n deleteErrorsUnderPrefix(userErrors, targetSegments)\n for (const [fieldKey, record] of Array.from(fields.entries())) {\n if (isPathPrefix(targetSegments, record.path)) clearFieldRecordFlags(fieldKey)\n }\n }\n\n function deleteErrorsUnderPrefix(\n map: Map<PathKey, ValidationError[]>,\n prefix: readonly Segment[]\n ): void {\n for (const [errorKey, errs] of Array.from(map.entries())) {\n const first = errs[0]\n if (first === undefined) continue\n if (isPathPrefix(prefix, first.path as readonly Segment[])) {\n map.delete(errorKey)\n }\n }\n }\n\n function clearFieldRecordFlags(pathKey: PathKey): void {\n const record = fields.get(pathKey)\n if (record === undefined) return\n fields.set(pathKey, {\n path: record.path,\n updatedAt: new Date().toISOString(),\n connected: record.connected,\n focused: null,\n blurred: null,\n touched: null,\n })\n }\n\n /**\n * True iff `prefix` is a path-prefix of `candidate`. Equal arrays count as\n * a prefix (every array is a prefix of itself). Segment equality is strict\n * `===` — `'0'` and `0` are distinct here even though canonicalizePath\n * normalises them upstream; both paths always come from the same\n * canonicalisation so the check holds.\n */\n function isPathPrefix(prefix: readonly Segment[], candidate: readonly Segment[]): boolean {\n if (prefix.length > candidate.length) return false\n for (let i = 0; i < prefix.length; i++) {\n if (prefix[i] !== candidate[i]) return false\n }\n return true\n }\n\n // --- Derived ---\n\n function isPristineAtPath(path: Path): boolean {\n const { key, segments } = canonicalizePath(path)\n // Storage match is necessary but not sufficient: a primitive leaf\n // toggled between \"displayed empty\" (blank + slim default)\n // and \"explicitly the slim default\" carries the same storage value\n // but differs visually. Compare both surfaces against the originals\n // snapshot so the blank contract dirties when membership\n // diverges.\n if (blankPaths.has(key) !== originalBlankPaths.has(key)) return false\n const entry = originals.get(key)\n if (entry === undefined) return true\n return Object.is(getAtPath(form.value, segments), entry.value)\n }\n\n function getFieldRecord(path: Path): FieldRecord | undefined {\n const { key } = canonicalizePath(path)\n return fields.get(key)\n }\n\n function getOriginalAtPath(path: Path): unknown {\n const { key } = canonicalizePath(path)\n return originals.get(key)?.value\n }\n\n function getFirstErrorElement(\n formInstanceId: string\n ): { path: Path; element: HTMLElement } | null {\n // Single-pass DOM-order walk over every registered element. The\n // sort cache is rebuilt lazily on the first read after a register/\n // deregister; subsequent calls amortise to O(n) until the next\n // mutation.\n sortedRegistrationsCache ??= rebuildSortedRegistrations()\n\n for (const entry of sortedRegistrationsCache) {\n // Scope to this form instance — when two `useForm()` calls share\n // a key, both write into `elements`; this filter keeps each\n // form's submit from focusing the other's input.\n if (elementToFormInstance.get(entry.element) !== formInstanceId) continue\n\n // `el.isConnected` covers \"component was unmounted, element\n // removed from DOM\" cases that lag the FieldRecord.connected\n // flag. `el.offsetParent === null` catches `display:none` and\n // its ancestor chain — the browser won't focus or scroll to a\n // hidden element anyway, so we keep walking.\n if (!entry.element.isConnected) continue\n if (entry.element.offsetParent === null) continue\n\n const { key } = canonicalizePath(entry.path)\n const hasSchemaErr = (schemaErrors.get(key)?.length ?? 0) > 0\n const hasUserErr = (userErrors.get(key)?.length ?? 0) > 0\n if (!hasSchemaErr && !hasUserErr) continue\n\n return { path: entry.path, element: entry.element }\n }\n return null\n }\n\n function rebuildSortedRegistrations(): Array<{ path: Path; element: HTMLElement }> {\n const flat: Array<{ path: Path; element: HTMLElement }> = []\n for (const [, record] of elements) {\n for (const el of record.elements) flat.push({ path: record.path, element: el })\n }\n // `compareDocumentPosition` returns a bitmask. The\n // `DOCUMENT_POSITION_FOLLOWING` bit (0x04) is set when the argument\n // node FOLLOWS the receiver in document order, which means the\n // receiver comes first → return -1 to keep `a` before `b`.\n flat.sort((a, b) =>\n a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1\n )\n return flat\n }\n\n return {\n formKey,\n form,\n fields,\n elements,\n schemaErrors,\n userErrors,\n derivedBlankErrors,\n originals,\n schema,\n ssr,\n shouldShowErrors: resolvedShouldShowErrors,\n submitting,\n activeSubmissions,\n submitCount,\n submitError,\n submissionGeneration,\n activeValidations,\n firstValidationDone,\n pathHasAsyncValidation,\n fieldValidationCounts,\n\n applyFormReplacement,\n setValueAtPath,\n getValueAtPath,\n\n reset,\n resetField,\n\n setSchemaErrorsForPath,\n setAllSchemaErrors,\n clearSchemaErrors,\n setAllUserErrors,\n addUserErrors,\n clearUserErrors,\n getErrorsForPath,\n ensurePathOrdinal,\n\n registerElement,\n deregisterElement,\n markFocused,\n markTouched,\n touchAtPath,\n markConnectedOptimistically,\n\n isPristineAtPath,\n getFieldRecord,\n getOriginalAtPath,\n getFirstErrorElement,\n cancelFieldValidation,\n scheduleFieldValidation,\n onFormChange,\n onSubmitSuccess,\n onReset,\n emitSubmitSuccess,\n registerCleanup,\n registerDrain,\n awaitPendingWrites,\n modules,\n persistOptIns,\n isSensitivePath: resolvedIsSensitivePath,\n segmentMatchesSensitive: resolvedSegmentMatchesSensitive,\n noSyncPaths,\n incrementNoSyncOptOut,\n decrementNoSyncOptOut,\n coerceIndex,\n blankPaths,\n originalBlankPaths,\n dispose,\n }\n}\n\nexport type { Path, PathKey, Segment }\n","import type { AbstractSchema, FormKey } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\n\n/**\n * Per-form options threaded from `useForm` into the adapter factory.\n * Today carries the resolved `maxRecursionDepth` so adapter walks can\n * cap their descent through recursive schemas; future per-form runtime\n * knobs land here too.\n */\nexport interface SchemaFactoryOptions {\n /** Resolved recursion ceiling (per-form > app-default > library default). */\n maxRecursionDepth: number\n}\n\n/**\n * Accept schema as either a direct value or a factory function\n * `(key, options) => schema`. The factory form is documented but\n * rarely used — it exists for schemas that want to embed the formKey\n * or the resolved per-form options (e.g. `maxRecursionDepth`) into\n * their adapter instance.\n */\nexport function getComputedSchema<F extends GenericForm, GetValueFormType>(\n formKey: FormKey,\n schemaOrCallback:\n | AbstractSchema<F, GetValueFormType>\n | ((formKey: FormKey, options: SchemaFactoryOptions) => AbstractSchema<F, GetValueFormType>),\n options: SchemaFactoryOptions\n): AbstractSchema<F, GetValueFormType> {\n if (typeof schemaOrCallback === 'function') return schemaOrCallback(formKey, options)\n return schemaOrCallback\n}\n","import { computed, shallowRef, type ComputedRef } from 'vue'\nimport type { HistoryConfig, ValidationError, WriteMeta } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { DEFAULT_HISTORY_MAX_SNAPSHOTS, normalizeNumericOption } from './defaults'\nimport {\n applyPatchesForward,\n applyPatchesInverse,\n diffAndApply,\n structuralSnapshot,\n type Patch,\n} from './diff-apply'\nimport type { PathKey } from './paths'\n\n/**\n * Bounded undo/redo history for a FormStore, stored as one base\n * snapshot plus a linear chain of forward deltas. Subscribes to\n * `onFormChange` to record a `Delta` between the prior state and the\n * post-mutation state on every form change; `undo` walks the chain\n * backward by applying each delta in inverse, `redo` walks forward\n * by re-applying.\n *\n * Storage shape:\n * - `base` — full `HistorySnapshot<F>` at the oldest reachable\n * position. Initially the form's mount-time state. Advanced\n * forward when the chain exceeds the capacity cap (the oldest\n * delta is folded into `base` and dropped).\n * - `undoDeltas` — forward deltas from `base` up to the current\n * state. `undo()` consumes the tail; new mutations append.\n * - `redoDeltas` — forward deltas from the current state up to\n * redoable states. Populated by `undo()`; cleared by any fresh\n * mutation.\n * - `currentSnapshot` — materialised state at the current position.\n * Acts as the diff anchor for the next mutation (we diff against\n * this, not the live `state.form.value` ref, because the live\n * ref mutates in-place during `applyFormReplacement`).\n *\n * Each `Delta` carries:\n * - `formPatches` — `Patch[]` from `diffAndApply`. Each `changed`\n * patch holds BOTH `oldValue` and `newValue`, making the patch\n * list self-invertible — no separate inverse-diff storage needed.\n * - `blankPathsAdded` / `blankPathsRemoved` — symmetric set diff.\n * Forward applies removed-then-added; inverse swaps them.\n * - `schemaErrors` / `userErrors` — present only when the errors\n * changed between snapshots. Each carries before+after entry\n * snapshots so undo/redo can restore either side without\n * walking back through the chain.\n *\n * `reset()` is treated as an ordinary mutation: `applyFormReplacement`\n * fires `onFormChange`, the resulting delta lands on `undoDeltas`,\n * and the pre-reset state stays one undo away. Persistence hydration\n * (`meta.hydration === true`) is the floor — both delta arrays wipe\n * and `base` re-seeds from the post-hydration snapshot, so `undo()`\n * can't reach back into a pre-hydration default the consumer never\n * saw.\n *\n * Field record state (touched / focused / blurred / connected) is\n * deliberately NOT snapshotted. Those flags represent UI interaction\n * history and shouldn't rewind when the user hits undo — a field that\n * was touched stays touched.\n */\n\nexport type HistorySnapshot<F> = {\n readonly form: F\n readonly blankPaths: ReadonlyArray<PathKey>\n readonly schemaErrors: ReadonlyArray<readonly [PathKey, ValidationError[]]>\n readonly userErrors: ReadonlyArray<readonly [PathKey, ValidationError[]]>\n}\n\nexport type HistoryModule = {\n undo(): boolean\n redo(): boolean\n /**\n * Wipe both delta arrays and reseed `base` from the current state.\n * The form value, errors, and blankPaths all stay where they are —\n * only the undo/redo chain resets. After `clear()`: `canUndo = false`,\n * `canRedo = false`, `historySize = 1`. Semantically equivalent to\n * the internal hydration-floor behaviour, exposed for consumers who\n * want a hard wipe after a \"save successful\" milestone or similar.\n */\n clear(): void\n canUndo: Readonly<ComputedRef<boolean>>\n canRedo: Readonly<ComputedRef<boolean>>\n historySize: Readonly<ComputedRef<number>>\n dispose(): void\n}\n\ntype ErrorEntries = ReadonlyArray<readonly [PathKey, ValidationError[]]>\n\ntype Delta = {\n readonly formPatches: ReadonlyArray<Patch>\n readonly blankPathsAdded: ReadonlyArray<PathKey>\n readonly blankPathsRemoved: ReadonlyArray<PathKey>\n readonly schemaErrors?: { readonly before: ErrorEntries; readonly after: ErrorEntries }\n readonly userErrors?: { readonly before: ErrorEntries; readonly after: ErrorEntries }\n}\n\nfunction captureErrorEntries(map: Map<PathKey, ValidationError[]>): ErrorEntries {\n const out: Array<readonly [PathKey, ValidationError[]]> = []\n for (const [k, v] of map) out.push([k, [...v]] as const)\n return out\n}\n\nfunction errorsEqual(a: ErrorEntries, b: ErrorEntries): boolean {\n if (a.length !== b.length) return false\n const bMap = new Map<PathKey, ValidationError[]>()\n for (const [k, v] of b) bMap.set(k, v)\n for (const [k, v] of a) {\n const bv = bMap.get(k)\n if (bv === undefined) return false\n if (v.length !== bv.length) return false\n for (let i = 0; i < v.length; i++) {\n const av = v[i] as ValidationError\n const bvi = bv[i] as ValidationError\n // Identity-equal: ValidationError objects pass by reference through\n // the snapshot chain (not cloned), so most comparisons short-circuit\n // here. Fall back to field-by-field compare only on identity miss.\n if (av === bvi) continue\n if (av.message !== bvi.message) return false\n if (av.code !== bvi.code) return false\n if (av.formKey !== bvi.formKey) return false\n if (av.path !== bvi.path) {\n if (av.path.length !== bvi.path.length) return false\n for (let j = 0; j < av.path.length; j++) {\n if (av.path[j] !== bvi.path[j]) return false\n }\n }\n }\n }\n return true\n}\n\nfunction diffBlankPaths(\n prev: ReadonlySet<PathKey>,\n curr: ReadonlySet<PathKey>\n): { added: PathKey[]; removed: PathKey[] } {\n const added: PathKey[] = []\n const removed: PathKey[] = []\n for (const k of curr) if (!prev.has(k)) added.push(k)\n for (const k of prev) if (!curr.has(k)) removed.push(k)\n return { added, removed }\n}\n\nfunction applyDeltaForward<F>(snap: HistorySnapshot<F>, d: Delta): HistorySnapshot<F> {\n const nextForm = applyPatchesForward(snap.form, d.formPatches) as F\n const nextBlank = new Set(snap.blankPaths)\n for (const k of d.blankPathsRemoved) nextBlank.delete(k)\n for (const k of d.blankPathsAdded) nextBlank.add(k)\n return {\n form: nextForm,\n blankPaths: [...nextBlank],\n schemaErrors: d.schemaErrors !== undefined ? d.schemaErrors.after : snap.schemaErrors,\n userErrors: d.userErrors !== undefined ? d.userErrors.after : snap.userErrors,\n }\n}\n\nfunction applyDeltaInverse<F>(snap: HistorySnapshot<F>, d: Delta): HistorySnapshot<F> {\n const prevForm = applyPatchesInverse(snap.form, d.formPatches) as F\n const prevBlank = new Set(snap.blankPaths)\n for (const k of d.blankPathsAdded) prevBlank.delete(k)\n for (const k of d.blankPathsRemoved) prevBlank.add(k)\n return {\n form: prevForm,\n blankPaths: [...prevBlank],\n schemaErrors: d.schemaErrors !== undefined ? d.schemaErrors.before : snap.schemaErrors,\n userErrors: d.userErrors !== undefined ? d.userErrors.before : snap.userErrors,\n }\n}\n\nexport function createHistoryModule<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n config: HistoryConfig\n): HistoryModule {\n // Sanitise the capacity cap. `NaN` would make `total > max` always\n // false (unbounded memory growth); `Infinity` likewise; negatives\n // and non-integers produce confusing slice behaviour. Falls back to\n // the library default on garbage. `max: 0` is preserved — equivalent\n // in effect to disabling history (no undo/redo positions retained),\n // but consumers may set it explicitly.\n const max = normalizeNumericOption({\n value:\n typeof config === 'object'\n ? (config.max ?? DEFAULT_HISTORY_MAX_SNAPSHOTS)\n : DEFAULT_HISTORY_MAX_SNAPSHOTS,\n source: 'useForm.history.max',\n allowInfinity: false,\n min: 0,\n defaultValue: DEFAULT_HISTORY_MAX_SNAPSHOTS,\n })\n\n function captureSnapshot(): HistorySnapshot<F> {\n return {\n form: structuralSnapshot(state.form.value) as unknown as F,\n blankPaths: [...state.blankPaths],\n schemaErrors: captureErrorEntries(state.schemaErrors),\n userErrors: captureErrorEntries(state.userErrors),\n }\n }\n\n // shallowRef avoids Vue's UnwrapRef recursion: the snapshots / delta\n // arrays are replaced wholesale on every mutation (spread into a new\n // array), so deep reactivity would only add overhead and produce\n // weird typing around `HistorySnapshot<F>` (UnwrapRef<F> !== F for\n // generic constraints).\n const initial = captureSnapshot()\n const base = shallowRef<HistorySnapshot<F>>(initial)\n const currentSnapshot = shallowRef<HistorySnapshot<F>>(initial)\n const undoDeltas = shallowRef<Delta[]>([])\n const redoDeltas = shallowRef<Delta[]>([])\n\n // When `undo()` / `redo()` calls `applyFormReplacement`, the\n // resulting `onFormChange` must NOT record a new delta (that would\n // duplicate the restored state and break the chain ordering). This\n // flag suppresses the next change event.\n let suppressNext = false\n\n function appendDelta(delta: Delta, newCurrent: HistorySnapshot<F>): void {\n // max: 0 — no positions retained beyond `base`. Advance base\n // forward in lockstep with the mutation; never grow the undo chain.\n // canUndo / canRedo stay false. Equivalent in effect to history\n // disabled, but a legitimate explicit override.\n if (max === 0) {\n base.value = newCurrent\n currentSnapshot.value = newCurrent\n redoDeltas.value = []\n return\n }\n undoDeltas.value = [...undoDeltas.value, delta]\n redoDeltas.value = []\n currentSnapshot.value = newCurrent\n // Cap on TOTAL reachable positions (= 1 + undoDeltas + redoDeltas).\n // After a fresh push, redoDeltas is empty, so the cap is enforced\n // by folding the oldest undo delta into `base`. This matches the\n // FIFO-eviction semantics of the prior stack model (oldest position\n // dropped when capacity is exceeded).\n while (1 + undoDeltas.value.length > max && undoDeltas.value.length > 0) {\n const oldest = undoDeltas.value[0] as Delta\n base.value = applyDeltaForward(base.value, oldest)\n undoDeltas.value = undoDeltas.value.slice(1)\n }\n }\n\n const unsubscribeChange = state.onFormChange((_next, meta?: WriteMeta) => {\n if (suppressNext) {\n suppressNext = false\n return\n }\n // Persistence hydration is the floor: the transient pre-hydration\n // default (briefly held between mount and hydrate-apply) is library\n // plumbing, not state the user ever saw. Re-seed `base` from the\n // post-hydration snapshot and wipe both delta arrays so `undo()`\n // can't reach back into a state the consumer never produced. Any\n // in-flight mutations that landed in the race window between mount\n // and hydration are also dropped — pre-hydration writes were\n // operating against stale defaults anyway.\n if (meta?.hydration === true) {\n clear()\n return\n }\n // Cross-tab apply: a sibling tab's broadcast landed via the\n // multi-tab sync module. Refresh the diff anchor so the next\n // LOCAL mutation diffs against the post-cross-tab state (correct\n // patch contents), but DON'T push a delta — remote writes aren't\n // part of THIS user's undo timeline. Each tab's history walks\n // its own user's intent, not a sibling's.\n if (meta?.crossTab === true) {\n currentSnapshot.value = captureSnapshot()\n return\n }\n\n const newSnap = captureSnapshot()\n const prevSnap = currentSnapshot.value\n\n const formPatches: Patch[] = []\n diffAndApply(prevSnap.form, newSnap.form, [], (p) => formPatches.push(p))\n\n const prevBlankSet = new Set(prevSnap.blankPaths)\n const currBlankSet = new Set(newSnap.blankPaths)\n const blankDiff = diffBlankPaths(prevBlankSet, currBlankSet)\n\n const delta: Delta = {\n formPatches,\n blankPathsAdded: blankDiff.added,\n blankPathsRemoved: blankDiff.removed,\n ...(errorsEqual(prevSnap.schemaErrors, newSnap.schemaErrors)\n ? {}\n : { schemaErrors: { before: prevSnap.schemaErrors, after: newSnap.schemaErrors } }),\n ...(errorsEqual(prevSnap.userErrors, newSnap.userErrors)\n ? {}\n : { userErrors: { before: prevSnap.userErrors, after: newSnap.userErrors } }),\n }\n\n appendDelta(delta, newSnap)\n })\n\n function restoreCurrent(snap: HistorySnapshot<F>): void {\n suppressNext = true\n // Re-seed `blankPaths` BEFORE the form replacement fires. Listeners\n // on `onFormChange` (persistence's onFormChange tap, devtools, the\n // user's own subscriptions) read the form alongside `blankPaths`\n // when deciding what to persist or surface; updating both before\n // the listener loop runs keeps the pair consistent. If blankPaths\n // landed AFTER applyFormReplacement, the listeners would see new\n // form + stale blank set for one tick.\n state.blankPaths.clear()\n for (const key of snap.blankPaths) state.blankPaths.add(key)\n // Undo / redo replays a whole-form snapshot, so the persist decision\n // can't be made per-path. Rule: if the form has any opted-in path\n // at all, the rewind reaches the persistence layer (so the durable\n // record matches what the user just rolled back to). If nothing is\n // opted in, no write — matches the per-element default.\n state.applyFormReplacement(snap.form, {\n persist: !state.persistOptIns.isEmpty(),\n })\n // Rebuild both error stores from the snapshot. Each writer clears +\n // repopulates its own Map; the two sources stay isolated.\n const schemaFlat = snap.schemaErrors.flatMap(([, errs]) => errs)\n const userFlat = snap.userErrors.flatMap(([, errs]) => errs)\n state.setAllSchemaErrors(schemaFlat)\n state.setAllUserErrors(userFlat)\n }\n\n function undo(): boolean {\n if (undoDeltas.value.length === 0) return false\n const d = undoDeltas.value[undoDeltas.value.length - 1] as Delta\n const restored = applyDeltaInverse(currentSnapshot.value, d)\n redoDeltas.value = [...redoDeltas.value, d]\n undoDeltas.value = undoDeltas.value.slice(0, -1)\n currentSnapshot.value = restored\n restoreCurrent(restored)\n return true\n }\n\n function redo(): boolean {\n if (redoDeltas.value.length === 0) return false\n const d = redoDeltas.value[redoDeltas.value.length - 1] as Delta\n const next = applyDeltaForward(currentSnapshot.value, d)\n undoDeltas.value = [...undoDeltas.value, d]\n redoDeltas.value = redoDeltas.value.slice(0, -1)\n currentSnapshot.value = next\n restoreCurrent(next)\n return true\n }\n\n function clear(): void {\n const fresh = captureSnapshot()\n base.value = fresh\n currentSnapshot.value = fresh\n undoDeltas.value = []\n redoDeltas.value = []\n }\n\n const canUndo = computed(() => undoDeltas.value.length > 0)\n const canRedo = computed(() => redoDeltas.value.length > 0)\n const historySize = computed(() => 1 + undoDeltas.value.length + redoDeltas.value.length)\n\n return {\n undo,\n redo,\n clear,\n canUndo,\n canRedo,\n historySize,\n dispose() {\n unsubscribeChange()\n undoDeltas.value = []\n redoDeltas.value = []\n },\n }\n}\n","/**\n * Deterministic non-cryptographic string hash. Used to compact long\n * structural-fingerprint strings into bounded-size storage-key tokens\n * (`attaform:formKey:<hash>` instead of\n * `attaform:formKey:object{\"a\":string,\"b\":number,...}`).\n *\n * Output: 11-char base36 string with leading zeros padded —\n * stable size regardless of input. ~53 bits of entropy (base of the\n * cyrb53 algorithm); collision space is 2^53. For the storage-key\n * disambiguation use case (a single app's worth of form schemas, all\n * fingerprinted at runtime) this is overkill.\n *\n * Properties:\n * - **Deterministic**: same input always produces the same output.\n * - **Sync, no allocations beyond the result**: hot-path-friendly;\n * no `crypto.subtle` (async) or `node:crypto` (server-only).\n * - **Browser + Node compatible**: only `Math.imul` and `String`\n * methods.\n *\n * NOT suitable for security-sensitive uses (auth tokens, integrity\n * checks). cyrb53 is non-cryptographic by design.\n *\n * Reference: bryc's collection of small JS hash functions\n * (https://github.com/bryc/code/blob/master/jshash/PRNGs.md).\n */\nexport function hashStableString(input: string, seed = 0): string {\n let h1 = 0xdeadbeef ^ seed\n let h2 = 0x41c6ce57 ^ seed\n for (let i = 0; i < input.length; i++) {\n const ch = input.charCodeAt(i)\n h1 = Math.imul(h1 ^ ch, 2654435761)\n h2 = Math.imul(h2 ^ ch, 1597334677)\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)\n // Combine the two 32-bit halves into a 53-bit value, base36-encode.\n // `padStart(11, '0')` keeps the output a fixed length so storage\n // keys are visually aligned and easy to grep.\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36).padStart(11, '0')\n}\n","import type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { applyPatchesForward, diffAndApply, structuralSnapshot, type Patch } from './diff-apply'\nimport { canonicalizePath, type Path, type PathKey, type Segment } from './paths'\n\n/**\n * Cross-tab form-state synchronisation over a `BroadcastChannel`.\n *\n * **Identity model.** Two `useForm({ key, schema })` callsites in\n * same-origin tabs join the same channel by deriving its name from the\n * consumer-supplied `formKey` + the schema fingerprint. Tabs auto-pair\n * without an opt-in flag; the only switch is `multiTab: false` to\n * disable. Anonymous (auto-keyed) forms skip the module entirely (no\n * shared identity → no channel to join).\n *\n * **Handshake.** A joining tab posts `{kind: 'hello'}`. Every\n * established tab responds with `{kind: 'announce', senderId}` (UUID\n * only — cheap). The joining tab waits a short collection window\n * (~50ms), picks the lowest-sorted `senderId` as leader, and posts\n * `{kind: 'requestSnapshot', targetId: leaderId}`. Only the leader\n * replies with `{kind: 'snapshot', form, blankPaths}`. Bandwidth on\n * N-tab join is N tiny announces + 1 snapshot — vs. the naive\n * \"everyone responds with a full snapshot\" which would be O(N) full\n * snapshots.\n *\n * **Steady state.** Every local mutation fires an `onFormChange`\n * listener that diffs against a per-module prior snapshot and posts\n * `{kind: 'patches', formPatches, blankPathsAdded, blankPathsRemoved}`\n * over the channel. Receivers apply via `applyPatchesForward` +\n * `state.applyFormReplacement(merged, { crossTab: true, persist: false })`.\n *\n * **Defenses (see the recipe's Security section for the threat model).**\n * 1. **`senderId` echo drop.** Per-module UUID stamped on every\n * outbound message; receivers drop messages whose `senderId` ===\n * own. Handles intra-tab self-loops (two `useForm({key:'x'})` in\n * one tab) and any UA echo behaviour.\n * 2. **Protocol versioning.** Every message carries `v: 1`; receivers\n * drop unknown versions silently. Lets us evolve the wire format\n * without silently corrupting older tabs running stale bundles.\n * 3. **Sensitive-path filtering.** Outbound strips patches at paths\n * matching `options.isSensitivePath`; inbound REJECTS the same\n * paths (defense in depth — the wire is never trusted, even though\n * the originating tab \"should have\" stripped them).\n * 4. **Path-segment safety.** Inbound rejects patches containing\n * `__proto__` / `constructor` / `prototype` — prototype-pollution\n * defense before `applyPatchesForward` touches the form.\n * 5. **Post-apply schema validate + rollback.** After applying\n * surviving patches, the caller's `validateForm` callback runs; on\n * throw the entire message is dropped and the form state stays\n * where it was.\n * 6. **Per-register opt-out (`noSyncPaths`).** Paths the consumer\n * marked `register('x', { multiTab: false })` are stripped on\n * outbound AND rejected on inbound — symmetric tab-local\n * behaviour for selected fields.\n *\n * **History stays local.** Inbound applies set `meta.crossTab: true`;\n * the history listener updates its diff anchor but does NOT push a\n * delta. `undo()` walks the local user's intent, not a sibling tab's.\n */\n\nexport type MultiTabSyncModule = {\n /** Tear down the channel + outbound listener. */\n dispose(): void\n /**\n * Lifecycle observable for tests. `'joining'` during the\n * mount-time handshake collection window; `'established'` once a\n * snapshot has arrived (or the join timed out into solo-tab mode).\n */\n readonly lifecycle: () => 'joining' | 'established'\n /**\n * The module's UUID. Stamped on every outbound message; receivers\n * drop messages with their own `senderId`. Exposed for tests that\n * need to verify echo-drop or fabricate hostile messages.\n */\n readonly senderId: string\n /** The channel name this module is bound to. Exposed for tests. */\n readonly channelName: string\n}\n\nexport type MultiTabSyncOptions<F> = {\n /**\n * Sensitive-path predicate threaded from the FormStore. Patches at\n * matching paths are stripped from outbound AND rejected on inbound\n * — defense in depth.\n */\n readonly isSensitivePath: (path: Path | PathKey | string) => boolean\n /**\n * Per-register opt-out registry — paths the consumer marked\n * `{ multiTab: false }` are tab-local in BOTH directions. Empty by\n * default; populated by Phase 7's register hook.\n */\n readonly noSyncPaths: ReadonlySet<PathKey>\n /**\n * Post-apply schema validation. Called by the inbound handler on\n * the candidate form value AFTER patches apply but BEFORE the\n * candidate replaces live state. MUST throw on validation failure;\n * the inbound handler catches and rolls back.\n *\n * Adapter implementations should call\n * `state.schema.validateAtPath(form, undefined, { sync: true })` and\n * throw on any non-success-sync result (or skip validation entirely\n * for async-only schemas — see the recipe for rationale).\n */\n readonly validateForm: (form: F) => void\n}\n\n/** Wire-format version. Bumps require coordinated deploys. */\nconst PROTOCOL_VERSION = 1 as const\n\n/** Collection window for `announce` messages during the join flow. */\nconst JOIN_COLLECTION_WINDOW_MS = 50\n/** Timeout per `requestSnapshot` attempt before falling back to next-lowest leader. */\nconst SNAPSHOT_TIMEOUT_MS = 200\n/** Max retries for leader-election before giving up and proceeding solo. */\nconst MAX_LEADER_ATTEMPTS = 3\n\ntype SyncMessage<F> =\n | { readonly v: 1; readonly kind: 'hello'; readonly senderId: string }\n | { readonly v: 1; readonly kind: 'announce'; readonly senderId: string }\n | {\n readonly v: 1\n readonly kind: 'requestSnapshot'\n readonly senderId: string\n readonly targetId: string\n }\n | {\n readonly v: 1\n readonly kind: 'snapshot'\n readonly senderId: string\n readonly form: F\n readonly blankPaths: readonly PathKey[]\n }\n | {\n readonly v: 1\n readonly kind: 'patches'\n readonly senderId: string\n readonly formPatches: readonly Patch[]\n readonly blankPathsAdded: readonly PathKey[]\n readonly blankPathsRemoved: readonly PathKey[]\n }\n\ntype Lifecycle = 'joining' | 'established'\n\ntype SnapshotState<F> = {\n readonly form: F\n readonly blankPathsSnapshot: ReadonlyArray<PathKey>\n}\n\nfunction isDangerousSegment(s: Segment): boolean {\n return s === '__proto__' || s === 'constructor' || s === 'prototype'\n}\n\nfunction pathContainsDangerousSegment(path: Path): boolean {\n for (let i = 0; i < path.length; i++) {\n if (isDangerousSegment(path[i] as Segment)) return true\n }\n return false\n}\n\nfunction diffBlankPaths(\n prev: ReadonlyArray<PathKey>,\n curr: ReadonlySet<PathKey>\n): { added: PathKey[]; removed: PathKey[] } {\n const added: PathKey[] = []\n const removed: PathKey[] = []\n const prevSet = new Set<PathKey>(prev)\n for (const k of curr) if (!prevSet.has(k)) added.push(k)\n for (const k of prev) if (!curr.has(k)) removed.push(k)\n return { added, removed }\n}\n\nfunction snapshotForm<F>(form: F): F {\n // Reuse the same structural snapshot helper history uses. Walks\n // plain object + array spine, leaves non-descendable values\n // (BigInt, Date, Map, Set, class instances) by reference. This\n // is fine for the diff anchor — the immutable values are\n // reference-stable, and the in-place merge inside\n // `applyFormReplacement` mutates the spine, not the leaves.\n // BroadcastChannel's own `postMessage` uses `structuredClone` to\n // serialise the message, which natively handles BigInt / Date /\n // Map / Set, so sending the diff'd `Patch[]` over the wire works.\n return structuralSnapshot(form)\n}\n\n/**\n * Deep-clone `value` while substituting any leaf whose enclosing path\n * matches `isSensitivePath` with `undefined`. Used to scrub\n * snapshots before posting them — even on the originating tab, a\n * snapshot in response to `hello` should not carry sensitive values\n * to fresh-mount siblings.\n */\nfunction stripSensitivePathsDeep(\n value: unknown,\n pathSoFar: Path,\n isSensitivePath: (p: Path) => boolean\n): unknown {\n if (value === null || typeof value !== 'object') return value\n if (Array.isArray(value)) {\n return value.map((item, i) => stripSensitivePathsDeep(item, [...pathSoFar, i], isSensitivePath))\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return value\n const out: Record<string, unknown> = {}\n const src = value as Record<string, unknown>\n for (const key of Object.keys(src)) {\n const childPath = [...pathSoFar, key]\n if (isSensitivePath(childPath)) {\n out[key] = undefined\n continue\n }\n out[key] = stripSensitivePathsDeep(src[key], childPath, isSensitivePath)\n }\n return out\n}\n\n/**\n * Type-guard for incoming messages. Validates the structural shape\n * before dispatch so a hostile sender can't crash the listener with\n * garbage. Rejects messages missing `v` / `kind` / `senderId`.\n */\nfunction isValidSyncMessage(data: unknown): data is SyncMessage<unknown> {\n if (data === null || typeof data !== 'object') return false\n const m = data as Record<string, unknown>\n if (m['v'] !== PROTOCOL_VERSION) return false\n if (typeof m['senderId'] !== 'string') return false\n if (typeof m['kind'] !== 'string') return false\n switch (m['kind']) {\n case 'hello':\n case 'announce':\n return true\n case 'requestSnapshot':\n return typeof m['targetId'] === 'string'\n case 'snapshot':\n return Array.isArray(m['blankPaths']) && 'form' in m\n case 'patches':\n return (\n Array.isArray(m['formPatches']) &&\n Array.isArray(m['blankPathsAdded']) &&\n Array.isArray(m['blankPathsRemoved'])\n )\n default:\n return false\n }\n}\n\nfunction generateSenderId(): string {\n try {\n // Available in evergreen browsers and Node 19+. Library code calls\n // it elsewhere (e.g. instanceId allocation), so the dependency is\n // already on the runtime surface.\n return globalThis.crypto.randomUUID()\n } catch {\n // Pathological fallback for ancient environments — collision\n // resistance is reduced but the module still functions; same-tab\n // dedup is the only consumer of senderId equality and intra-tab\n // collisions are vanishingly unlikely.\n return `atta-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`\n }\n}\n\n/**\n * Construct a cross-tab sync module bound to `channelName`. Returns a\n * stub no-op module if `BroadcastChannel` is unavailable in the\n * runtime — callers should already have gated on availability +\n * `window.isSecureContext`, but the guard makes the module safe to\n * instantiate from any environment.\n */\nexport function createMultiTabSyncModule<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n channelName: string,\n options: MultiTabSyncOptions<F>\n): MultiTabSyncModule {\n if (typeof BroadcastChannel === 'undefined') {\n return {\n dispose: () => undefined,\n lifecycle: () => 'established',\n senderId: '',\n channelName,\n }\n }\n\n let channel: BroadcastChannel\n try {\n channel = new BroadcastChannel(channelName)\n } catch {\n return {\n dispose: () => undefined,\n lifecycle: () => 'established',\n senderId: '',\n channelName,\n }\n }\n\n const senderId = generateSenderId()\n let lifecycle: Lifecycle = 'joining'\n let disposed = false\n\n // Ephemeral roster for the join flow. Populated by `announce`\n // messages during the collection window; consumed by the leader\n // election. Cleared once the joining tab transitions to\n // `'established'` (no further use case for the set).\n const peerIds = new Set<string>()\n let joinCollectionTimer: ReturnType<typeof setTimeout> | null = null\n let snapshotTimeoutTimer: ReturnType<typeof setTimeout> | null = null\n let leaderAttempts = 0\n\n // Per-module prior anchor for outbound diffs. Refreshed after every\n // posted `patches` message AND after every accepted inbound apply\n // (so the next local diff is against post-apply state, not the\n // stale pre-apply form).\n let prior: SnapshotState<F> = {\n form: snapshotForm(state.form.value),\n blankPathsSnapshot: [...state.blankPaths],\n }\n\n function safePost(msg: SyncMessage<F>): void {\n if (disposed) return\n try {\n channel.postMessage(msg)\n } catch {\n // Channel closed under our feet (e.g., tab navigating away\n // while a postMessage queues). Drop silently.\n }\n }\n\n function refreshPrior(): void {\n prior = {\n form: snapshotForm(state.form.value),\n blankPathsSnapshot: [...state.blankPaths],\n }\n }\n\n function isPathLocallySuppressed(path: Path): boolean {\n if (pathContainsDangerousSegment(path)) return true\n if (options.isSensitivePath(path)) return true\n const { key } = canonicalizePath([...path])\n if (options.noSyncPaths.has(key)) return true\n return false\n }\n\n function postPatches(): void {\n if (lifecycle !== 'established') return\n const next = snapshotForm(state.form.value)\n const rawPatches: Patch[] = []\n diffAndApply(prior.form, next, [], (p) => rawPatches.push(p))\n const safePatches: Patch[] = []\n for (const p of rawPatches) {\n if (isPathLocallySuppressed(p.path)) continue\n safePatches.push(p)\n }\n const { added, removed } = diffBlankPaths(prior.blankPathsSnapshot, state.blankPaths)\n // Suppress noisy zero-delta posts (e.g., the form changed only at\n // a sensitive path — after filtering, nothing remains).\n if (safePatches.length === 0 && added.length === 0 && removed.length === 0) {\n prior = { form: next, blankPathsSnapshot: [...state.blankPaths] }\n return\n }\n safePost({\n v: PROTOCOL_VERSION,\n kind: 'patches',\n senderId,\n formPatches: safePatches,\n blankPathsAdded: added,\n blankPathsRemoved: removed,\n })\n prior = { form: next, blankPathsSnapshot: [...state.blankPaths] }\n }\n\n // Outbound: every local non-crossTab non-hydration mutation diffs\n // against `prior` and posts the resulting patches. Joining tabs\n // suppress their own outbound traffic until they're established —\n // otherwise they'd broadcast pre-handshake noise.\n const unsubscribeChange = state.onFormChange((_next, meta) => {\n if (disposed) return\n if (lifecycle !== 'established') return\n if (meta?.crossTab === true) return\n if (meta?.hydration === true) {\n // Hydration realigned local state; refresh the diff anchor\n // without posting. Siblings hydrate independently to the same\n // value, so channel traffic would be wasted.\n refreshPrior()\n return\n }\n postPatches()\n })\n\n function applyIncomingForm(form: F, blankPaths: ReadonlyArray<PathKey>): void {\n // Sync blank-paths set BEFORE applying the form value so the\n // resulting `onFormChange` emission sees a coherent (form,\n // blankPaths) pair. Listeners that read both during a single\n // microtick (history, persistence, devtools) wouldn't observe\n // mid-update divergence.\n state.blankPaths.clear()\n for (const k of blankPaths) state.blankPaths.add(k)\n state.applyFormReplacement(form, { crossTab: true, persist: false })\n refreshPrior()\n }\n\n function handlePatches(msg: SyncMessage<F> & { kind: 'patches' }): void {\n if (lifecycle !== 'established') return\n const safePatches: Patch[] = []\n for (const p of msg.formPatches) {\n if (!Array.isArray(p.path)) continue\n if (isPathLocallySuppressed(p.path)) continue\n safePatches.push(p)\n }\n // Filter blank-path deltas with the same predicate. A sensitive\n // blank-path key shouldn't leak via the membership signal either.\n const safeBlankAdded: PathKey[] = []\n for (const k of msg.blankPathsAdded) {\n const segs = canonicalizePath(k).segments\n if (isPathLocallySuppressed(segs)) continue\n safeBlankAdded.push(k)\n }\n const safeBlankRemoved: PathKey[] = []\n for (const k of msg.blankPathsRemoved) {\n const segs = canonicalizePath(k).segments\n if (isPathLocallySuppressed(segs)) continue\n safeBlankRemoved.push(k)\n }\n if (safePatches.length === 0 && safeBlankAdded.length === 0 && safeBlankRemoved.length === 0) {\n return\n }\n const candidate = applyPatchesForward(state.form.value, safePatches) as F\n // Post-apply schema validation runs ONLY if the pre-apply form\n // was already valid — otherwise a form that mounts in an\n // intentionally-invalid state (empty defaults that violate\n // refinements, mid-edit field-array seeds) would reject every\n // remote update. The local `validateOn` cycle surfaces any\n // resulting errors on the receiver normally.\n try {\n options.validateForm(state.form.value)\n try {\n options.validateForm(candidate)\n } catch {\n // Patches would have invalidated a previously-valid form —\n // rollback. The originating tab's mutation is dropped on\n // this receiver; last-writer-wins re-converges on the next\n // valid mutation.\n return\n }\n } catch {\n // Pre-apply form was already invalid; skip post-validation\n // (no new attack surface — the form was already in an invalid\n // state from the user's POV, the local validate cycle\n // surfaces errors regardless of where the data came from).\n }\n const nextBlankPaths = new Set(state.blankPaths)\n for (const k of safeBlankRemoved) nextBlankPaths.delete(k)\n for (const k of safeBlankAdded) nextBlankPaths.add(k)\n applyIncomingForm(candidate, [...nextBlankPaths])\n }\n\n function handleSnapshot(msg: SyncMessage<F> & { kind: 'snapshot' }): void {\n if (lifecycle !== 'joining') return\n try {\n options.validateForm(msg.form)\n } catch {\n // Leader sent a snapshot we can't accept; remain in 'joining'\n // and let the retry/timeout flow elect a different leader.\n return\n }\n if (snapshotTimeoutTimer !== null) {\n clearTimeout(snapshotTimeoutTimer)\n snapshotTimeoutTimer = null\n }\n if (joinCollectionTimer !== null) {\n clearTimeout(joinCollectionTimer)\n joinCollectionTimer = null\n }\n applyIncomingForm(msg.form, msg.blankPaths)\n lifecycle = 'established'\n peerIds.clear()\n }\n\n function respondToHello(): void {\n safePost({ v: PROTOCOL_VERSION, kind: 'announce', senderId })\n }\n\n function respondToSnapshotRequest(): void {\n const scrubbedForm = stripSensitivePathsDeep(state.form.value, [], options.isSensitivePath) as F\n safePost({\n v: PROTOCOL_VERSION,\n kind: 'snapshot',\n senderId,\n form: scrubbedForm,\n blankPaths: [...state.blankPaths],\n })\n }\n\n channel.onmessage = (event: MessageEvent): void => {\n if (disposed) return\n const data = event.data\n if (!isValidSyncMessage(data)) return\n const msg = data as SyncMessage<F>\n // Echo drop — own messages NEVER apply (intra-tab self-loop +\n // any UA echo behaviour).\n if (msg.senderId === senderId) return\n switch (msg.kind) {\n case 'hello':\n if (lifecycle !== 'established') return\n respondToHello()\n break\n case 'announce':\n if (lifecycle === 'joining') peerIds.add(msg.senderId)\n break\n case 'requestSnapshot':\n if (lifecycle !== 'established') return\n if (msg.targetId !== senderId) return\n respondToSnapshotRequest()\n break\n case 'snapshot':\n handleSnapshot(msg)\n break\n case 'patches':\n handlePatches(msg)\n break\n }\n }\n\n function electLeaderAndRequest(): void {\n if (disposed) return\n if (peerIds.size === 0) {\n // No siblings answered — proceed solo. Local hydration/defaults\n // become this tab's baseline.\n lifecycle = 'established'\n refreshPrior()\n return\n }\n const sorted = [...peerIds].sort()\n const leaderId = sorted[0] as string\n peerIds.delete(leaderId)\n leaderAttempts++\n safePost({\n v: PROTOCOL_VERSION,\n kind: 'requestSnapshot',\n senderId,\n targetId: leaderId,\n })\n snapshotTimeoutTimer = setTimeout(() => {\n snapshotTimeoutTimer = null\n if (disposed) return\n if (lifecycle === 'established') return\n if (leaderAttempts >= MAX_LEADER_ATTEMPTS || peerIds.size === 0) {\n // Out of retries / out of candidates — fall back to solo.\n lifecycle = 'established'\n refreshPrior()\n return\n }\n electLeaderAndRequest()\n }, SNAPSHOT_TIMEOUT_MS)\n }\n\n function joinFlow(): void {\n safePost({ v: PROTOCOL_VERSION, kind: 'hello', senderId })\n joinCollectionTimer = setTimeout(() => {\n joinCollectionTimer = null\n if (disposed) return\n if (lifecycle === 'established') return\n electLeaderAndRequest()\n }, JOIN_COLLECTION_WINDOW_MS)\n }\n\n joinFlow()\n\n return {\n dispose: () => {\n if (disposed) return\n disposed = true\n if (joinCollectionTimer !== null) {\n clearTimeout(joinCollectionTimer)\n joinCollectionTimer = null\n }\n if (snapshotTimeoutTimer !== null) {\n clearTimeout(snapshotTimeoutTimer)\n snapshotTimeoutTimer = null\n }\n unsubscribeChange()\n try {\n channel.close()\n } catch {\n // No-op — close failures are non-recoverable.\n }\n },\n lifecycle: () => lifecycle,\n senderId,\n channelName,\n }\n}\n\n/** Shared module-cache key used by `state.modules.set/get`. */\nexport const MULTI_TAB_SYNC_MODULE_KEY = 'multiTabSync'\n","import { __DEV__ } from './dev'\n\n/**\n * Feature identifiers for one-shot secure-context dev warnings. Each\n * unique key emits at most one warning per app-load — the multi-tab\n * sync module and the built-in persistence storage adapters use this\n * to surface \"this feature noop'd because you're on plain HTTP\"\n * without spamming the console once per form mount.\n *\n * See the multi-tab-sync recipe's Security section for the rationale\n * — the gate matches `window.isSecureContext`, which is `true` for\n * HTTPS in production AND localhost in development. Plain HTTP on a\n * real hostname noops with this warning.\n */\nexport type InsecureContextFeature = 'multiTab' | 'persist:local' | 'persist:session'\n\nconst warned = new Set<InsecureContextFeature>()\n\n/**\n * Emit a one-shot console warning when a security-gated feature\n * would have instantiated but `window.isSecureContext === false`.\n * No-op in production builds.\n */\nexport function warnOnceInsecureContext(feature: InsecureContextFeature): void {\n if (!__DEV__) return\n if (warned.has(feature)) return\n warned.add(feature)\n const message = featureMessage(feature)\n console.warn(`[attaform] ${message}`)\n}\n\nfunction featureMessage(feature: InsecureContextFeature): string {\n switch (feature) {\n case 'multiTab':\n return (\n 'Multi-tab sync requires a secure context (HTTPS or localhost). ' +\n 'Plain HTTP on a real hostname is interceptable by network observers, ' +\n 'so the sync module is disabled. Serve over HTTPS in production ' +\n '(or develop on `localhost`) to enable cross-tab synchronisation. ' +\n 'Use `multiTab: false` on `useForm` to silence this warning.'\n )\n case 'persist:local':\n return (\n \"Built-in `persist: 'local'` storage requires a secure context \" +\n '(HTTPS or localhost). Plain HTTP on a real hostname is ' +\n 'MITM-interceptable, so the persistence layer is disabled. ' +\n 'Serve over HTTPS to enable localStorage persistence, or pass a ' +\n 'custom storage adapter to opt out of the secure-context gate.'\n )\n case 'persist:session':\n return (\n \"Built-in `persist: 'session'` storage requires a secure context \" +\n '(HTTPS or localhost). Plain HTTP on a real hostname is ' +\n 'MITM-interceptable, so the persistence layer is disabled. ' +\n 'Serve over HTTPS to enable sessionStorage persistence, or pass a ' +\n 'custom storage adapter to opt out of the secure-context gate.'\n )\n }\n}\n\n/**\n * Test-only helper: reset the one-shot dedup so subsequent\n * `warnOnceInsecureContext` calls fire fresh. Probes that assert\n * \"warning fires exactly once across many mounts\" need to drain\n * state between scenarios.\n */\nexport function resetInsecureContextWarnDedup(): void {\n warned.clear()\n}\n\n/**\n * Cross-runtime `isSecureContext` probe. Returns `true` when the\n * runtime supports secure-context detection AND the page is in one\n * (HTTPS or localhost). Returns `false` otherwise. SSR (where\n * `window` is undefined) returns `false` — multi-tab sync and\n * built-in persistence are client-only by design.\n */\nexport function isSecureContext(): boolean {\n return typeof window !== 'undefined' && window.isSecureContext === true\n}\n","import { getCurrentInstance, getCurrentScope, onScopeDispose, provide, toRaw, useId } from 'vue'\nimport { buildFormApi } from '../core/build-form-api'\nimport { createFormStore, type FormStore } from '../core/create-form-store'\nimport {\n ANONYMOUS_FORM_KEY_PREFIX,\n DEFAULT_MAX_RECURSION_DEPTH,\n DEFAULT_PERSISTENCE_DEBOUNCE_MS,\n normalizeNumericOption,\n PERSISTENCE_KEY_PREFIX,\n RESERVED_KEY_PREFIX,\n} from '../core/defaults'\nimport { __DEV__ } from '../core/dev'\nimport { captureUserCallSite } from '../core/dev-stack-trace'\nimport { AnonPersistError, InvalidUseFormConfigError, ReservedFormKeyError } from '../core/errors'\nimport { extractSchemaFields } from '../core/extract-schema-fields'\nimport type { FieldState } from '../core/field-state-api'\nimport { getComputedSchema } from '../core/get-computed-schema'\nimport { createHistoryModule, type HistoryModule } from '../core/history'\nimport {\n buildPersistedPayload,\n cleanupOrphanKeys,\n createDebouncedWriter,\n filterErrorsByPaths,\n getStorageAdapter,\n mergeSparseHydration,\n normalizePersistConfig,\n PERSISTENCE_MODULE_KEY,\n pluckPaths,\n readPersistedPayload,\n resolveStorageKeyBase,\n sweepAllOrphansAcrossStandardStores,\n sweepNonConfiguredStandardStoresForOrphans,\n type PersistenceModule,\n} from '../core/persistence'\nimport {\n createIsSensitivePath,\n createSegmentMatchesSensitive,\n} from '../core/persistence/sensitive-names'\nimport { hashStableString } from '../core/hash'\nimport { createMultiTabSyncModule, MULTI_TAB_SYNC_MODULE_KEY } from '../core/multi-tab-sync'\nimport { isSecureContext, warnOnceInsecureContext } from '../core/insecure-context-warn'\nimport { canonicalizePath, type Path, type PathKey } from '../core/paths'\nimport { deleteAtPath, getAtPath, setAtPath, isPlainRecord } from '../core/path-walker'\nimport { ensureAttaformInstalled } from '../core/plugin'\nimport { kFormContext, kFormInstanceId, useRegistry } from '../core/registry'\nimport { resolveShouldShowErrors } from '../core/should-show-errors'\nimport { walkUnsetSentinels } from '../core/unset-walker'\nimport type {\n AbstractSchema,\n AttaformDefaults,\n FormKey,\n PersistConfig,\n PersistConfigOptions,\n UseFormReturnType,\n UseFormConfiguration,\n ValidationError,\n} from '../types/types-api'\nimport type { DeepPartial, DefaultValuesShape, GenericForm, WriteShape } from '../types/types-core'\n\n/**\n * Schema-agnostic `useForm`. Accepts any object that implements\n * `AbstractSchema` — useful when integrating a custom schema\n * adapter or a third-party validation library.\n *\n * ```ts\n * import { useForm } from 'attaform'\n *\n * const form = useForm({\n * schema: myCustomAdapter,\n * defaultValues: { name: '' },\n * })\n * ```\n *\n * Most consumers prefer a typed entry point that wraps the underlying\n * library's schema with the matching adapter automatically; see the\n * subpath documentation for the available adapters.\n *\n * Returns the same form API as the typed entry points; see\n * `UseFormReturnType` for the full surface.\n */\n\nexport function useAbstractForm<\n Form extends GenericForm,\n GetValueFormType extends GenericForm = Form,\n>(\n configuration: UseFormConfiguration<\n Form,\n GetValueFormType,\n AbstractSchema<Form, GetValueFormType>,\n DeepPartial<DefaultValuesShape<Form>>\n >\n): UseFormReturnType<Form, GetValueFormType> {\n // Foot-gun guard: catches `useForm()` (no args), `useForm(null)`,\n // `useForm(rawSchema)` (any schema-like object passed as the first\n // argument — its `.schema` field is undefined), and the explicit\n // `useForm({ schema: undefined })` case. Throws synchronously\n // before any downstream code reads `configuration.schema`.\n if (\n configuration === undefined ||\n configuration === null ||\n (configuration as { schema?: unknown }).schema === undefined\n ) {\n throw new InvalidUseFormConfigError()\n }\n\n const key = resolveFormKey(configuration.key)\n\n // One FormStore per (app, formKey). Multiple useForm calls with the same\n // key resolve to the same instance — that's the shared-store semantic\n // for forms that explicitly opt in to a stable key.\n //\n // Lazy-install: if the consumer hasn't called `createAttaform()`,\n // attach the registry now. Idempotent — explicit installs (Nuxt\n // module, manual `app.use(createAttaform({ defaults }))`) win when\n // they ran first. The strict `useRegistry()` below still throws\n // `OutsideSetupError` when called outside setup; the lazy install\n // only ever fires when an instance is available.\n const instance = getCurrentInstance()\n if (instance !== null) ensureAttaformInstalled(instance.appContext.app)\n const registry = useRegistry()\n\n // Merge app-level defaults from the registry over per-form options.\n // Per-form values always win for scalars; `validateOn` and `debounceMs`\n // resolve independently so consumers can set `debounceMs` globally\n // and override `validateOn` per-form. Every downstream read uses\n // `merged` so the merge happens exactly once. Runs BEFORE schema\n // resolution so the merged `maxRecursionDepth` can thread into the\n // adapter factory.\n const merged = mergeWithDefaults(registry.defaults, configuration)\n\n // Resolve the schema (accepts either an AbstractSchema or a factory).\n // Preserve both generics — dropping `GetValueFormType` here would make\n // `state.schema.getSchemasAtPath(...)` return `AbstractSchema<_, Form>[]`\n // for consumers whose schema intentionally produces a different runtime\n // shape (e.g. an adapter that narrows via a transform). The factory\n // receives the resolved per-form options (`maxRecursionDepth`) so the\n // adapter can bake them into its walk closures.\n //\n // Sanitise the consumer-supplied value: `NaN` / `-Infinity` /\n // non-numbers fall back to the library default with a dev-warn;\n // negatives clamp to 0; non-integers floor; `Infinity` is allowed\n // (disables the cap). The adapter's `>=` comparisons assume integer\n // depth, so the normalisation prevents footguns at the boundary.\n const maxRecursionDepth = normalizeNumericOption({\n value: merged.maxRecursionDepth ?? DEFAULT_MAX_RECURSION_DEPTH,\n source: 'useForm.maxRecursionDepth',\n allowInfinity: true,\n min: 0,\n defaultValue: DEFAULT_MAX_RECURSION_DEPTH,\n })\n const resolvedSchema = getComputedSchema(key, configuration.schema, { maxRecursionDepth })\n\n // Eager throw: persistence configured without an explicit `key:`. An\n // anonymous synthetic key (`__atta:anon:*`) drifts across mounts (HMR /\n // route changes / SSR↔CSR) and can collide between unrelated forms —\n // refusing here keeps the namespace stable and forecloses on the\n // future encrypted-backend case where collision becomes a key-derivation\n // overlap. Throws in dev and prod alike. The error body carries the\n // schema's top-level fields and a captured call-site so the offender\n // is identifiable from the message alone.\n if (configuration.persist !== undefined && configuration.key === undefined) {\n throw new AnonPersistError({\n cause: 'no-key',\n schemaFields: extractSchemaFields(resolvedSchema),\n callSite: captureUserCallSite(),\n })\n }\n\n const existing = registry.forms.get(key) as FormStore<Form, GetValueFormType> | undefined\n if (__DEV__ && existing !== undefined) {\n // Shared-key semantics are a feature when consumers OPT in to them\n // (two `useForm({ key: 'x' })` calls that genuinely want the same\n // store). They're a silent-collision footgun when two unrelated\n // parts of an app happen to agree on a key. Fingerprinting the\n // schema turns collision into a diagnosable warning: if the\n // second call's schema has a different structural fingerprint\n // than the first's, the forms almost certainly shouldn't be\n // sharing. The second call's schema is then silently dropped in\n // favour of the first's — matching what already happens (only\n // the first caller's config wires the FormStore).\n warnOnSchemaFingerprintMismatch(key, existing.schema, resolvedSchema)\n // Persist is a single-IO-channel concern (one storage key, one\n // debounce timer, one subscription). The first useForm call wires\n // it; subsequent calls' `persist:` configurations are silently\n // dropped. When the second caller passes a DIFFERENT persist\n // config, that drop is a footgun: modal-team dev configures\n // `'session'`, finds nothing in sessionStorage, debugs for an hour\n // — the main-form team wired `'local'` first. Surface the divergence\n // as a dev-warn so the surprise is explicit. `validateOn` /\n // `debounceMs` / `coerce` / `rememberVariants` / `shouldShowErrors`\n // are now per-instance, so they don't need this guard;\n // `defaultValues` is intentionally first-wins (the live store\n // state is what the modal should see); `strict` is construction-\n // only and the seed has already fired.\n warnOnPersistDivergence(key, existing, configuration.persist)\n }\n const state: FormStore<Form, GetValueFormType> =\n existing ?? buildFreshState<Form, GetValueFormType>(key, resolvedSchema, merged, registry)\n\n // Ref-count this consumer. When the component's effect scope tears down,\n // release the count; the registry evicts the FormStore once the last\n // consumer disposes. Guarded on `getCurrentScope()` so callers without an\n // effect-scope context (defensive — setup() always provides one) don't\n // leak a pinned consumer. See registry.trackConsumer for the counter.\n if (getCurrentScope() !== undefined) {\n const releaseConsumer = registry.trackConsumer(key)\n onScopeDispose(releaseConsumer)\n }\n\n // Wire persistence (opt-in) — only on fresh state creation, skipped\n // on SSR. `existing` means a prior useForm() already mounted and\n // wired persistence; we don't double-subscribe. The handle is cached\n // on `state.modules` so `buildFormApi` can plug `form.persist` /\n // `form.clearPersistedDraft` into the consumer-facing API. The\n // disposer is registered on the FormStore (not on this consumer's\n // scope) so persistence survives any single consumer unmounting — it\n // tears down only when the last consumer releases and the registry\n // evicts the state.\n //\n // The shorthand input (`persist: 'local'`, `persist: customAdapter`)\n // is normalised to the resolved options bag once at this boundary —\n // Anonymous + persist enforcement. Dev throws (catches the bug at\n // the offending useForm() call); prod returns `true` so the wiring\n // block below skips entirely AND cleans up any prior persisted\n // entries — we'd rather pretend persist wasn't configured than\n // silently mis-route data between forms that happened to share an\n // anon id. Runs regardless of SSR / first-mount-vs-rehook so the\n // dev-mode throw fires on the SSR pass too (without a server-side\n // throw, the SSR pass would succeed silently and the client would\n // throw on hydration — that surfaces as a confusing hydration\n // mismatch instead of pointing at the actual config bug).\n const persistDisabledByAnonRule =\n merged.persist !== undefined && enforceAnonPersistRule(state.formKey, registry.ssr)\n // everything below operates on the resolved shape.\n if (existing === undefined && !registry.ssr) {\n if (merged.persist !== undefined && !persistDisabledByAnonRule) {\n const resolvedPersist = normalizePersistConfig(merged.persist)\n // Secure-context gate for BUILT-IN storage adapters. Plain HTTP\n // on a real hostname leaves localStorage / sessionStorage open\n // to MITM injection — same threat profile as multi-tab sync. The\n // gate noops the persistence wiring entirely with a one-shot\n // dev warning. Custom storage adapters (consumer-supplied\n // objects) bypass the gate — the consumer owns that storage\n // layer's security posture (could be encrypted, server-side,\n // behind a tunnel, etc.).\n const storageKind = resolvedPersist.storage\n const isBuiltinStorage = typeof storageKind === 'string'\n const secureContextOk = !isBuiltinStorage || isSecureContext()\n if (!secureContextOk) {\n const feature: 'persist:local' | 'persist:session' =\n storageKind === 'session' ? 'persist:session' : 'persist:local'\n warnOnceInsecureContext(feature)\n void sweepAllOrphansAcrossStandardStores(`${PERSISTENCE_KEY_PREFIX}${state.formKey}`)\n } else {\n const persistenceBase = resolveStorageKeyBase(resolvedPersist, state.formKey)\n // Cross-store orphan cleanup: any standard backend not matching\n // the configured one gets every attaform-managed key under the\n // base wiped (unfingerprinted AND stale-fingerprint alike).\n // Ensures stale drafts can't survive in stores the dev migrated\n // AWAY from. Fire-and-forget; backend unavailability is silent.\n void sweepNonConfiguredStandardStoresForOrphans(resolvedPersist.storage, persistenceBase)\n const persistenceModule = wirePersistence(state, resolvedPersist)\n state.modules.set(PERSISTENCE_MODULE_KEY, persistenceModule)\n // Drain BEFORE the synchronous teardown: the registry will await\n // `awaitPendingWrites` before calling `dispose`, so the last\n // debounced keystroke gets to disk before the FormStore is\n // evicted from the registry's `forms` map.\n state.registerDrain(() => persistenceModule.awaitPendingWrites())\n state.registerCleanup(() => persistenceModule.dispose())\n }\n } else {\n // Either the dev didn't configure `persist:` OR we just disabled\n // it via the anon-persist rule. Either way, sweep every\n // attaform-managed key under this form's base across all standard\n // backends so dropping (or refusing to wire) persistence\n // actually leaves storage clean.\n void sweepAllOrphansAcrossStandardStores(`${PERSISTENCE_KEY_PREFIX}${state.formKey}`)\n }\n }\n\n // Wire multi-tab sync. Fresh-state-only — the module subscribes\n // to FormStore events, so subscribing twice would double-broadcast.\n // Registers AFTER persistence (so persistence hydration is the floor\n // — when a BroadcastChannel snapshot arrives, it overrides the\n // disk-persisted baseline) and BEFORE history (so the crossTab-meta\n // history-listener guard is in place by the time the first incoming\n // message lands).\n //\n // Activation requires ALL of:\n // 1. `multiTab` cascade resolves to !== false (per-form > global > library default `true`)\n // 2. Consumer-supplied `key` (anonymous forms skip — channel would be solo)\n // 3. Runtime has `BroadcastChannel`\n // 4. `window.isSecureContext === true` (HTTPS or localhost)\n //\n // The else branch fires a one-shot dev warning when a keyed form\n // requested sync but the secure-context gate blocked it — saves\n // consumers from debugging \"why isn't sync working in prod\" in\n // silence.\n if (\n existing === undefined &&\n merged.multiTab !== false &&\n configuration.key !== undefined &&\n !registry.ssr\n ) {\n const hasBroadcastChannel = typeof BroadcastChannel !== 'undefined'\n const secureContext = isSecureContext()\n if (hasBroadcastChannel && secureContext) {\n // Channel name = `attaform:sync:${formKey}:${fingerprint hash}`.\n // Wrap the fingerprint read so an adapter bug throwing here\n // doesn't poison the rest of the form lifecycle — the sync\n // module just skips instantiation. The schema-fingerprint\n // mismatch warning surfaces the underlying adapter issue\n // separately.\n let channelName: string | null\n try {\n channelName = `attaform:sync:${state.formKey}:${hashStableString(state.schema.fingerprint())}`\n } catch {\n channelName = null\n }\n if (channelName !== null) {\n const syncModule = createMultiTabSyncModule(state, channelName, {\n isSensitivePath: state.isSensitivePath,\n noSyncPaths: state.noSyncPaths,\n validateForm: (form) => {\n // Sync-preferred schema validation. Async-only schemas\n // return a Promise — for those we skip the gate and trust\n // the patch (last-writer-wins; local validate cycle catches\n // issues on next user interaction).\n const result = state.schema.validateAtPath(form, undefined, { sync: true })\n if (result instanceof Promise) return\n if (!result.success) {\n throw new Error('attaform multi-tab sync: post-apply schema validation failed')\n }\n },\n })\n state.modules.set(MULTI_TAB_SYNC_MODULE_KEY, syncModule)\n state.registerCleanup(() => syncModule.dispose())\n }\n } else if (hasBroadcastChannel && !secureContext) {\n warnOnceInsecureContext('multiTab')\n }\n }\n\n // Wire history (opt-in). Fresh-state-only — the module subscribes\n // to FormStore events, so subscribing twice would double-push\n // snapshots. Cache the module on the FormStore so subsequent\n // `useForm` / `injectForm` calls for the same key retrieve the\n // SAME instance, keeping `canUndo` / `canRedo` / `historySize` /\n // `undo` / `redo` consistent across mount order.\n if (existing === undefined && merged.history !== undefined) {\n const historyModule = createHistoryModule(state, merged.history)\n state.modules.set(HISTORY_MODULE_KEY, historyModule)\n state.registerCleanup(() => historyModule.dispose())\n }\n\n // Provide the FormStore to descendants via `kFormContext` so\n // `injectForm()` can resolve it without prop-threading.\n //\n // ONLY anonymous `useForm()` calls fill the ambient slot. Keyed forms\n // are explicitly addressable via `injectForm<F>(key)` and don't\n // pollute the ambient context — keeping the two resolution modes\n // semantically distinct. A descendant of a keyed-only parent that\n // calls `injectForm<F>()` (no key) gets the \"no ambient form\"\n // throw, which is the right error: the form has a name; address it.\n //\n // Ambient mode is still \"last-provide wins\" among siblings: if two\n // anonymous `useForm()` calls run in the same component, the second\n // overwrites the first and descendants only see the second. We record\n // the per-instance history of ANONYMOUS provides here (silently) so\n // that a descendant's `injectForm<F>()` call can walk up, detect\n // the collision, and warn lazily. Recording is skipped on SSR so the\n // client-side warn fires once, not once-per-render-pass.\n if (configuration.key === undefined) {\n recordAmbientProvide(registry.ssr)\n provide(kFormContext, state as FormStore<GenericForm>)\n }\n\n // Per-`useForm()`-call instance ID. Distinct from `state.formKey`:\n // the key identifies a SHARED FormStore (so two `useForm({ key:\n // 'signup' })` calls return the same store), while `formInstanceId`\n // identifies THIS specific callsite — important for `focusFirstError`\n // / `scrollToFirstError` to scope to the elements THIS caller's\n // `v-register` directives bound to. SSR-safe via Vue 3.5+'s\n // `useId()`. Outside Vue setup (tests, ad-hoc composable use) we\n // fall back to a module-local counter — uniqueness is what matters,\n // and tests don't share form-instance state across mounts anyway.\n const formInstanceId =\n getCurrentInstance() !== null ? useId() : `atta:form-instance:${formInstanceCounter++}`\n // Provided so descendants reaching via `injectForm()` inherit this ID\n // and their locally-registered elements tag against the same instance.\n // Sibling `useForm()` calls (different tree positions) provide their\n // own IDs and stay isolated.\n if (getCurrentInstance() !== null) {\n provide(kFormInstanceId, formInstanceId)\n }\n\n const apiOptions: Parameters<typeof buildFormApi<Form, GetValueFormType>>[2] = {}\n if (merged.onInvalidSubmit !== undefined) {\n apiOptions.onInvalidSubmit = merged.onInvalidSubmit\n }\n const history = state.modules.get(HISTORY_MODULE_KEY) as HistoryModule | undefined\n if (history !== undefined) {\n apiOptions.history = history\n }\n // Per-instance config lifts: each `useForm()` callsite carries its\n // own `validateOn` / `debounceMs` / `shouldShowErrors` / `coerce` /\n // `rememberVariants`. These thread through `buildFormApi` into\n // register's coerce closure, the field-state predicate, and store\n // writes' WriteMeta — so two `useForm({ key })` calls (modal + main)\n // can validate on different cadences and surface errors with\n // different visibility rules even though they share a FormStore.\n if (merged.validateOn !== undefined) {\n apiOptions.validateOn = merged.validateOn\n }\n const mergedDebounceMs = (merged as { debounceMs?: number }).debounceMs\n if (mergedDebounceMs !== undefined) {\n apiOptions.debounceMs = mergedDebounceMs\n }\n if (merged.shouldShowErrors !== undefined) {\n apiOptions.shouldShowErrors = resolveShouldShowErrors(merged.shouldShowErrors)\n }\n if (merged.coerce !== undefined) {\n apiOptions.coerce = merged.coerce\n }\n if (merged.rememberVariants !== undefined) {\n apiOptions.rememberVariants = merged.rememberVariants\n }\n return buildFormApi<Form, GetValueFormType>(state, formInstanceId, apiOptions)\n}\n\n/**\n * Merge app-level defaults from the registry over a per-form\n * configuration. Per-form values always win for scalars; `validateOn`\n * and `debounceMs` resolve independently so a default like\n * `{ debounceMs: 100 }` carries through even when the per-form call\n * passes `{ validateOn: 'blur' }`. See `AttaformDefaults` for the\n * full merge contract.\n */\nfunction mergeWithDefaults<\n Form extends GenericForm,\n GetValueFormType extends GenericForm,\n Schema extends AbstractSchema<Form, GetValueFormType>,\n Defaults extends DeepPartial<DefaultValuesShape<Form>>,\n>(\n defaults: AttaformDefaults,\n configuration: UseFormConfiguration<Form, GetValueFormType, Schema, Defaults>\n): UseFormConfiguration<Form, GetValueFormType, Schema, Defaults> {\n // exactOptionalPropertyTypes rejects explicit `undefined` on optional\n // properties (different from omitting), so conditionally spread each\n // resolved value rather than assigning undefined into the field.\n const strict = configuration.strict ?? defaults.strict\n const onInvalidSubmit = configuration.onInvalidSubmit ?? defaults.onInvalidSubmit\n const history = configuration.history ?? defaults.history\n const rememberVariants = configuration.rememberVariants ?? defaults.rememberVariants\n const coerce = configuration.coerce ?? defaults.coerce\n const validateOn = configuration.validateOn ?? defaults.validateOn\n // `debounceMs` is type-narrowed in the public discriminated union to\n // disallow non-`'change'` mode + debounce; here at the resolution\n // boundary we only see the unwrapped fields, so the access is\n // unconditional. The runtime check in `create-form-store.ts` ignores\n // the value under non-`'change'` modes regardless.\n const debounceMs = (configuration as { debounceMs?: number }).debounceMs ?? defaults.debounceMs\n const shouldShowErrors = configuration.shouldShowErrors ?? defaults.shouldShowErrors\n const maxRecursionDepth = configuration.maxRecursionDepth ?? defaults.maxRecursionDepth\n // sensitiveNames REPLACES (doesn't extend) — consumers compose\n // additive lists themselves via `[...DEFAULT_SENSITIVE_NAMES, ...]`.\n // Per-form value wins; falls back to global default. Empty array\n // `[]` is the explicit opt-out and is preserved through the merge.\n const sensitiveNames = configuration.sensitiveNames ?? defaults.sensitiveNames\n // multiTab cascade: per-form > global > library default (`true`).\n // The library-default `true` is applied later at the wiring site\n // (so the merged config still distinguishes \"consumer didn't say\"\n // from an explicit `true` for downstream diagnostics).\n const multiTab = configuration.multiTab ?? defaults.multiTab\n return {\n ...configuration,\n ...(strict === undefined ? {} : { strict }),\n ...(onInvalidSubmit === undefined ? {} : { onInvalidSubmit }),\n ...(history === undefined ? {} : { history }),\n ...(rememberVariants === undefined ? {} : { rememberVariants }),\n ...(coerce === undefined ? {} : { coerce }),\n ...(validateOn === undefined ? {} : { validateOn }),\n ...(debounceMs === undefined ? {} : { debounceMs }),\n ...(shouldShowErrors === undefined ? {} : { shouldShowErrors }),\n ...(maxRecursionDepth === undefined ? {} : { maxRecursionDepth }),\n ...(sensitiveNames === undefined ? {} : { sensitiveNames }),\n ...(multiTab === undefined ? {} : { multiTab }),\n } as UseFormConfiguration<Form, GetValueFormType, Schema, Defaults>\n}\n\n/**\n * Shared key for the per-state history module cache. Exported would be\n * over-sharing — the only callers are this file and `injectForm`.\n */\nconst HISTORY_MODULE_KEY = 'history'\n\nfunction buildFreshState<F extends GenericForm, G extends GenericForm = F>(\n key: FormKey,\n schema: AbstractSchema<F, G>,\n configuration: UseFormConfiguration<\n F,\n G,\n AbstractSchema<F, G>,\n DeepPartial<DefaultValuesShape<F>>\n >,\n registry: ReturnType<typeof useRegistry>\n): FormStore<F, G> {\n const pending = registry.pendingHydration.get(key)\n if (pending !== undefined) registry.pendingHydration.delete(key)\n // Pre-pass: replace every `unset` sentinel in defaultValues with the\n // schema's slim default and collect the corresponding path keys.\n // Also auto-marks every primitive leaf the consumer did NOT cover —\n // a freshly opened form has no user input yet, so unspecified leaves\n // are logically blank. Devs opt a leaf out by supplying a non-`unset`\n // value for it. The walker mirrors `DefaultValuesShape<T>`'s\n // recursion; runtime landing of `unset` at a non-primitive leaf\n // produces a dev-warn (TS catches this at compile time but plain-JS\n // consumers bypass).\n const walked = walkUnsetSentinels(\n configuration.defaultValues,\n schema as unknown as AbstractSchema<GenericForm, GenericForm>\n )\n // Hydration precedence: when a hydration payload is present its\n // `blankPaths` field is the authoritative truth. We still\n // run the walker to scrub `unset` symbols out of `defaultValues` (so\n // they never reach storage), but discard the discovered paths in\n // favour of the hydrated set. Without this, a server-rendered form\n // with no blank paths would gain ones the client's\n // construction-time defaults invented.\n const initialBlankPaths: ReadonlyArray<string> | undefined =\n pending === undefined ? walked.paths : undefined\n // `configuration` has already passed through `mergeWithDefaults`, so\n // `sensitiveNames` here is the cascade-resolved value (per-form >\n // global > undefined-falls-to-library-default). An empty array `[]`\n // is the explicit opt-out (\"nothing is sensitive on this form\") and\n // the factory honors it. The resulting closures are frozen onto the\n // FormStore so persistence, multi-tab sync, and DevTools all share\n // one source of truth.\n const resolvedSensitiveNames = configuration.sensitiveNames\n const resolvedIsSensitivePath =\n resolvedSensitiveNames === undefined ? undefined : createIsSensitivePath(resolvedSensitiveNames)\n const resolvedSegmentMatchesSensitive =\n resolvedSensitiveNames === undefined\n ? undefined\n : createSegmentMatchesSensitive(resolvedSensitiveNames)\n const createOptions: Parameters<typeof createFormStore<F, G>>[0] = {\n formKey: key,\n schema,\n defaultValues: walked.cleanedValues as DeepPartial<WriteShape<F>> | undefined,\n ...(configuration.strict !== undefined ? { strict: configuration.strict } : {}),\n hydration: pending,\n ...(configuration.validateOn !== undefined ? { validateOn: configuration.validateOn } : {}),\n ...((configuration as { debounceMs?: number }).debounceMs !== undefined\n ? { debounceMs: (configuration as { debounceMs?: number }).debounceMs }\n : {}),\n ssr: registry.ssr,\n ...(configuration.rememberVariants !== undefined\n ? { rememberVariants: configuration.rememberVariants }\n : {}),\n ...(configuration.coerce !== undefined ? { coerce: configuration.coerce } : {}),\n ...(configuration.shouldShowErrors !== undefined\n ? { shouldShowErrors: configuration.shouldShowErrors }\n : {}),\n ...(initialBlankPaths !== undefined ? { initialBlankPaths } : {}),\n ...(resolvedIsSensitivePath !== undefined ? { isSensitivePath: resolvedIsSensitivePath } : {}),\n ...(resolvedSegmentMatchesSensitive !== undefined\n ? { segmentMatchesSensitive: resolvedSegmentMatchesSensitive }\n : {}),\n }\n const state = createFormStore<F, G>(createOptions)\n // Storage type is FormStore<GenericForm>; the lookup above narrows\n // back to the caller's (F, G) via the `existing as FormStore<Form,\n // GetValueFormType>` cast. The registry Map is intentionally\n // generic-erased — the alternative (parameterising the Map) would\n // force every internal caller to carry both generics.\n ;(registry.forms as Map<FormKey, FormStore<GenericForm>>).set(\n key,\n state as unknown as FormStore<GenericForm>\n )\n return state\n}\n\n/**\n * Module-local counter for the \"no Vue instance in scope\" fallback\n * (tests, raw composable calls outside setup). Collisions with\n * user-supplied keys are avoided by the reserved `__atta:anon:` prefix\n * (consumer keys starting with `__atta:` are rejected at construction).\n * Inside\n * setup — the common path — `useId()` produces a tree-position-stable\n * id that matches across SSR hydration, so two mounts of the same\n * component tree resolve to the same anonymous key and hydration\n * works without user bookkeeping.\n */\nlet anonCounter = 0\n\n/**\n * Module-local counter for `formInstanceId` allocation outside Vue\n * setup (tests, ad-hoc composable usage). The setup-context path uses\n * `useId()` for SSR-stable IDs; this counter is the test-only fallback.\n */\nlet formInstanceCounter = 0\n\n/**\n * One entry per ANONYMOUS `useForm()` call that landed in a\n * component's ambient provide slot. Keyed forms aren't recorded —\n * they don't fill the ambient slot in the first place. `source` is\n * the best-effort user call site (first non-attaform frame off\n * `new Error().stack`) — printed in the collision warning so the\n * author can navigate to each offending call site.\n */\nexport type AmbientProvideEntry = {\n readonly source: string | undefined\n}\n\n/**\n * Tracks which Vue component instances have already run\n * `provide(kFormContext, ...)` via `useAbstractForm`. Dev-only —\n * `null` in production so the WeakMap allocation tree-shakes out.\n * A `WeakMap` keyed by the instance object lets Vue GC each\n * component's entry when it unmounts without us tracking\n * lifecycle.\n *\n * Exported so `injectForm<F>()` (no key) can walk the parent\n * chain and emit a collision warning only when a descendant\n * actually consumes the ambient slot — eager warning in\n * `useForm()` misfired on components that call useForm multiple\n * times intentionally but have no keyless consumer.\n */\nexport const ambientProvideHistory: WeakMap<object, AmbientProvideEntry[]> | null = __DEV__\n ? new WeakMap<object, AmbientProvideEntry[]>()\n : null\n\nfunction recordAmbientProvide(ssr: boolean): void {\n if (!__DEV__ || ssr || ambientProvideHistory === null) return\n const instance = getCurrentInstance()\n if (instance === null) return\n const instanceKey = instance as unknown as object\n // Caller already gated on `configuration.key === undefined`, so every\n // recorded entry corresponds to an anonymous useForm() call. No need\n // to carry a key — synthetic `__atta:anon:<id>` keys aren't addressable\n // by the author and would only add noise to the warning.\n const entry: AmbientProvideEntry = {\n source: captureUserCallSite(),\n }\n const existing = ambientProvideHistory.get(instanceKey)\n if (existing === undefined) {\n ambientProvideHistory.set(instanceKey, [entry])\n return\n }\n existing.push(entry)\n}\n\n/**\n * Normalise `configuration.key` into a concrete FormKey. Explicit keys\n * pass through after a reserved-namespace check (anything starting\n * with `__atta:` is rejected with `ReservedFormKeyError`); empty /\n * nullish keys are treated as anonymous and allocated a unique id\n * under the `__atta:anon:` prefix. The reserved-prefix reject + the\n * synthetic-prefix reservation together guarantee zero collision\n * between consumer-chosen keys and library-allocated synthetic ones.\n *\n * Anonymous semantics: each `useForm({ schema })` call without a key\n * resolves to a distinct FormStore. Descendant components reach it via\n * ambient `injectForm<F>()`; cross-component lookup by key is not\n * possible (and not meaningful — the key is synthetic). Callers that\n * need shared state, distant lookup, persistence defaults, or a\n * recognisable DevTools label should pass an explicit `key`.\n */\nfunction resolveFormKey(key: FormKey | undefined): FormKey {\n if (key !== undefined && key !== null && key !== '') {\n // Reject any consumer-supplied key in the reserved `__atta:`\n // namespace. Without this, a consumer key like `__atta:anon:0`\n // could silently collide with the synthetic anonymous-key\n // allocation below — both would land on the same FormStore in\n // the registry, and the dev-mode schema-fingerprint warning\n // only catches collisions when schemas differ. Throwing here\n // makes the collision impossible by construction.\n if (key.startsWith(RESERVED_KEY_PREFIX)) {\n throw new ReservedFormKeyError(key)\n }\n return key\n }\n // In setup context, `useId()` threads through Vue's SSR id-allocator\n // so server-rendered and client-hydrated trees agree on the same\n // synthetic key.\n if (getCurrentInstance() !== null) {\n return `${ANONYMOUS_FORM_KEY_PREFIX}${useId()}`\n }\n // Outside setup (tests, ad-hoc composable use) there's no Vue\n // instance to draw from; fall back to a module-local counter.\n return `${ANONYMOUS_FORM_KEY_PREFIX}${anonCounter++}`\n}\n\n/**\n * Dev-only: warn when a second `useForm` lands on the same key with\n * a structurally-different schema. Two schemas compute their own\n * fingerprints; we compare the strings and flag mismatches. An\n * adapter-thrown `fingerprint()` is caught (never crashes the form)\n * and surfaced as a `console.error` in dev — the mismatch check is\n * skipped, matching the \"allow the inconsistency\" failure mode. See\n * `AbstractSchema.fingerprint()` in types-api.ts for the contract.\n */\nfunction warnOnSchemaFingerprintMismatch(\n key: FormKey,\n existing: AbstractSchema<GenericForm, GenericForm>,\n incoming: AbstractSchema<GenericForm, GenericForm>\n): void {\n let existingFp: string\n let incomingFp: string\n try {\n existingFp = existing.fingerprint()\n incomingFp = incoming.fingerprint()\n } catch (error) {\n console.error(\n `[attaform] fingerprint() threw for key \"${key}\"; skipping mismatch check.`,\n error\n )\n return\n }\n if (existingFp === incomingFp) return\n console.warn(\n `[attaform] useForm() calls with key \"${key}\" use different schemas; first wins, second is ignored. Use identical schemas or unique keys.\\n existing: ${existingFp}\\n incoming: ${incomingFp}`\n )\n}\n\n/**\n * Dev-only: warn when a second `useForm` lands on the same key with a\n * `persist:` config that diverges from what the first call wired. The\n * persist channel is single-IO (one storage key, one debounce timer);\n * silent drop is a high-stakes footgun (\"I configured persist but\n * sessionStorage is empty\"). Skipped when the second call passes no\n * persist config (intentional inheritance), and when the comparison\n * is deemed equivalent (same `storage` reference / kind, same `key`,\n * same `debounceMs`). Custom adapter functions compare by reference\n * — distinct closures look distinct, which is conservative but\n * correct: distinct closures may persist to different backends.\n */\nfunction warnOnPersistDivergence<F extends GenericForm>(\n key: FormKey,\n existing: FormStore<F, GenericForm>,\n incomingPersist: PersistConfig | undefined\n): void {\n if (incomingPersist === undefined) return\n const wired = existing.modules.get(PERSISTENCE_MODULE_KEY) as PersistenceModule | undefined\n const incomingNormalized = normalizePersistConfig(incomingPersist)\n if (wired === undefined) {\n console.warn(\n `[attaform] useForm({ key: \"${key}\" }) passed a persist config but the first useForm({ key }) call didn't wire persistence; the new config is silently dropped. Pass persist on the first call, or remove persist here to make the inheritance explicit.`\n )\n return\n }\n if (persistConfigsEquivalent(wired.wiredConfig, incomingNormalized)) return\n console.warn(\n `[attaform] useForm({ key: \"${key}\" }) passed a persist config that differs from the first useForm({ key }) call's; first wins, this one is ignored.\\n wired: ${describePersist(wired.wiredConfig)}\\n incoming: ${describePersist(incomingNormalized)}`\n )\n}\n\nfunction persistConfigsEquivalent(a: PersistConfigOptions, b: PersistConfigOptions): boolean {\n if (a.storage !== b.storage) return false\n if ((a.key ?? undefined) !== (b.key ?? undefined)) return false\n if ((a.debounceMs ?? undefined) !== (b.debounceMs ?? undefined)) return false\n return true\n}\n\nfunction describePersist(config: PersistConfigOptions): string {\n const storage = typeof config.storage === 'string' ? config.storage : 'custom-adapter'\n const parts = [`storage=${storage}`]\n if (config.key !== undefined) parts.push(`key=${config.key}`)\n if (config.debounceMs !== undefined) parts.push(`debounceMs=${config.debounceMs}`)\n return `{ ${parts.join(', ')} }`\n}\n\n/**\n * Wire persistence to a fresh FormStore:\n *\n * 1. Resolve the storage adapter (dynamic-imported — `'local'` never\n * pulls IDB code; tree-shakes cleanly).\n * 2. Async-read any persisted payload and apply it via\n * `applyFormReplacement`. First render shows schema defaults\n * (the \"flash of default state\" — documented tradeoff for\n * async backends).\n * 3. Subscribe a debounced writer to `onFormChange`; every mutation\n * schedules a write.\n * 4. Subscribe a `removeItem` on submit-success (when\n * `clearOnSubmitSuccess` is not explicitly false).\n * 5. Return a disposer that flushes any pending write, cancels\n * the debounce, and removes subscribers. Called on consumer\n * teardown.\n */\nfunction wirePersistence<F extends GenericForm>(\n state: FormStore<F, GenericForm>,\n config: PersistConfigOptions\n): PersistenceModule {\n // Fingerprint the schema once and bake it into the storage key. Any\n // structural schema change (added/removed/renamed field, type swap)\n // produces a different fingerprint, so the new mount looks up a fresh\n // key — the old draft becomes an orphan, cleaned up in the same mount\n // by `cleanupOrphanKeys` below. No manual version protocol required.\n // Hash the long structural fingerprint into a fixed-size token before\n // baking it into the storage key. The raw fingerprint is the\n // schema's full shape stringified (`object{\"address\":object{...}}`),\n // which works correctly for invalidation but produces 200+ char\n // storage keys for non-trivial schemas AND leaks the schema's\n // structure into client-side storage. The hash preserves\n // determinism (same schema → same hash) without either downside.\n const fingerprint = hashStableString(state.schema.fingerprint())\n const base = resolveStorageKeyBase(config, state.formKey)\n const key = `${base}:${fingerprint}`\n // Sanitise the persistence debounce — same rules as field validation:\n // `NaN` would fire synchronously, `Infinity` would stall the event\n // loop for ~24.8 days then wrap. Both fall back to the library default.\n const debounceMs = normalizeNumericOption({\n value: config.debounceMs ?? DEFAULT_PERSISTENCE_DEBOUNCE_MS,\n source: 'useForm.persist.debounceMs',\n allowInfinity: false,\n min: 0,\n defaultValue: DEFAULT_PERSISTENCE_DEBOUNCE_MS,\n })\n const include = config.include ?? 'form'\n const clearOnSubmitSuccess = config.clearOnSubmitSuccess ?? true\n\n // Single shared adapter promise — both the hydration path and the\n // write/clear paths await it. Avoids a race where an early write\n // (fast debounceMs) would see `adapter === null` and skip silently\n // because the dynamic-import hadn't resolved yet.\n const adapterPromise = getStorageAdapter(config.storage)\n let disposed = false\n // Tracks the in-flight final flush kicked off by `dispose()`. Returned\n // by `awaitPendingWrites` so the registry can drain pending storage\n // writes before evicting the FormStore — without this, the last\n // debounced keystroke is silently dropped on unmount.\n let inFlightFinalFlush: Promise<void> | null = null\n // Snapshot of opt-in paths captured at SCHEDULE time. Vue's unmount\n // lifecycle runs directive `beforeUnmount` (which clears per-element\n // opt-ins) BEFORE the effect-scope dispose that triggers our drain.\n // Without a snapshot, a write flushed during the drain sees zero\n // opt-ins and wipes the storage entry. The snapshot lets the eventual\n // write reflect the moment-in-time opt-ins as the user typed.\n let pendingOptedInPaths: Set<PathKey> | null = null\n\n const writer = createDebouncedWriter(async () => {\n // No bail at entry: this closure runs from two paths — the\n // debounce timer firing (which already gated on `disposed` via the\n // schedule call) and the final flush from `dispose()`. The final\n // flush's invocation order (flush BEFORE disposed flips) lets this\n // write complete; the post-await guards below catch the rare case\n // where adapter resolution is slow enough to overlap with the\n // disposed flip.\n //\n // Use the schedule-time snapshot if present (handles the unmount\n // race where beforeUnmount has cleared the live registry). Falls\n // back to the live registry for any non-listener-triggered path.\n const optedInPaths = pendingOptedInPaths ?? new Set<PathKey>(state.persistOptIns.optedInPaths())\n pendingOptedInPaths = null\n const adapter = await adapterPromise\n if (disposed) return\n // Sparse-payload reshape: the persisted form contains only paths\n // that were opted in via `register('foo', { persist: true })`. If\n // every opt-in has been torn down, wipe the entry rather than\n // write a hollow envelope (matches the per-element security model\n // — no opt-ins → nothing to persist).\n if (optedInPaths.size === 0) {\n await adapter.removeItem(key)\n return\n }\n // Unwrap the reactive form to a plain object before handing it to\n // the adapter — IDB's `structuredClone` can't serialise Vue\n // proxies (DATA_CLONE_ERR), and local/session stringify the\n // proxy's own-enumerable keys anyway.\n const rawForm = toRaw(state.form.value)\n const filteredForm = pluckPaths(rawForm, optedInPaths) as F\n // Build the envelope with the attaform-internal envelope version baked\n // in by `buildPersistedPayload`. Consumers no longer manage `v` —\n // schema-content invalidation lives at the storage-key level via\n // the fingerprint suffix.\n const filteredSchemaErrors = filterErrorsByPaths(state.schemaErrors, optedInPaths)\n const filteredUserErrors = filterErrorsByPaths(state.userErrors, optedInPaths)\n // Blank paths are part of the restorable UI state, so\n // they ride the same opt-in gate as form values: only persist\n // the entries whose paths are also opted in for persistence.\n const filteredTransientEmpty = new Set<string>()\n for (const tk of state.blankPaths) {\n if (optedInPaths.has(tk as PathKey)) filteredTransientEmpty.add(tk)\n }\n const payload = buildPersistedPayload<F>(\n filteredForm,\n include,\n filteredSchemaErrors,\n filteredUserErrors,\n filteredTransientEmpty\n )\n await adapter.setItem(key, payload)\n }, debounceMs)\n\n const unsubscribeChange = state.onFormChange((_next, meta) => {\n if (disposed || inFlightFinalFlush !== null) return\n // Cross-tab apply: a sibling tab already wrote this value to its\n // own persistence layer; double-persisting from the receiving\n // tab would be wasted I/O. The multi-tab sync module sets\n // `persist: false` for this reason, which the next check already\n // catches — but adding the explicit `crossTab` early return makes\n // the intent legible at the listener boundary.\n if (meta?.crossTab === true) return\n // Per-element opt-in: only writes whose source declared `persist: true`\n // reach the storage adapter. Programmatic `form.setValue`, history\n // undo without opt-ins, devtools edits to non-opted paths, and\n // `reset()` all bypass this gate by passing no meta (or `persist:\n // false`).\n if (meta?.persist !== true) return\n // Snapshot opt-in paths NOW — Vue's unmount fires directive\n // beforeUnmount (which calls persistOptIns.removeAllFor) BEFORE\n // the scope-dispose that drives our drain. Capturing at schedule\n // time means the eventual write sees the opt-ins as they were\n // when the user typed, not as they were stripped.\n pendingOptedInPaths = new Set<PathKey>(state.persistOptIns.optedInPaths())\n writer.schedule()\n })\n\n const unsubscribeSuccess = clearOnSubmitSuccess\n ? state.onSubmitSuccess(() => {\n if (disposed) return\n // Flush any pending/in-flight write BEFORE removing — otherwise\n // a timer that fires between submit and removeItem re-persists\n // the now-stale state. `flush()` awaits the in-flight promise\n // if one exists; if there's only a timer, it fires it\n // immediately and awaits. After that, removeItem wins.\n void (async () => {\n await writer.flush()\n if (disposed) return\n const adapter = await adapterPromise\n if (disposed) return\n await adapter.removeItem(key)\n })()\n })\n : () => undefined\n\n // Async setup: resolve the adapter, then read back the persisted\n // payload. If the caller unmounts before this finishes, `disposed`\n // is true — the restore is skipped.\n void (async () => {\n const adapter = await adapterPromise\n if (disposed) return\n // Orphan cleanup: delete any attaform-managed key under the same base\n // whose fingerprint suffix doesn't match the current schema. Runs\n // once per mount, fire-and-forget. Bounded cost: typically 0-1\n // orphans per form.\n void cleanupOrphanKeys(adapter, base, key)\n try {\n const raw = await adapter.getItem(key)\n const payload = readPersistedPayload<F>(raw)\n if (payload === null) {\n // Truly-absent entries are a no-op. A non-null raw that didn't\n // parse is a stale payload — wrong attaform envelope version, or\n // malformed shape — wipe so the next mount reads cleanly.\n if (raw !== null && raw !== undefined) {\n await adapter.removeItem(key)\n }\n return\n }\n if (disposed) return\n // Sparse-aware replacement: the persisted form may contain only\n // a subset of paths (the ones opted into persistence on the\n // previous mount). Merge over the current form (which carries\n // schema defaults at this point — wirePersistence runs before\n // any user mutation could have happened) so non-persisted paths\n // keep their schema defaults.\n const merged = mergeSparseHydration(\n toRaw(state.form.value) as F,\n payload.data.form,\n state.schema as unknown as Parameters<typeof mergeSparseHydration>[2]\n )\n // `hydration: true` tells listeners (notably the history module)\n // that this replacement is the baseline, not a user mutation —\n // history wipes its stacks and reseeds with the post-hydration\n // snapshot so `undo()` can't reach the transient pre-hydration\n // default the form briefly held between mount and hydrate.\n state.applyFormReplacement(merged, { hydration: true })\n // payload. Persistence is per-element opt-in, so the persisted\n // payload only covers paths within the opt-in scope (the leaf\n // paths populated in `payload.data.form`). Construction-time\n // auto-marks for paths OUTSIDE that scope must survive —\n // without this, a non-opted-in numeric field's slim default\n // (`0`) would lose its blank mark on hydrate and surface as\n // `'0'` in its <input> instead of empty.\n //\n // Within the opt-in scope, the persisted state IS the truth: a\n // persisted path that's no longer blank (the user\n // typed) clears the construction-time mark, and a persisted\n // path that IS blank (still slim default) re-asserts.\n const persistedLeafPaths = collectPersistedLeafPaths(payload.data.form)\n for (const k of persistedLeafPaths) {\n state.blankPaths.delete(k)\n state.originalBlankPaths.delete(k)\n }\n for (const k of payload.data.blankPaths ?? []) {\n state.blankPaths.add(k as PathKey)\n state.originalBlankPaths.add(k as PathKey)\n }\n if (include === 'form+errors') {\n // Each store rebuilds independently from its persisted entries.\n // Consumers who bumped `version` already had their payload\n // rejected above.\n if (payload.data.schemaErrors !== undefined) {\n const flat = payload.data.schemaErrors.flatMap(([, errs]) => errs)\n state.setAllSchemaErrors(flat)\n }\n if (payload.data.userErrors !== undefined) {\n const flat = payload.data.userErrors.flatMap(([, errs]) => errs)\n state.setAllUserErrors(flat)\n }\n }\n // Post-hydration revalidation: the construction-time seed ran\n // against the empty default, so its errors describe a stale\n // value. Async-only verdicts additionally never fire at\n // construction (the sync seed contract can't surface them;\n // schemas with async refinements / transforms / pipes degrade\n // to success there). A full async run at the root path wipes\n // `schemaErrors` and re-stamps with the authoritative result\n // for the rehydrated value — sync errors get refreshed, async\n // verdicts fire, the form lands in the state the persisted\n // value actually deserves.\n state.scheduleFieldValidation([], true /* immediate */)\n } catch {\n // Adapter IO errors shouldn't surface; storage adapters are\n // \"best-effort\" and already log their own warnings.\n }\n })()\n\n // Note: a \"configured but no fields opted in\" check used to live here\n // (microtask-deferred warn). Removed — having the persist capability\n // configured without spending it on a register() call is a valid\n // dormant state (scaffolding, A/B'd opt-ins, future-flagged fields).\n // The library shouldn't lecture the consumer for not exercising every\n // configured option. Eager throws only fire on actual contradictions\n // (no-key + persist; register-with-persist + no useForm-persist).\n\n /**\n * Imperative one-shot write. Read-merge-write strategy: flush any\n * pending debounced write first (so it can't overwrite our update),\n * read the existing payload, set the path's current value, optionally\n * merge in this path's errors, and write back. Preserves untouched\n * paths in storage.\n */\n async function writePathImmediately(path: Path): Promise<void> {\n if (disposed) return\n await writer.flush()\n if (disposed) return\n const adapter = await adapterPromise\n if (disposed) return\n const raw = await adapter.getItem(key)\n const existing = readPersistedPayload<F>(raw)\n const baseForm = existing?.data.form ?? ({} as F)\n const value = getAtPath(toRaw(state.form.value), path)\n const nextForm = setAtPath(baseForm, path, value) as F\n // Refresh this path's blank entry — and any descendants\n // — while preserving entries for OTHER paths the previous mount\n // persisted. Non-leaf writes (`writePathImmediately('user')`)\n // overwrite the entire subtree, so any disk entries below the\n // write path are dropped first; the live in-memory set then\n // contributes whatever marks are still active under that subtree.\n const { key: pathKey } = canonicalizePath(path)\n const transientSet = new Set<string>(\n (existing?.data.blankPaths ?? []).filter(\n (k) => k !== pathKey && !isDescendantPathKey(k, pathKey)\n )\n )\n for (const liveKey of state.blankPaths) {\n if (liveKey === pathKey || isDescendantPathKey(liveKey, pathKey)) {\n transientSet.add(liveKey)\n }\n }\n if (include === 'form') {\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form', new Map(), new Map(), transientSet)\n )\n return\n }\n // include === 'form+errors': preserve the rest of the persisted\n // error map and refresh the entry for this path's canonical key.\n const schemaMap = new Map<string, ValidationError[]>(existing?.data.schemaErrors ?? [])\n const userMap = new Map<string, ValidationError[]>(existing?.data.userErrors ?? [])\n const currentSchema = state.schemaErrors.get(pathKey)\n const currentUser = state.userErrors.get(pathKey)\n if (currentSchema !== undefined && currentSchema.length > 0) {\n schemaMap.set(pathKey, [...currentSchema])\n } else {\n schemaMap.delete(pathKey)\n }\n if (currentUser !== undefined && currentUser.length > 0) {\n userMap.set(pathKey, [...currentUser])\n } else {\n userMap.delete(pathKey)\n }\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form+errors', schemaMap, userMap, transientSet)\n )\n }\n\n /**\n * Wipe the persisted entry. Without `path`, removes the whole key.\n * With `path`, deletes only that subpath (and any matching error\n * entries) and writes back; the entry is removed entirely if the\n * resulting form value is empty.\n */\n async function clearPersistedDraft(path?: Path): Promise<void> {\n if (disposed) return\n await writer.flush()\n if (disposed) return\n const adapter = await adapterPromise\n if (disposed) return\n if (path === undefined) {\n await adapter.removeItem(key)\n return\n }\n const raw = await adapter.getItem(key)\n const existing = readPersistedPayload<F>(raw)\n if (existing === null) return\n const nextForm = deleteAtPath(existing.data.form, path) as F\n if (isEmptyContainer(nextForm)) {\n await adapter.removeItem(key)\n return\n }\n const { key: pathKey } = canonicalizePath(path)\n // Drop the cleared path AND every descendant from the persisted\n // blank list so a later mount doesn't restore an\n // \"empty\" UI state for a path that no longer has any value\n // behind it. Non-leaf clears (`clearPersistedDraft('user')`)\n // wipe the whole user.* subtree.\n const transientSet = new Set(\n (existing.data.blankPaths ?? []).filter(\n (k) => k !== pathKey && !isDescendantPathKey(k, pathKey)\n )\n )\n if (include === 'form') {\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form', new Map(), new Map(), transientSet)\n )\n return\n }\n const schemaErrors = (existing.data.schemaErrors ?? []).filter(([k]) => k !== pathKey)\n const userErrors = (existing.data.userErrors ?? []).filter(([k]) => k !== pathKey)\n const schemaMap = new Map<string, ValidationError[]>(schemaErrors.map(([k, v]) => [k, [...v]]))\n const userMap = new Map<string, ValidationError[]>(userErrors.map(([k, v]) => [k, [...v]]))\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form+errors', schemaMap, userMap, transientSet)\n )\n }\n\n function awaitPendingWrites(): Promise<void> {\n // If dispose() already kicked off the final flush, return THAT\n // promise so the registry awaits the same drain instead of\n // scheduling a parallel one.\n if (inFlightFinalFlush !== null) return inFlightFinalFlush\n if (disposed) return Promise.resolve()\n return writer.flush().catch(() => undefined)\n }\n\n function dispose(): void {\n if (disposed || inFlightFinalFlush !== null) return\n unsubscribeChange()\n unsubscribeSuccess()\n // CRITICAL: flush BEFORE flipping `disposed`. The previous order\n // (set disposed=true, then call writer.flush()) caused the writer\n // closure to bail immediately, silently dropping the last\n // keystroke whenever a component unmounted within the debounce\n // window. Now we kick off the flush, then flip `disposed` only\n // after the in-flight write finishes.\n inFlightFinalFlush = writer\n .flush()\n .catch(() => undefined)\n .finally(() => {\n disposed = true\n inFlightFinalFlush = null\n })\n // Fire-and-forget — `awaitPendingWrites` exposes the promise for\n // callers that need to drain (the registry on consumer-eviction;\n // SSR shutdown).\n void inFlightFinalFlush\n }\n\n return {\n wiredConfig: config,\n writePathImmediately,\n clearPersistedDraft,\n awaitPendingWrites,\n dispose,\n }\n}\n\n/**\n * Treat `null`, `undefined`, `[]`, and `{}` as \"nothing left to keep.\"\n * Used by `clearPersistedDraft(path)` to decide whether to wipe the\n * entire entry instead of writing a hollow envelope back.\n */\nfunction isEmptyContainer(value: unknown): boolean {\n if (value === undefined || value === null) return true\n if (Array.isArray(value)) return value.length === 0\n if (isPlainRecord(value)) return Object.keys(value).length === 0\n return false\n}\n\n/**\n * Tracks the FormStore identities the anon-persist warn already\n * fired for in production. Dev-mode throws (via AnonPersistError)\n * don't need a dedupe set — the throw aborts the call before\n * subsequent identical calls can land.\n */\nconst warnedAnonPersistKeys: Set<string> = new Set<string>()\n\n/**\n * Anonymous + `persist:` is unsafe by construction: the synthetic\n * `__atta:anon:<id>` identity drifts on every remount (Vue's `useId()`\n * allocator is per-app and per-tree-position; HMR rebuilds the\n * instance) AND can collide between two unrelated anon forms that\n * happen to land on the same id. With matching schemas + backend,\n * the second form would read the first's draft and write back over\n * it — actual cross-form data leakage, not just stale entries.\n *\n * Two-tier handling:\n * - **Dev** (`__DEV__` true): throw `AnonPersistError`. Hard-fails\n * the call at the offending useForm() site.\n * - **Prod**: one-shot `console.warn` + return `true` so the\n * caller skips persistence wiring entirely. A deployed app\n * shipping the anti-pattern shouldn't hard-crash, but it also\n * shouldn't silently mis-route data — disabling the mechanism\n * is the safe failure.\n *\n * Returns `true` when persistence MUST be skipped (anon + persist).\n */\nfunction enforceAnonPersistRule(formKey: string, ssr: boolean): boolean {\n if (!formKey.startsWith(ANONYMOUS_FORM_KEY_PREFIX)) return false\n if (__DEV__)\n throw new AnonPersistError({\n cause: 'no-key',\n callSite: captureUserCallSite(),\n })\n // Production: warn + tell the caller to skip wiring. Client-only\n // warn (skip server logs to avoid spamming SSR per-request output).\n // Persist is still skipped on the SSR pass — same disabling\n // outcome — just without the log noise.\n if (!ssr && !warnedAnonPersistKeys.has(formKey)) {\n warnedAnonPersistKeys.add(formKey)\n console.warn(\n \"[attaform] persist: ignored — anonymous useForm() can't safely persist \" +\n '(key drift + cross-form collision risk).\\n' +\n ' Persistence is disabled for this form; the app keeps working.\\n' +\n \" Fix: useForm({ schema, key: 'login', persist: '...' })\"\n )\n }\n return true\n}\n\n/**\n * Walk a sparse persisted form and collect the canonical PathKey of\n * every leaf. \"Leaf\" = anything that isn't a plain object or array\n * (so primitives, null, deserialized Dates / strings all count). The\n * persisted form's leaves correspond 1:1 with the per-element opt-in\n * scope at the time persistence wrote, which the hydration path uses\n * to bound which blank entries to overwrite.\n */\nfunction collectPersistedLeafPaths(form: unknown): PathKey[] {\n const out: PathKey[] = []\n walk(form, [])\n return out\n\n function walk(node: unknown, prefix: Path): void {\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n walk(node[i], [...prefix, i])\n }\n return\n }\n if (isPlainRecord(node)) {\n for (const key of Object.keys(node)) {\n walk((node as Record<string, unknown>)[key], [...prefix, key])\n }\n return\n }\n if (prefix.length === 0) return // root scalar — no path to canonicalize\n out.push(canonicalizePath(prefix).key)\n }\n}\n\n/**\n * `true` when `candidate` names a strict descendant of `ancestor` in\n * canonical PathKey form (`JSON.stringify(segments)`).\n *\n * `'[\"user\"]'` is the ancestor; `'[\"user\",\"age\"]'` and\n * `'[\"user\",\"address\",\"line1\"]'` are descendants. A pure prefix match\n * isn't enough — `'[\"userId\"]'` shares the `'[\"user'` prefix with\n * `'[\"user\"]'` but is not a descendant. The check anchors on the\n * comma that separates the parent's last segment from its first\n * child segment.\n */\nfunction isDescendantPathKey(candidate: string, ancestor: string): boolean {\n if (candidate.length <= ancestor.length) return false\n if (!ancestor.endsWith(']')) return false\n const childPrefix = `${ancestor.slice(0, -1)},`\n return candidate.startsWith(childPrefix)\n}\n\nexport type { FieldState }\n","import { getCurrentInstance, getCurrentScope, inject, onScopeDispose, useId } from 'vue'\nimport { buildFormApi } from '../core/build-form-api'\nimport type { FormStore } from '../core/create-form-store'\nimport { __DEV__ } from '../core/dev'\nimport { captureUserCallSite } from '../core/dev-stack-trace'\nimport type { HistoryModule } from '../core/history'\nimport { ensureAttaformInstalled } from '../core/plugin'\nimport { kFormContext, kFormInstanceId, useRegistry, type AttaformRegistry } from '../core/registry'\nimport type { FormKey, UseFormReturnType } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport { ambientProvideHistory } from './use-abstract-form'\n\n/**\n * Module-local counter for the test/ad-hoc fallback when neither an\n * ambient `kFormInstanceId` provide nor a Vue instance is available.\n * Uniqueness is sufficient — these consumers don't share an\n * `instanceId` with anything else in the tree by definition.\n */\nlet injectedInstanceCounter = 0\n\n/**\n * Access an existing form from a descendant component without passing\n * it through props. Counterpart to `useForm` — `useForm` creates and\n * provides; `injectForm` looks up via Vue's inject mechanism.\n *\n * Two ways to call it:\n *\n * ```ts\n * // Reach the nearest ancestor's anonymous useForm() call.\n * const form = injectForm<SignupShape>()\n *\n * // Reach a specific form by its key — works from anywhere in the app.\n * const cart = injectForm<CartShape>('cart')\n * ```\n *\n * Resolution rules (no-key form):\n * - Closest ambient ancestor wins.\n * - Only anonymous `useForm()` (no `key`) fills the ambient slot;\n * keyed forms are reachable only via `injectForm(key)`.\n * - Inherits the resolved ancestor's `formInstanceId`.\n *\n * Resolution rules (keyed form): registry lookup by string key,\n * independent of component-tree position.\n *\n * Returns `null` when no matching form exists (no ambient ancestor, or\n * the named key isn't registered). A dev-mode warning points at the\n * call site to help diagnose typos. Always narrow before using:\n *\n * ```ts\n * const form = injectForm<Shape>('signup')\n * if (!form) return\n * form.register('email')\n * ```\n *\n * Pass the `Form` generic explicitly — Vue's provide/inject erases\n * generics, so the library can't recover the shape automatically.\n *\n * The form is kept alive for this component's lifetime; once every\n * consumer unmounts, the form is cleaned up automatically.\n */\nexport function injectForm<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(\n key?: FormKey\n): UseFormReturnType<Form, GetValueFormType> | null {\n // Lazy-install: if no `useForm` ancestor and no explicit\n // `createAttaform()`, the registry is missing. Auto-install here so\n // `injectForm` collapses to its existing \"no form for that key\" /\n // \"no ambient form context\" null-return + dev-warning paths instead\n // of throwing the misleading `RegistryNotInstalledError`. The strict\n // `useRegistry()` below still surfaces `OutsideSetupError` when\n // called outside setup.\n const instance = getCurrentInstance()\n if (instance !== null) ensureAttaformInstalled(instance.appContext.app)\n const registry = useRegistry()\n\n const state = resolveState<Form>(key, registry)\n if (state === null) return null\n\n // Ref-count this consumer so the FormStore survives until every nested\n // component that reached it has torn down. Mirrors the behaviour in\n // useAbstractForm — see registry.trackConsumer for the counter semantics.\n if (getCurrentScope() !== undefined) {\n const releaseConsumer = registry.trackConsumer(state.formKey)\n onScopeDispose(releaseConsumer)\n }\n\n // Pull the cached history module (if the owning `useForm` wired it)\n // so every consumer's API surface includes a live `form.history`\n // namespace. Without this, consumers reached via the context would\n // receive inert stubs even when history is enabled on the form.\n const apiOptions: Parameters<typeof buildFormApi<Form, GetValueFormType>>[2] = {}\n const history = state.modules.get('history') as HistoryModule | undefined\n if (history !== undefined) {\n apiOptions.history = history\n }\n // Inherit the ancestor `useForm()`'s instanceId when one is provided.\n // Keeps parent-submit-focus working for inputs registered by deep\n // children using `injectForm()` + their own local `register()` calls\n // — both sides tag against the SAME instance.\n //\n // Falls back to a fresh ID when:\n // - `injectForm('cart')` reaches a form by key from a tree branch\n // that has no ambient provide chain to it (cross-tree access);\n // - or no Vue instance is available (test / ad-hoc usage).\n // In those cases the consumer's local registrations are isolated —\n // the original `useForm()` callsite's `focusFirstError` won't see\n // them, but the consumer's own focus calls work locally.\n const ambientInstanceId = getCurrentInstance() !== null ? inject(kFormInstanceId, null) : null\n const formInstanceId =\n ambientInstanceId ??\n (getCurrentInstance() !== null\n ? useId()\n : `atta:form-instance-injected:${injectedInstanceCounter++}`)\n return buildFormApi<Form, GetValueFormType>(\n state as FormStore<Form, GetValueFormType>,\n formInstanceId,\n apiOptions\n )\n}\n\n/**\n * Resolves the FormStore for the requested key (or the ambient slot\n * when no key was passed). Returns `null` on miss; the caller propagates\n * that null straight out to the consumer.\n *\n * Both miss modes log a dev-mode warning carrying the user's call-site\n * frame — a typo'd key reads as \"[attaform] injectForm: no form registered\n * for key 'userz'. Returning null. (pages/profile.vue:42)\" rather than\n * as a stack trace from inside attaform internals.\n */\nfunction resolveState<Form extends GenericForm>(\n key: FormKey | undefined,\n registry: AttaformRegistry\n): FormStore<Form> | null {\n if (key !== undefined) {\n const stored = registry.forms.get(key) as FormStore<Form> | undefined\n if (stored === undefined) {\n warnMiss(`no form registered for key '${key}'`, registry.ssr)\n return null\n }\n return stored\n }\n const ambient = inject(kFormContext, null) as FormStore<Form> | null\n if (ambient === null) {\n warnMiss('no ambient form context', registry.ssr)\n return null\n }\n warnIfAmbientProviderHadDuplicates()\n return ambient\n}\n\n/**\n * Skipped on SSR — Nuxt's `dev:ssr-logs` hook forwards server warns to\n * the browser console alongside the client-side warn that fires from\n * the hydration setup, so the same miss would surface twice per page\n * load. The signal is identical on both passes (registry state is\n * deterministic across SSR/client), so emitting only on the client is\n * lossless and halves dev-mode noise. Production stays silent on both.\n */\nfunction warnMiss(detail: string, ssr: boolean): void {\n if (!__DEV__ || ssr) return\n const frame = captureUserCallSite()\n console.warn(\n `[attaform] injectForm: ${detail}. Returning null.` + (frame !== undefined ? ` ${frame}` : '')\n )\n}\n\n/**\n * Walk up from the current component to the nearest ancestor that\n * registered an ambient provide (tracked in `ambientProvideHistory`).\n * If that ancestor recorded more than one ANONYMOUS `useForm()` call,\n * a descendant reaching for the ambient slot only sees the last one\n * — warn so the author picks between adding a key and splitting the\n * component.\n *\n * The eager version of this check lived at the `useForm()` call site\n * and fired once per extra form regardless of whether any descendant\n * actually used the ambient slot. That made spike / test pages wall-\n * warn for a non-problem; this version fires at most once per\n * `injectForm()` consumer that genuinely collides.\n *\n * Keyed `useForm()` calls don't appear here — they don't fill the\n * ambient slot at all (they're addressable explicitly via\n * `injectForm<F>(key)`), so they can't collide with each other\n * or with anonymous siblings on this axis.\n */\nfunction warnIfAmbientProviderHadDuplicates(): void {\n if (!__DEV__ || ambientProvideHistory === null) return\n let ancestor = getCurrentInstance()?.parent ?? null\n while (ancestor !== null) {\n const history = ambientProvideHistory.get(ancestor as unknown as object)\n if (history !== undefined) {\n if (history.length > 1) {\n const lines = history.map((entry) => ` - ${entry.source ?? '<unknown location>'}`)\n console.warn(\n '[attaform] injectForm<F>() (no key) resolved against ' +\n 'an ancestor with multiple anonymous useForm() calls; descendants ' +\n 'only see the last-provided form. Anonymous useForm() calls were:\\n' +\n lines.join('\\n') +\n '\\nFix: pass a key to each call (e.g. useForm({ schema, key: \"x\" })) ' +\n 'and reach them via injectForm<F>(\"x\"), or split the forms ' +\n 'across separate components.'\n )\n }\n return\n }\n ancestor = ancestor.parent\n }\n}\n"],"names":["arr","rec","childRoot","out","cursorRecord","walk","shouldWarnOnce","walked","ok","segments","options","mutated","defaultIsSensitivePath","defaultSegmentMatchesSensitive","currentValue","memoryForUnion","parentKey","diffBlankPaths"],"mappings":";;;;AAsCA,MAAM,SAAA,GAA2B,OAAO,WAAW,CAAA;AAEnD,SAAS,WAAA,CAAY,OAAgB,OAAA,EAA8C;AACjF,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW,OAAO,SAAA;AAClD,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,SAAA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