attaform 0.27.5 → 0.28.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 (184) hide show
  1. package/dist/abstract.d.mts +5 -4
  2. package/dist/abstract.mjs +4 -3
  3. package/dist/chunks/fingerprint.mjs +0 -1
  4. package/dist/chunks/fingerprint2.mjs +1 -2
  5. package/dist/dev/abstract.mjs +4 -0
  6. package/dist/{chunks → dev/chunks}/dev-key-collision-warnings.mjs +0 -1
  7. package/dist/{chunks → dev/chunks}/devtools.mjs +5 -6
  8. package/dist/{chunks/fingerprint.cjs → dev/chunks/fingerprint.mjs} +7 -10
  9. package/dist/{chunks/fingerprint2.cjs → dev/chunks/fingerprint2.mjs} +32 -35
  10. package/dist/dev/directive.mjs +1 -0
  11. package/dist/dev/history.mjs +89 -0
  12. package/dist/dev/index.mjs +5 -0
  13. package/dist/dev/runtime/plugins/attaform.mjs +40 -0
  14. package/dist/{shared/attaform.f2zyNh5d.cjs → dev/shared/attaform-dev.6qxD-Yqo.mjs} +187 -43
  15. package/dist/{shared/attaform.CQN9R62B.cjs → dev/shared/attaform-dev.BJGA_UOS.mjs} +1 -4
  16. package/dist/{shared/attaform.Dc1mx48r.mjs → dev/shared/attaform-dev.BR8u0YOZ.mjs} +6 -7
  17. package/dist/dev/shared/attaform-dev.BXE2cr0L.mjs +220 -0
  18. package/dist/dev/shared/attaform-dev.By4PRjt0.mjs +248 -0
  19. package/dist/{shared/attaform.Cg_8gFQ7.mjs → dev/shared/attaform-dev.D2I8e_Mm.mjs} +132 -568
  20. package/dist/dev/shared/attaform-dev.Dr2YzS5B.mjs +197 -0
  21. package/dist/{shared/attaform.nMaz2C5P.mjs → dev/shared/attaform-dev.P7cseiEG.mjs} +178 -397
  22. package/dist/{shared/attaform.BypWgXRB.mjs → dev/shared/attaform-dev.WmuhD_CZ.mjs} +3955 -5029
  23. package/dist/{shared/attaform.Dkjh_F30.mjs → dev/shared/attaform-dev.oYrkP9dj.mjs} +160 -508
  24. package/dist/dev/zod-v3.mjs +17 -0
  25. package/dist/dev/zod-v4.mjs +16 -0
  26. package/dist/dev/zod.mjs +5 -0
  27. package/dist/directive.d.mts +20 -0
  28. package/dist/directive.mjs +1 -0
  29. package/dist/esbuild.mjs +0 -1
  30. package/dist/history.d.mts +59 -0
  31. package/dist/history.mjs +89 -0
  32. package/dist/index.d.mts +11 -5
  33. package/dist/index.mjs +5 -4
  34. package/dist/nuxt.d.mts +1 -1
  35. package/dist/nuxt.mjs +5 -2
  36. package/dist/rollup.mjs +0 -1
  37. package/dist/rspack.d.mts +6 -1
  38. package/dist/rspack.mjs +0 -1
  39. package/dist/runtime/components/AttaformDevtoolsPanel.vue +9 -8
  40. package/dist/runtime/plugins/attaform.mjs +1 -2
  41. package/dist/shared/{attaform.CIBMfxg9.d.ts → attaform.B4VkS43-.d.mts} +2 -2
  42. package/dist/shared/{attaform.Cg1rUfcF.cjs → attaform.B8k8JrmK.mjs} +3778 -5297
  43. package/dist/shared/attaform.BJGA_UOS.mjs +0 -1
  44. package/dist/shared/{attaform.CTiZ9Rrv.mjs → attaform.C09fpdLS.mjs} +172 -16
  45. package/dist/shared/{attaform.Bh8A6YAc.cjs → attaform.CJP3RkGa.mjs} +141 -590
  46. package/dist/shared/{attaform.CzL2CZ8U.d.ts → attaform.Cgu-hdSb.d.mts} +328 -78
  47. package/dist/shared/attaform.Cs2Rbdlo.mjs +0 -1
  48. package/dist/shared/{attaform.DcFDQVpa.d.ts → attaform.D5V4tZWq.d.mts} +79 -179
  49. package/dist/shared/{attaform.CF-EnyJn.cjs → attaform.D6DCnnQu.mjs} +11 -16
  50. package/dist/shared/attaform.DhnPb6nK.mjs +0 -1
  51. package/dist/shared/attaform.Dq4vWxuG.mjs +197 -0
  52. package/dist/shared/attaform.JfSWdEcb.d.mts +44 -0
  53. package/dist/shared/attaform.KvlEedlF.mjs +0 -1
  54. package/dist/shared/{attaform.Crv0RNiz.cjs → attaform.NLmerepI.mjs} +175 -557
  55. package/dist/shared/attaform.h0i6LijT.mjs +242 -0
  56. package/dist/shared/{attaform.Biytrv0-.cjs → attaform.uLbun31C.mjs} +204 -544
  57. package/dist/shared/attaform.v0fQtWyA.mjs +0 -1
  58. package/dist/shared/attaform.wfY8XFvm.mjs +197 -0
  59. package/dist/transforms.mjs +0 -1
  60. package/dist/vite.d.mts +17 -5
  61. package/dist/vite.mjs +24 -2
  62. package/dist/webpack.d.mts +6 -1
  63. package/dist/webpack.mjs +0 -1
  64. package/dist/zod-v3.d.mts +11 -6
  65. package/dist/zod-v3.mjs +17 -4
  66. package/dist/zod-v4.d.mts +12 -6
  67. package/dist/zod-v4.mjs +16 -4
  68. package/dist/zod.d.mts +4 -3
  69. package/dist/zod.mjs +5 -4
  70. package/package.json +23 -8
  71. package/skills/attaform/SKILL.md +2 -1
  72. package/dist/abstract.cjs +0 -48
  73. package/dist/abstract.cjs.map +0 -1
  74. package/dist/abstract.d.cts +0 -42
  75. package/dist/abstract.d.ts +0 -42
  76. package/dist/abstract.mjs.map +0 -1
  77. package/dist/chunks/dev-key-collision-warnings.cjs +0 -25
  78. package/dist/chunks/dev-key-collision-warnings.cjs.map +0 -1
  79. package/dist/chunks/dev-key-collision-warnings.mjs.map +0 -1
  80. package/dist/chunks/devtools.cjs +0 -157
  81. package/dist/chunks/devtools.cjs.map +0 -1
  82. package/dist/chunks/devtools.mjs.map +0 -1
  83. package/dist/chunks/fingerprint.cjs.map +0 -1
  84. package/dist/chunks/fingerprint.mjs.map +0 -1
  85. package/dist/chunks/fingerprint2.cjs.map +0 -1
  86. package/dist/chunks/fingerprint2.mjs.map +0 -1
  87. package/dist/esbuild.cjs +0 -28
  88. package/dist/esbuild.cjs.map +0 -1
  89. package/dist/esbuild.d.cts +0 -56
  90. package/dist/esbuild.d.ts +0 -56
  91. package/dist/esbuild.mjs.map +0 -1
  92. package/dist/index.cjs +0 -51
  93. package/dist/index.cjs.map +0 -1
  94. package/dist/index.d.cts +0 -249
  95. package/dist/index.d.ts +0 -249
  96. package/dist/index.mjs.map +0 -1
  97. package/dist/nuxt.cjs +0 -84
  98. package/dist/nuxt.cjs.map +0 -1
  99. package/dist/nuxt.d.cts +0 -66
  100. package/dist/nuxt.d.ts +0 -66
  101. package/dist/nuxt.mjs.map +0 -1
  102. package/dist/rollup.cjs +0 -24
  103. package/dist/rollup.cjs.map +0 -1
  104. package/dist/rollup.d.cts +0 -35
  105. package/dist/rollup.d.ts +0 -35
  106. package/dist/rollup.mjs.map +0 -1
  107. package/dist/rspack.cjs +0 -10
  108. package/dist/rspack.cjs.map +0 -1
  109. package/dist/rspack.d.cts +0 -40
  110. package/dist/rspack.d.ts +0 -40
  111. package/dist/rspack.mjs.map +0 -1
  112. package/dist/runtime/components/AttaformDevtoolsPanel.vue.d.ts +0 -7
  113. package/dist/runtime/components/DevtoolsValueTree.vue.d.ts +0 -35
  114. package/dist/runtime/plugins/attaform.cjs +0 -43
  115. package/dist/runtime/plugins/attaform.cjs.map +0 -1
  116. package/dist/runtime/plugins/attaform.d.cts +0 -5
  117. package/dist/runtime/plugins/attaform.d.ts +0 -5
  118. package/dist/runtime/plugins/attaform.mjs.map +0 -1
  119. package/dist/shared/attaform.B3abZaCV.d.cts +0 -2484
  120. package/dist/shared/attaform.BJGA_UOS.mjs.map +0 -1
  121. package/dist/shared/attaform.Bh8A6YAc.cjs.map +0 -1
  122. package/dist/shared/attaform.Biytrv0-.cjs.map +0 -1
  123. package/dist/shared/attaform.Bn0IzhD_.cjs +0 -800
  124. package/dist/shared/attaform.Bn0IzhD_.cjs.map +0 -1
  125. package/dist/shared/attaform.BypWgXRB.mjs.map +0 -1
  126. package/dist/shared/attaform.C9fPTxjB.d.cts +0 -41
  127. package/dist/shared/attaform.C9fPTxjB.d.ts +0 -41
  128. package/dist/shared/attaform.CF-EnyJn.cjs.map +0 -1
  129. package/dist/shared/attaform.CJ1Z9Mz4.d.mts +0 -2484
  130. package/dist/shared/attaform.CQN9R62B.cjs.map +0 -1
  131. package/dist/shared/attaform.CTiZ9Rrv.mjs.map +0 -1
  132. package/dist/shared/attaform.Cg1rUfcF.cjs.map +0 -1
  133. package/dist/shared/attaform.Cg_8gFQ7.mjs.map +0 -1
  134. package/dist/shared/attaform.Crv0RNiz.cjs.map +0 -1
  135. package/dist/shared/attaform.Cs2Rbdlo.mjs.map +0 -1
  136. package/dist/shared/attaform.CzL2CZ8U.d.cts +0 -4713
  137. package/dist/shared/attaform.CzL2CZ8U.d.mts +0 -4713
  138. package/dist/shared/attaform.DRUT703x.d.cts +0 -56
  139. package/dist/shared/attaform.DRUT703x.d.ts +0 -56
  140. package/dist/shared/attaform.DYwyM5Cp.d.cts +0 -232
  141. package/dist/shared/attaform.Dc1mx48r.mjs.map +0 -1
  142. package/dist/shared/attaform.DhnPb6nK.mjs.map +0 -1
  143. package/dist/shared/attaform.Dkjh_F30.mjs.map +0 -1
  144. package/dist/shared/attaform.DoQm_Vkd.cjs +0 -58
  145. package/dist/shared/attaform.DoQm_Vkd.cjs.map +0 -1
  146. package/dist/shared/attaform.DrHOqB-d.d.mts +0 -232
  147. package/dist/shared/attaform.KvlEedlF.mjs.map +0 -1
  148. package/dist/shared/attaform.RaTzp1WF.cjs +0 -26
  149. package/dist/shared/attaform.RaTzp1WF.cjs.map +0 -1
  150. package/dist/shared/attaform.f2zyNh5d.cjs.map +0 -1
  151. package/dist/shared/attaform.nMaz2C5P.mjs.map +0 -1
  152. package/dist/shared/attaform.v0fQtWyA.mjs.map +0 -1
  153. package/dist/shared/attaform.yUrz7C2z.cjs +0 -29
  154. package/dist/shared/attaform.yUrz7C2z.cjs.map +0 -1
  155. package/dist/transforms.cjs +0 -12
  156. package/dist/transforms.cjs.map +0 -1
  157. package/dist/transforms.d.cts +0 -73
  158. package/dist/transforms.d.ts +0 -73
  159. package/dist/transforms.mjs.map +0 -1
  160. package/dist/vite.cjs +0 -363
  161. package/dist/vite.cjs.map +0 -1
  162. package/dist/vite.d.cts +0 -133
  163. package/dist/vite.d.ts +0 -133
  164. package/dist/vite.mjs.map +0 -1
  165. package/dist/webpack.cjs +0 -10
  166. package/dist/webpack.cjs.map +0 -1
  167. package/dist/webpack.d.cts +0 -37
  168. package/dist/webpack.d.ts +0 -37
  169. package/dist/webpack.mjs.map +0 -1
  170. package/dist/zod-v3.cjs +0 -53
  171. package/dist/zod-v3.cjs.map +0 -1
  172. package/dist/zod-v3.d.cts +0 -246
  173. package/dist/zod-v3.d.ts +0 -246
  174. package/dist/zod-v3.mjs.map +0 -1
  175. package/dist/zod-v4.cjs +0 -55
  176. package/dist/zod-v4.cjs.map +0 -1
  177. package/dist/zod-v4.d.cts +0 -172
  178. package/dist/zod-v4.d.ts +0 -172
  179. package/dist/zod-v4.mjs.map +0 -1
  180. package/dist/zod.cjs +0 -51
  181. package/dist/zod.cjs.map +0 -1
  182. package/dist/zod.d.cts +0 -7
  183. package/dist/zod.d.ts +0 -7
  184. package/dist/zod.mjs.map +0 -1
