@thomasfosterau/effect-forms 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +100 -0
- package/dist/index.d.ts +878 -0
- package/dist/index.js +1768 -0
- package/dist/index.js.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thomas Foster
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# @thomasfosterau/effect-forms
|
|
2
|
+
|
|
3
|
+
Framework-neutral, **Effect-native** form validation and state — schema-driven validation, nested errors, posted-value retention, status messages, and native input constraints, built on **Effect Schema** with no framework dependency. The Svelte 5 bindings live in [`@thomasfosterau/effect-forms-svelte`](../svelte).
|
|
4
|
+
|
|
5
|
+
## Why
|
|
6
|
+
|
|
7
|
+
The app validates everything with Effect Schema (Zod is gone). The progressive form libraries in the ecosystem are excellent, but they speak Standard Schema / Zod and bake in a framework. This package keeps the ergonomics — one schema drives validation, errors nest by field, posted values survive a failed submit, native input constraints come for free — while staying on Effect Schema and free of any framework, so the core is testable in isolation and reusable from a Worker, the CLI, or a Svelte route.
|
|
8
|
+
|
|
9
|
+
## The shape
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import * as Schema from "effect/Schema";
|
|
13
|
+
import * as Effect from "effect/Effect";
|
|
14
|
+
import { Form } from "@thomasfosterau/effect-forms";
|
|
15
|
+
|
|
16
|
+
const Signup = Schema.Struct({
|
|
17
|
+
name: Schema.String.check(Schema.isMinLength(2)),
|
|
18
|
+
age: Schema.optional(Schema.FiniteFromString),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const signupForm = Form.make(Signup, {
|
|
22
|
+
id: "signup",
|
|
23
|
+
defaults: { name: "", age: undefined },
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// In a server action / load:
|
|
27
|
+
const state = await Effect.runPromise(signupForm.validate(request));
|
|
28
|
+
// state: { id, valid, posted, data, errors, constraints, message? }
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Building a form incrementally
|
|
32
|
+
|
|
33
|
+
`Form.make` binds a hand-written `Schema.Struct`. When you'd rather compose a form field by field — reusing field groups, merging them, and attaching whole-form (cross-field) rules — reach for `FormBuilder`:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import * as Schema from "effect/Schema";
|
|
37
|
+
import { Field, Form, FormBuilder } from "@thomasfosterau/effect-forms";
|
|
38
|
+
|
|
39
|
+
const signup = FormBuilder.empty
|
|
40
|
+
.addField("email", Schema.String.check(Schema.isMinLength(3)))
|
|
41
|
+
.addField("password", Schema.String.check(Schema.isMinLength(8)))
|
|
42
|
+
.addField("confirm", Schema.String)
|
|
43
|
+
.addField(Field.makeArrayField("tags", Schema.String)) // an array field
|
|
44
|
+
.refine((v) =>
|
|
45
|
+
v.password === v.confirm ? undefined : { path: ["confirm"], issue: "Passwords must match" },
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
// Bind it exactly like a schema (defaults are derived when omitted):
|
|
49
|
+
const form = Form.fromBuilder(signup, { id: "signup" });
|
|
50
|
+
const state = await Effect.runPromise(form.validate(request));
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`FormBuilder.buildSchema` collapses the builder into an ordinary `Schema.Struct` (array fields become `Schema.Array(item)`) with each synchronous `refine` applied as a struct-level check — so it decodes, derives constraints, and validates like any schema. `refineEffect` attaches an **asynchronous** whole-form rule (a uniqueness check against a service, say); Effect Schema has no effectful filter, so `Form.fromBuilder` runs those on the Effect validate path and folds their failures into the same error tree.
|
|
54
|
+
|
|
55
|
+
Modules are exposed as Effect-style namespaces (`Form`, `State`, `Result`, `Errors`, …). `Form.make(schema, { defaults })` is the server-side validate-and-seed entry point:
|
|
56
|
+
|
|
57
|
+
- **`validate(input)`** accepts a `FormData`, `URLSearchParams`, `Request`, or a plain object. It parses the body (nested `author.name` / `tags[0]` / `tags[]` notation), decodes it through the schema collecting **every** field error (`errors: "all"`), and returns a serialisable [`FormState`](src/State.ts) — valid with the decoded data, or invalid with the nested [`FormErrors`](src/Errors.ts) tree and the **posted values preserved** so the form re-renders what the user typed. It is an `Effect`, so a schema that requires decoding services composes naturally; it never fails on the error channel (validation failures live in the returned state).
|
|
58
|
+
- **`empty()`** seeds a blank, unposted form from the defaults — what a `load` returns to render a create form.
|
|
59
|
+
|
|
60
|
+
## What's in the box
|
|
61
|
+
|
|
62
|
+
| Module | Purpose |
|
|
63
|
+
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
64
|
+
| [`Form`](src/Form.ts) | `make` — bind a schema to a form (validate + empty); `fromBuilder` — bind a `FormBuilder`. |
|
|
65
|
+
| [`FormBuilder`](src/FormBuilder.ts) | Compose a form field by field: `addField` / `merge` / `refine` / `refineEffect` / `buildSchema`. |
|
|
66
|
+
| [`Field`](src/Field.ts) | `makeField` / `makeArrayField` field defs + guards, and blank-default derivation from a schema — `defaultValue` / `defaultEncodedValues` for a builder field, `schemaAt` / `defaultItemAt` for any nested path. |
|
|
67
|
+
| [`State`](src/State.ts) | `FormState`, `makeFormState`, `setMessage`, `withError`, `FormStateSchema` (transport). |
|
|
68
|
+
| [`Errors`](src/Errors.ts) | The nested `FormErrors` tree + `issuesToErrors` / `flattenErrors` / `getError` / `setError` / `mergeErrors` / `remapIndices`; `FieldValidators` per-source error tracking via `replaceAt` / `setSourceAt` / `clearSourceAt` / `mergeSourced`. |
|
|
69
|
+
| [`Issues`](src/Issues.ts) | `FormIssue` + the Effect Schema issue-tree walker. |
|
|
70
|
+
| [`FormData`](src/FormData.ts) | `formDataToObject` / `parseFieldPath` — structured parsing of an HTML body. |
|
|
71
|
+
| [`Path`](src/Path.ts) | `getAt` / `setAt` (immutable) along a `FormPath`, `toString` / `fromString` notation conversion, the type-level `FieldPath<T>` / `PathValue<T, P>` deep-key projections a typed field handle is built on, and the `IndexMap` constructors (`removeAt` / `insertAt` / `swapAt` / `moveAt` / `replaceAt` / `clearAll`) + `remapIndex` / `remapKeyedRecord` for keeping per-index state in sync with an array mutation. |
|
|
72
|
+
| [`Coerce`](src/Coerce.ts) | Tri-state (value / `null` / `undefined`) coercers for the form boundary. |
|
|
73
|
+
| [`Constraints`](src/Constraints.ts) | `constraintsFromSchema` — native input attributes (`required`, `minlength`/`maxlength`, `min`/`max`, `pattern`, `step`) derived from the schema AST, including into array items; `constraintAt` reads one field's leaf out of the derived tree. |
|
|
74
|
+
| [`Mode`](src/Mode.ts) | `FormMode` + `parse` — when a form validates (`onSubmit` / `onBlur` / `onChange`), whether it auto-submits, and when a posted form revalidates (`revalidate`). |
|
|
75
|
+
| [`Result`](src/Result.ts) | `FormActionResult` — the framework-neutral submission outcome (success / failure / redirect / error). |
|
|
76
|
+
| [`Validate`](src/Validate.ts) | `validateValue` / `validateValueSync` — ad-hoc value/field validation; `FieldValidators` + `runSyncFieldValidator` / `runAsyncFieldValidator` — per-field sync/async validators (debounced, fiber-cancellable). |
|
|
77
|
+
|
|
78
|
+
## Notes
|
|
79
|
+
|
|
80
|
+
- **Coercion is the schema's job.** An HTML body is all strings; build the schema from coercing leaves (`Schema.FiniteFromString`, `Schema.BooleanFromString`, the `Coerce` helpers) so the parsed object decodes cleanly. The parser never guesses types.
|
|
81
|
+
- **Errors nest by field.** Leaf fields are `string[]`; nested objects / array indices nest; a branch's own (cross-field) message lives under `_errors`. The tree is plain JSON — it crosses the SSR boundary unchanged.
|
|
82
|
+
- **Update semantics.** The `Coerce` helpers honour the value / `null` / `undefined` contract (set / clear / carry-forward) the app uses for partial updates.
|
|
83
|
+
- **Constraint derivation reads schema checks, not just optionality.** `constraintsFromSchema` walks each property's `.check()`s for the `meta` annotation Effect Schema's built-in checks carry (`isMinLength`, `isLengthBetween`, `isPattern`, `isGreaterThanOrEqualTo`, `isBetween`, `isMultipleOf`, `isInt`, …), unwraps `optional` / `NullOr` unions, and descends into struct and array-item shapes. A check with no recognised `meta` tag (a bare `Schema.filter` predicate) derives nothing — there's no attribute to guess at. Anything the walk can't (or shouldn't) infer goes through the `overrides` argument, which always wins on conflict.
|
|
84
|
+
- **Errors have a source.** `Errors.SourcedErrors` keeps a `client` tree (browser-side validation) parallel to a `server` tree (the last submission), merged for display by `mergeSourced`. `Errors.replaceAt` / `setSourceAt` / `clearSourceAt` update one path in one source without disturbing the rest — what a reactive store needs so a server-reported failure survives a client revalidation of some _other_ field, but clears once its own field changes.
|
|
85
|
+
|
|
86
|
+
## File naming
|
|
87
|
+
|
|
88
|
+
Source modules use PascalCase file names, matching Effect's own convention (`effect/Schema`, `effect/SchemaParser`). The package has a single entry point: every module is re-exported from the `.` barrel, so there are no subpaths to import from.
|
|
89
|
+
|
|
90
|
+
## Development
|
|
91
|
+
|
|
92
|
+
From the repository root:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
vp run -r build # build every package with tsdown
|
|
96
|
+
vp check # format (Oxfmt), lint (Oxlint), type-check (tsgolint)
|
|
97
|
+
vp run -r test # unit tests
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Or from this directory: `vp test run` / `vp test run --coverage`.
|