remix 3.0.0-beta.0 → 3.0.0-beta.2
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/dist/fetch-router.d.ts +7 -0
- package/dist/fetch-router.d.ts.map +1 -1
- package/dist/node-tsx/load-module.d.ts +2 -0
- package/dist/node-tsx/load-module.d.ts.map +1 -0
- package/dist/node-tsx/load-module.js +2 -0
- package/dist/node-tsx.d.ts +3 -0
- package/dist/node-tsx.d.ts.map +1 -0
- package/{src/node-serve.ts → dist/node-tsx.js} +2 -1
- package/dist/render-middleware.d.ts +2 -0
- package/dist/render-middleware.d.ts.map +1 -0
- package/dist/render-middleware.js +2 -0
- package/dist/route-pattern/href.d.ts +2 -0
- package/dist/route-pattern/href.d.ts.map +1 -0
- package/dist/route-pattern/href.js +2 -0
- package/dist/route-pattern/join.d.ts +2 -0
- package/dist/route-pattern/join.d.ts.map +1 -0
- package/dist/route-pattern/join.js +2 -0
- package/dist/route-pattern/match.d.ts +2 -0
- package/dist/route-pattern/match.d.ts.map +1 -0
- package/dist/route-pattern/match.js +2 -0
- package/package.json +158 -44
- package/src/assert/README.md +109 -0
- package/src/assets/README.md +539 -0
- package/src/async-context-middleware/README.md +100 -0
- package/src/auth/README.md +445 -0
- package/src/auth-middleware/README.md +246 -0
- package/src/cli/README.md +78 -0
- package/src/compression-middleware/README.md +176 -0
- package/src/cookie/README.md +106 -0
- package/src/cop-middleware/README.md +117 -0
- package/src/cors-middleware/README.md +174 -0
- package/src/csrf-middleware/README.md +99 -0
- package/src/data-schema/README.md +422 -0
- package/src/data-table/README.md +552 -0
- package/src/data-table-mysql/README.md +97 -0
- package/src/data-table-postgres/README.md +74 -0
- package/src/data-table-sqlite/README.md +84 -0
- package/src/fetch-proxy/README.md +46 -0
- package/src/fetch-router/README.md +902 -0
- package/src/fetch-router.ts +7 -0
- package/src/file-storage/README.md +57 -0
- package/src/file-storage-s3/README.md +47 -0
- package/src/form-data-middleware/README.md +109 -0
- package/src/form-data-parser/README.md +160 -0
- package/src/fs/README.md +60 -0
- package/src/headers/README.md +629 -0
- package/src/html-template/README.md +101 -0
- package/src/lazy-file/README.md +109 -0
- package/src/logger-middleware/README.md +132 -0
- package/src/method-override-middleware/README.md +71 -0
- package/src/mime/README.md +110 -0
- package/src/multipart-parser/README.md +241 -0
- package/src/node-fetch-server/README.md +352 -0
- package/src/node-tsx/README.md +79 -0
- package/src/node-tsx/load-module.ts +2 -0
- package/{dist/node-serve.js → src/node-tsx.ts} +2 -1
- package/src/render-middleware/README.md +99 -0
- package/src/render-middleware.ts +2 -0
- package/src/route-pattern/README.md +291 -0
- package/src/route-pattern/href.ts +2 -0
- package/src/route-pattern/join.ts +2 -0
- package/src/route-pattern/match.ts +2 -0
- package/src/session/README.md +171 -0
- package/src/session-middleware/README.md +109 -0
- package/src/session-storage-memcache/README.md +37 -0
- package/src/session-storage-redis/README.md +37 -0
- package/src/static-middleware/README.md +89 -0
- package/src/tar-parser/README.md +74 -0
- package/src/terminal/README.md +92 -0
- package/src/test/README.md +430 -0
- package/src/ui/README.md +219 -0
- package/src/ui/accordion/README.md +166 -0
- package/src/ui/anchor/README.md +153 -0
- package/src/ui/animation/README.md +316 -0
- package/src/ui/breadcrumbs/README.md +55 -0
- package/src/ui/button/README.md +44 -0
- package/src/ui/combobox/README.md +145 -0
- package/src/ui/glyph/README.md +72 -0
- package/src/ui/listbox/README.md +115 -0
- package/src/ui/menu/README.md +96 -0
- package/src/ui/popover/README.md +122 -0
- package/src/ui/scroll-lock/README.md +33 -0
- package/src/ui/select/README.md +107 -0
- package/src/ui/server/README.md +90 -0
- package/src/ui/test/README.md +107 -0
- package/src/ui/theme/README.md +103 -0
- package/dist/node-serve.d.ts +0 -2
- package/dist/node-serve.d.ts.map +0 -1
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# csrf-middleware
|
|
2
|
+
|
|
3
|
+
CSRF protection middleware for Remix. It provides synchronizer-token validation backed by session storage, plus origin checks for unsafe requests.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Session-Backed Tokens** - Creates and persists CSRF tokens in the request session
|
|
8
|
+
- **Flexible Token Extraction** - Reads tokens from headers, form fields, query params, or a custom resolver
|
|
9
|
+
- **Origin Validation** - Validates `Origin`/`Referer` for unsafe methods with customizable policies
|
|
10
|
+
- **Configurable Enforcement** - Control safe methods, token keys, and failure responses
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm i remix
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
This middleware requires [`session-middleware`](https://github.com/remix-run/remix/tree/main/packages/session-middleware) to run before it.
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { createCookie } from 'remix/cookie'
|
|
24
|
+
import { createRouter } from 'remix/router'
|
|
25
|
+
import { createCookieSessionStorage } from 'remix/session-storage/cookie'
|
|
26
|
+
import { session } from 'remix/middleware/session'
|
|
27
|
+
import { csrf, getCsrfToken } from 'remix/middleware/csrf'
|
|
28
|
+
|
|
29
|
+
let sessionCookie = createCookie('__session', { secrets: ['secret1'] })
|
|
30
|
+
let sessionStorage = createCookieSessionStorage()
|
|
31
|
+
|
|
32
|
+
let router = createRouter({
|
|
33
|
+
middleware: [session(sessionCookie, sessionStorage), csrf()],
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
router.get('/form', (context) => {
|
|
37
|
+
let token = getCsrfToken(context)
|
|
38
|
+
|
|
39
|
+
return new Response(`
|
|
40
|
+
<form method="post" action="/submit">
|
|
41
|
+
<input type="hidden" name="_csrf" value="${token}" />
|
|
42
|
+
<button type="submit">Submit</button>
|
|
43
|
+
</form>
|
|
44
|
+
`)
|
|
45
|
+
})
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Token Sources
|
|
49
|
+
|
|
50
|
+
By default, `csrf()` checks token values in this order:
|
|
51
|
+
|
|
52
|
+
1. Request headers: `X-Csrf-Token`, `X-Xsrf-Token`, `Csrf-Token`
|
|
53
|
+
2. Form field: `_csrf` (requires `formData()` middleware to parse request bodies)
|
|
54
|
+
3. Query param: `_csrf`
|
|
55
|
+
|
|
56
|
+
You can override extraction using `value(context)`.
|
|
57
|
+
|
|
58
|
+
Headers and form fields are the preferred transports. Query param fallback exists for compatibility, but it is the weakest option because tokens are more likely to be exposed in logs, history, and copied URLs.
|
|
59
|
+
|
|
60
|
+
## Origin Validation
|
|
61
|
+
|
|
62
|
+
For unsafe methods (`POST`, `PUT`, `PATCH`, `DELETE`), the middleware validates request origin.
|
|
63
|
+
|
|
64
|
+
- Default: same-origin validation when `Origin` or `Referer` is present
|
|
65
|
+
- Custom: provide `origin` as string, regex, array, or function
|
|
66
|
+
- Missing origin behavior: controlled by `allowMissingOrigin` (default `true`)
|
|
67
|
+
|
|
68
|
+
## Caveats
|
|
69
|
+
|
|
70
|
+
- The synchronizer token is the primary defense in `csrf()`. `Origin` and `Referer` checks are an additional signal, not the only protection.
|
|
71
|
+
- By default, unsafe requests with a valid token still pass when `Origin` and `Referer` are both missing. Set `allowMissingOrigin: false` if your deployment wants to require provenance headers on unsafe requests.
|
|
72
|
+
- Query param tokens are supported for compatibility, but they should not be the default recommendation. Prefer headers or hidden form fields when you control the client.
|
|
73
|
+
- If you want to reject more unsafe requests before token validation, especially when browser provenance headers are available, layer [`cop-middleware`](https://github.com/remix-run/remix/tree/main/packages/cop-middleware) in front of `csrf()`.
|
|
74
|
+
|
|
75
|
+
## Why This Exists
|
|
76
|
+
|
|
77
|
+
Modern browsers now provide stronger cross-origin signals like `Sec-Fetch-Site`, and explicit
|
|
78
|
+
`SameSite=Lax` cookies already block many CSRF attacks. We have considered the lighter,
|
|
79
|
+
tokenless model used by Go's `CrossOriginProtection`, and we think it is a good fit when a
|
|
80
|
+
deployment can make all of the guarantees that model depends on.
|
|
81
|
+
|
|
82
|
+
Remix cannot assume those guarantees for every app. `csrf()` still exists as the conservative
|
|
83
|
+
option for apps that want synchronizer tokens in addition to origin checks, especially for
|
|
84
|
+
session-backed HTML form workflows and mixed deployment environments.
|
|
85
|
+
|
|
86
|
+
If your deployment can guarantee the prerequisites for the tokenless model, this middleware is
|
|
87
|
+
optional. In that case, [`cop-middleware`](https://github.com/remix-run/remix/tree/main/packages/cop-middleware)
|
|
88
|
+
may be a better fit.
|
|
89
|
+
|
|
90
|
+
## Related Packages
|
|
91
|
+
|
|
92
|
+
- [`cop-middleware`](https://github.com/remix-run/remix/tree/main/packages/cop-middleware) - Middleware for tokenless cross-origin protection using browser provenance headers
|
|
93
|
+
- [`fetch-router`](https://github.com/remix-run/remix/tree/main/packages/fetch-router) - Router for the web Fetch API
|
|
94
|
+
- [`session-middleware`](https://github.com/remix-run/remix/tree/main/packages/session-middleware) - Session middleware required by `csrf()`
|
|
95
|
+
- [`form-data-middleware`](https://github.com/remix-run/remix/tree/main/packages/form-data-middleware) - Needed for form body token extraction
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
See [LICENSE](https://github.com/remix-run/remix/blob/main/LICENSE)
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
# data-schema
|
|
2
|
+
|
|
3
|
+
Tiny, standards-aligned data validation for Remix and the wider TypeScript ecosystem.
|
|
4
|
+
|
|
5
|
+
- [Standard Schema](https://standardschema.dev/) v1 compatible
|
|
6
|
+
- Sync-first, minimal API surface
|
|
7
|
+
- Runs anywhere JavaScript runs (browser, Node.js, Bun, Deno, Workers)
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { enum_, literal, number, object, parse, string, variant } from 'remix/data-schema'
|
|
13
|
+
import { email, maxLength, min, minLength } from 'remix/data-schema/checks'
|
|
14
|
+
import * as coerce from 'remix/data-schema/coerce'
|
|
15
|
+
|
|
16
|
+
let User = object({
|
|
17
|
+
id: string(),
|
|
18
|
+
email: string().pipe(email()),
|
|
19
|
+
username: string().pipe(minLength(3), maxLength(20)),
|
|
20
|
+
age: coerce.number().pipe(min(13)),
|
|
21
|
+
role: enum_(['admin', 'member', 'guest']),
|
|
22
|
+
flags: object({
|
|
23
|
+
beta: coerce.boolean(),
|
|
24
|
+
}),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
let Event = variant('type', {
|
|
28
|
+
created: object({ type: literal('created'), id: string() }),
|
|
29
|
+
updated: object({ type: literal('updated'), id: string(), version: number() }),
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
let user = parse(User, {
|
|
33
|
+
id: 'u1',
|
|
34
|
+
email: 'ada@example.com',
|
|
35
|
+
username: 'ada',
|
|
36
|
+
age: '37',
|
|
37
|
+
role: 'admin',
|
|
38
|
+
flags: { beta: 'true' },
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
let event = parse(Event, { type: 'created', id: 'evt_1' })
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Parsing
|
|
45
|
+
|
|
46
|
+
Use `parse()` when you want a typed value or an exception.
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { object, string, number, parse } from 'remix/data-schema'
|
|
50
|
+
|
|
51
|
+
let User = object({ name: string(), age: number() })
|
|
52
|
+
|
|
53
|
+
let user = parse(User, { name: 'Ada', age: 37 })
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Use `parseSafe()` when you prefer explicit branching over exceptions.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { object, string, number, parseSafe } from 'remix/data-schema'
|
|
60
|
+
|
|
61
|
+
let User = object({ name: string(), age: number() })
|
|
62
|
+
|
|
63
|
+
let result = parseSafe(User, input)
|
|
64
|
+
|
|
65
|
+
if (!result.success) {
|
|
66
|
+
// result.issues — array of { message, path? }
|
|
67
|
+
} else {
|
|
68
|
+
let user = result.value
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Both `parse` and `parseSafe` accept any [Standard Schema](https://standardschema.dev/) v1 schema, not just data-schema's own schemas. You can pass a Zod, Valibot, or ArkType schema and they'll work.
|
|
73
|
+
|
|
74
|
+
For `FormData` and `URLSearchParams`, use the `remix/data-schema/form-data` helpers to build
|
|
75
|
+
schemas that plug into the same `parse()` / `parseSafe()` flow:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import * as s from 'remix/data-schema'
|
|
79
|
+
import * as f from 'remix/data-schema/form-data'
|
|
80
|
+
import * as checks from 'remix/data-schema/checks'
|
|
81
|
+
import * as coerce from 'remix/data-schema/coerce'
|
|
82
|
+
|
|
83
|
+
let Login = f.object({
|
|
84
|
+
email: f.field(coerce.string().pipe(checks.email())),
|
|
85
|
+
password: f.field(s.string().pipe(checks.minLength(8))),
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
let credentials = s.parse(Login, await request.formData())
|
|
89
|
+
let filters = s.parse(
|
|
90
|
+
f.object({
|
|
91
|
+
query: f.field(s.defaulted(s.string(), '')),
|
|
92
|
+
tags: f.fields(s.array(s.string())),
|
|
93
|
+
}),
|
|
94
|
+
new URL(request.url).searchParams,
|
|
95
|
+
)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`f.object(...)` is the root schema for `FormData` and `URLSearchParams`.
|
|
99
|
+
Use `f.field(...)` for one text value, `f.fields(...)` for repeated text values,
|
|
100
|
+
`f.file(...)` for one uploaded file, and `f.files(...)` for repeated files.
|
|
101
|
+
When you want a fallback value, prefer `s.defaulted(s.string(), '')`.
|
|
102
|
+
File helpers are intended for `FormData`; `URLSearchParams` only supports text values.
|
|
103
|
+
|
|
104
|
+
You can also customize built-in validation messages with `errorMap`:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { object, parseSafe, string } from 'remix/data-schema'
|
|
108
|
+
import { minLength } from 'remix/data-schema/checks'
|
|
109
|
+
|
|
110
|
+
let User = object({
|
|
111
|
+
name: string(),
|
|
112
|
+
username: string().pipe(minLength(3)),
|
|
113
|
+
})
|
|
114
|
+
let result = parseSafe(User, input, {
|
|
115
|
+
locale: 'es',
|
|
116
|
+
errorMap(context) {
|
|
117
|
+
if (context.code === 'type.string') {
|
|
118
|
+
return 'Se esperaba texto'
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (context.code === 'string.min_length') {
|
|
122
|
+
return (
|
|
123
|
+
'Debe tener al menos ' + String((context.values as { min: number }).min) + ' caracteres'
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`errorMap` receives `{ code, defaultMessage, path, values, input, locale }`.
|
|
131
|
+
Return `undefined` to keep the default message.
|
|
132
|
+
|
|
133
|
+
## Primitives
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { string, number, boolean, bigint, symbol, null_, undefined_ } from 'remix/data-schema'
|
|
137
|
+
|
|
138
|
+
string() // validates typeof === 'string'
|
|
139
|
+
number() // validates finite numbers (rejects NaN, Infinity)
|
|
140
|
+
boolean() // validates typeof === 'boolean'
|
|
141
|
+
bigint() // validates typeof === 'bigint'
|
|
142
|
+
symbol() // validates typeof === 'symbol'
|
|
143
|
+
null_() // validates value === null
|
|
144
|
+
undefined_() // validates value === undefined
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Literals, enums, and unions
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { literal, enum_, union } from 'remix/data-schema'
|
|
151
|
+
|
|
152
|
+
// Exact value match
|
|
153
|
+
let yes = literal('yes')
|
|
154
|
+
|
|
155
|
+
// One of several allowed values
|
|
156
|
+
let Status = enum_(['active', 'inactive', 'pending'])
|
|
157
|
+
|
|
158
|
+
// First schema that matches wins
|
|
159
|
+
let StringOrNumber = union([string(), number()])
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Objects
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import { object, string, number, optional, defaulted } from 'remix/data-schema'
|
|
166
|
+
|
|
167
|
+
let User = object({
|
|
168
|
+
name: string(),
|
|
169
|
+
bio: optional(string()), // accepts undefined
|
|
170
|
+
role: defaulted(string(), 'user'), // fills in 'user' when undefined
|
|
171
|
+
age: number(),
|
|
172
|
+
})
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Unknown keys are stripped by default. Change this with `unknownKeys`:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
object({ name: string() }, { unknownKeys: 'passthrough' }) // keeps unknown keys
|
|
179
|
+
object({ name: string() }, { unknownKeys: 'error' }) // rejects unknown keys
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Collections
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
import { array, tuple, record, map, set, string, number, boolean } from 'remix/data-schema'
|
|
186
|
+
|
|
187
|
+
array(number()) // number[]
|
|
188
|
+
tuple([string(), number(), boolean()]) // [string, number, boolean]
|
|
189
|
+
record(string(), number()) // Record<string, number>
|
|
190
|
+
map(string(), number()) // Map<string, number>
|
|
191
|
+
set(number()) // Set<number>
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Modifiers
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { nullable, optional, defaulted, string, number } from 'remix/data-schema'
|
|
198
|
+
|
|
199
|
+
nullable(string()) // string | null
|
|
200
|
+
optional(number()) // number | undefined
|
|
201
|
+
defaulted(string(), 'n/a') // fills 'n/a' when undefined
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Instance checks
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
import { instanceof_, object } from 'remix/data-schema'
|
|
208
|
+
|
|
209
|
+
let Schema = object({
|
|
210
|
+
created: instanceof_(Date),
|
|
211
|
+
pattern: instanceof_(RegExp),
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Any
|
|
216
|
+
|
|
217
|
+
Accept any value without validation. Useful when part of a structure is opaque.
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { any, object, string } from 'remix/data-schema'
|
|
221
|
+
|
|
222
|
+
let Envelope = object({
|
|
223
|
+
type: string(),
|
|
224
|
+
payload: any(),
|
|
225
|
+
})
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Custom rules with `.refine()`
|
|
229
|
+
|
|
230
|
+
Add domain-specific validation logic inline. The predicate runs after the schema validates.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { number, string, object } from 'remix/data-schema'
|
|
234
|
+
|
|
235
|
+
let Profile = object({
|
|
236
|
+
username: string().refine((s) => s.length >= 3, 'Too short'),
|
|
237
|
+
age: number().refine((n) => n >= 18, 'Must be an adult'),
|
|
238
|
+
})
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Output transforms with `.transform()`
|
|
242
|
+
|
|
243
|
+
Map a validated value into the shape your app wants. The transformer runs after the schema validates and changes the parsed output type.
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
import { object, parse, string } from 'remix/data-schema'
|
|
247
|
+
|
|
248
|
+
let Event = object({
|
|
249
|
+
id: string(),
|
|
250
|
+
createdAt: string()
|
|
251
|
+
.refine((value) => !Number.isNaN(Date.parse(value)), 'Expected valid date')
|
|
252
|
+
.transform((value) => new Date(value)),
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
let event = parse(Event, {
|
|
256
|
+
id: 'evt_1',
|
|
257
|
+
createdAt: '2026-04-25T00:00:00.000Z',
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
event.createdAt // Date
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Use `.refine()` for checks that reject values without changing them. Use `.transform()` for safe, synchronous mappings; thrown errors are propagated instead of converted into validation issues.
|
|
264
|
+
|
|
265
|
+
## Validation pipelines with `.pipe()`
|
|
266
|
+
|
|
267
|
+
Compose reusable `Check` objects for common constraints.
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
import { object, string, number } from 'remix/data-schema'
|
|
271
|
+
import { minLength, maxLength, email, min, max } from 'remix/data-schema/checks'
|
|
272
|
+
|
|
273
|
+
let Credentials = object({
|
|
274
|
+
username: string().pipe(minLength(3), maxLength(20)),
|
|
275
|
+
email: string().pipe(email()),
|
|
276
|
+
age: number().pipe(min(13), max(130)),
|
|
277
|
+
})
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
Built-in checks: `minLength`, `maxLength`, `email`, `url`, `min`, `max`.
|
|
281
|
+
|
|
282
|
+
## Coercing input values
|
|
283
|
+
|
|
284
|
+
Turn stringly-typed inputs (like form data or query strings) into real types at the schema boundary.
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
import { object, parse } from 'remix/data-schema'
|
|
288
|
+
import * as coerce from 'remix/data-schema/coerce'
|
|
289
|
+
|
|
290
|
+
let Query = object({
|
|
291
|
+
page: coerce.number(),
|
|
292
|
+
includeArchived: coerce.boolean(),
|
|
293
|
+
since: coerce.date(),
|
|
294
|
+
limit: coerce.bigint(),
|
|
295
|
+
search: coerce.string(),
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
let query = parse(Query, {
|
|
299
|
+
page: '2',
|
|
300
|
+
includeArchived: 'true',
|
|
301
|
+
since: '2025-01-01',
|
|
302
|
+
limit: '100',
|
|
303
|
+
search: 42,
|
|
304
|
+
})
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## Discriminated unions
|
|
308
|
+
|
|
309
|
+
Pick the right schema based on a discriminator property.
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
import { literal, number, object, string, variant } from 'remix/data-schema'
|
|
313
|
+
|
|
314
|
+
let Event = variant('type', {
|
|
315
|
+
created: object({ type: literal('created'), id: string() }),
|
|
316
|
+
updated: object({ type: literal('updated'), id: string(), version: number() }),
|
|
317
|
+
})
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## Recursive schemas
|
|
321
|
+
|
|
322
|
+
Model trees and self-referencing structures. `lazy()` defers schema resolution to avoid circular references.
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { array, object, string } from 'remix/data-schema'
|
|
326
|
+
import { lazy } from 'remix/data-schema/lazy'
|
|
327
|
+
import type { Schema } from 'remix/data-schema'
|
|
328
|
+
|
|
329
|
+
type TreeNode = { id: string; children: TreeNode[] }
|
|
330
|
+
|
|
331
|
+
let Node: Schema<unknown, TreeNode> = lazy(() => object({ id: string(), children: array(Node) }))
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## Aborting early
|
|
335
|
+
|
|
336
|
+
By default, validation collects all issues in a single pass. To stop at the first issue, enable `abortEarly`.
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
import { object, string, number, parseSafe } from 'remix/data-schema'
|
|
340
|
+
|
|
341
|
+
let result = parseSafe(
|
|
342
|
+
object({ name: string(), age: number() }),
|
|
343
|
+
{ name: 123, age: 'x' },
|
|
344
|
+
{ abortEarly: true },
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
if (!result.success) {
|
|
348
|
+
console.log(result.issues) // only the first issue
|
|
349
|
+
}
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Type inference
|
|
353
|
+
|
|
354
|
+
Extract input and output types from any Standard Schema-compatible schema.
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
import { object, string, number } from 'remix/data-schema'
|
|
358
|
+
import type { InferInput, InferOutput } from 'remix/data-schema'
|
|
359
|
+
|
|
360
|
+
let User = object({ name: string(), age: number() })
|
|
361
|
+
|
|
362
|
+
type UserInput = InferInput<typeof User> // unknown
|
|
363
|
+
type UserOutput = InferOutput<typeof User> // { name: string; age: number }
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
## Extending data-schema
|
|
367
|
+
|
|
368
|
+
Build custom schemas using `createSchema`, `createIssue`, and `fail`. These are the same primitives used internally by every built-in schema.
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
import { createSchema, createIssue, fail } from 'remix/data-schema'
|
|
372
|
+
import type { Schema } from 'remix/data-schema'
|
|
373
|
+
|
|
374
|
+
// A schema that validates a non-empty trimmed string
|
|
375
|
+
function trimmedString(): Schema<unknown, string> {
|
|
376
|
+
return createSchema(function validate(value, context) {
|
|
377
|
+
if (typeof value !== 'string') {
|
|
378
|
+
return fail('Expected string', context.path)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
let trimmed = value.trim()
|
|
382
|
+
|
|
383
|
+
if (trimmed.length === 0) {
|
|
384
|
+
return fail('Expected non-empty string', context.path)
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
return { value: trimmed }
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// A schema that validates a [lat, lng] coordinate pair
|
|
392
|
+
function latLng(): Schema<unknown, [number, number]> {
|
|
393
|
+
return createSchema(function validate(value, context) {
|
|
394
|
+
if (!Array.isArray(value) || value.length !== 2) {
|
|
395
|
+
return fail('Expected [lat, lng] pair', context.path)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
let issues = []
|
|
399
|
+
let [lat, lng] = value
|
|
400
|
+
|
|
401
|
+
if (typeof lat !== 'number' || lat < -90 || lat > 90) {
|
|
402
|
+
issues.push(createIssue('Latitude must be between -90 and 90', [...context.path, 0]))
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (typeof lng !== 'number' || lng < -180 || lng > 180) {
|
|
406
|
+
issues.push(createIssue('Longitude must be between -180 and 180', [...context.path, 1]))
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (issues.length > 0) {
|
|
410
|
+
return { issues }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
return { value: [lat, lng] }
|
|
414
|
+
})
|
|
415
|
+
}
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
The validator function receives the raw value and a context with the current `path` and `options`. Return `{ value }` on success or `{ issues: [...] }` on failure. The returned schema is fully Standard Schema v1-compatible and supports `.pipe()` and `.refine()` out of the box.
|
|
419
|
+
|
|
420
|
+
## License
|
|
421
|
+
|
|
422
|
+
See [LICENSE](https://github.com/remix-run/remix/blob/main/LICENSE)
|