@@ -1,2484 +0,0 @@
1
- import { G as GenericForm, F as FormKey, a as UseFormReturnType, a4 as RegisterValue, T as PathKey, k as DisplayCtx, w as GetDisplayState, l as DisplayMachine, S as Path, a9 as SlimPrimitiveKind, C as CoercionEntry, e as CoercionRegistry, af as ValidationError, A as AbstractSchema, aj as WriteMeta, h as DeepPartial, ak as WriteShape, as as TransformAbortHolder, ad as ValidateOn, d as AttaformDefaults, at as RegisterModelDynamicCustomDirective } from './attaform.CzL2CZ8U.mjs';
2
- import { Ref, ComputedRef, App, InjectionKey, Plugin } from 'vue';
3
-
4
- /**
5
- * Options accepted by `injectForm` when passing an object instead of
6
- * a bare key string. `__ssrAccessed: true` is set by the Phase 3
7
- * `attaform-vite` transform on descendant calls whose template reads
8
- * the injected form's reactive state — it tells the runtime to
9
- * enqueue the form for SSR prefetch and register the descendant's
10
- * `onServerPrefetch` hook. Consumers may set it manually as the
11
- * escape hatch when the transform isn't installed or doesn't see
12
- * the reference.
13
- */
14
- type InjectFormInput = {
15
- readonly key?: FormKey;
16
- /**
17
- * Set by the Vite transform when this `injectForm` call site sits in
18
- * a component whose template / script reads the form's reactive
19
- * state. On the server, this enqueues the form for SSR prefetch and
20
- * wires `onServerPrefetch` so the descendant awaits the activation
21
- * promise before its render emits HTML.
22
- *
23
- * @internal Transform-emitted. Manual use is the documented escape
24
- * hatch when the transform can't reach the reference (dynamic
25
- * property access, untransformed bundlers).
26
- */
27
- readonly __ssrAccessed?: boolean;
28
- };
29
- /**
30
- * Access an existing form from a descendant component without passing
31
- * it through props. Counterpart to `useForm` — `useForm` creates and
32
- * provides; `injectForm` looks up via Vue's inject mechanism.
33
- *
34
- * Three ways to call it:
35
- *
36
- * ```ts
37
- * // Reach the nearest ancestor's anonymous useForm() call.
38
- * const form = injectForm<SignupShape>()
39
- *
40
- * // Reach a specific form by its key — works from anywhere in the app.
41
- * const cart = injectForm<CartShape>('cart')
42
- *
43
- * // Options form. The Vite transform emits this with `__ssrAccessed: true`
44
- * // when the descendant's template / script reads the form's reactive
45
- * // state, so the descendant participates in SSR prefetch coordination.
46
- * const cart = injectForm<CartShape>({ key: 'cart', __ssrAccessed: true })
47
- * ```
48
- *
49
- * Resolution rules (no-key form):
50
- * - Closest ambient ancestor wins.
51
- * - Only anonymous `useForm()` (no `key`) fills the ambient slot;
52
- * keyed forms are reachable only via `injectForm(key)`.
53
- * - Inherits the resolved ancestor's `formInstanceId`.
54
- *
55
- * Resolution rules (keyed form): registry lookup by string key,
56
- * independent of component-tree position.
57
- *
58
- * Returns `null` when no matching form exists (no ambient ancestor, or
59
- * the named key isn't registered yet). A dev-mode warning points at the
60
- * call site, lists the registered keys, and flags the mount-timing case
61
- * (a form created by a child or sibling isn't registered until its own
62
- * setup runs). Always narrow before using:
63
- *
64
- * ```ts
65
- * const form = injectForm<Shape>('signup')
66
- * if (!form) return
67
- * form.register('email')
68
- * ```
69
- *
70
- * Pass the `Form` generic explicitly — Vue's provide/inject erases
71
- * generics, so the library can't recover the shape automatically.
72
- *
73
- * The form is kept alive for this component's lifetime; once every
74
- * consumer unmounts, the form is cleaned up automatically.
75
- */
76
- declare function injectForm<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(input?: FormKey | InjectFormInput): UseFormReturnType<Form, GetValueFormType> | null;
77
-
78
- /**
79
- * Re-bind a parent's `v-register` onto an inner native element. Use
80
- * inside a component that wraps a single form field whose root is
81
- * NOT the input itself (e.g. a labelled-row that renders `<label>`
82
- * around the input).
83
- *
84
- * ```vue
85
- * <!-- Parent -->
86
- * <MyInput v-register="form.register('email')" />
87
- *
88
- * <!-- MyInput.vue -->
89
- * <script setup lang="ts">
90
- * import { useRegister } from 'attaform'
91
- * const rv = useRegister()
92
- * // rv.path / rv.segments / rv.formKey / rv.formInstanceId / rv.innerRef
93
- * // are all reachable directly — no `.value` unwrap.
94
- * </script>
95
- *
96
- * <template>
97
- * <label class="field">
98
- * <span>Email</span>
99
- * <input v-register="rv" />
100
- * </label>
101
- * </template>
102
- * ```
103
- *
104
- * Returns a hybrid Proxy: it answers `__v_isRef` / `.value` like a
105
- * Vue `Ref<RegisterValue | undefined>` (so templates auto-unwrap
106
- * correctly and `v-register="rv"` feeds the underlying RV to the
107
- * directive — preserving the directive's path-migration diff across
108
- * renders), AND every other property read pierces to the captured
109
- * RV's field (so `rv.path` works directly in script setup). Reads
110
- * inside reactive scopes (`computed` / `watchEffect`) track the
111
- * underlying `shallowRef`, so `rv.path` re-runs when the parent
112
- * rebinds to a different path.
113
- *
114
- * Unbound state: when the parent didn't pass `v-register`, every
115
- * piercing read returns `undefined` at runtime, and the return type
116
- * surfaces this honestly as `UseRegisterReturn<V> | undefined`.
117
- * Consumers defend with optional chaining (`rv?.formKey`,
118
- * `rv?.segments`); the directive accepts `undefined` peacefully (its
119
- * binding value type is already `RegisterValue<V> | undefined`), so
120
- * `v-register="rv"` works whether or not a parent has bound. The
121
- * composable's `onMounted` warn fires once per instance to surface
122
- * the misuse case at runtime.
123
- *
124
- * Diagnostic: in dev mode, a single `console.warn` fires per instance
125
- * at `onMounted` if the captured value is still `undefined` — by then
126
- * the parent has had its full mount lifecycle to bind, so a missing
127
- * binding is conclusive misuse. The warn does NOT fire on every read
128
- * of the proxy, and is intentionally silent under SSR
129
- * (`renderToString` skips `onMounted`); the CSR hydration pass
130
- * surfaces the same diagnostic without double-counting through Nuxt's
131
- * `dev:ssr-logs` channel.
132
- *
133
- * When the wrapper's root IS the input itself, Vue's attribute
134
- * fallthrough handles the binding and `useRegister` is unnecessary.
135
- * For wrappers that bind multiple fields (compound forms), use
136
- * `injectForm<Form>(key?)` and call `ctx.register(...)` directly.
137
- */
138
-
139
- /**
140
- * Return type of `useRegister()`. Hybrid of `RegisterValue<V>` (so
141
- * `rv.path` / `rv.segments` / `rv.formKey` etc. work directly in
142
- * script setup) and `Ref<RegisterValue<V> | undefined>` (so Vue's
143
- * template auto-unwrap surfaces the underlying RV to `v-register`
144
- * and the directive's path-migration diff sees the real RV across
145
- * renders).
146
- *
147
- * The two surfaces don't clash at the type level: `RegisterValue`
148
- * doesn't carry a `value` field, and `Ref<T>`'s `value: T` becomes
149
- * the hybrid's only `.value`. Older code that read `rv.value?.path`
150
- * keeps working; new code can write `rv.path` directly.
151
- */
152
- type UseRegisterReturn<V = unknown> = RegisterValue<V> & Ref<RegisterValue<V> | undefined>;
153
- declare function useRegister<V = unknown>(): UseRegisterReturn<V> | undefined;
154
-
155
- /**
156
- * Per-form display engine: owns the clock and the timers that the pure
157
- * `getDisplayState` reducer policy needs, so the reducer itself stays a
158
- * deterministic `(prev, ctx) => next` function.
159
- *
160
- * It keeps a `Map` of the machines that are still *active* (a spinner is
161
- * showing, a verdict is being held, or a `reviewAt` deadline is pending),
162
- * a single reactive `tick` ref, and a single `setTimeout` aimed at the
163
- * nearest `reviewAt` across every active field. When a field-state
164
- * computed reads `resolve`, it subscribes to `tick`; when the timer
165
- * fires, `tick` bumps and every dependent computed re-runs the reducer,
166
- * so a field whose deadline elapsed transitions (verdict → spinner, or
167
- * spinner → settled verdict) without any per-field watcher.
168
- *
169
- * Eviction: a machine is dropped once it reaches a terminal *idle* state
170
- * with no pending review. Error / success / pending machines are retained
171
- * so the reducer can hold the prior verdict under the show-delay window of
172
- * the *next* validation streak (no success → idle → success flicker). The
173
- * retained set is bounded by the rendered non-idle fields; none of them
174
- * arm a timer, so retention costs memory, never CPU.
175
- *
176
- * Untrusted reducer: `getDisplayState` is consumer-overridable, so the
177
- * engine treats the returned `reviewAt` as untrusted. A non-finite deadline
178
- * (NaN / ±Infinity from a custom predicate's bad arithmetic) is ignored
179
- * rather than handed to `setTimeout`, where it coerces to 0 and spins; an
180
- * over-large finite deadline is clamped below the 32-bit `setTimeout`
181
- * overflow; and the timer refuses to re-arm for the exact deadline it just
182
- * fired, so a predicate re-emitting a fixed or past `reviewAt` can't drive an
183
- * infinite fire loop. None of these arise from the library default, which
184
- * always advances its deadline or drops it.
185
- *
186
- * Background tabs: `setTimeout` is throttled to >= 1s while a tab is hidden,
187
- * so a min-visible hold can overshoot. A `visibilitychange` listener bumps
188
- * the clock on return to the foreground, so any overdue deadline resolves at
189
- * once instead of lingering.
190
- *
191
- * SSR: no clock, no timers, no listener. With `now` frozen and nothing
192
- * validating at render, the reducer returns the plain verdict (never
193
- * pending) and the engine stores nothing, so the server HTML and the
194
- * client's first render agree — no hydration mismatch on the display
195
- * projection.
196
- */
197
- type DisplayEngine = {
198
- /**
199
- * Resolve a path's next `DisplayMachine`. Subscribes the calling
200
- * computed to the engine clock, threads the path's previous machine
201
- * through `reducer`, persists or evicts the result, and re-arms the
202
- * single timer to the nearest deadline.
203
- */
204
- resolve(key: PathKey, ctx: DisplayCtx, reducer: GetDisplayState): DisplayMachine;
205
- /** Drop every retained machine and cancel the timer (used by `reset()`). */
206
- clear(): void;
207
- /** Tear down for good: `clear()` plus detaching the visibility listener. */
208
- dispose(): void;
209
- /** Introspection for tests: count of retained machines. */
210
- size(): number;
211
- /** Introspection for tests: whether a path currently has a retained machine. */
212
- has(key: PathKey): boolean;
213
- /** Introspection for tests: whether a deadline timer is currently armed. */
214
- hasTimer(): boolean;
215
- };
216
-
217
- /**
218
- * Per-path field status. Replaced wholesale (not mutated in place) on
219
- * every change. Five semantic groups:
220
- *
221
- * - `connected` — is a DOM element registered for this path?
222
- * - `focused` / `blurred` — DOM-state flags. `null` while no element
223
- * is connected (no DOM means the concepts don't apply); plain
224
- * booleans once connected, with the invariant `blurred === !focused`
225
- * enforced by `markFocused`.
226
- * - `touched` — focus/blur history, not DOM state. Always a plain
227
- * boolean: `false` at registration, sticky `true` after first blur,
228
- * cleared only by `form.reset()` / `form.resetField(path)`. Persists
229
- * across disconnects so v-if'd-away fields don't lose their touched
230
- * state on rehide (wizard "show review of touched fields" patterns
231
- * rely on this).
232
- * - `interacted` — value-mutation history, not DOM state. Plain
233
- * boolean: `false` at registration, sticky `true` once the user
234
- * issues a value edit through the directive's input listeners
235
- * (never on hydration, default seeding, or programmatic setValue);
236
- * cleared with `touched` by `form.reset()` / `form.resetField(path)`.
237
- * - `blurredAfterInteraction` — the first blur that follows a value
238
- * edit (the field has been edited and then left). Plain boolean,
239
- * sticky `true`. A tab-through blur with no prior edit does NOT set
240
- * it (`interacted` is still false at that blur). Composes
241
- * `interacted` with the departure; drives the default display gate.
242
- */
243
- type FieldRecord = {
244
- readonly path: Path;
245
- readonly updatedAt: string | null;
246
- readonly connected: boolean;
247
- readonly focused: boolean | null;
248
- readonly blurred: boolean | null;
249
- readonly touched: boolean;
250
- readonly interacted: boolean;
251
- readonly blurredAfterInteraction: boolean;
252
- };
253
- /** Per-path DOM element tracking. Client-only. */
254
- type ElementRecord = {
255
- /**
256
- * Original Path captured at first registration. Stored alongside the
257
- * elements Set so the DOM-order sort cache can recover the structured
258
- * Path without round-tripping through `JSON.parse(pathKey)`.
259
- */
260
- readonly path: Path;
261
- readonly elements: Set<HTMLElement>;
262
- };
263
- /**
264
- * Per-path record stored in `originals`. Pairing `segments` with the tracked
265
- * value means `dirty` and `resetField`'s container loop don't have to
266
- * `JSON.parse(pathKey)` on every iteration — the canonical Path is already
267
- * sitting next to the value it belongs to. PathKey still keys the Map (the
268
- * stable string is the only collision-free identifier), but downstream
269
- * iteration reads `segments` directly.
270
- */
271
- type OriginalsRecord = {
272
- readonly segments: Path;
273
- readonly value: unknown;
274
- };
275
-
276
- /**
277
- * Schema-driven coercion of user-typed DOM values at the v-register
278
- * directive layer. When the slim schema declares a numeric or
279
- * boolean type at a path, the directive coerces incoming string
280
- * values (`'25'` → `25`, `'true'` → `true`) before the slim-primitive
281
- * gate sees the write — making the schema authoritative for storage
282
- * shape and freeing consumers from sprinkling `.number` modifiers
283
- * across templates.
284
- *
285
- * Coercion is consumer-extensible: a `CoercionRegistry` is just an
286
- * `Array<CoercionEntry>` keyed at config time by `(input, output)`
287
- * `SlimPrimitiveKind` literals. The library ships
288
- * `defaultCoercionRules` (string→number, string→boolean) and
289
- * `defineCoercion` for type-narrowed authoring; consumers spread the
290
- * defaults to extend or supply their own array to replace.
291
- *
292
- * Coercion applies ONLY to user-typed DOM values flowing through
293
- * the directive's assigner. Programmatic writes (`form.setValue`,
294
- * `setValueWithInternalPath`) bypass coercion — they're authoritative
295
- * writes whose strict typing is on the caller. This mirrors the
296
- * `transforms` pipeline's user-input-only contract.
297
- */
298
-
299
- /**
300
- * Type-narrowing helper for authoring entries. At runtime it's
301
- * identity; at compile time it preserves the `input` / `output`
302
- * literal types so `transform`'s parameter is narrowed to the
303
- * runtime type instead of widening to `SlimRuntimeOf<SlimPrimitiveKind>`.
304
- *
305
- * Without this helper, authoring `{ input: 'string', output:
306
- * 'number', transform: (s) => ... }` against the broader
307
- * `CoercionEntry` widens `s` to `string | number | boolean | ...`,
308
- * forcing a cast in every transform body. `defineCoercion` is the
309
- * opaque-free idiom.
310
- */
311
- declare function defineCoercion<I extends SlimPrimitiveKind, O extends SlimPrimitiveKind>(entry: CoercionEntry<I, O>): CoercionEntry<I, O>;
312
- /**
313
- * Internal index built from a `CoercionRegistry` at config-resolve
314
- * time. Keyed by `${input}->${output}` for O(1) per-keystroke
315
- * dispatch. The authoring shape (array, ergonomic, type-narrowing-
316
- * friendly) and the dispatch shape (Map, fast) decouple cleanly.
317
- */
318
- type CoercionIndex = ReadonlyMap<`${SlimPrimitiveKind}->${SlimPrimitiveKind}`, CoercionEntry>;
319
- /**
320
- * The library's built-in registry. Two cells: string→number and
321
- * string→boolean. Re-exported so consumers can spread it when
322
- * supplying a custom registry that extends defaults.
323
- */
324
- declare const defaultCoercionRules: CoercionRegistry;
325
-
326
- type FormStore<F extends GenericForm, G extends GenericForm = F> = {
327
- readonly formKey: FormKey;
328
- readonly form: Ref<F>;
329
- readonly fields: Map<PathKey, FieldRecord>;
330
- readonly elements: Map<PathKey, ElementRecord>;
331
- /**
332
- * Schema-driven errors. Written ONLY by the schema validation pipeline:
333
- * `scheduleFieldValidation`, `handleSubmit`, the construction-time seed,
334
- * history restore, and hydration. Cleared by `reset` / `resetField` and by
335
- * a successful submit. `setErrors` / `clearErrors` do NOT touch this Map.
336
- */
337
- readonly schemaErrors: Map<PathKey, ValidationError[]>;
338
- /**
339
- * User-injected errors. Written ONLY by the `setErrors` / `clearErrors`
340
- * API surface (and history / hydration replay). Survives schema revalidation and
341
- * successful submits — the consumer owns its lifetime explicitly.
342
- */
343
- readonly userErrors: Map<PathKey, ValidationError[]>;
344
- /**
345
- * Reactively-derived "No value supplied" errors. Pure function of
346
- * `(blankPaths, schema.isRequiredAtPath)` — no writers, no clears.
347
- * Membership tracks `blankPaths` automatically: typing a value into
348
- * a blank required numeric field removes the path from `blankPaths`
349
- * and the derived error vanishes; clearing the numeric input re-adds
350
- * the path and the error reappears. The `errors` proxy and
351
- * `getErrorsForPath` merge this map in alongside `schemaErrors` and
352
- * `userErrors`, so consumers see the "this required field is empty"
353
- * error the moment it's true — no `validate()` / `handleSubmit`
354
- * call required. Honors the founding principle that
355
- * `errors = f(schema, state)`.
356
- *
357
- * Most entries flow through this map for `number` / `bigint` leaves
358
- * (where the side-channel is needed to distinguish "user typed 0"
359
- * from "user supplied nothing"). String / boolean leaves only land
360
- * here when the consumer explicitly opted in via the `unset`
361
- * sentinel — see `docs/validation/blank.md`.
362
- */
363
- readonly derivedBlankErrors: ComputedRef<ReadonlyMap<PathKey, ValidationError[]>>;
364
- readonly originals: Map<PathKey, OriginalsRecord>;
365
- /**
366
- * Reactive set of paths whose displayed state should be EMPTY even
367
- * though storage holds a real, schema-conformant value (the slim
368
- * default). It exists exclusively to record **storage / display
369
- * divergence** — the case where the runtime can't tell "user typed
370
- * 0" from "user supplied nothing" by looking at storage alone.
371
- *
372
- * The mechanism shines for `number` / `bigint`: storage holds the
373
- * slim default (`0` / `0n`) but the DOM input shows `''`, so the
374
- * directive's input listener marks the path here on clear. Strings
375
- * and booleans don't need it — `''` storage equals `''` display,
376
- * `false` storage equals unchecked display — so they're never
377
- * auto-marked. Consumers can still mark any primitive leaf
378
- * explicitly via the `unset` sentinel (`defaultValues: { x: unset }`,
379
- * `setValue('x', unset)`, `reset({ x: unset })`); the mark is then
380
- * a documented signal of consumer intent rather than runtime
381
- * inference.
382
- *
383
- * Reads (`displayValue` computed, `fields.<path>.blank`,
384
- * `derivedBlankErrors` computed) track via Vue 3.5's reactive Set
385
- * handlers. Writes happen inside `setValueAtPath` (gate-hook
386
- * bookkeeping: `blank: true` meta adds the path; any other write
387
- * removes it) and `reset`.
388
- *
389
- * Storage NEVER reflects this set — calculations and reads against
390
- * `form.value` see the slim default. The set is purely a UI/intent
391
- * channel that `derivedBlankErrors` consults to surface
392
- * "No value supplied" errors for required schemas.
393
- *
394
- * See `docs/validation/blank.md` for the conceptual model.
395
- */
396
- readonly blankPaths: Set<PathKey>;
397
- /**
398
- * Snapshot of `blankPaths` captured at construction (and
399
- * re-captured on `reset(args)`). Used by dirty calculation: a path
400
- * whose membership differs from the snapshot is dirty even if
401
- * storage matches the original. Eagerly populated to avoid a "dirty
402
- * on first read" race after construction.
403
- */
404
- readonly originalBlankPaths: Set<PathKey>;
405
- readonly schema: AbstractSchema<F, G>;
406
- /**
407
- * Server-side flag, plumbed in from `registry.ssr`. The
408
- * `register()`-returned `markConnectedOptimistically()` reads this
409
- * before flipping `connected: true`; on the client it's a no-op so
410
- * the eventual directive lifecycle remains the source of truth.
411
- */
412
- readonly ssr: boolean;
413
- /**
414
- * Resolved `getDisplayState` predicate driving `field.displayState`,
415
- * the `show*` booleans, and their `form.meta` rollups. Resolved once
416
- * at construction via `resolveGetDisplayState(options.getDisplayState)`;
417
- * `undefined` config falls through to `defaultDisplayState`. The
418
- * field-state computeds read the resolved function directly on every
419
- * read.
420
- */
421
- readonly getDisplayState: GetDisplayState;
422
- /**
423
- * Per-form display engine: owns the clock and the single timer the timed
424
- * `getDisplayState` reducer policy needs, keeping the reducer itself a
425
- * pure `(prev, ctx) => next` function. The field-state computeds route
426
- * every `displayState` read through `displayEngine.resolve(...)`, which
427
- * threads the path's previous machine, persists or evicts the result, and
428
- * re-arms the nearest-deadline timer. Constructed once at form
429
- * construction; torn down via `registerCleanup` on store eviction.
430
- */
431
- readonly displayEngine: DisplayEngine;
432
- readonly submitting: Ref<boolean>;
433
- readonly activeSubmissions: Ref<number>;
434
- readonly submissionAttempts: Ref<number>;
435
- /**
436
- * `true` once a `handleSubmit` callback resolved without throwing.
437
- * Independent of `submissionAttempts` — a failed submit increments
438
- * attempts but leaves `submitted` at `false`. Cleared by `reset()`
439
- * alongside the rest of the submission surface.
440
- */
441
- readonly submitted: Ref<boolean>;
442
- readonly submitError: Ref<Error | null>;
443
- readonly departAttempts: Ref<number>;
444
- /**
445
- * Effective data-freeze state: `true` when either the form's own
446
- * `disabled` config resolves truthy or `externalLock` is set. Read at
447
- * the write chokepoint (`setValueAtPath`), the register value's
448
- * `disabled`, and the field display predicate.
449
- */
450
- readonly effectiveDisabled: ComputedRef<boolean>;
451
- /**
452
- * Wizard-driven freeze channel. `useWizard` sets this `true` for a
453
- * locked step's member form; ORed into `effectiveDisabled` so the
454
- * wizard lock is authoritative and a member form cannot escape it by
455
- * passing `disabled: false`. Default `false`.
456
- */
457
- readonly externalLock: Ref<boolean>;
458
- /**
459
- * `true` while a function-form `defaultValues` factory is in flight.
460
- * Stays `false` for plain-value `defaultValues`. Shared across every
461
- * `useForm({ key })` call that resolves to this store — the second
462
- * caller sees the first caller's hydration state.
463
- */
464
- readonly hydrating: Ref<boolean>;
465
- /**
466
- * Error from the most recent function-form `defaultValues` factory.
467
- * Normalized to a `ValidationError` (code `atta:hydration-failed`) so the
468
- * shape matches `form.errors` / `form.meta.errors` entries. `null` when
469
- * no factory has fired or the last one succeeded.
470
- */
471
- readonly hydrateError: Ref<ValidationError | null>;
472
- /**
473
- * The function-form `defaultValues` factory, captured at the first
474
- * `useForm({ key })` call that wired this store. `undefined` for
475
- * plain-value forms. Read by `form.rehydrate()`.
476
- */
477
- readonly defaultValuesFactory: Ref<(() => unknown | Promise<unknown>) | undefined>;
478
- /**
479
- * `true` when this store carries an SSR prefetch queue (server path
480
- * where `state.activate()` must enqueue intent before deciding
481
- * whether to fire). The flag lets `buildFormApi` skip the lazy
482
- * activation gate for forms with no factory AND no SSR prefetch —
483
- * the common client-side case where `gated()` is otherwise pure
484
- * reactive overhead on every public method call.
485
- */
486
- readonly hasSsrPrefetch: boolean;
487
- /**
488
- * `true` once the form's effective defaults have been applied —
489
- * sync `defaultValues` at construction, or async factory whose
490
- * settle completed. Stays `false` for dormant lazy forms until they
491
- * activate. Read by `useWizard` to decide whether seed status or
492
- * live meta should surface.
493
- */
494
- readonly defaultsResolved: Ref<boolean>;
495
- /**
496
- * `true` once the captured async factory has been kicked off (set
497
- * synchronously by `activate()`, before the factory itself resolves).
498
- * Distinct from `defaultsResolved`, which only flips after the factory
499
- * settles. The pair lets the API surface tell "we've started" apart
500
- * from "we're done."
501
- */
502
- readonly activated: Ref<boolean>;
503
- /**
504
- * In-flight activation promise. Concurrent callers (cross-component
505
- * SSR consumers, recursive factory reads, parallel `activate()`
506
- * calls) receive the same promise, ensuring the factory runs once
507
- * even under contention.
508
- */
509
- readonly activationPromise: Ref<Promise<void> | undefined>;
510
- /**
511
- * Idempotent activation entrypoint. Fires the captured function-form
512
- * `defaultValues` factory on first call and stores the in-flight
513
- * promise. Subsequent calls return the same promise until the factory
514
- * settles; thereafter calls return `Promise.resolve()`. Plain-value
515
- * forms (no factory captured) always return a resolved promise. The
516
- * public API surface routes all reactive interactions (getters and
517
- * methods, except `key`) through this entrypoint so the form
518
- * activates on first use.
519
- */
520
- activate(): Promise<void>;
521
- /**
522
- * Re-fire the captured function-form `defaultValues` factory. Throws
523
- * synchronously when no factory was captured (plain-value form).
524
- * Resolves after `hydrating` flips back to `false`; consumers can
525
- * `await form.rehydrate()` to gate UI on the fresh load.
526
- *
527
- * Does NOT touch dirty / touched / submit state — chain
528
- * `form.reset()` if you want a clean baseline.
529
- */
530
- rehydrate(): Promise<void>;
531
- /**
532
- * Incremented by every `reset()` call. The submit wrapper captures
533
- * this at entry and skips writing `submitError` from a catch that
534
- * fires *after* a reset — otherwise a reset-during-submit would
535
- * visibly clear `submitError` and then have it reappear when the
536
- * in-flight promise rejects.
537
- */
538
- readonly submissionGeneration: Ref<number>;
539
- /**
540
- * Counts in-flight validation calls across every `validate()` ref and
541
- * every `validateAsync(...)` / `handleSubmit` pre-check. `validating`
542
- * on the public API mirrors `activeValidations.value > 0`. Tracked
543
- * separately from submissions because a validate-while-submitting
544
- * (e.g. a debounced field check overlapping a submit) needs to show
545
- * the union of both surfaces.
546
- */
547
- readonly activeValidations: Ref<number>;
548
- /**
549
- * `true` once the form has completed at least one validation pass
550
- * — flips when `activeValidations` returns to 0 from any positive
551
- * value. Until that happens, `meta.valid` and `field.valid` report
552
- * `false` even when `schemaErrors.size === 0`, because the absence
553
- * of errors at frame 1 is just "we haven't checked yet," not "we
554
- * checked and it's clean."
555
- *
556
- * This closes the brief flash window for schemas where the slim
557
- * default-derivation parse strips refinements (`.refine`,
558
- * `.superRefine`, async validators): the slim parse passes, no
559
- * construction-time errors land, and the queued microtask hasn't
560
- * run yet — so without the gate, frame 1 paints the form as
561
- * "valid" before the real verdict arrives a tick later.
562
- *
563
- * Initialized to `!strict`: non-strict consumers opt out of the
564
- * validation pipeline by design, so locking them on
565
- * `firstValidationDone === false` would defeat the opt-out.
566
- * Reset is left untouched — the post-reset validation flips it
567
- * back true on completion, same as the construction-time path.
568
- */
569
- readonly firstValidationDone: Ref<boolean>;
570
- /**
571
- * `true` when the sub-schema rooted at `path` (or any of its
572
- * descendants) declares async work — composes
573
- * `schema.getSchemasAtPath(path)` with each candidate's
574
- * `needsAsyncValidation()`, memoised per canonical path key for
575
- * the lifetime of the FormStore. Used by `meta.valid` /
576
- * `field.valid` to skip the `firstValidationDone` gate on subtrees
577
- * that are fully synchronous: their verdict resolves at construction
578
- * (or on the next per-field run) without waiting on a microtask, so
579
- * honouring the form-wide gate would just play dumb about a known
580
- * answer.
581
- */
582
- pathHasAsyncValidation(path: Path): boolean;
583
- /**
584
- * Precomputed-key shortcut for `pathHasAsyncValidation`. The
585
- * canonical key is required and must correspond to `segments`; the
586
- * helper skips the `canonicalizePath` round-trip so descendant-walk
587
- * loops (whose Map iteration already yields the canonical key) can
588
- * read the async-gate verdict without a per-leaf canonicalize.
589
- */
590
- pathHasAsyncValidationByKey(key: PathKey, segments: Path): boolean;
591
- /**
592
- * Per-path counter of in-flight field-level validation runs.
593
- * `field.validating` on `FieldState` mirrors
594
- * `(fieldValidationCounts.get(key) ?? 0) > 0`.
595
- *
596
- * Incremented at the same point as `activeValidations` inside
597
- * `scheduleFieldValidation`'s `run` closure (right before the schema
598
- * call) and decremented in the matching `.finally` — so the per-path
599
- * bookkeeping is exactly co-extensive with the form-wide counter for
600
- * the field-scheduled branch. Whole-form `validate()` /
601
- * `validateAsync()` runs touch `activeValidations` only; they don't
602
- * have a single field path and so don't contribute here.
603
- *
604
- * Counter (not Set) because two runs for the same path can briefly
605
- * overlap: when an in-flight run is aborted and a new run starts,
606
- * the new run increments before the aborted run's `.finally`
607
- * decrements. With `> 0` semantics the field stays "validating"
608
- * across the abort/restart boundary.
609
- *
610
- * Reactive Map: Vue 3's `reactive(new Map())` proxy makes `.get()`,
611
- * `.has()`, and `.size` track per-key, so the FieldState
612
- * computed only re-runs when the count for ITS key changes.
613
- */
614
- readonly fieldValidationCounts: Map<PathKey, number>;
615
- /**
616
- * Per-path `Date.now()` stamp marking when the field's LATEST validation
617
- * run started, re-anchored on every run start (every increment), deleted
618
- * on the `→ 0` edge. The display reducer reads it as `ctx.validatingSince`
619
- * to time the anti-flash spinner, which measures `now - validatingSince`:
620
- * re-anchoring on each run means a burst of keystrokes (each aborting the
621
- * prior run and starting a new one) keeps pushing the stamp forward, so the
622
- * spinner stays suppressed until the user pauses rather than surfacing
623
- * mid-typing. Anchoring only at the streak start would pin it to the first
624
- * keystroke, because with `debounceMs: 0` the aborted run's decrement lands
625
- * after the next run's increment and the count never returns to 0 between
626
- * fast keystrokes. The field-state container walk takes the descendant-min
627
- * so a row spinner anchors at its earliest still-active leaf. Runtime-only,
628
- * never hydrated, like the counts. REACTIVE: the display computed reads this
629
- * (as `ctx.validatingSince`) but not the `validating` flag, and a long
630
- * validation that settles with an unchanged verdict (same error, still
631
- * invalid) leaves `errors` / `valid` untouched — so a non-reactive map would
632
- * leave a held `pending` spinner stranded after the run ends, until some
633
- * unrelated reactive change happened to re-run the computed. Reactivity ties
634
- * the computed to both the streak start (set) and end (delete).
635
- */
636
- readonly fieldValidatingSince: Map<PathKey, number>;
637
- /**
638
- * Per-path counter of in-flight async-transform runs (the async
639
- * branch of the `register({ transforms })` pipeline). `> 0` drives
640
- * `field.transforming` / `field.busy`. Counter, not flag, for the
641
- * same overlap reason as `fieldValidationCounts`, except a superseding
642
- * input releases the prior run synchronously before incrementing the
643
- * new one — so the count is the live in-flight depth at the path
644
- * (effectively 0 or 1). Reactive Map, like the validation counters.
645
- */
646
- readonly fieldTransformCounts: Map<PathKey, number>;
647
- /**
648
- * Per-path `ssr ? 0 : Date.now()` stamp marking when the path's latest
649
- * async transform opened; the display reducer reads it (as
650
- * `ctx.transformingSince`) to time the gated busy spinner. Mirrors
651
- * `fieldValidatingSince` exactly: re-anchored on each run start,
652
- * deleted on the `→ 0` edge, reactive for the held-spinner reason.
653
- */
654
- readonly fieldTransformingSince: Map<PathKey, number>;
655
- /**
656
- * Per-path latest async-transform failure (a rejected transform, or a
657
- * resolved value the write gate refused), surfaced as
658
- * `field.transformError`. Cleared when a fresh run opens at the path
659
- * and on `reset()`. A channel separate from validation `errors`.
660
- */
661
- readonly transformErrors: Map<PathKey, Error | null>;
662
- /**
663
- * Form-wide count of in-flight async-transform runs. Drives the
664
- * `settleTransforms` quiescence guard and the `handleSubmit` drain
665
- * barrier. `Math.max(0, …)`-clamped on release so a doubled decrement
666
- * (a run's own `endTransform` after a synchronous cancel release)
667
- * can't drive it negative.
668
- */
669
- readonly activeTransforms: Ref<number>;
670
- /**
671
- * Replace the form value wholesale. Optional `meta` is forwarded to
672
- * every `onFormChange` listener so they can decide whether THIS write
673
- * is one they care about (e.g. history tagging a hydration replay).
674
- */
675
- applyFormReplacement(next: F, meta?: WriteMeta): void;
676
- /**
677
- * Set a single path's value. `meta` is forwarded to listeners via
678
- * `applyFormReplacement` (see above). Public `form.setValue` passes no
679
- * meta.
680
- *
681
- * Returns `false` when the slim-primitive gate rejects the write
682
- * (the value's primitive shape doesn't match the schema's slim
683
- * shape at the path). The store is unchanged in that case.
684
- */
685
- setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean;
686
- getValueAtPath(path: Path): unknown;
687
- /**
688
- * Stable identity for the array element at `path`. An array element
689
- * (numeric last segment) carries its allocated identity token,
690
- * maintained by `array-identity.ts` across structural mutations.
691
- * Empty for any non-array-element path: a record entry, a
692
- * fixed-object field, a container, or the root. Backs `FieldState.key`.
693
- */
694
- arrayElementKey(path: Path): string;
695
- reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void;
696
- resetField(path: Path): void;
697
- setSchemaErrorsForPath(path: Path, errors: ValidationError[]): void;
698
- setAllSchemaErrors(errors: readonly ValidationError[]): void;
699
- clearSchemaErrors(path?: Path): void;
700
- /**
701
- * Replace `schemaErrors` under `path` with `errors`, keying each
702
- * error by its OWN absolute path. Used by validation pipelines
703
- * (scheduleFieldValidation, validateAsync, handleSubmit, reset)
704
- * to commit a parse result wholesale — entries not in the new
705
- * pass get dropped from the subtree, surviving keys update in
706
- * place to preserve insertion order. Pass `path === []` for the
707
- * whole-form scope.
708
- */
709
- applySchemaErrorsForSubtree(path: Path, errors: ValidationError[]): void;
710
- setAllUserErrors(errors: readonly ValidationError[]): void;
711
- setUserErrorsForPath(path: Path, errors: readonly ValidationError[]): void;
712
- clearUserErrors(path?: Path): void;
713
- /**
714
- * Merged read — returns `[...schemaErrors[path], ...userErrors[path]]`.
715
- * Schema errors come first (structural validation before business logic),
716
- * matching the iteration order for `getFirstErrorElement` and the
717
- * top-level `errors` drillable Proxy.
718
- */
719
- getErrorsForPath(path: Path): ValidationError[];
720
- /**
721
- * Returns a stable schema-declaration ordinal for `key`, assigning a
722
- * fresh one if the path hasn't been seen before. Drives
723
- * `form.meta.errors` sort order so the aggregate is a function of the
724
- * SET of errors currently present (not the temporal order their
725
- * Map keys were last `set`). Construction-time seed walks every leaf
726
- * in the schema's slim default; runtime callers (DU variant 2, dynamic
727
- * array indices, refines targeting cross-field paths) pick up
728
- * first-encounter ordinals and keep them for the form's lifetime.
729
- */
730
- ensurePathOrdinal(key: PathKey): number;
731
- /**
732
- * Register `element` as a binding for `path`, tagged with the calling
733
- * `useForm()` instance's `formInstanceId`. The ID is the disambiguator
734
- * used by `getFirstErrorElement` to scope focus / scroll to elements
735
- * THIS form instance owns — important when two `useForm()` calls share
736
- * a `key` (e.g. sidebar + main rendering the same form), since both
737
- * write into one shared element store.
738
- */
739
- registerElement(path: Path, element: HTMLElement, formInstanceId: string): boolean;
740
- deregisterElement(path: Path, element: HTMLElement): number;
741
- /**
742
- * Optional `meta.instance` carries per-`useForm()`-instance overrides
743
- * for `validateOn` / `debounceMs` so the blur-trigger respects the
744
- * caller's config when sibling instances share a FormStore.
745
- */
746
- markFocused(path: Path, focused: boolean, meta?: {
747
- readonly instance?: WriteMeta['instance'];
748
- }): void;
749
- /**
750
- * Flip `interacted: true` on a leaf — the sticky value-mutation flag.
751
- * Driven by the directive's input listeners (via the RegisterValue's
752
- * `markInteracted`); idempotent, never set by programmatic writes.
753
- */
754
- markInteracted(path: Path): void;
755
- /**
756
- * Walk every active-variant leaf under `segments` and flip
757
- * `touched: true`. Powers `form.touch(path?)`. Idempotent;
758
- * does not mutate value / focused / blurred or trigger validation.
759
- */
760
- touchAtPath(segments: Path): void;
761
- /**
762
- * SSR-only optimistic mark: flip `connected: true` on the field
763
- * record without an actual DOM element. Called by the `vRegisterHint`
764
- * compile-time transform via `RegisterValue.markConnectedOptimistically()`
765
- * for every element rendered with `v-register`. Idempotent + no-op on
766
- * the client (the directive's `created` hook is the authoritative
767
- * source there).
768
- */
769
- markConnectedOptimistically(path: Path): void;
770
- /**
771
- * Client-side connected mark for a `v-register` component host that binds
772
- * value via the v-model channel but has no single inner control to latch
773
- * (a composite widget, or none found). The directive calls it on mount
774
- * (`true`) and unmount (`false`). Distinct from the SSR-only
775
- * `markConnectedOptimistically`; idempotent on the leading edge.
776
- *
777
- * `hostEl` (the host root) is recorded on connect as this path's
778
- * focus-first-error anchor, scoped to `formInstanceId` the same way a
779
- * registered control is. A no-latch host enters no `elements` record, so
780
- * without this it is absent from `getFirstErrorElement`'s walk; the anchor
781
- * lets that walk resolve a focus target from the host subtree.
782
- */
783
- markHostConnected(path: Path, connected: boolean, hostEl: HTMLElement, formInstanceId: string): void;
784
- /**
785
- * Leaf-only pristine check. `originals` is populated via
786
- * `diffAndApply`'s `added` patches, which fire only on primitive
787
- * leaves — a container path (e.g. `['profile']`) that isn't in
788
- * `originals` returns `true` here even when a descendant is dirty.
789
- * Callers that need container semantics should either loop over
790
- * leaves or walk `originals` manually. The public `getFieldState`
791
- * surface is typed to accept leaf paths only, so in practice this
792
- * isn't exposed to consumers.
793
- */
794
- isPristineAtPath(path: Path): boolean;
795
- /**
796
- * Precomputed-key shortcut for `isPristineAtPath`. The canonical
797
- * key is required and must correspond to `segments`; the helper
798
- * skips the `canonicalizePath` round-trip so descendant-walk loops
799
- * (whose Map iteration already yields the canonical key) can read
800
- * the pristine verdict without a per-leaf canonicalize.
801
- */
802
- isPristineAtPathByKey(key: PathKey, segments: Path): boolean;
803
- /**
804
- * Whether any tracked array under `path` has changed shape — a reorder,
805
- * insert, or removal — relative to its construction/reset baseline. The
806
- * structural half of `dirty`: per-element baselines travel with their
807
- * element across a mutation, so a positional value comparison alone can
808
- * no longer see the shape change.
809
- */
810
- hasStructuralChangeUnder(path: Path): boolean;
811
- /**
812
- * Whether a baseline-present container under `path` was replaced wholesale by
813
- * a non-container (e.g. `setValue('profile', undefined)`) and is still absent.
814
- * The other half of removal-driven `dirty`: such a subtree's leaves vanish
815
- * from the live value, so neither the present-leaf walk nor the array tracker
816
- * can see the loss. Self-filters by current liveness, so a refilled path stops
817
- * counting.
818
- */
819
- hasRemovedSubtreeUnder(path: Path): boolean;
820
- getFieldRecord(path: Path): FieldRecord | undefined;
821
- getOriginalAtPath(path: Path): unknown;
822
- /**
823
- * Returns the first errored field's first connected, visible DOM
824
- * element scoped to `formInstanceId` — the target that
825
- * `focusFirstError` / `scrollToFirstError` act on. "First" is
826
- * VISUAL-first (DOM-tree order via `compareDocumentPosition`), not
827
- * schema-declaration order, so a field rendered above another in the
828
- * template focuses first regardless of which one the schema declared
829
- * earlier. CSS `order:` flexbox/grid reordering is NOT respected
830
- * (DOM-tree order wins) — documented as a tradeoff against forcing
831
- * sync layout on every comparison.
832
- *
833
- * The `formInstanceId` filter scopes focus to elements registered
834
- * through THIS form instance. When two `useForm({ key })` calls share
835
- * a key, both register into the same element store; without the
836
- * filter, the sidebar form's submit could focus the main form's
837
- * input. With it, each `useForm()` callsite focuses only its own
838
- * elements.
839
- *
840
- * Returns `null` when every errored path has no currently-attached
841
- * element registered to this instance (fields behind `v-if="false"`,
842
- * unmounted components, or a hidden `display:none` parent). Callers
843
- * get the choice of no-op or a dev-only warning.
844
- */
845
- getFirstErrorElement(formInstanceId: string): {
846
- path: Path;
847
- element: HTMLElement;
848
- } | null;
849
- /**
850
- * Cancel every in-flight field-level validation run — clears timers
851
- * for debounced 'change' runs that haven't fired, latches `aborted`
852
- * for runs whose async parse is in flight. Called by `handleSubmit`
853
- * at entry (submit validation is authoritative) and by `reset()`.
854
- */
855
- cancelFieldValidation(): void;
856
- /**
857
- * Open an async-transform run at `key` — bump the run token, increment
858
- * the in-flight counters, stamp `transformingSince`, clear any prior
859
- * `transformError`, register `holder` for later abort. Returns the run
860
- * token. See `InternalRegisterValue.beginTransform`.
861
- */
862
- beginTransform(key: PathKey, holder: TransformAbortHolder): number;
863
- /** `true` while `token` is the live async-transform run at `key`. */
864
- isCurrentTransform(key: PathKey, token: number): boolean;
865
- /**
866
- * Close the run `token` at `key`: release the counters (no-op if the
867
- * run was already released by a supersede / cancel) and flush settled
868
- * `settleTransforms` waiters.
869
- */
870
- endTransform(key: PathKey, token: number): void;
871
- /** Record a per-field normalization failure at `key` (`field.transformError`). */
872
- setTransformError(key: PathKey, err: Error): void;
873
- /**
874
- * Abort + release every in-flight async-transform run (all paths) and
875
- * clear `transformErrors`. Mirrors `cancelFieldValidation`; called by
876
- * `reset()` and store teardown.
877
- */
878
- cancelTransforms(): void;
879
- /**
880
- * Path-scoped counterpart to `cancelTransforms`: abort + release only
881
- * the runs at-or-under `prefix`, clearing their `transformError`.
882
- * Called by `resetField`.
883
- */
884
- cancelTransformsUnder(prefix: Path): void;
885
- /**
886
- * Resolve once async transforms are quiescent — globally (`path`
887
- * omitted) or at-or-under `path`. Resolve-never-reject. See
888
- * `UseFormReturnType.settleTransforms`.
889
- */
890
- settleTransforms(path?: string | Path): Promise<void>;
891
- /**
892
- * Kick off (or schedule) a field-level validation run for `path`. Pass
893
- * `path = []` to cover the whole form; `applySchemaErrorsForSubtree`
894
- * then wipes every `schemaErrors` entry and replaces them with the
895
- * adapter's full async response. Used by persistence's post-hydration
896
- * revalidation and by the construction-time async-refine seed.
897
- *
898
- * `immediate: true` skips the debounce window — the runtime kicks off
899
- * the adapter call on the next microtask. Internal callsites use this
900
- * for one-shot triggers; the per-keystroke writers pass `false` to
901
- * coalesce rapid mutations under the configured debounceMs.
902
- *
903
- * `override` carries per-`useForm()`-instance values: when provided,
904
- * the scheduler honors `override.mode` instead of the store's
905
- * captured `validateOn`, and `override.debounceMs` instead of the
906
- * store's captured `debounceMs`. Used so sibling instances sharing a
907
- * FormStore can each validate on their own cadence.
908
- */
909
- scheduleFieldValidation(path: Path, immediate: boolean, override?: {
910
- readonly mode?: ValidateOn;
911
- readonly debounceMs?: number;
912
- }): void;
913
- /**
914
- * Subscribe to every `applyFormReplacement`. Fires synchronously
915
- * after `form.value` has been swapped to `next` and all field /
916
- * originals bookkeeping has run. Used by undo/redo to hook the single
917
- * mutation funnel. The optional `meta` carries the originating call
918
- * site's intent; subscribers that don't care about meta can ignore the
919
- * parameter. Returns an unsubscribe function.
920
- */
921
- onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void;
922
- /**
923
- * Subscribe to successful submissions. Fires after the consumer's
924
- * `onSubmit` callback has resolved — not on validation failure,
925
- * not on callback throw. The DevTools panel rides this to surface a
926
- * submit event. Returns an unsubscribe function.
927
- */
928
- onSubmitSuccess(listener: () => void): () => void;
929
- /**
930
- * Subscribe to `reset()` calls. Fires AFTER reset has replaced
931
- * the form and cleared errors + lifecycle, so listeners see the
932
- * fresh post-reset state. Used by the history module to drop the
933
- * undo/redo stack on reset. Returns an unsubscribe function.
934
- */
935
- onReset(listener: () => void): () => void;
936
- /**
937
- * Internal: notify submit-success subscribers. Called by
938
- * `handleSubmit` in `process-form.ts` once the user callback has
939
- * resolved. Consumers shouldn't call this directly.
940
- */
941
- emitSubmitSuccess(): void;
942
- /**
943
- * Register a teardown function whose lifetime is bound to the
944
- * FormStore itself (not a consumer's Vue effect scope). Called by
945
- * `dispose()` when the last consumer unmounts. Used by persistence /
946
- * history wiring so their subscribers aren't detached prematurely
947
- * when only the first consumer unmounts but others remain.
948
- */
949
- registerCleanup(fn: () => void): void;
950
- /**
951
- * Register an async drain function. Called by the registry before
952
- * `dispose()` so async background work — chiefly the persistence
953
- * layer's debounced storage writes — has a chance to settle without
954
- * losing the last keystroke. Each registered function is awaited in
955
- * parallel; failures are swallowed to keep eviction reliable.
956
- */
957
- registerDrain(fn: () => Promise<void>): void;
958
- /**
959
- * Drain async work registered via `registerDrain`. Resolves once
960
- * every registered drain has settled (in parallel). Safe to call
961
- * repeatedly — registered drains decide their own idempotency.
962
- */
963
- awaitPendingWrites(): Promise<void>;
964
- /**
965
- * Cache for per-state modules (history, persistence) that must
966
- * outlive any single consumer. Subsequent `useForm` / `injectForm`
967
- * calls for the same key read from this map so the public API shape
968
- * is identical regardless of mount order. Keyed by a string identifier
969
- * owned by the caller (e.g. `'history'`).
970
- */
971
- readonly modules: Map<string, unknown>;
972
- /**
973
- * Resolved schema-coercion index — the merged config from
974
- * `createAttaform({ defaults: { coerce } })` ∪ `useForm({ coerce })`,
975
- * keyed by `${input}->${output}` for O(1) per-keystroke dispatch.
976
- * Empty Map when coercion is disabled. Read at `register()` time
977
- * by `buildCoerceFn` to bake the per-path coerce closure on
978
- * `RegisterValue.coerce`.
979
- */
980
- readonly coerceIndex: CoercionIndex;
981
- /**
982
- * Tear down non-reactive resources owned by this FormStore. Invoked
983
- * by the registry when the last consumer unmounts. Cancels pending
984
- * field-validation timers, drops every subscriber, and fires each
985
- * cleanup hook registered via `registerCleanup`.
986
- */
987
- dispose(): void;
988
- };
989
-
990
- /**
991
- * Public types for `useWizard` — the multistep-form orchestrator.
992
- *
993
- * The wizard is built around an ordered list of step slots. Each slot
994
- * resolves to a participating form: an existing `useForm` reference, a
995
- * bare string key (desugared to a noop form so affordance steps
996
- * participate uniformly), an eagerly-evaluated function slot for
997
- * runtime branching, or a `lazy()`-wrapped function slot that caches
998
- * its resolution and re-fires only on its own tracked deps.
999
- *
1000
- * The wizard surface is loosely keyed (`Record<FormKey, …>`).
1001
- * Cross-component flows threaded through `injectWizard` lose lexical
1002
- * key knowledge anyway, so the public read surface is a string-keyed
1003
- * record. Typed per-form access flows back through the original form
1004
- * refs and through `wizard.handleSubmit`'s `ctx.get(formRef)` accessor.
1005
- */
1006
-
1007
- /**
1008
- * Minimum structural shape the wizard requires from a participating
1009
- * form. Constraining to the full `UseFormReturnType` would force
1010
- * contravariant unification of the storage / read shapes across all
1011
- * steps; the wizard does not care about those — it routes by `key` at
1012
- * runtime and exposes the original form objects untouched.
1013
- */
1014
- type AnyForm = {
1015
- readonly key: FormKey;
1016
- };
1017
- /**
1018
- * Per-form summary surface — what `wizard.statuses[key]` exposes (and
1019
- * what `defaultStatuses` seeds). Distinct from `form.meta`: `FormStatus`
1020
- * is the cross-step rollup optimized for template ergonomics
1021
- * (`{{ wizard.statuses.cargo.valid }}`), while `form.meta` carries the
1022
- * full per-form lifecycle surface.
1023
- *
1024
- * Field semantics:
1025
- * - `valid` — `form.meta.valid`. `false` while errors exist or while
1026
- * the first-validation-done gate has not flipped.
1027
- * - `dirty` — `form.meta.dirty`. `true` once any value differs from
1028
- * the original defaults.
1029
- * - `submitted` — `form.meta.submitted`. `true` once a `handleSubmit`
1030
- * callback has resolved without throwing. A failed submit
1031
- * (validation or callback rejection) leaves this `false`;
1032
- * `submissionAttempts > 0` is the "user has tried" signal.
1033
- * - `errorCount` — `form.meta.errorCount`. Count of active validation
1034
- * errors (zero when valid).
1035
- * - `locked`: `true` when this step sits after an uncleared gate. Its
1036
- * member form is frozen (data writes no-op) and navigation to it is
1037
- * refused, so a stepper can render it as an unreachable step. `false`
1038
- * when no gate seals it. Orthogonal to `gate`: the first uncleared
1039
- * gate reads `locked: false` (you must reach it to clear it), while a
1040
- * later gate sealed behind it reads both `gate: 'uncleared'` and
1041
- * `locked: true`.
1042
- * - `gate`: this step's own role as a hard prerequisite. `null` when the
1043
- * step is not a `gate()`; `'uncleared'` while its member form is
1044
- * unconfirmed (so it seals every later step); `'cleared'` once
1045
- * confirmed by a clean member submit or seeded cleared via
1046
- * `defaultStatuses`. Reflects the live compiled shape, so a conditional
1047
- * `gate()` that a function slot drops resolves to `null`.
1048
- *
1049
- * Noop forms generated for string slots surface as default-valid
1050
- * (`{ valid: true, dirty: false, submitted: false, errorCount: 0, locked: false, gate: null }`),
1051
- * unless the string slot is a `gate('...')`, whose `gate` tracks the
1052
- * in-session acknowledgment.
1053
- */
1054
- type FormStatus = {
1055
- readonly valid: boolean;
1056
- readonly dirty: boolean;
1057
- readonly submitted: boolean;
1058
- readonly errorCount: number;
1059
- readonly locked: boolean;
1060
- readonly gate: 'cleared' | 'uncleared' | null;
1061
- };
1062
- /**
1063
- * Seed shape accepted by `useWizard({ defaultStatuses })`. Every field is
1064
- * optional; an omitted meta field falls back to the pending sentinel on
1065
- * read.
1066
- *
1067
- * `locked` is never accepted: it is purely live-derived (sealed behind an
1068
- * earlier uncleared gate) and overlaid on every status read, so a seeded
1069
- * value would be ignored.
1070
- *
1071
- * `gate` is a WRITE-only seed, not a status field echoed back on read. A
1072
- * seed of `'cleared'` latches the gate's cleared state once at construction
1073
- * (an SSR restore of a confirmed prerequisite); the live `gate` overlay
1074
- * then owns the read. `'uncleared'` is the default and seeds nothing. Only
1075
- * a step that compiles to a `gate()` honors it — other keys ignore it.
1076
- */
1077
- type FormStatusSeed = {
1078
- readonly valid?: boolean;
1079
- readonly dirty?: boolean;
1080
- readonly submitted?: boolean;
1081
- readonly errorCount?: number;
1082
- readonly gate?: 'cleared' | 'uncleared';
1083
- };
1084
- /**
1085
- * Flat error shape returned per form by `wizard.allErrors[key]`. Each
1086
- * entry carries the formKey + path tuple so consumers can route to the
1087
- * offending field from a wizard-wide error summary.
1088
- */
1089
- type WizardAggregateError = {
1090
- readonly formKey: FormKey;
1091
- readonly path: ReadonlyArray<string | number>;
1092
- readonly message: string;
1093
- readonly code?: string;
1094
- };
1095
- /**
1096
- * Mirror of `form.values`' call-or-read pattern, one level deep.
1097
- * Drillable as `wizard.statuses.cargo.valid` (readable), as
1098
- * `wizard.statuses('cargo')` (callable single-key), or as
1099
- * `wizard.statuses()` (callable no-arg returns the whole record).
1100
- */
1101
- type WizardStatusesProxy<S extends Record<string, FormStatus>> = ((key?: keyof S) => FormStatus | S) & Readonly<S>;
1102
- /**
1103
- * One compiled position in the wizard's flow. The wizard surface
1104
- * exposes an ordered array of these as `wizard.steps`, plus a
1105
- * `wizard.forms` record keyed by `step.key` for direct lookup.
1106
- *
1107
- * String slots in the source `steps` array desugar to noop forms
1108
- * before compilation, so every compiled step carries a `form`
1109
- * regardless of source kind.
1110
- */
1111
- type CompiledStep = {
1112
- readonly key: FormKey;
1113
- readonly form: AnyForm;
1114
- };
1115
- /**
1116
- * Shape of a participating form as seen from inside a function slot's
1117
- * `ctx.forms[key]` lookup. Adds `values` to the structural `AnyForm`
1118
- * minimum so routing decisions can read live form state.
1119
- *
1120
- * Values are typed loose because the wizard does not generically thread
1121
- * each step's schema through `ctx.forms`. For typed access inside slot
1122
- * bodies, close over the original form ref instead of routing through
1123
- * `ctx.forms`.
1124
- */
1125
- type WizardCtxForm = AnyForm & {
1126
- readonly values: Readonly<Record<string, unknown>>;
1127
- };
1128
- /**
1129
- * Context object passed to function slots in the `steps` array. The
1130
- * `forms` record exposes the wizard's statically-known forms (every
1131
- * top-level `AnyForm` slot plus every noop form synthesized for a
1132
- * top-level string slot). `currentKey` mirrors the live wizard step.
1133
- *
1134
- * Function slots re-evaluate reactively when the values they read
1135
- * mutate (typically `ctx.forms.<key>.values.<path>`). The `forms`
1136
- * accumulator itself is stable across re-evaluations so the slot's
1137
- * lookup identity stays referentially equal. Effectful slot bodies
1138
- * should be avoided; routing decisions live here.
1139
- */
1140
- type WizardCtx = {
1141
- readonly forms: Readonly<Record<FormKey, WizardCtxForm>>;
1142
- readonly currentKey: FormKey | undefined;
1143
- };
1144
- /**
1145
- * What a function slot or a `lazy()` / `gate()` resolver may yield: a
1146
- * participating form, a bare affordance key, a nested `lazy()` / `gate()`
1147
- * wrapper (so the two compose in either order), or `null` / `undefined`
1148
- * to drop the position from the compiled list.
1149
- */
1150
- type SlotResolution<Ctx = WizardCtx> = AnyForm | string | null | undefined | LazyMarker<Ctx> | GateMarker;
1151
- /**
1152
- * Internal phantom brand for `LazyMarker`. The runtime brand symbol
1153
- * lives in `core/wizard-lazy.ts`; this declaration keeps the marker
1154
- * type unforgeable without circular module imports.
1155
- */
1156
- declare const _lazyBrand: unique symbol;
1157
- /**
1158
- * Brand-typed marker returned by `lazy((ctx) => …)`. Wrapping a
1159
- * function slot in `lazy()` gives that slot its own memoization cache:
1160
- * the resolver fires once on the first compile pass, and the result
1161
- * stays cached until one of the resolver's own tracked reactive reads
1162
- * changes (or `wizard.reset()` invalidates the cache). Heavy or
1163
- * one-shot lookups (network-backed factories, expensive derivations)
1164
- * do not re-fire because an unrelated slot's deps changed.
1165
- *
1166
- * Construct via the `lazy()` helper exported from the same entry as
1167
- * `useWizard`. The marker is opaque at the type level; consumers do
1168
- * not assemble it directly.
1169
- */
1170
- type LazyMarker<Ctx = WizardCtx> = {
1171
- readonly [_lazyBrand]: true;
1172
- readonly resolve: (ctx: Ctx) => SlotResolution<Ctx>;
1173
- };
1174
- /**
1175
- * Internal phantom brand for `GateMarker`. The runtime brand symbol
1176
- * lives in `core/wizard-gate.ts`; this declaration keeps the marker
1177
- * type unforgeable without circular module imports.
1178
- */
1179
- declare const _gateBrand: unique symbol;
1180
- /**
1181
- * Brand-typed marker returned by `gate(step)`. Wrapping a slot in
1182
- * `gate()` makes it a hard prerequisite: an uncleared gate seals every
1183
- * step positioned after it, and the gate's own form is the only way
1184
- * past. A gate clears on a member form's clean submit (confirmation),
1185
- * never on a value merely going valid (intent), and its form freezes
1186
- * once cleared so a back-navigation is a read-only review.
1187
- *
1188
- * `Inner` carries the wrapped slot's static type so `gate` stays
1189
- * transparent to the type machinery: `gate(form)` still contributes the
1190
- * form's key to `wizard.forms` and still counts as a guaranteed step,
1191
- * while `gate(lazy(fn))` stays maybe-absent exactly like the lazy slot
1192
- * it wraps. See {@link UnwrapGate}.
1193
- *
1194
- * Construct via the `gate()` helper exported from the same entry as
1195
- * `useWizard`. The marker is opaque at the type level; consumers do not
1196
- * assemble it directly.
1197
- */
1198
- type GateMarker<Inner = unknown> = {
1199
- readonly [_gateBrand]: true;
1200
- readonly inner: Inner;
1201
- };
1202
- /**
1203
- * Strip every `gate()` wrapper off a slot type, exposing the inner
1204
- * slot's static shape. A gate is identity-on-shape — it changes runtime
1205
- * reachability, never the compiled type — so the forms map and the
1206
- * non-empty-tuple predicate both unwrap it before inspecting a slot.
1207
- * Recursive, so a doubly-wrapped `gate(gate(form))` still resolves to
1208
- * `form`. This is what makes `gate(lazy(s))` and `lazy((ctx) => gate(s))`
1209
- * agree at the type level as well as at runtime.
1210
- */
1211
- type UnwrapGate<T> = T extends GateMarker<infer Inner> ? UnwrapGate<Inner> : T;
1212
- /**
1213
- * One position in the source `useWizard({ steps })` array. Each slot
1214
- * resolves to a compiled `{ key, form }` step, or drops out:
1215
- *
1216
- * - `AnyForm` — a form declared via `useForm`. Surfaced as-is.
1217
- * - `string` — bare key. The wizard generates a noop form
1218
- * under the hood so the external surface stays
1219
- * uniform across affordance positions (intro,
1220
- * terms, congratulations, review surfaces).
1221
- * - `null` / `undefined` — a literal absence, dropped from the compiled
1222
- * list. Lets a conditional step read inline as
1223
- * `cond ? form : null` without pre-filtering the
1224
- * array.
1225
- * - function — eager slot, re-evaluates reactively. Returns a
1226
- * `SlotResolution`, or `null` / `undefined` to
1227
- * drop the slot from the compiled list.
1228
- * - `LazyMarker` — memoized function slot (see `lazy`).
1229
- * - `GateMarker` — hard-prerequisite wrapper (see `gate`). Wraps
1230
- * any of the above; transparent to the compiled
1231
- * step's type, opaque to reachability.
1232
- */
1233
- type StepSlot<Ctx = WizardCtx> = AnyForm | string | null | undefined | ((ctx: Ctx) => SlotResolution<Ctx>) | LazyMarker<Ctx> | GateMarker;
1234
- /**
1235
- * Shape returned by the `restore` callback. Carries the active step's
1236
- * key; intentionally open-ended (object form) so future additions land
1237
- * without a callback-signature break.
1238
- */
1239
- type WizardRestoreState = {
1240
- readonly step?: FormKey;
1241
- };
1242
- /**
1243
- * `restore` callback signature. Invoked at construction and watched
1244
- * reactively via `watchEffect` so external state changes (browser
1245
- * back/forward, cross-tab events, route changes) re-apply through the
1246
- * wizard. Returning `undefined` falls through to the first step.
1247
- */
1248
- type WizardRestoreFn = () => WizardRestoreState | undefined;
1249
- /**
1250
- * `persist` callback signature. Invoked whenever `wizard.currentStep`
1251
- * changes; the wizard diffs against the last persisted value to break
1252
- * the restore-persist loop, so the callback only fires when the active
1253
- * step actually moves.
1254
- */
1255
- type WizardPersistFn = (state: WizardRestoreState) => void;
1256
- /**
1257
- * Submit context passed to the `onSubmit` callback registered via
1258
- * `wizard.handleSubmit(onSubmit, onError?)`. `handleSubmit` always
1259
- * processes the whole step list, so `values` carries every form's
1260
- * parsed output regardless of which step fired the submit.
1261
- *
1262
- * - `values` — namespaced aggregate keyed by form key, mirroring
1263
- * `wizard.allValues`. Reflects parsed output for every
1264
- * form whose validation has settled; noops contribute an
1265
- * empty record.
1266
- * - `get(form)` — typed accessor that reads the parsed output for a
1267
- * specific form ref. Works across cross-component graphs
1268
- * because the form ref carries its schema info.
1269
- * - `currentKey` — key of the step that fired this submission.
1270
- * - `isFinal` — `true` when `currentKey` is the last position in
1271
- * `wizard.steps`. Positional only: it reports where the
1272
- * submit fired, never what got validated. A user who steps
1273
- * back, edits, and submits from the middle sees
1274
- * `isFinal === false`, yet the whole list is still
1275
- * processed and `done` still latches on success.
1276
- */
1277
- type WizardSubmitContext = {
1278
- readonly values: Readonly<Record<FormKey, unknown>>;
1279
- readonly get: <F extends AnyForm>(form: F) => F extends {
1280
- readonly values: infer V;
1281
- } ? V : unknown;
1282
- readonly currentKey: FormKey;
1283
- readonly isFinal: boolean;
1284
- };
1285
- /**
1286
- * `onSubmit` callback registered via `wizard.handleSubmit`. Sync or
1287
- * async; the returned promise gates `wizard.submitting`.
1288
- */
1289
- type WizardOnSubmit = (ctx: WizardSubmitContext) => void | Promise<void>;
1290
- /**
1291
- * Optional `onError` callback registered via `wizard.handleSubmit`.
1292
- * Receives the aggregate error list spanning EVERY step (handleSubmit
1293
- * validates the whole wizard), so a failed submit surfaces every form's
1294
- * errors at once, not just the active step's. Entries originate from
1295
- * per-form validation, activation failures (`atta:activation-failed`),
1296
- * and a submit callback that left errors on a processed step (the
1297
- * `setErrors(...); return` server-rejection path). Sync or async; the
1298
- * returned promise gates `wizard.submitting`.
1299
- */
1300
- type WizardOnError = (errors: readonly WizardAggregateError[]) => void | Promise<void>;
1301
- /**
1302
- * Options for `useWizard({ steps, … })`. `steps` is the only required
1303
- * field; the rest are optional and default sensibly for the common
1304
- * URL-synchronized wizard case.
1305
- */
1306
- type WizardOptions = {
1307
- /**
1308
- * Ordered list of slots that compile into the wizard's positional
1309
- * step list. See `StepSlot` for the per-slot shape contract.
1310
- */
1311
- readonly steps: ReadonlyArray<StepSlot>;
1312
- /**
1313
- * Identifier used to register the wizard handle in the per-app
1314
- * registry. Descendant components call `injectWizard(key)` to reach
1315
- * the same wizard without prop-threading. Anonymous wizards (option
1316
- * omitted) get a synthetic `__atta:anon-wizard:<id>` key resolved
1317
- * via `useId()` so SSR-rendered and client-hydrated trees agree on
1318
- * the same registry entry; the synthetic key is opaque and
1319
- * descendants reach an anonymous wizard via ambient `injectWizard()`
1320
- * rather than by key.
1321
- *
1322
- * Duplicate-key registration is first-wins-silently (dev-warn on the
1323
- * second registration) to mirror `useForm`'s shared-key behavior.
1324
- * The dev-warn fires only for explicit keys — two anonymous wizards
1325
- * are guaranteed distinct synthetic keys, so the warning never
1326
- * misfires on independent anonymous wizards on the same page.
1327
- */
1328
- readonly key?: string;
1329
- /**
1330
- * Seed status payload used while a form is pre-resolved (async
1331
- * `defaultValues` in flight, or wizard-deferred non-current).
1332
- * Mirrors `defaultValues`' trichotomy: plain object, sync factory,
1333
- * or async factory.
1334
- *
1335
- * Status resolution priority per form:
1336
- * 1. `store.defaultsResolved === true` → derive from `form.meta`
1337
- * 2. else noop form → built-in always-valid status
1338
- * 3. else seed value for this key → seed over the pending sentinel
1339
- * 4. else → pending sentinel
1340
- *
1341
- * `locked` is never seeded: it is computed live from the wizard's gates
1342
- * and overlaid on every status read. `gate: 'cleared'` IS honored, but as
1343
- * a one-shot seed of the gate's cleared latch at construction (an SSR
1344
- * restore of a confirmed prerequisite), not as a status field echoed on
1345
- * read — the live `gate` overlay owns the read. Only a step that compiles
1346
- * to a `gate()` honors it. See `FormStatusSeed`.
1347
- *
1348
- * SSR note: the async factory resolves after hydration (client-only), so
1349
- * a gate seeded through it clears post-hydration. For a gate that must
1350
- * render open on the first server byte, use the plain or sync-factory
1351
- * form (resolve server truth in the page's `setup` await).
1352
- *
1353
- * Unknown keys in the seed object dev-warn so a stale resume payload
1354
- * surfaces at construction.
1355
- */
1356
- readonly defaultStatuses?: Record<string, FormStatusSeed> | (() => Record<string, FormStatusSeed>) | (() => Promise<Record<string, FormStatusSeed>>);
1357
- /**
1358
- * Optional progress override. When omitted, the wizard exposes
1359
- * `progress` as `valid_step_count / count` (normalised to `[0, 1]`).
1360
- * When provided, the returned number is used as-is — the consumer is
1361
- * responsible for any normalisation.
1362
- *
1363
- * The override is invoked inside a Vue `computed` so it must be
1364
- * synchronous and may only read reactive sources.
1365
- */
1366
- readonly progress?: (steps: ReadonlyArray<CompiledStep>) => number;
1367
- /**
1368
- * When `wizard.handleSubmit` finds errors, automatically focus the
1369
- * first failing form: jump to its step and invoke its
1370
- * `applyInvalidSubmitPolicy()` (focus / scroll per the form's own
1371
- * `onInvalidSubmit` configuration). Default `true`; pass `false` to
1372
- * keep the active step where the user left it and handle navigation
1373
- * manually in the `onError` callback.
1374
- */
1375
- readonly focusFirstError?: boolean;
1376
- /**
1377
- * Source of truth for the active step. Invoked at construction and
1378
- * re-evaluated reactively via `watchEffect`. Default callback reads
1379
- * `?step=<key>` from the URL via `wizard-history.ts`; pass `false`
1380
- * to disable URL sync, or provide a custom callback for non-router
1381
- * persistence (localStorage, broadcast channel, etc.).
1382
- */
1383
- readonly restore?: WizardRestoreFn | false;
1384
- /**
1385
- * Destination for the active step. Invoked whenever `currentStep`
1386
- * changes, with a diff check to break the restore-persist loop.
1387
- * Default callback writes `?step=<key>` via `wizard-history.ts`;
1388
- * pass `false` to disable persistence, or provide a custom callback
1389
- * to scope the param name or write to alternate storage.
1390
- */
1391
- readonly persist?: WizardPersistFn | false;
1392
- };
1393
- /**
1394
- * True when a single slot is guaranteed to contribute exactly one
1395
- * compiled step: a bare form or affordance string that is neither
1396
- * nullish nor a (maybe-absent) function / `lazy()` slot. One of these
1397
- * anywhere in the tuple proves the compiled list is non-empty.
1398
- */
1399
- type IsGuaranteedStep<T, U = UnwrapGate<T>> = [null] extends [U] ? false : [undefined] extends [U] ? false : U extends LazyMarker | ((...args: unknown[]) => unknown) ? false : U extends string ? true : U extends {
1400
- readonly key: string;
1401
- } ? true : false;
1402
- /**
1403
- * Predicate: is the steps tuple statically guaranteed to compile to a
1404
- * non-empty list? True when at least one element is a guaranteed step
1405
- * (see `IsGuaranteedStep`). Function / `lazy()` slots may resolve to
1406
- * nothing, and `null` / `undefined` (a literal absence or a
1407
- * `cond ? form : null` union) is an explicit drop, so none of those
1408
- * prove non-emptiness; a tuple of only maybe-absent slots stays
1409
- * honestly `| undefined`.
1410
- *
1411
- * Used to narrow `currentStep` / `activeForm` to their non-`undefined`
1412
- * shapes in the common-case wizard, while keeping the honest union
1413
- * everywhere a runtime drop is reachable.
1414
- */
1415
- type StaticallyNonEmpty<S> = S extends readonly [infer First, ...infer Rest] ? IsGuaranteedStep<First> extends true ? true : StaticallyNonEmpty<Rest> : false;
1416
- /** Active step's key, narrowed to `string` when `S` is statically safe. */
1417
- type CurrentStepOf<S> = StaticallyNonEmpty<S> extends true ? FormKey : FormKey | undefined;
1418
- /**
1419
- * Active step's form handle, schema-erased to `UseFormReturnType<GenericForm>`
1420
- * and narrowed to non-`undefined` when `S` is statically safe. The runtime
1421
- * value is a live facade over the active step, so reads (`.values`, `.meta`,
1422
- * `.history`) and `.handleSubmit` always target the current step. Values are
1423
- * loose here because the active step's schema is not statically known; reach
1424
- * for the original form ref or `ctx.get(ref)` when you need typed per-step
1425
- * values.
1426
- */
1427
- type ActiveFormOf<S> = StaticallyNonEmpty<S> extends true ? UseFormReturnType<GenericForm> : UseFormReturnType<GenericForm> | undefined;
1428
- /**
1429
- * Per-slot contribution to {@link FormsRecordOf}. Unwraps a `gate()`
1430
- * wrapper (transparent to the compiled type) and strips a `null` /
1431
- * `undefined` (a literal absence or a `cond ? form : null` union) off the
1432
- * slot first, so both a conditionally-present form and a `gate(form)`
1433
- * still map to their key and stay concretely typed on `wizard.forms`; a
1434
- * purely nullish slot contributes nothing.
1435
- */
1436
- type SlotRecord<First, U = UnwrapGate<First>, F = Exclude<U, null | undefined>> = [F] extends [
1437
- never
1438
- ] ? unknown : F extends string ? {
1439
- readonly [P in F]: AnyForm;
1440
- } : F extends {
1441
- readonly key: infer K extends string;
1442
- } ? {
1443
- readonly [P in K]: F;
1444
- } : unknown;
1445
- /**
1446
- * Recursive tuple walk that builds the static portion of
1447
- * `wizard.forms`. Each step slot contributes to the record:
1448
- *
1449
- * - **String slot** (`'review'`): the literal becomes the record key
1450
- * and the value is `AnyForm` (the noop form synthesized for the
1451
- * affordance position is opaque at the type level).
1452
- * - **Form slot** (a `useForm` reference with a literal `key` field):
1453
- * the form's own `key` becomes the record key, and the value is
1454
- * the concrete form handle type — so drilling
1455
- * `wizard.forms.shipping.values.address` carries the schema-derived
1456
- * field types through. A form kept behind a `cond ? form : null`
1457
- * conditional still maps to its key.
1458
- * - **`null` / `undefined` slot**: contributes nothing.
1459
- * - **Function / `lazy()` slot**: contributes nothing to the static
1460
- * map. Runtime-resolved forms are still reachable via the
1461
- * catch-all index signature on `WizardForms` (typed as `AnyForm`).
1462
- * - **`gate()` slot**: transparent — unwrapped to the slot it wraps, so
1463
- * `gate(form)` contributes the form's key and `gate(lazy(fn))`
1464
- * contributes nothing, exactly like the wrapped slot on its own.
1465
- *
1466
- * Recursion is bounded by the tuple length; real-world wizards land
1467
- * well below the TS instantiation budget.
1468
- */
1469
- type FormsRecordOf<S> = S extends readonly [
1470
- infer First,
1471
- ...infer Rest extends ReadonlyArray<StepSlot>
1472
- ] ? SlotRecord<First> & FormsRecordOf<Rest> : unknown;
1473
- /**
1474
- * `wizard.forms` typed view. Combines the static per-step type map
1475
- * with a catch-all `Record<FormKey, AnyForm>` fallback so:
1476
- *
1477
- * - Statically known slot keys → concrete form type via `FormsRecordOf`
1478
- * - Any other string key → `AnyForm` via the index signature
1479
- *
1480
- * The intersection collapses to the concrete form for statically
1481
- * known keys (because the concrete form type extends `AnyForm`) and
1482
- * to `AnyForm` for unknown keys.
1483
- */
1484
- type WizardForms<S> = FormsRecordOf<S> & Readonly<Record<FormKey, AnyForm>>;
1485
- /**
1486
- * Return shape of `useWizard({ steps, … })`. Every reactive read is a
1487
- * plain getter (no `.value`) — `wizard.currentStep`, `wizard.progress`,
1488
- * `wizard.allValues` track inside `computed` / template effects
1489
- * directly.
1490
- *
1491
- * Parameterized by the steps tuple `S` so active-position fields
1492
- * (`currentStep`, `activeForm`) narrow to non-undefined for the common
1493
- * case (all positional Form / string slots) and stay as honest unions
1494
- * when a function or `lazy()` slot can drop the compiled position at
1495
- * runtime. The `const` type parameter on `useWizard` preserves literal
1496
- * tuple types without consumer-side `as const`, so the narrowing
1497
- * happens automatically from the call site.
1498
- *
1499
- * - `currentStep` — key of the active step. Narrows to `string` when
1500
- * the steps tuple is statically guaranteed to
1501
- * compile to a non-empty list (all positional
1502
- * Form / string slots, no function or `lazy()`
1503
- * slots). Otherwise reads as `string | undefined`
1504
- * so the degenerate case (empty list at runtime)
1505
- * surfaces honestly.
1506
- * - `activeForm` — a LIVE view of the active step's form. Operating
1507
- * through it always targets the current step, so a
1508
- * handler captured once at setup
1509
- * (`wizard.activeForm.handleSubmit(() =>
1510
- * wizard.next())`) retargets as the wizard advances.
1511
- * No longer `===` the raw per-step handle; reach for
1512
- * `wizard.forms[key]` when you need raw identity.
1513
- * Same `undefined` narrowing as `currentStep`. Noop
1514
- * forms cover string slots in the normal path.
1515
- * - `activeIndex` — 0-based position of the active step.
1516
- * - `isFinalStep` — `true` when `currentStep === steps[count - 1].key`.
1517
- * - `steps` — ordered list of compiled `{ key, form }` slots.
1518
- * - `forms` — record indexable by step key; the value is the
1519
- * full form handle resolved for that slot.
1520
- * - `count` — `steps.length`.
1521
- * - `statuses` — callable readonly proxy over the per-key
1522
- * `FormStatus` record. Noop-form keys always read
1523
- * as default-valid.
1524
- * - `allValues` — namespaced aggregate of each form's values, keyed
1525
- * by step key.
1526
- * - `allErrors` — namespaced aggregate of each form's validation
1527
- * errors, keyed by step key. Noop forms map to an
1528
- * empty list.
1529
- * - `progress` — normalised step-validity ratio (or the consumer's
1530
- * `progress` override). Forward-looking: noops count
1531
- * as always-valid.
1532
- * - `canAdvance` — `true` when `activeIndex < count - 1`. Pure
1533
- * positional check; navigation never gates on
1534
- * validity.
1535
- * - `canGoBack` — `true` when `activeIndex > 0`.
1536
- * - `complete` — `isFinalStep && every step's form is valid`.
1537
- * Forward-looking; reactive to current form
1538
- * validity. Gates "Finish button enable" style UI.
1539
- * - `done` — monotonic latch: flips `true` the first time a
1540
- * `handleSubmit` resolves without throwing AND leaves
1541
- * no errors set on any step, and stays `true` through
1542
- * subsequent edits or invalidations. A callback that
1543
- * calls `setErrors` and returns (the documented
1544
- * server-rejection path) is a failed submit, so it
1545
- * does not flip `done`. Only `reset()` flips it back.
1546
- * Gates "show success card" style UI that should
1547
- * reflect submission history rather than current
1548
- * validity.
1549
- * - `submitting` — `true` while a `wizard.handleSubmit` call is in
1550
- * flight. Global re-entrance guard: every
1551
- * navigation method also refuses while this is on.
1552
- * - `submissionAttempts` — count of `wizard.handleSubmit` invocations
1553
- * (success or failure). Always bumps, including on
1554
- * noop-form steps.
1555
- * - `submitError` — the error THROWN by the most recent
1556
- * `wizard.handleSubmit` callback (or its `onError`),
1557
- * coerced to a real `Error`. Mirrors
1558
- * `form.meta.submitError`: this is the unexpected-throw
1559
- * channel, so an expected rejection handled via
1560
- * `setErrors` (no throw) surfaces through the error
1561
- * surface and `onError` instead, leaving this `null`.
1562
- * Cleared at submit entry and by `reset()`, parked here
1563
- * rather than re-thrown, so the handler resolves and
1564
- * never manufactures a `window` unhandledrejection.
1565
- * `null` on success.
1566
- * - `visited` — append-only breadcrumb of navigated step keys.
1567
- * `back()` does not pop; the trail is the audit
1568
- * log, not the back-stack.
1569
- * - `next/back/goTo` — pure navigation. Refuses while `submitting`.
1570
- * - `tryNext()` — submit the active step, and once that submit
1571
- * resolves clean, advance; invalid input keeps the pin
1572
- * put under the form's standard error reveal (first
1573
- * error focused, display state advanced). The advance
1574
- * runs after the submit settles, so a `gate()` on the
1575
- * active step clears in a single call. Inline-bindable
1576
- * (`@click="wizard.tryNext()"`); resolves to whether
1577
- * the pin moved. No-ops to `false` on a degenerate or
1578
- * final-step wizard (finish via `handleSubmit`).
1579
- * - `handleSubmit(onSubmit, onError?)` — always validates the entire
1580
- * step list, from any step, and never advances the
1581
- * pin: on success it latches `done`; on any error it
1582
- * focuses the first failing step and fires `onError`
1583
- * with errors spanning every step. To gate advancing
1584
- * a step on its own validity, compose with the active
1585
- * form's submit: `activeForm.handleSubmit(() =>
1586
- * wizard.next())`. Returns an event handler suitable
1587
- * for `<form @submit>` or imperative use.
1588
- * - `reset()` — zeros wizard lifecycle (`submissionAttempts`,
1589
- * `visited`), resets every form, returns
1590
- * `currentStep` to `steps[0].key`, and invokes
1591
- * `persist` with the cleared state. Re-applies the
1592
- * `defaultStatuses` gate seed, so a reboot returns to
1593
- * the seeded initial clearance, not fully sealed.
1594
- * - `relock(key, commit)` — re-seal a cleared gate, contingent on
1595
- * `commit`. Awaits `commit` (a server-side revoke) and
1596
- * re-seals only if it resolves clean, so the gate reflects
1597
- * server-confirmed truth the same way a clearing submit
1598
- * does; a thrown `commit` leaves it as-is. Seal-only (never
1599
- * opens a gate), so it cannot become the leading-signal
1600
- * foot-gun `gate()` exists to prevent. `commit` is required
1601
- * (pass `() => {}` for a deliberate client-only re-seal).
1602
- * Resolves whether the gate ended up sealed; never rejects.
1603
- * Resolves `false` (dev-warn) on a non-gate key.
1604
- */
1605
- type UseWizardReturnType<S extends ReadonlyArray<StepSlot> = ReadonlyArray<StepSlot>> = {
1606
- readonly key: string;
1607
- readonly currentStep: CurrentStepOf<S>;
1608
- readonly activeForm: ActiveFormOf<S>;
1609
- readonly activeIndex: number;
1610
- readonly isFinalStep: boolean;
1611
- readonly steps: ReadonlyArray<CompiledStep>;
1612
- readonly forms: WizardForms<S>;
1613
- readonly count: number;
1614
- readonly statuses: WizardStatusesProxy<Record<string, FormStatus>>;
1615
- readonly allValues: Readonly<Record<FormKey, unknown>>;
1616
- readonly allErrors: Readonly<Record<FormKey, readonly WizardAggregateError[]>>;
1617
- readonly progress: number;
1618
- readonly canAdvance: boolean;
1619
- readonly canGoBack: boolean;
1620
- readonly complete: boolean;
1621
- readonly done: boolean;
1622
- readonly submitting: boolean;
1623
- readonly submissionAttempts: number;
1624
- readonly submitError: Error | null;
1625
- readonly visited: readonly FormKey[];
1626
- readonly next: () => Promise<void>;
1627
- readonly back: () => void;
1628
- readonly goTo: (key: string) => void;
1629
- readonly tryNext: () => Promise<boolean>;
1630
- readonly handleSubmit: (onSubmit: WizardOnSubmit, onError?: WizardOnError) => (event?: Event) => Promise<void>;
1631
- readonly reset: () => void;
1632
- readonly relock: (key: FormKey, commit: () => void | Promise<void>) => Promise<boolean>;
1633
- };
1634
-
1635
- /**
1636
- * Portable SSR detection. The plugin captures this value at install time and
1637
- * exposes it via the registry so every runtime branch reads a single source
1638
- * of truth instead of sniffing `import.meta.*` (bundler-specific) at each
1639
- * call site.
1640
- *
1641
- * Consumers can override the heuristic explicitly via
1642
- * `createAttaform({ ssr: true })`; the default handles the common
1643
- * Node-vs-browser split without relying on any bundler-injected flag.
1644
- */
1645
- interface SSRDetectOptions {
1646
- /**
1647
- * Force SSR-vs-client mode, bypassing the `typeof window` heuristic.
1648
- * `true` activates the SSR code paths (no devtools, no persistence
1649
- * wiring, payload serialisation enabled); `false` forces client mode.
1650
- * The Nuxt plugin sets this from `import.meta.server` so SSR detection
1651
- * never depends on whether `window` is polyfilled. Tests that need to
1652
- * exercise the SSR code paths under jsdom pass `ssr: true`.
1653
- */
1654
- ssr?: boolean;
1655
- }
1656
-
1657
- /**
1658
- * Per-Vue-app container for all form state instances. Each
1659
- * `app.use(createAttaform())` call gets its own registry,
1660
- * so the library runs under bare Vue 3 + SSR (via
1661
- * `@vue/server-renderer`) and Nuxt with the same code path.
1662
- *
1663
- * Each form's state lives in `forms: Map<FormKey, FormStore<GenericForm>>`.
1664
- * The type relaxation at storage time is necessary because different
1665
- * forms in the same app have different `Form` generics; callers recover
1666
- * the specific form type via `useForm`'s overloads.
1667
- */
1668
- /**
1669
- * Serialised snapshot of one form's state, captured by
1670
- * `renderAttaformState` for SSR and replayed by
1671
- * `hydrateAttaformState` on the client. Round-trips through
1672
- * JSON-safe tuples; field references are intentionally omitted
1673
- * (DOM nodes don't survive serialisation).
1674
- */
1675
- type SerializedFormData = {
1676
- /** The form's value at snapshot time. */
1677
- readonly form: unknown;
1678
- /**
1679
- * Errors produced by the schema at snapshot time. Replayed into
1680
- * the client form's error state at hydration; cleared on
1681
- * successful re-validation client-side.
1682
- */
1683
- readonly schemaErrors: ReadonlyArray<readonly [string, unknown]>;
1684
- /**
1685
- * Errors set explicitly via `setErrors` (typically a server
1686
- * response) at snapshot time. Replayed at hydration; persists across
1687
- * client-side re-validation.
1688
- */
1689
- readonly userErrors: ReadonlyArray<readonly [string, unknown]>;
1690
- /** Per-field metadata (timestamps, raw values, connection flags) captured at snapshot time. */
1691
- readonly fields: ReadonlyArray<readonly [string, unknown]>;
1692
- /**
1693
- * Path keys that were in the form's `blankPaths` set at
1694
- * snapshot time. Round-trips the "displayed empty" UI state across
1695
- * the SSR boundary — without it, the client briefly renders
1696
- * `String(slim-default)` (e.g. `'0'`) for fields the server
1697
- * rendered as blank. Optional in the wire format so older payload
1698
- * shapes deserialise cleanly.
1699
- */
1700
- readonly blankPaths?: ReadonlyArray<string>;
1701
- };
1702
- type PendingHydration = Map<FormKey, SerializedFormData>;
1703
- /**
1704
- * The library's per-Vue-app container. One `AttaformRegistry` is
1705
- * created per `app.use(createAttaform())` call.
1706
- *
1707
- * Most consumers never touch this directly — `useForm` and
1708
- * `injectForm` reach the registry on your behalf. Access it
1709
- * explicitly only when wiring SSR or a custom plugin integration.
1710
- */
1711
- type AttaformRegistry = {
1712
- /**
1713
- * Live forms keyed by `FormKey`.
1714
- * @internal
1715
- */
1716
- readonly forms: Map<FormKey, FormStore<GenericForm>>;
1717
- /**
1718
- * Live wizards keyed by the consumer-supplied `key` option. Populated
1719
- * by `useWizard(entryForm, { key })`; consulted by `injectWizard(key)` to
1720
- * resolve cross-component wizard handles. Anonymous wizards (no
1721
- * `key`) do NOT register here — they're reachable only via ambient
1722
- * provide/inject.
1723
- * @internal
1724
- */
1725
- readonly wizards: Map<string, UseWizardReturnType>;
1726
- /**
1727
- * Snapshots staged by `hydrateAttaformState` waiting to be consumed by the next `useForm` call.
1728
- * @internal
1729
- */
1730
- readonly pendingHydration: PendingHydration;
1731
- /** `true` while running on the server during SSR; `false` on the client. */
1732
- readonly ssr: boolean;
1733
- /** App-level defaults applied to every `useForm` call. */
1734
- readonly defaults: AttaformDefaults;
1735
- /**
1736
- * Track a consumer of `key`. Returns a dispose function — call it
1737
- * when the consumer unmounts. The form is evicted automatically
1738
- * when the last consumer disposes, so long-running SPAs don't
1739
- * leak detached state across navigations.
1740
- * @internal
1741
- */
1742
- readonly trackConsumer: (key: FormKey) => () => void;
1743
- /**
1744
- * Track a consumer of wizard `key`. Returns a dispose function — call
1745
- * it when the consumer unmounts. The wizard handle is evicted from
1746
- * `wizards` once the last consumer disposes, mirroring the form
1747
- * consumer-counting mechanics. Anonymous wizards never enter this
1748
- * counter (they have no key to count under).
1749
- * @internal
1750
- */
1751
- readonly trackWizardConsumer: (key: string) => () => void;
1752
- /**
1753
- * Mark a form as eligible for SSR prefetch. The form's
1754
- * `onServerPrefetch` hook consults `shouldPrefetch(key)` and runs the
1755
- * captured `defaultValues` factory only when this set contains the
1756
- * key (and the skip set does not). Set by `form.activate()`,
1757
- * `useWizard`'s current-step auto-mark, and the future Vite transform.
1758
- * @internal
1759
- */
1760
- readonly enqueuePrefetch: (key: FormKey) => void;
1761
- /**
1762
- * Mark a form as ineligible for SSR prefetch. Overrides `enqueuePrefetch`.
1763
- * Used by `useWizard` to keep non-current steps dormant on the
1764
- * server even when a transform mark or stray `activate()` would
1765
- * otherwise enqueue them — the wizard's "user isn't on this step"
1766
- * signal wins.
1767
- * @internal
1768
- */
1769
- readonly skipPrefetch: (key: FormKey) => void;
1770
- /**
1771
- * Whether `key`'s SSR prefetch should run. Returns `true` iff the key
1772
- * is enqueued AND not skipped.
1773
- * @internal
1774
- */
1775
- readonly shouldPrefetch: (key: FormKey) => boolean;
1776
- /**
1777
- * Wait for all pending persistence writes across every live form
1778
- * to settle. Useful for SSR shutdown and integration tests that
1779
- * need a deterministic teardown.
1780
- * @internal
1781
- */
1782
- readonly shutdown: () => Promise<void>;
1783
- };
1784
- /**
1785
- * The Vue `InjectionKey` under which the registry is provided on the
1786
- * app. Most consumers never need this — `useForm` and
1787
- * `injectForm` resolve the registry automatically.
1788
- */
1789
- declare const kAttaformRegistry: InjectionKey<AttaformRegistry>;
1790
- declare module 'vue' {
1791
- interface App {
1792
- /** @internal */
1793
- _attaform?: AttaformRegistry;
1794
- }
1795
- }
1796
- /** Options for `createRegistry`. */
1797
- type CreateRegistryOptions = SSRDetectOptions & {
1798
- /**
1799
- * App-level defaults applied to every `useForm` call. Per-form
1800
- * options always win. Omitted is equivalent to `{}`.
1801
- */
1802
- defaults?: AttaformDefaults;
1803
- };
1804
- /**
1805
- * Create a fresh `AttaformRegistry`. `createAttaform()` calls
1806
- * this internally — most consumers never need to call it directly.
1807
- * Use it when building a custom plugin that doesn't want the
1808
- * `createAttaform` plugin's auto-install behaviour (e.g. test
1809
- * harnesses, embedded apps).
1810
- */
1811
- declare function createRegistry(options?: CreateRegistryOptions): AttaformRegistry;
1812
- /**
1813
- * Look up the current app's registry from inside a component's
1814
- * `setup()` (or any synchronous code on the setup call stack).
1815
- *
1816
- * Most consumers don't need this — `useForm` and `injectForm`
1817
- * call it on your behalf. Reach for it directly when building
1818
- * custom integrations that need the raw registry.
1819
- *
1820
- * Throws:
1821
- * - `OutsideSetupError` when called outside a Vue setup context
1822
- * (e.g. from an event handler or async callback). Move the call
1823
- * into setup, or trigger it from a child component.
1824
- * - `RegistryNotInstalledError` when called inside setup but the
1825
- * plugin wasn't installed. Add
1826
- * `app.use(createAttaform())` to your app entry.
1827
- */
1828
- declare function useRegistry(): AttaformRegistry;
1829
- /**
1830
- * Look up a Vue app's registry by `App` reference. Used by
1831
- * SSR helpers (`renderAttaformState`, `hydrateAttaformState`) that
1832
- * run outside a component setup context.
1833
- *
1834
- * Throws `RegistryNotInstalledError` when the app hasn't been wired
1835
- * with `createAttaform()`.
1836
- */
1837
- declare function getRegistryFromApp(app: App): AttaformRegistry;
1838
-
1839
- /**
1840
- * Multistep-form orchestrator built around an ordered list of step slots.
1841
- * Each slot resolves to a participating form: an existing `useForm`
1842
- * reference, a bare string key (desugared to a noop form so affordance
1843
- * steps participate uniformly), an eagerly-evaluated function slot for
1844
- * runtime branching, or a `lazy()`-wrapped function slot that caches
1845
- * its resolution and re-fires only on its own tracked deps.
1846
- *
1847
- * The wizard's surface is read-only from the consumer's side:
1848
- * navigation (`next` / `back` / `goTo`) walks positional indices,
1849
- * `handleSubmit` validates the whole step list from any step and never
1850
- * advances (gate advance with `activeForm.handleSubmit(() =>
1851
- * wizard.next())`), and URL synchronization rides on `restore` /
1852
- * `persist` callbacks that default to `?step=<key>`.
1853
- */
1854
- declare function useWizard<const S extends ReadonlyArray<StepSlot>>(options: WizardOptions & {
1855
- readonly steps: S;
1856
- }): UseWizardReturnType<S>;
1857
-
1858
- /**
1859
- * Options accepted by `injectWizard` when passing an object instead of
1860
- * a bare key string. Mirrors `injectForm`'s `InjectFormInput` shape so
1861
- * the two composables present an identical call surface.
1862
- */
1863
- type InjectWizardInput = {
1864
- readonly key?: string | undefined;
1865
- };
1866
- /**
1867
- * Access an existing wizard handle from a descendant component without
1868
- * passing it through props. Counterpart to `useWizard` — `useWizard`
1869
- * creates and provides; `injectWizard` looks up via Vue's inject
1870
- * mechanism or the per-app registry.
1871
- *
1872
- * Three ways to call it:
1873
- *
1874
- * ```ts
1875
- * // Reach the nearest ancestor's useWizard call (ambient).
1876
- * const wizard = injectWizard()
1877
- *
1878
- * // Reach a specific wizard by its key — works from anywhere in the app.
1879
- * const signup = injectWizard('signup-wizard')
1880
- *
1881
- * // Object form (equivalent; convenient for spread).
1882
- * const signup = injectWizard({ key: 'signup-wizard' })
1883
- * ```
1884
- *
1885
- * Resolution rules (no-key form):
1886
- * - Closest ambient ancestor wins via `provide(kAttaformAncestorWizard)`.
1887
- * - Only anonymous (no-`key`) `useWizard()` calls fill the ambient
1888
- * slot. Descendants of a keyed wizard must address it explicitly
1889
- * via `injectWizard('the-key')`. Mirrors `useForm`'s ambient gate.
1890
- *
1891
- * Resolution rules (keyed form): registry lookup by string key,
1892
- * independent of component-tree position. The wizard must have been
1893
- * constructed with `useWizard({ steps, key })` to be reachable.
1894
- *
1895
- * Returns `null` when no matching wizard exists (no ambient ancestor,
1896
- * or the named key isn't registered yet). A dev-mode warning points at
1897
- * the call site, lists the registered keys, and flags the mount-timing
1898
- * case (a wizard created by a child or sibling isn't registered until
1899
- * its own setup runs). Always narrow before using:
1900
- *
1901
- * ```ts
1902
- * const wizard = injectWizard('signup')
1903
- * if (!wizard) return
1904
- * wizard.next()
1905
- * ```
1906
- *
1907
- * Consumer ref-counting: keyed lookups pin the wizard handle in the
1908
- * registry for this component's lifetime, so the handle survives even
1909
- * if the parent `useWizard` component unmounts before the child does.
1910
- * Once every consumer disposes, the registry evicts the entry on the
1911
- * next microtask. Ambient lookups don't ref-count — the parent
1912
- * `useWizard`'s scope owns the lifetime.
1913
- */
1914
- declare function injectWizard(input?: string | InjectWizardInput): UseWizardReturnType | null;
1915
-
1916
- /**
1917
- * Wrap a function slot in `lazy()` to give that slot its own memoized
1918
- * cache, distinct from the wizard-wide step compiler.
1919
- *
1920
- * Default function slots in `useWizard({ steps })` re-evaluate whenever
1921
- * the compiled step list re-evaluates, including when an unrelated
1922
- * slot's reactive deps change. That keeps the rail correct but can
1923
- * trigger spurious work in a resolver that is expensive (a network
1924
- * lookup, a heavy schema derivation, an async-derived factory).
1925
- *
1926
- * `lazy()` isolates each wrapped slot behind its own cache. The
1927
- * resolver runs eagerly on the first compile pass; subsequent reads
1928
- * reuse the cached form. The cache invalidates only when one of the
1929
- * resolver's own tracked reactive dependencies changes (Vue's
1930
- * `computed` semantics applied to a slot), or when `wizard.reset()`
1931
- * triggers a global re-compile:
1932
- *
1933
- * const wizard = useWizard({
1934
- * steps: [
1935
- * account,
1936
- * lazy((ctx) => loadShippingForm(ctx.forms.account.values.region)),
1937
- * confirm,
1938
- * ],
1939
- * })
1940
- *
1941
- * Resolution semantics:
1942
- * - Eager at construction so `wizard.steps` and SSR markup are honest
1943
- * from t=0.
1944
- * - Memoized: the resolver re-fires only when one of its own tracked
1945
- * reads changes. An unrelated slot re-evaluating does not re-fire
1946
- * this one.
1947
- * - `wizard.reset()` clears every lazy slot's cache so a reboot truly
1948
- * resolves from scratch.
1949
- * - Resolving to `null` or `undefined` drops the slot from the compiled
1950
- * list until the resolver next re-fires.
1951
- * - The resolver may return a `gate()` wrapper, so a lazy slot can gate
1952
- * what it resolves to; `lazy((ctx) => gate(s))` and `gate(lazy(s))`
1953
- * resolve identically.
1954
- *
1955
- * The runtime brand returned by `lazy()` is opaque. Use
1956
- * {@link isLazyMarker} to detect it.
1957
- */
1958
- declare function lazy<Ctx = WizardCtx>(resolve: (ctx: Ctx) => SlotResolution<Ctx>): LazyMarker<Ctx>;
1959
-
1960
- /**
1961
- * Wrap a step slot in `gate()` to make it a hard prerequisite: while the
1962
- * gate is uncleared, every step positioned after it is inaccessible, and
1963
- * the gate's own form is the only way past.
1964
- *
1965
- * A gate is safe by construction. It does not hand the consumer a
1966
- * predicate to key on; it bakes the correct semantics in:
1967
- *
1968
- * - **Confirmation, not intent.** The gate clears only when a member
1969
- * form submits clean, never when a value merely goes valid. Checking
1970
- * the box does nothing; submitting the consent step is what opens the
1971
- * rail. This is the whole reason `gate()` exists: a leading value
1972
- * signal lets a downstream step collect data before the prerequisite
1973
- * is confirmed.
1974
- * - **Linear-forward.** An uncleared gate seals every step after it.
1975
- * Order places it: put `gate(step)` immediately before what it
1976
- * guards. Everything downstream is both un-navigable and, through the
1977
- * `disabled` data freeze, un-fillable, so a deep link, the browser
1978
- * back button, or a stray `goTo` all redirect to the gate.
1979
- * - **Freeze-after-clear.** A cleared gate's own form freezes, so
1980
- * navigating back to it is a read-only review with no withdrawal
1981
- * path. There is no re-lock dance.
1982
- *
1983
- * Wrap any slot kind:
1984
- *
1985
- * const wizard = useWizard({ steps: [gate(consent), shipping, payment] })
1986
- *
1987
- * A **form** gate (`gate(consentForm)`) clears when its form submits
1988
- * clean, and is treated as pre-cleared on reload when its member form
1989
- * rehydrates already valid (a persisted consent), so a seeded-valid gate
1990
- * SSR-renders open. A bare-string **affordance** gate (`gate('terms')`)
1991
- * clears on acknowledgment (advancing past it), and re-prompts each
1992
- * session because that acknowledgment is ephemeral.
1993
- *
1994
- * Conditional gates come from composition, not an options bag:
1995
- *
1996
- * () => (transfer.values.amount > 10_000 ? gate(kyc) : kyc)
1997
- *
1998
- * `gate()` composes with `lazy()` in either order:
1999
- * `gate(lazy(fn))` and `lazy((ctx) => gate(fn(ctx)))` resolve
2000
- * identically.
2001
- *
2002
- * The runtime brand returned by `gate()` is opaque. Use
2003
- * {@link isGateMarker} to detect it.
2004
- */
2005
- declare function gate<const Inner extends StepSlot>(step: Inner): GateMarker<Inner>;
2006
-
2007
- /**
2008
- * Stable identifiers for library-emitted `ValidationError` codes.
2009
- *
2010
- * Convention: `<scope>:<kebab-case-identifier>`. Three scopes are
2011
- * recognised by the library:
2012
- *
2013
- * - `atta:` — emitted by the framework-agnostic core (this map).
2014
- * - `zod:` — emitted by the Zod adapter; computed inline from
2015
- * `issue.code` (e.g. `zod:too_small`). No enum here because
2016
- * Zod's code list evolves.
2017
- * - consumer-defined — anything the consumer's backend / app stamps
2018
- * onto a `ValidationError` (a server response handed to `setErrors`,
2019
- * or a code passed inline). Pick a scope (`api:`, `auth:`, etc.) and
2020
- * stay consistent.
2021
- *
2022
- * Use these constants in tests and error-routing UI:
2023
- *
2024
- * ```ts
2025
- * if (error.code === AttaformErrorCode.NoValueSupplied) {
2026
- * // user hasn't filled this field
2027
- * }
2028
- * ```
2029
- */
2030
- declare const AttaformErrorCode: {
2031
- /** A required field is in the blank set — user hasn't supplied a value. */
2032
- readonly NoValueSupplied: "atta:no-value-supplied";
2033
- /** The schema adapter's `validateAtPath` threw synchronously. */
2034
- readonly AdapterThrew: "atta:adapter-threw";
2035
- /**
2036
- * User code inside a `z.preprocess`, `.refine`, or `.transform`
2037
- * threw (sync or async). The adapter caught the throw and surfaced
2038
- * it as a `ValidationError` at the field path so the form's normal
2039
- * error pipeline handles it instead of leaking as an unhandled
2040
- * rejection or routing through `submitError`.
2041
- */
2042
- readonly ValidatorThrew: "atta:validator-threw";
2043
- /**
2044
- * A function-form `defaultValues` factory threw or its promise
2045
- * rejected. The runtime captures the raw error on `form.hydrateError`
2046
- * and ALSO surfaces a form-level `ValidationError` (path `[]`) so
2047
- * the standard error pipeline carries the signal. Critical for the
2048
- * SSR round-trip: `hydrateError` itself does not ride the wire
2049
- * payload, but `schemaErrors` does, so the client sees the failure
2050
- * after rehydration without an extra channel.
2051
- */
2052
- readonly HydrationFailed: "atta:hydration-failed";
2053
- /** The supplied path didn't resolve to any node in the schema. */
2054
- readonly PathNotFound: "atta:path-not-found";
2055
- /**
2056
- * A walked form's `activate()` (async `defaultValues` factory) threw
2057
- * during `wizard.handleSubmit`'s path walk. Surfaced as a synthetic
2058
- * `ValidationError` at the form-level path (`[]`) so the wizard's
2059
- * aggregate error pipeline can carry the failure alongside ordinary
2060
- * validation errors. The raw factory error remains on
2061
- * `form.hydrateError` for retry UX.
2062
- */
2063
- readonly ActivationFailed: "atta:activation-failed";
2064
- /**
2065
- * Default code stamped on a manual error set through `form.setErrors`
2066
- * when the caller omits an explicit `code`. The `setErrors` input is
2067
- * lenient (`code` optional), so this is the fallback that keeps every
2068
- * produced `ValidationError` carrying a stable, branchable identifier.
2069
- * Override it per error by passing your own `code` (`api:…`, `auth:…`).
2070
- */
2071
- readonly UserError: "atta:user-error";
2072
- /**
2073
- * Stamped on a `ValidationError` synthesized from a throw or rejection
2074
- * out of a `handleSubmit` `onSubmit` callback. The raw error also lands
2075
- * on `form.meta.submitError` (a raw-`Error` inspection channel); this
2076
- * code marks the copy piped into the user-error layer so the failure
2077
- * also surfaces on `form.errors` / `meta.ownErrors` / `firstOwnError`
2078
- * where the UI already reads. A throw carrying its own `path` / `code`
2079
- * keeps them; a bare `Error` or a non-Error throw defaults here at the
2080
- * form-level path `[]`.
2081
- */
2082
- readonly SubmitError: "atta:submit-error";
2083
- /**
2084
- * Synthesized by `wizard.handleSubmit` when the whole-wizard submit
2085
- * would otherwise succeed but a `gate()` step is still uncleared. A
2086
- * gate clears only on its member form's clean submit (confirmation), so
2087
- * a downstream step that happens to be valid-by-default must not let the
2088
- * wizard finish past an unconfirmed prerequisite. Emitted at the gate
2089
- * form's key (path `[]`) so the aggregate error pipeline routes focus to
2090
- * the gate, and `done` never latches.
2091
- */
2092
- readonly GateNotCleared: "atta:gate-not-cleared";
2093
- };
2094
- type AttaformErrorCode = (typeof AttaformErrorCode)[keyof typeof AttaformErrorCode];
2095
-
2096
- /**
2097
- * Options for `createAttaform()`.
2098
- */
2099
- type AttaformPluginOptions = SSRDetectOptions & {
2100
- /**
2101
- * Whether to install the Vue DevTools integration. Default `true`.
2102
- * The integration is dev-only: the `import('./devtools')` sits behind
2103
- * the `__DEV__` flag, so a consumer's production build folds it out
2104
- * entirely (no devtools chunk shipped, no fetch attempted). In
2105
- * development the DevTools peer is loaded lazily and a missing peer
2106
- * fails silently. Pass `false` to skip the integration even in dev.
2107
- */
2108
- devtools?: boolean;
2109
- /**
2110
- * App-level defaults applied to every `useForm` call in this app.
2111
- * Per-form options always win. See `AttaformDefaults` for
2112
- * the supported option set and the merge rules.
2113
- *
2114
- * ```ts
2115
- * app.use(
2116
- * createAttaform({
2117
- * defaults: { debounceMs: 100 },
2118
- * })
2119
- * )
2120
- * ```
2121
- */
2122
- defaults?: AttaformDefaults;
2123
- };
2124
- /**
2125
- * Create the Vue plugin that installs the form library on a Vue
2126
- * application. Required only when you want app-wide options
2127
- * (`defaults`, `devtools: false`, `ssr: true`) — for the default
2128
- * setup, `useForm` / `injectForm` / `useRegister` lazy-install the
2129
- * registry on first use.
2130
- *
2131
- * ```ts
2132
- * import { createApp } from 'vue'
2133
- * import { createAttaform } from 'attaform'
2134
- *
2135
- * createApp(App)
2136
- * .use(createAttaform({ defaults: { debounceMs: 100 } }))
2137
- * .mount('#app')
2138
- * ```
2139
- *
2140
- * Under SSR with bare Vue 3, install explicitly with `{ ssr: true }`
2141
- * from your server entry — the SSR serialization helpers
2142
- * (`renderAttaformState` / `hydrateAttaformState`) require an
2143
- * already-attached registry and don't trigger lazy install. Under
2144
- * Nuxt, install via `attaform/nuxt` instead — the Nuxt module wires
2145
- * both server and client automatically.
2146
- *
2147
- * Installing more than once on the same app is a no-op (the second
2148
- * call logs a dev-mode warning).
2149
- */
2150
- declare function createAttaform(options?: AttaformPluginOptions): Plugin;
2151
-
2152
- /**
2153
- * Serialised snapshot of every form in a Vue app, produced by
2154
- * `renderAttaformState` and consumed by `hydrateAttaformState`.
2155
- *
2156
- * JSON-safe — pass to `JSON.stringify`, `devalue`, or any other
2157
- * serialiser before embedding in your SSR payload.
2158
- */
2159
- type SerializedAttaformState = {
2160
- /** Tuples of `[formKey, snapshot]` for every form in the app. */
2161
- readonly forms: ReadonlyArray<readonly [FormKey, SerializedFormData]>;
2162
- };
2163
- /**
2164
- * Snapshot every form on a Vue app for SSR. Call from your server
2165
- * entry after rendering the app:
2166
- *
2167
- * ```ts
2168
- * import { renderToString } from '@vue/server-renderer'
2169
- * import { renderAttaformState, escapeForInlineScript } from 'attaform'
2170
- *
2171
- * const html = await renderToString(app)
2172
- * const state = renderAttaformState(app)
2173
- * const payload = escapeForInlineScript(JSON.stringify(state))
2174
- *
2175
- * return `
2176
- * ${html}
2177
- * <script>window.__ATTAFORM_STATE__ = ${payload}</script>
2178
- * `
2179
- * ```
2180
- *
2181
- * Pair with `hydrateAttaformState` on the client to restore the
2182
- * forms in their server-rendered state. Nuxt users don't need this —
2183
- * `attaform/nuxt` wires SSR automatically.
2184
- */
2185
- declare function renderAttaformState(app: App): SerializedAttaformState;
2186
- /**
2187
- * Restore forms from a server-rendered snapshot on the client. Call
2188
- * from your client entry before mounting:
2189
- *
2190
- * ```ts
2191
- * import { createApp } from 'vue'
2192
- * import { createAttaform, hydrateAttaformState } from 'attaform'
2193
- *
2194
- * const app = createApp(App).use(createAttaform())
2195
- * hydrateAttaformState(app, window.__ATTAFORM_STATE__)
2196
- * app.mount('#app')
2197
- * ```
2198
- *
2199
- * The next `useForm({ key })` call for each serialised form picks up
2200
- * the snapshot transparently — no further action is required.
2201
- */
2202
- declare function hydrateAttaformState(app: App, payload: SerializedAttaformState): void;
2203
-
2204
- /**
2205
- * Escape a JSON string so it's safe to embed inside an inline
2206
- * `<script>` tag during SSR. Plain `JSON.stringify` is not safe — a
2207
- * form value containing the literal substring `</script>` would
2208
- * break out of the script tag.
2209
- *
2210
- * ```ts
2211
- * const payload = escapeForInlineScript(JSON.stringify(renderAttaformState(app)))
2212
- * // `<script>window.__ATTAFORM_STATE__ = ${payload}</script>` is safe.
2213
- * ```
2214
- *
2215
- * Output remains valid JSON — `JSON.parse` round-trips back to the
2216
- * original value on the client.
2217
- */
2218
- declare function escapeForInlineScript(json: string): string;
2219
-
2220
- /**
2221
- * Symbol slot used by custom directive integrations to install an
2222
- * assigner on the bound element. Read by the v-register directive
2223
- * when a DOM event fires:
2224
- *
2225
- * ```ts
2226
- * import { assignKey } from 'attaform'
2227
- * el[assignKey] = (value) => myCustomWriter(value)
2228
- * ```
2229
- *
2230
- * Most consumers never need this — the built-in directives wire
2231
- * default assigners for text inputs, checkboxes, radios, and selects.
2232
- */
2233
- declare const assignKey: unique symbol;
2234
-
2235
- /**
2236
- * The `v-register` directive. Bind a form field to a native input,
2237
- * select, textarea, checkbox, or radio:
2238
- *
2239
- * ```vue
2240
- * <input v-register="form.register('email')" />
2241
- * <select v-register="form.register('country')">
2242
- * <option value="us">US</option>
2243
- * <option value="uk">UK</option>
2244
- * </select>
2245
- * ```
2246
- *
2247
- * The directive picks the right binding strategy automatically based
2248
- * on the element's `tagName` and `type`. Registered globally by
2249
- * `createAttaform()`. Most consumers never import it directly, but
2250
- * it's exposed for advanced integrations that wire directives
2251
- * manually.
2252
- */
2253
- declare const vRegister: RegisterModelDynamicCustomDirective;
2254
-
2255
- /**
2256
- * Type guard for a `RegisterValue`. Returns `true` when `val` looks
2257
- * like the object returned from `form.register(path)`.
2258
- *
2259
- * ```ts
2260
- * if (isRegisterValue(slotValue)) {
2261
- * // slotValue.innerRef is now a Ref<unknown>
2262
- * }
2263
- * ```
2264
- *
2265
- * Useful when building wrapper components that accept either a
2266
- * `RegisterValue` or a plain ref via the same prop.
2267
- */
2268
- declare function isRegisterValue<Value = unknown>(val: unknown): val is RegisterValue<Value>;
2269
-
2270
- /**
2271
- * Shared building blocks for Attaform's two devtools surfaces — the Vue
2272
- * DevTools (Chrome-extension) inspector wired up in `./devtools.ts`, and
2273
- * the Nuxt DevTools (overlay) panel wired up via `../../nuxt.ts` +
2274
- * `../pages/_attaform_devtools.vue`.
2275
- *
2276
- * Houses the window-bridge contract both surfaces consume so a new
2277
- * bridge field lands in one file. Both surfaces render RAW form values
2278
- * by design — DevTools is a dev-only surface, and redaction across every
2279
- * place a value surfaces is impractical security theater rather than a
2280
- * real safeguard.
2281
- */
2282
-
2283
- /**
2284
- * Property key on `window` that the Nuxt-side dev plugin attaches the
2285
- * bridge object to. The iframe-mounted overlay panel reads
2286
- * `window.parent[DEVTOOLS_WINDOW_KEY]` to reach the host app's registry.
2287
- *
2288
- * Underscored + namespaced to make accidental collision with consumer
2289
- * globals vanishingly unlikely. Stable across versions — bumping it
2290
- * would silently disconnect older library builds from newer overlay
2291
- * panels in the same browser tab during a library upgrade.
2292
- */
2293
- declare const DEVTOOLS_WINDOW_KEY = "__attaform_devtools__";
2294
- /**
2295
- * Shape of the object the host plugin attaches to `window` in dev mode.
2296
- * The iframe overlay panel reads this to discover the live registry and
2297
- * render its forms.
2298
- *
2299
- * Single-registry assumption: the latest `createAttaform()` install
2300
- * wins. Multi-app pages (rare; typically only seen in micro-frontend
2301
- * setups) will only see one app's forms in the panel. Documented but
2302
- * not actively supported — the alternative (a Set of registries with
2303
- * union-rendering) is a future call if a real consumer hits it.
2304
- */
2305
- interface AttaformDevtoolsBridge {
2306
- registry: AttaformRegistry;
2307
- /**
2308
- * The library version, surfaced in the panel's footer for support /
2309
- * bug-report context. Read from `package.json` at host-plugin init.
2310
- */
2311
- version: string;
2312
- }
2313
- declare global {
2314
- interface Window {
2315
- [DEVTOOLS_WINDOW_KEY]?: AttaformDevtoolsBridge;
2316
- }
2317
- }
2318
-
2319
- /**
2320
- * Typed error classes thrown by the form library. Each one signals a
2321
- * distinct misuse so calling code can branch on `instanceof` instead
2322
- * of pattern-matching error messages.
2323
- *
2324
- * Every class extends `AttaformError`, so consumers can write a single
2325
- * polymorphic catch (`catch (e) { if (e instanceof AttaformError) ... }`)
2326
- * instead of OR-chaining checks for each subclass. `AttaformError` itself
2327
- * extends the standard `Error`, so existing `instanceof Error` usage
2328
- * keeps working.
2329
- */
2330
-
2331
- /**
2332
- * Base for every error class thrown by `attaform`. Sets
2333
- * `this.name` from the constructor's `new.target.name`, so subclasses
2334
- * don't have to redeclare their own name override.
2335
- */
2336
- declare class AttaformError extends Error {
2337
- constructor(message: string, options?: ErrorOptions);
2338
- }
2339
- /**
2340
- * Thrown when a path string is malformed — typically a dotted path
2341
- * with empty segments (e.g. `'a..b'`, leading or trailing dots).
2342
- * Use array form (`['a', 'b']`) for keys that contain literal dots.
2343
- */
2344
- declare class InvalidPathError extends AttaformError {
2345
- }
2346
- /**
2347
- * Thrown when `useForm` receives an invalid configuration — most often
2348
- * a schema passed directly as the first argument, or no argument at
2349
- * all. The configuration is an options bag; the schema is one of
2350
- * several fields, even when it's the only one in use.
2351
- *
2352
- * ```ts
2353
- * // ✗ Crashes deep inside the validator with an opaque message:
2354
- * const form = useForm(z.object({ ... }))
2355
- * // ✗ Same:
2356
- * const form = useForm()
2357
- * // ✓ Pass the schema as the `schema` field:
2358
- * const form = useForm({ schema: z.object({ ... }) })
2359
- * ```
2360
- *
2361
- * The same shape applies to every entry point: `attaform/zod`,
2362
- * `attaform/zod-v3`, `attaform/zod-v4`, and the schema-agnostic
2363
- * `attaform` root.
2364
- */
2365
- declare class InvalidUseFormConfigError extends AttaformError {
2366
- constructor();
2367
- }
2368
- /**
2369
- * Thrown when a `handleSubmit`-supplied `onError` callback itself
2370
- * throws or rejects. Wraps the inner failure so both the original
2371
- * cause (via `error.cause`) and the propagation site are visible.
2372
- */
2373
- declare class SubmitErrorHandlerError extends AttaformError {
2374
- }
2375
- /**
2376
- * Thrown when an `attaform` API needs the registry attached to a Vue
2377
- * app but it isn't there yet. Component-level entry points (`useForm`,
2378
- * `injectForm`, `useRegister`) lazy-install the registry on first use,
2379
- * so this error is mostly reached by SSR helpers — `renderAttaformState`
2380
- * and `hydrateAttaformState` — which run outside a setup context and
2381
- * have no current instance to install against.
2382
- *
2383
- * Fix: add `app.use(createAttaform())` (or `app.use(createAttaform({
2384
- * ssr: true }))` on the server) to your SSR entry, before
2385
- * `renderToString` / hydration. Under Nuxt, `attaform/nuxt` already
2386
- * does this; the error usually points at a non-Nuxt SSR setup that
2387
- * hasn't installed explicitly.
2388
- */
2389
- declare class RegistryNotInstalledError extends AttaformError {
2390
- constructor();
2391
- }
2392
- /**
2393
- * Thrown when `useForm` / `injectForm` is called outside of a
2394
- * Vue `setup()` function — typically from an event handler, watcher,
2395
- * or async callback that runs after mount.
2396
- *
2397
- * Fix: move the call into `setup()`, or trigger it from a child
2398
- * component whose `setup()` runs the composable.
2399
- */
2400
- declare class OutsideSetupError extends AttaformError {
2401
- constructor();
2402
- }
2403
- /**
2404
- * Thrown when a `useForm({ key })` call uses a key starting with
2405
- * `__atta:`. That prefix is reserved for keys the library generates
2406
- * internally (e.g. for anonymous `useForm()` calls without an
2407
- * explicit key). Pick a different prefix for your form.
2408
- */
2409
- declare class ReservedFormKeyError extends AttaformError {
2410
- constructor(key: string);
2411
- }
2412
-
2413
- /**
2414
- * Anti-flash timing for the library-default display reducer.
2415
- *
2416
- * - `showDelay` — how long in-flight work (a validation run or an async
2417
- * register transform) may run before its spinner is allowed to show. Work
2418
- * that settles inside this window never reveals `'pending'` at all, so a
2419
- * fast (often synchronous) check does not flash a spinner on every keystroke.
2420
- * - `minVisible` — once shown, the minimum time the spinner stays up. Work
2421
- * that lands just past `showDelay` is held here so the spinner does not
2422
- * itself flash on and immediately off.
2423
- *
2424
- * Both are milliseconds.
2425
- */
2426
- type DisplayTimings = {
2427
- readonly showDelay: number;
2428
- readonly minVisible: number;
2429
- };
2430
- /**
2431
- * Library-default anti-flash timings. `showDelay: 120` cleanly swallows
2432
- * synchronous, microtask-resolved, and tiny-async work (validation runs and
2433
- * async register transforms alike) so none of them flash a spinner;
2434
- * `minVisible: 120` keeps a shown spinner snappy once one does land.
2435
- * Retune via {@link makeDefaultDisplayState} without touching the engine.
2436
- */
2437
- declare const DEFAULT_TIMINGS: DisplayTimings;
2438
- /**
2439
- * Build a default `getDisplayState` reducer with custom anti-flash timing.
2440
- * Power users who want a tighter or looser spinner than {@link DEFAULT_TIMINGS}
2441
- * pass their own `{ showDelay, minVisible }`:
2442
- *
2443
- * ```ts
2444
- * import { makeDefaultDisplayState } from 'attaform'
2445
- *
2446
- * useForm({
2447
- * schema,
2448
- * getDisplayState: makeDefaultDisplayState({ showDelay: 50, minVisible: 200 }),
2449
- * })
2450
- * ```
2451
- *
2452
- * The returned reducer is pure: the engine injects `now` and threads the
2453
- * previous machine, so the same `(prev, ctx)` always yields the same next
2454
- * machine. It shapes only the display projection — `errors`, `valid`,
2455
- * `validating`, and the underlying validation run exactly as before.
2456
- */
2457
- declare function makeDefaultDisplayState({ showDelay, minVisible, }: DisplayTimings): GetDisplayState;
2458
- /**
2459
- * Library-default `getDisplayState` reducer. Resolves every path's
2460
- * `field.displayState` — and thus `field.show*` and the `form.meta`
2461
- * rollups — whenever the consumer has not configured an override at the
2462
- * per-form or plugin level. Built from {@link DEFAULT_TIMINGS}; publicly
2463
- * re-exported so an override can compose with it (a layered reducer that
2464
- * special-cases a subtree but otherwise defers picks up future
2465
- * refinements for free):
2466
- *
2467
- * ```ts
2468
- * import { defaultDisplayState } from 'attaform'
2469
- *
2470
- * useForm({
2471
- * schema,
2472
- * getDisplayState: (prev, ctx) => {
2473
- * const next = defaultDisplayState(prev, ctx)
2474
- * return next.display === 'success' && ctx.field.path[0] === 'username'
2475
- * ? { display: 'idle' }
2476
- * : next
2477
- * },
2478
- * })
2479
- * ```
2480
- */
2481
- declare const defaultDisplayState: GetDisplayState;
2482
-
2483
- export { renderAttaformState as $, createAttaform as B, DEFAULT_TIMINGS as D, createRegistry as E, defaultCoercionRules as H, defaultDisplayState as J, defineCoercion as K, escapeForInlineScript as M, gate as N, OutsideSetupError as O, getRegistryFromApp as P, hydrateAttaformState as Q, RegistryNotInstalledError as R, injectForm as T, injectWizard as V, isRegisterValue as X, kAttaformRegistry as Y, lazy as Z, makeDefaultDisplayState as _, useRegister as a0, useRegistry as a1, useWizard as a2, vRegister as a3, AttaformError as c, AttaformErrorCode as d, DEVTOOLS_WINDOW_KEY as f, InvalidPathError as i, InvalidUseFormConfigError as j, ReservedFormKeyError as k, SubmitErrorHandlerError as n, assignKey as z };
2484
- export type { AttaformRegistry as A, CompiledStep as C, FormStatus as F, GateMarker as G, InjectWizardInput as I, LazyMarker as L, SerializedAttaformState as S, UseRegisterReturn as U, WizardAggregateError as W, AnyForm as a, AttaformDevtoolsBridge as b, AttaformPluginOptions as e, DisplayTimings as g, FormStatusSeed as h, SerializedFormData as l, StepSlot as m, UseWizardReturnType as o, WizardCtx as p, WizardCtxForm as q, WizardOnError as r, WizardOnSubmit as s, WizardOptions as t, WizardPersistFn as u, WizardRestoreFn as v, WizardRestoreState as w, WizardStatusesProxy as x, WizardSubmitContext as y };