ovr 6.2.5 → 7.0.0-next.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 (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +289 -123
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +360 -148
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -265
  136. package/src/render/index.ts +0 -318
@@ -0,0 +1,1720 @@
1
+ import { Fragment, type JSX, jsx } from "../jsx/index.js";
2
+ import type { Multipart } from "../multipart/index.js";
3
+ import {
4
+ Schema,
5
+ ShapeUtil,
6
+ annotate,
7
+ append,
8
+ exact,
9
+ normalizers,
10
+ own,
11
+ } from "../schema/index.js";
12
+ import { Checksum, Codec, Size } from "../util/index.js";
13
+
14
+ /** Internal protocol for a GET route, to make the form its fields render. */
15
+ export const query = Symbol("query");
16
+
17
+ /** A field's components and render, which a route's form reads */
18
+ const component = Symbol("component");
19
+ const render = Symbol("render");
20
+
21
+ /**
22
+ * Each route's form, kept apart from the route so its parsing is not part of
23
+ * the route's API.
24
+ */
25
+ export const forms = new WeakMap<object, Form<any>>();
26
+
27
+ /**
28
+ * Maximum encoded state size in bytes. Outside the class, since a static that
29
+ * reads another module is a side effect, which keeps `Form` in bundles that
30
+ * only use `Field`.
31
+ */
32
+ const maxStateBytes = 4 * Size.kb;
33
+
34
+ /**
35
+ * Form schema with JSX rendering capabilities.
36
+ *
37
+ * Parses `FormData` or `URLSearchParams` and generates form field
38
+ * components.
39
+ *
40
+ * @template Shape Form field shape type
41
+ */
42
+ export class Form<Shape extends Field.Shape = Field.Shape> {
43
+ /** Query param keys ordered as `[return, form]`. */
44
+ static readonly params = ["_return", "_form"] as const;
45
+
46
+ /** Maximum serialized size for a single persisted value. */
47
+ static readonly #maxValueChars = 512;
48
+
49
+ /** Schema used to validate persisted form values, see `#value`. */
50
+ static #valueSchema?: Schema<Field.Value>;
51
+
52
+ /** Form id. */
53
+ readonly #id: string;
54
+
55
+ /**
56
+ * If search params fill the fields by name, as a GET form submits them.
57
+ * Other forms restore only what they persisted, so a link cannot fill them.
58
+ */
59
+ #query = false;
60
+
61
+ /** Field definitions. */
62
+ readonly shape: Shape;
63
+
64
+ /** Field names in definition order. */
65
+ readonly names: ShapeUtil.Name<Shape>[];
66
+
67
+ /** Maximum expected multipart parts derived from field cardinality. */
68
+ readonly parts: number;
69
+
70
+ /**
71
+ * Create a new form schema validator.
72
+ *
73
+ * @param shape Form fields
74
+ */
75
+ constructor(shape: Shape) {
76
+ this.shape = shape;
77
+ this.names = Object.keys(this.shape) as ShapeUtil.Name<Shape>[];
78
+ this.#id = Checksum.djb2(this.names.join());
79
+ this.parts = Object.values(this.shape).reduce(
80
+ (sum, field) => sum + field.parts,
81
+ 0,
82
+ );
83
+ }
84
+
85
+ /**
86
+ * Built on first use: a schema built as the class loads is a side effect,
87
+ * which would keep `Form` in bundles that only use `Field`.
88
+ *
89
+ * @returns Schema used to validate persisted form values
90
+ */
91
+ static #value() {
92
+ return (Form.#valueSchema ??= Schema.union([
93
+ Schema.string(),
94
+ Schema.number(),
95
+ Schema.boolean(),
96
+ Schema.array(Schema.string()),
97
+ ]));
98
+ }
99
+
100
+ /** @returns The form for a GET route, whose submission is the page's URL */
101
+ [query]() {
102
+ const form = new Form(this.shape);
103
+ form.#query = true;
104
+ return form;
105
+ }
106
+
107
+ /**
108
+ * @param name Form data name
109
+ * @returns The field, own fields only, so a name such as "constructor" has none
110
+ */
111
+ #field(name: string) {
112
+ return Object.hasOwn(this.shape, name) ? this.shape[name] : undefined;
113
+ }
114
+
115
+ /**
116
+ * @param name Unexpected form field name
117
+ * @param path Parent path
118
+ * @returns Schema issue for unexpected form field names
119
+ */
120
+ #unexpected(name: string, path: Schema.Issue.Path = []) {
121
+ return new Schema.Issue(
122
+ "known form data name",
123
+ [...path, name],
124
+ "Unexpected form data name",
125
+ );
126
+ }
127
+
128
+ /**
129
+ * Sanitizes render-state values by removing unsupported or oversized entries.
130
+ *
131
+ * @param values Candidate values to keep
132
+ * @param persist When `true`, only allow fields marked with `.persist()`
133
+ * @param limit When `true`, drop values too long to keep in the URL
134
+ * @returns Sanitized values
135
+ */
136
+ #sanitize(values?: Record<string, unknown>, persist = true, limit = true) {
137
+ const sanitized: Field.Value.Map<Shape> = {};
138
+
139
+ if (values) {
140
+ for (const [name, value] of Object.entries(values)) {
141
+ const field = this.#field(name);
142
+
143
+ if (
144
+ field &&
145
+ field.type !== "file" &&
146
+ (!persist || FieldSchema.persisted(field)) &&
147
+ value != null
148
+ ) {
149
+ const result = Form.#value().parse(value);
150
+
151
+ if (
152
+ !result.issues &&
153
+ (!limit ||
154
+ JSON.stringify(result.data).length <= Form.#maxValueChars)
155
+ ) {
156
+ own(sanitized, name, result.data);
157
+ }
158
+ }
159
+ }
160
+
161
+ if (Object.keys(sanitized).length) return sanitized;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Decode form state, over the initial values.
167
+ *
168
+ * @param stateInput Current page URL
169
+ * @param initial Initial values, submitted values take precedence
170
+ */
171
+ #decode(
172
+ stateInput?: URL,
173
+ initial?: Field.Value.Initial<Shape>,
174
+ ): Field.State<Shape> | undefined {
175
+ const state = this.#restore(stateInput);
176
+ // initial values come from the server, not the URL, so no size limit
177
+ const values = this.#sanitize(initial, false, false);
178
+
179
+ if (!values) return state;
180
+
181
+ return { id: this.#id, ...state, values: { ...values, ...state?.values } };
182
+ }
183
+
184
+ /**
185
+ * Restore form state from the URL.
186
+ *
187
+ * @param stateInput Current page URL
188
+ */
189
+ #restore(stateInput?: URL): Field.State<Shape> | undefined {
190
+ if (stateInput) {
191
+ const { searchParams } = stateInput;
192
+ const values = this.#sanitize(
193
+ (this.#query ? this.names : []).reduce<Record<string, unknown>>(
194
+ (data, name) => {
195
+ if (searchParams.has(name)) {
196
+ const value = FieldSchema.read(
197
+ this.shape[name]!,
198
+ searchParams,
199
+ name,
200
+ );
201
+
202
+ if (value != null) own(data, name, value);
203
+ }
204
+
205
+ return data;
206
+ },
207
+ {},
208
+ ),
209
+ false,
210
+ );
211
+ const encoded = searchParams.get(Form.params[1]);
212
+
213
+ if (encoded && encoded.length <= maxStateBytes * 2) {
214
+ try {
215
+ const result = Schema.string()
216
+ .json(
217
+ Schema.object({
218
+ id: Schema.literal(this.#id),
219
+ issues: Schema.array(
220
+ Schema.object({
221
+ expected: Schema.string(),
222
+ path: Schema.array(
223
+ Schema.union([Schema.string(), Schema.number()]),
224
+ ),
225
+ message: Schema.string(),
226
+ }).transform(
227
+ (issue) =>
228
+ new Schema.Issue(
229
+ issue.expected,
230
+ issue.path,
231
+ issue.message,
232
+ ),
233
+ ),
234
+ ).optional(),
235
+ values: Schema.object(
236
+ this.names.reduce<Schema.Object.Shape>((shape, name) => {
237
+ own(shape, name, Form.#value().optional());
238
+
239
+ return shape;
240
+ }, {}),
241
+ ).optional(),
242
+ }),
243
+ )
244
+ .parse(Codec.decode(Codec.Base64Url.decode(encoded)));
245
+
246
+ // valid only for this form, its id is a literal
247
+ if (!result.issues) {
248
+ const current = this.#sanitize(result.data.values);
249
+
250
+ return {
251
+ ...result.data,
252
+ values: (values || current) && { ...values, ...current },
253
+ } as unknown as Field.State<Shape>;
254
+ }
255
+ } catch {}
256
+ }
257
+
258
+ return values && { id: this.#id, values };
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Create an invalid result, encoding the issues and persisted values so the
264
+ * next render can show them.
265
+ *
266
+ * @param issues Issues
267
+ * @param values Submitted values, only persisted fields are kept
268
+ * @returns Invalid result with its encoded search param
269
+ */
270
+ #invalid(issues: Schema.Issue[], values: Record<string, unknown>) {
271
+ const result = new Schema.AggregateIssue(issues, this.#sanitize(values));
272
+ const persisted = result.values;
273
+ let search: Field.Parse.Result.Search;
274
+
275
+ // encode everything first, then trim persisted values until the state fits
276
+ for (let i = this.names.length; ; i--) {
277
+ const state = Codec.encode(
278
+ JSON.stringify({
279
+ issues: result.issues,
280
+ id: this.#id,
281
+ // issues only when nothing is persisted
282
+ ...(persisted && Object.keys(persisted).length
283
+ ? { values: persisted }
284
+ : {}),
285
+ } satisfies Field.State),
286
+ );
287
+
288
+ if (state.byteLength <= maxStateBytes) {
289
+ search = [[Form.params[1], Codec.Base64Url.encode(state)]];
290
+ break;
291
+ }
292
+
293
+ if (!persisted || !i) break;
294
+
295
+ delete persisted[this.names[i - 1]!];
296
+ }
297
+
298
+ return Object.assign(result, { search });
299
+ }
300
+
301
+ /**
302
+ * Parse and validate form data.
303
+ *
304
+ * @param source FormData, URLSearchParams, or Multipart to parse
305
+ * @param path Internal path reference
306
+ * @returns Parsed result
307
+ */
308
+ parse = async (
309
+ source: FormData | URLSearchParams | Multipart,
310
+ path: Schema.Issue.Path = [],
311
+ ): Promise<Field.Parse.Result<Shape>> => {
312
+ const data: Record<string, unknown> = {};
313
+ const issues: Schema.Issue[] = [];
314
+ const values: Record<string, unknown> = {};
315
+ let form: FormData | URLSearchParams;
316
+ let stream: AsyncGenerator<Multipart.Part> | undefined;
317
+
318
+ if (source instanceof FormData) {
319
+ form = source;
320
+
321
+ for (const name of new Set(source.keys())) {
322
+ if (!this.#field(name)) issues.push(this.#unexpected(name, path));
323
+ }
324
+ } else if (source instanceof URLSearchParams) {
325
+ form = source;
326
+ } else {
327
+ // the only other source is a Multipart, read one part at a time
328
+ form = new FormData();
329
+ const iter = source[Symbol.asyncIterator]();
330
+
331
+ // a failure ends the parts, which also stops the upload
332
+ try {
333
+ let current: IteratorResult<Multipart.Part>;
334
+
335
+ while ((current = await iter.next()) && !current.done) {
336
+ const part = current.value;
337
+
338
+ if (part.name) {
339
+ const field = this.#field(part.name);
340
+
341
+ if (!field) {
342
+ issues.push(this.#unexpected(part.name, path));
343
+ } else if (field.streaming) {
344
+ // expose current and rest of the parts to the user
345
+ stream = (async function* () {
346
+ try {
347
+ // have to yield the current part first
348
+ // this is why the multipart can't be passed directly
349
+ yield part;
350
+
351
+ let next: IteratorResult<Multipart.Part>;
352
+
353
+ while ((next = await iter.next()) && !next.done) {
354
+ yield next.value;
355
+ }
356
+ } finally {
357
+ try {
358
+ await iter.return?.();
359
+ } catch {}
360
+ }
361
+ })();
362
+
363
+ break;
364
+ } else {
365
+ form.append(part.name, await part.value());
366
+ }
367
+ }
368
+ }
369
+ } catch (error) {
370
+ await iter.return?.().catch(() => {});
371
+ throw error;
372
+ }
373
+ }
374
+
375
+ for (const [name, field] of Object.entries(this.shape)) {
376
+ if (!field.streaming) {
377
+ const value = FieldSchema.read(field, form, name);
378
+ const result = field.parse(value, [...path, name]);
379
+
380
+ if (result.issues) {
381
+ append(issues, result.issues);
382
+ } else if (result.data !== undefined) {
383
+ own(data, name, result.data);
384
+ }
385
+
386
+ // a cleared field is recorded empty, so it overrides initial values
387
+ if (FieldSchema.persisted(field)) own(values, name, value ?? "");
388
+ }
389
+ }
390
+
391
+ if (issues.length) {
392
+ if (stream) {
393
+ // invalid result does not expose streamed parts, drain
394
+ try {
395
+ for await (const _ of stream);
396
+ } catch {}
397
+ }
398
+
399
+ return this.#invalid(issues, values);
400
+ }
401
+
402
+ return {
403
+ data: data as Field.Parse.Data<Shape>,
404
+ stream,
405
+ invalid: (messages: Field.Parse.Messages<Shape>) =>
406
+ this.#invalid(
407
+ Object.entries(messages).flatMap(([name, message]) =>
408
+ typeof message === "string"
409
+ ? [new Schema.Issue("valid", [name], message)]
410
+ : [],
411
+ ),
412
+ values,
413
+ ),
414
+ };
415
+ };
416
+
417
+ /**
418
+ * Render a single form field.
419
+ *
420
+ * @param props Component props
421
+ * @example
422
+ *
423
+ * ```tsx
424
+ * <User.Field name="username" />
425
+ * ```
426
+ */
427
+ Field = ({
428
+ values,
429
+ ...props
430
+ }: Field.Component.Props<Shape> & {
431
+ values?: Field.Value.Initial<Shape> | undefined;
432
+ }) =>
433
+ this.shape[props.name]![render]({
434
+ ...props,
435
+ state: this.#decode(props.state, values),
436
+ });
437
+
438
+ /**
439
+ * Render all form fields.
440
+ *
441
+ * @param props Component props
442
+ * @example
443
+ *
444
+ * ```tsx
445
+ * <User.Fields />
446
+ * ```
447
+ */
448
+ Fields = ({
449
+ values,
450
+ ...props
451
+ }: // partial because name is not required
452
+ Partial<Field.Component.Props<Shape>> & {
453
+ values?: Field.Value.Initial<Shape> | undefined;
454
+ } = {}) => {
455
+ const state = this.#decode(props.state, values); // pulled out to not call each map iteration
456
+
457
+ return this.names.map((name) =>
458
+ this.shape[name]![render]({ ...props, name, state }),
459
+ );
460
+ };
461
+
462
+ /**
463
+ * Access bound sub-components for a field.
464
+ *
465
+ * @template N Type of the form field name
466
+ * @param props Field component props
467
+ * @example
468
+ *
469
+ * ```tsx
470
+ * const Radio = User.component({ name: "radio" });
471
+ *
472
+ * <Radio.Label />
473
+ * <Radio.Control />
474
+ * ```
475
+ */
476
+ component = <N extends ShapeUtil.Name<Shape>>({
477
+ values,
478
+ ...props
479
+ }: { name: N } & Field.Component.Props<Shape> & {
480
+ values?: Field.Value.Initial<Shape> | undefined;
481
+ }): Field.Component<Shape[N]> =>
482
+ this.shape[props.name]![component]({
483
+ ...props,
484
+ state: this.#decode(props.state, values),
485
+ });
486
+ }
487
+
488
+ /** Default message for a required field */
489
+ const required = "Required field";
490
+
491
+ /** Default message for a choice that is not one of the options */
492
+ const choose = "Select an option";
493
+
494
+ /**
495
+ * @param value Form data entry
496
+ * @returns `true` for a file a person chose, a browser sends an empty one otherwise
497
+ */
498
+ const chosenFile = (value: FormDataEntryValue | null): value is File =>
499
+ value instanceof File && (value.name !== "" || value.size > 0);
500
+
501
+ /**
502
+ * @param data Form data
503
+ * @param name HTML name attribute
504
+ * @returns Every value of the name, or `undefined` when there is none
505
+ */
506
+ const readMany = (data: FormData | URLSearchParams, name: string) => {
507
+ const value = data.getAll(name);
508
+
509
+ return value.length ? value : undefined;
510
+ };
511
+
512
+ /**
513
+ * Represents a form field with parsing logic and rendering metadata.
514
+ *
515
+ * @template Output Output type of the field
516
+ * @template Tag Tag name
517
+ * @template Type Input type
518
+ * @template Values Persisted field value type
519
+ * @template Stream If the field should be streamed as a part
520
+ */
521
+ class FieldSchema<
522
+ Output = unknown,
523
+ Tag extends Field.Tag = "input",
524
+ Type extends Field.Type = Field.Type,
525
+ Values extends Field.Options | undefined = undefined,
526
+ Stream extends boolean | undefined = undefined,
527
+ > extends Schema<Output> {
528
+ /** Read the value from form data */
529
+ readonly #read: Field.Read;
530
+
531
+ /** Field type */
532
+ readonly type: Type;
533
+
534
+ // tag and options are public so emitted .d.ts preserves
535
+ // field discriminants for correct types
536
+ /** Field tag */
537
+ readonly tag: Tag;
538
+
539
+ /** Choices of a select, radio, or checkbox group */
540
+ readonly options: Values;
541
+
542
+ /** Maximum expected multipart part count for this field name. */
543
+ readonly parts: number;
544
+
545
+ /** If the field should be streamed as a part */
546
+ readonly streaming: Stream | undefined;
547
+
548
+ /** If the field should persist invalid-state values. */
549
+ readonly #persist: boolean;
550
+
551
+ /** Field options */
552
+ readonly #config: Field.Config<Values, Tag>;
553
+
554
+ /** If the control can't be left empty, found on first render */
555
+ #requires?: boolean;
556
+
557
+ /**
558
+ * Create a new field.
559
+ *
560
+ * @param options Field options
561
+ * @param schema How to validate the input
562
+ * @param read How to read the form data
563
+ * @param parts Maximum expected multipart parts for this field
564
+ * @param stream If this field should be streamed as a multipart part
565
+ * @param persist If this field should persist invalid state values
566
+ */
567
+ constructor(
568
+ config: Field.Config<Values, Tag>,
569
+ schema: Schema<Output> | Schema.Def,
570
+ // default to a single value, treating blank as missing
571
+ read: Field.Read = (data, name) => data.get(name) || undefined,
572
+ parts = 1,
573
+ stream?: Stream,
574
+ persist = false,
575
+ ) {
576
+ super(schema instanceof Schema ? schema.def : schema);
577
+
578
+ this.#config = config;
579
+ this.tag = (config.tag ?? "input") as Tag;
580
+ this.options = config.options as Values;
581
+ this.#read = read;
582
+ this.type = config.props?.type as Type;
583
+ this.parts = parts;
584
+ this.streaming = stream;
585
+ this.#persist = persist;
586
+ }
587
+
588
+ /**
589
+ * @returns `true` when the control can't be left empty
590
+ */
591
+ #required() {
592
+ return (this.#requires ??=
593
+ // a lone checkbox reads as false, and `required` on each box of a
594
+ // group would make every box required
595
+ this.type !== "checkbox" &&
596
+ this.type !== "hidden" &&
597
+ Boolean(this.parse(this.#read(new URLSearchParams(), "")).issues));
598
+ }
599
+
600
+ /** How each picker writes its value */
601
+ static readonly #formats: Record<string, string | undefined> = {
602
+ date: "Date as YYYY-MM-DD",
603
+ "datetime-local": "Date and time as YYYY-MM-DDTHH:mm",
604
+ month: "Month as YYYY-MM",
605
+ week: "Week as YYYY-Www, such as 2026-W46",
606
+ time: "Time as HH:mm",
607
+ color: "Color as #rrggbb",
608
+ };
609
+
610
+ /**
611
+ * @internal The label people read, which names a terse field such as
612
+ * `dob`, and an unchecked box's default
613
+ * @param io Side of the description
614
+ * @returns Keywords added to the property's JSON Schema
615
+ */
616
+ override [annotate](io: "input" | "output") {
617
+ const { label } = this.#config;
618
+ const { description } = this;
619
+ // what a browser's picker sends, which a string alone does not say
620
+ const format = FieldSchema.#formats[this.type as string];
621
+ const described = [description?.replace(/\.$/, ""), format]
622
+ .filter(Boolean)
623
+ .join(". ");
624
+
625
+ return {
626
+ ...(label && { title: label }),
627
+ ...(described && { description: described }),
628
+ ...(this.type === "date" && { format: "date" }),
629
+ // a browser leaves an unchecked box out and it reads as false, so
630
+ // input, such as an agent's, may leave it out too
631
+ ...(io === "input" &&
632
+ this.type === "checkbox" &&
633
+ !this.options && { default: false }),
634
+ };
635
+ }
636
+
637
+ /**
638
+ * @param field Field instance
639
+ * @param data Form data source
640
+ * @param name HTML name attribute
641
+ * @returns Raw field input
642
+ */
643
+ static read(
644
+ field: Field.Any,
645
+ data: FormData | URLSearchParams,
646
+ name: string,
647
+ ) {
648
+ return field.#read(data, name);
649
+ }
650
+
651
+ /**
652
+ * Stream this field as a multipart request `Part`.
653
+ *
654
+ * @returns Part field
655
+ */
656
+ stream(): Field.Instance<Output, Tag, Type, Values, true> {
657
+ return this.#copy({ stream: true });
658
+ }
659
+
660
+ /**
661
+ * Name the field. People read it as the control's label, or a group's
662
+ * legend, and agents as the field's `title`. Without one it is the field's
663
+ * name.
664
+ *
665
+ * ```ts
666
+ * Field.email().label("Email address");
667
+ * ```
668
+ *
669
+ * @param text Label
670
+ * @returns Field with the label
671
+ */
672
+ label(text: string): Field.Instance<Output, Tag, Type, Values, Stream> {
673
+ return this.#with({ label: text });
674
+ }
675
+
676
+ /**
677
+ * Attributes for the field's control wherever it renders, such as a
678
+ * placeholder. Those for one form are passed when it renders.
679
+ *
680
+ * ```ts
681
+ * Field.email().control({ placeholder: "name@example.com" });
682
+ * ```
683
+ *
684
+ * @param attributes Attributes of the control's element
685
+ * @returns Field with the attributes
686
+ */
687
+ control(
688
+ attributes: Tag extends "select"
689
+ ? Field.Props.Select
690
+ : Tag extends "textarea"
691
+ ? Field.Props.Textarea
692
+ : // the field is its type
693
+ Field.Props.Input & { readonly type?: never },
694
+ ): Field.Instance<Output, Tag, Type, Values, Stream> {
695
+ return this.#with({
696
+ props: { ...this.#config.props, ...attributes } as Field.Props,
697
+ });
698
+ }
699
+
700
+ /**
701
+ * @param changes What to change
702
+ * @returns The same field with them
703
+ */
704
+ #with(changes: Pick<Field.Config, "label" | "props">) {
705
+ return this.#copy({ config: { ...this.#config, ...changes } });
706
+ }
707
+
708
+ /**
709
+ * @template O Output type of the copy
710
+ * @template S If the copy streams as a part
711
+ * @param changes What the copy changes, the rest is this field's
712
+ * @returns A copy of this field
713
+ */
714
+ #copy<O = Output, S extends boolean | undefined = Stream>({
715
+ config = this.#config,
716
+ def = this.def,
717
+ stream = this.streaming as S,
718
+ persist = this.#persist,
719
+ }: {
720
+ config?: Field.Config<Values, Tag>;
721
+ def?: Schema.Def;
722
+ stream?: S;
723
+ persist?: boolean;
724
+ }) {
725
+ return new FieldSchema<O, Tag, Type, Values, S>(
726
+ config,
727
+ def,
728
+ this.#read,
729
+ this.parts,
730
+ stream,
731
+ persist,
732
+ );
733
+ }
734
+
735
+ /**
736
+ * Take more than one value: files, or options of a select. The value is
737
+ * an array, required to have one unless the field is made optional after.
738
+ *
739
+ * ```ts
740
+ * Field.file().multiple();
741
+ * Field.select(["red", "green", "blue"]).multiple();
742
+ * ```
743
+ *
744
+ * @returns Field whose value is an array
745
+ */
746
+ multiple(
747
+ this: Field.Instance<File, "input", "file", Values, Stream>,
748
+ ): Field.Instance<File[], "input", "file", Values, Stream>;
749
+ multiple<V extends string>(
750
+ this: Field.Instance<V, "select", Type, readonly [V, ...V[]], Stream>,
751
+ ): Field.Instance<V[], "select", Type, readonly [V, ...V[]], Stream>;
752
+ // the overloads above are its types
753
+ multiple(): any {
754
+ const file = this.type === "file";
755
+ const { description, ...def } = this.def;
756
+ // each value is checked as this field checks one, and a description
757
+ // given before describes the field, not each value
758
+ const array = Schema.array(
759
+ (description === undefined
760
+ ? this
761
+ : this.#copy({ def })) as Schema<unknown>,
762
+ file ? required : choose,
763
+ );
764
+
765
+ return new FieldSchema(
766
+ { ...this.#config, props: { ...this.#config.props, multiple: true } },
767
+ description === undefined ? array : { ...array.def, description },
768
+ file
769
+ ? (data, name) => {
770
+ const files = data.getAll(name).filter(chosenFile);
771
+ return files.length ? files : undefined;
772
+ }
773
+ : readMany,
774
+ file ? Infinity : this.options!.length,
775
+ this.streaming,
776
+ this.#persist,
777
+ );
778
+ }
779
+
780
+ /**
781
+ * Persist this field in the encoded invalid form state.
782
+ *
783
+ * Use this for non-sensitive values that should refill after an invalid
784
+ * redirect.
785
+ *
786
+ * @template U Input type, one that can persist: not a password or file
787
+ * @returns Field that persists submitted values across invalid redirects
788
+ */
789
+ persist<
790
+ U extends (Tag extends "input" ? Exclude<Type, "password" | "file"> : Type),
791
+ >(
792
+ this: Field.Instance<Output, Tag, U, Values, Stream>,
793
+ ): Field.Instance<Output, Tag, U, Values, Stream>;
794
+ persist() {
795
+ return this.#copy({ persist: true });
796
+ }
797
+
798
+ /**
799
+ * Derive a new Field from the current instance type.
800
+ *
801
+ * @template O Output type of the new Field
802
+ * @param def Definition of the new Field
803
+ * @returns New `Field` instance
804
+ */
805
+ protected override derive<O>(
806
+ def: Schema.Def,
807
+ ): Field.Instance<O, Tag, Type, Values, Stream> {
808
+ return this.#copy<O>({ def });
809
+ }
810
+
811
+ /**
812
+ * @template S Form shape type
813
+ * @param props Field control props
814
+ * @returns Field component with sub-components
815
+ */
816
+ [component]<S extends Field.Shape>(
817
+ props: Field.Component.Props<S, false>,
818
+ ): Field.Component<this>;
819
+ [component]<S extends Field.Shape>({
820
+ state,
821
+ ...props
822
+ }: Field.Component.Props<S, false>): unknown {
823
+ const value = state?.values?.[props.name];
824
+ const issue = state?.issues?.find((i) => i.path[0] === props.name);
825
+ const issueId = issue && `${props.name}-issue`;
826
+ const hidden = this.type === "hidden";
827
+ const { label = props.name } = this.#config;
828
+ const { description } = this;
829
+ const descriptionId =
830
+ description && !hidden ? `${props.name}-description` : undefined;
831
+ const control = {
832
+ id: hidden ? undefined : props.name,
833
+ required: this.#required(),
834
+ autofocus: issue && state?.issues?.[0] === issue,
835
+ "aria-invalid": issue && "true",
836
+ // read with the control: its description, then what is wrong with it
837
+ "aria-describedby":
838
+ [descriptionId, issueId].filter(Boolean).join(" ") || undefined,
839
+ ...this.#config.props,
840
+ ...props,
841
+ };
842
+
843
+ /**
844
+ * @param option Option value
845
+ * @returns `true` when the value has the option
846
+ */
847
+ const chosen = (option: string) =>
848
+ Array.isArray(value)
849
+ ? value.includes(option) // checkboxes and multiselect
850
+ : value === option; // radio and select
851
+
852
+ const Description = (data: Field.Component.Description = {}) =>
853
+ descriptionId && // render nothing without a description
854
+ jsx("p", {
855
+ id: descriptionId,
856
+ children: description,
857
+ "data-description": true,
858
+ ...data,
859
+ });
860
+
861
+ const Issue = (data: Field.Component.Issue = {}) =>
862
+ issue && // render nothing if no issue
863
+ !hidden &&
864
+ jsx("p", {
865
+ id: issueId,
866
+ children: issue.message,
867
+ "data-issue": issue && state!.issues!.indexOf(issue), // issue index starting from 0
868
+ ...data,
869
+ });
870
+
871
+ if (this.options && this.tag !== "select") {
872
+ // radio/checkboxes
873
+ // make multiple ids for the group so all don't have the same id
874
+ const groupId = (value: string) =>
875
+ `${control.name}-${value}`.toLowerCase();
876
+
877
+ const Control = (
878
+ data: Field.Component.Control.Group<"input", Field.Options>,
879
+ ) =>
880
+ jsx(this.tag, {
881
+ ...control,
882
+ id: groupId(data.value),
883
+ // autofocus only the first input in the group
884
+ autofocus: control.autofocus && data.value === this.options?.[0],
885
+ checked: chosen(data.value),
886
+ ...data,
887
+ });
888
+
889
+ const Label = ({
890
+ value,
891
+ ...rest
892
+ }: Field.Component.Label.Group<Field.Options>) =>
893
+ jsx("label", { for: groupId(value), children: value, ...rest });
894
+
895
+ return {
896
+ Description,
897
+ Issue,
898
+ Label,
899
+ Control,
900
+ Root: (data: Field.Component.Root = {}) => jsx("fieldset", data),
901
+ Option: ({
902
+ value,
903
+ ...rest
904
+ }: Field.Component.Option.Input<Field.Options>) =>
905
+ jsx("div", {
906
+ children: [Control({ value }), Label({ value })],
907
+ ...rest,
908
+ }),
909
+ Legend: (data: Field.Component.Legend = {}) =>
910
+ jsx("legend", { children: label, ...data }),
911
+ ...this,
912
+ };
913
+ }
914
+
915
+ return {
916
+ Description,
917
+ Issue,
918
+ Root: (data: Field.Component.Root = {}) =>
919
+ hidden ? Fragment(data) : jsx("div", data),
920
+ Label: (data: Field.Component.Label = {}) =>
921
+ !hidden && jsx("label", { for: control.id, children: label, ...data }),
922
+ Control: (data?: Field.Component.Control<Tag>) => {
923
+ const attrs = { ...control, ...data };
924
+
925
+ if (value !== undefined) {
926
+ if (this.tag === "textarea") {
927
+ attrs.children = value;
928
+ } else if (this.tag === "input") {
929
+ if (this.type === "checkbox") {
930
+ attrs.checked = value;
931
+ } else {
932
+ attrs.value = value;
933
+ }
934
+ }
935
+ }
936
+
937
+ return jsx(this.tag, attrs);
938
+ },
939
+ Option:
940
+ // select
941
+ this.options &&
942
+ ((data: Field.Component.Option<Field.Options>) =>
943
+ jsx("option", {
944
+ children: data.value,
945
+ selected: chosen(data.value),
946
+ ...data,
947
+ })),
948
+ ...this,
949
+ };
950
+ }
951
+
952
+ /**
953
+ * @template S Form shape type
954
+ * @param props Field control props including `name` of the field to render
955
+ * @returns Component that renders the HTML field with default structure
956
+ */
957
+ [render]<S extends Field.Shape>(props: Field.Component.Props<S, false>) {
958
+ // the sub-components of each kind of field, told apart by `options` and `tag` below
959
+ const c = this[component](
960
+ props,
961
+ ) as unknown as Field.Component<Field.Any> & {
962
+ Legend: (props?: Field.Component.Legend) => JSX.Element;
963
+ Option: (props: Field.Component.Option<Field.Options>) => JSX.Element;
964
+ };
965
+ const { options } = this;
966
+
967
+ return c.Root({
968
+ children: [
969
+ options && this.tag !== "select"
970
+ ? // radio/checkboxes, a group with a legend, each value labelled
971
+ [
972
+ c.Legend(),
973
+ options.map((value) =>
974
+ jsx("div", {
975
+ children: [c.Control({ value }), c.Label({ value })],
976
+ }),
977
+ ),
978
+ ]
979
+ : [
980
+ c.Label(),
981
+ // a select has an option for each value
982
+ c.Control(
983
+ options && {
984
+ children: options.map((value) => c.Option({ value })),
985
+ },
986
+ ),
987
+ ],
988
+ c.Description(),
989
+ c.Issue(),
990
+ ],
991
+ });
992
+ }
993
+
994
+ /**
995
+ * @param field Field definition
996
+ * @returns `true` when the field persists invalid-state values
997
+ */
998
+ static persisted(field: Field.Any) {
999
+ return field.#persist;
1000
+ }
1001
+ }
1002
+
1003
+ /**
1004
+ * @param value Schema
1005
+ * @returns `true` for a form field, such as a table column made with `Field`
1006
+ */
1007
+ export const field = (value: unknown): value is Field.Any =>
1008
+ value instanceof FieldSchema;
1009
+
1010
+ export namespace Field {
1011
+ /** Fields by name, as a route's `fields` takes them. */
1012
+ export type Shape = Record<string, Field.Any>;
1013
+
1014
+ /** Persisted form value */
1015
+ export type Value = string | number | boolean | string[];
1016
+
1017
+ export namespace Value {
1018
+ /**
1019
+ * Value map by field name.
1020
+ *
1021
+ * @template S Shape type
1022
+ */
1023
+ export type Map<S extends Shape = Shape> = Partial<
1024
+ Record<ShapeUtil.Name<S>, Value>
1025
+ >;
1026
+
1027
+ /**
1028
+ * Initial values by field name, for example a record being edited.
1029
+ * Values a field cannot render, such as dates and `null`, are skipped.
1030
+ *
1031
+ * @template S Shape type
1032
+ */
1033
+ export type Initial<S extends Shape = Shape> = {
1034
+ readonly [K in ShapeUtil.Name<S>]?: unknown;
1035
+ };
1036
+ }
1037
+
1038
+ /**
1039
+ * Encoded form state.
1040
+ *
1041
+ * @template S Shape type to infer value keys from
1042
+ */
1043
+ export interface State<S extends Shape = Shape> {
1044
+ /** Form id generated using the field names */
1045
+ readonly id: string;
1046
+
1047
+ /** Non-empty list of validation issues */
1048
+ readonly issues?: Schema.Issue.List;
1049
+
1050
+ /** Map of field names to possible values */
1051
+ readonly values?: Value.Map<S>;
1052
+ }
1053
+
1054
+ export namespace Parse {
1055
+ /**
1056
+ * Field names that are not marked to stream as multipart parts.
1057
+ *
1058
+ * @template S Form shape
1059
+ */
1060
+ type NonStreamNames<S extends Shape> = {
1061
+ [K in keyof S]-?: S[K] extends Field.Instance<any, any, any, any, infer P>
1062
+ ? P extends true
1063
+ ? never
1064
+ : K
1065
+ : never;
1066
+ }[keyof S];
1067
+
1068
+ /**
1069
+ * Parsed data shape with streamed `stream()` fields removed.
1070
+ *
1071
+ * @template S Form shape
1072
+ */
1073
+ type NonStreamShape<S extends Shape> = Pick<S, NonStreamNames<S>>;
1074
+
1075
+ /**
1076
+ * Parsed form data output.
1077
+ *
1078
+ * @template S Form shape
1079
+ */
1080
+ export type Data<S extends Shape> = Schema.Infer<NonStreamShape<S>>;
1081
+
1082
+ /**
1083
+ * Form parse result.
1084
+ *
1085
+ * @template S Form shape
1086
+ * @template M Extra invalid result metadata
1087
+ */
1088
+ export type Result<
1089
+ S extends Shape,
1090
+ M extends object = {},
1091
+ > = Schema.Parse.Result<
1092
+ Data<S>,
1093
+ Result.Invalid<M>,
1094
+ {
1095
+ /** Rest of the multipart parts to stream */
1096
+ readonly stream?: AsyncGenerator<Multipart.Part> | undefined;
1097
+
1098
+ /**
1099
+ * Create an invalid result for issues found after parsing, for
1100
+ * example a database constraint, keeping persisted values.
1101
+ *
1102
+ * @param messages Issue message by field name
1103
+ */
1104
+ readonly invalid: (
1105
+ messages: Messages<S>,
1106
+ ) => Schema.Parse.Invalid & Result.Invalid<M>;
1107
+ }
1108
+ >;
1109
+
1110
+ /**
1111
+ * Issue messages by field name.
1112
+ *
1113
+ * @template S Form shape
1114
+ */
1115
+ export type Messages<S extends Shape> = {
1116
+ readonly [K in ShapeUtil.Name<S>]?: string;
1117
+ };
1118
+
1119
+ export namespace Result {
1120
+ /** Form search params iterable */
1121
+ export type Search = [["_form", string]] | undefined;
1122
+
1123
+ /**
1124
+ * Invalid result metadata.
1125
+ *
1126
+ * @template M Extra invalid result metadata
1127
+ */
1128
+ export type Invalid<M extends object = {}> = {
1129
+ /** Encoded URL search param field state */
1130
+ readonly search: Search;
1131
+
1132
+ /** Invalid parses do not expose remaining multipart parts */
1133
+ readonly stream?: never;
1134
+ } & M;
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * Base options to create a Field.
1140
+ *
1141
+ * @template V Choices of a select, radio, or checkbox group
1142
+ * @template T Tag name
1143
+ */
1144
+ export interface Config<
1145
+ V extends Options | undefined = undefined,
1146
+ T extends Tag = Tag,
1147
+ > {
1148
+ /**
1149
+ * Tag name.
1150
+ *
1151
+ * @default "input"
1152
+ */
1153
+ readonly tag?: T;
1154
+
1155
+ /** Choices of a select, radio, or checkbox group */
1156
+ readonly options?: V;
1157
+
1158
+ /** What people call the field, set with `label()` */
1159
+ readonly label?: string;
1160
+
1161
+ /** Field props */
1162
+ readonly props?: Props | undefined;
1163
+ }
1164
+
1165
+ /**
1166
+ * Raw field value before schema parsing.
1167
+ *
1168
+ * Single-value fields read one entry, multi-value fields read all entries,
1169
+ * and checkboxes read presence.
1170
+ */
1171
+ export type Input =
1172
+ FormDataEntryValue | FormDataEntryValue[] | boolean | undefined;
1173
+
1174
+ /**
1175
+ * @param data FormData or URLSearchParams
1176
+ * @param name HTML name attribute
1177
+ * @returns Resolved value read from the form data
1178
+ */
1179
+ export type Read = (data: FormData | URLSearchParams, name: string) => Input;
1180
+
1181
+ /** Form field tag name */
1182
+ export type Tag = "input" | "textarea" | "select";
1183
+
1184
+ /** `<input type=...>` */
1185
+ export type Type = JSX.IntrinsicElements["input"]["type"];
1186
+
1187
+ /** Value type for select and radio options */
1188
+ export type Options = readonly [string, ...string[]];
1189
+
1190
+ /**
1191
+ * Field instance type
1192
+ *
1193
+ * @template Output Parsed value
1194
+ * @template Tag Element tag
1195
+ * @template Type Input type
1196
+ * @template Values Options of a select, radio, or checkbox group
1197
+ * @template Stream Whether the field streams as a multipart part
1198
+ */
1199
+ export type Instance<
1200
+ Output = unknown,
1201
+ Tag extends Field.Tag = "input",
1202
+ Type extends Field.Type = Field.Type,
1203
+ Values extends Field.Options | undefined = undefined,
1204
+ Stream extends boolean | undefined = undefined,
1205
+ > = FieldSchema<Output, Tag, Type, Values, Stream>;
1206
+
1207
+ /** Any field - `<input type=...>` / `<select>` / `<textarea>` */
1208
+ export type Any = Instance<
1209
+ any,
1210
+ Tag,
1211
+ Type,
1212
+ Options | undefined,
1213
+ boolean | undefined
1214
+ >;
1215
+
1216
+ /**
1217
+ * Obtain the tag name of a field.
1218
+ *
1219
+ * @template F Field
1220
+ */
1221
+ export type TagOf<F extends Any> =
1222
+ F extends Instance<any, infer T, Field.Type, Field.Options | undefined>
1223
+ ? T
1224
+ : Tag;
1225
+
1226
+ export namespace Component {
1227
+ /**
1228
+ * Component props available to users to pass into the
1229
+ * constructed `<Field />` component.
1230
+ *
1231
+ * @template S Form shape type
1232
+ * @template I `true` the state is a `URL`, `false` is just `State`
1233
+ */
1234
+ export type Props<S extends Field.Shape, I extends boolean = true> = {
1235
+ /** Field name attribute */
1236
+ readonly name: ShapeUtil.Name<S>;
1237
+
1238
+ /** Form state */
1239
+ readonly state?: (I extends true ? URL : Field.State<S>) | undefined;
1240
+ } & Field.Props;
1241
+
1242
+ /** Root element for the Field component */
1243
+ export type Root = JSX.IntrinsicElements["div"];
1244
+
1245
+ export namespace Root {
1246
+ /** Root for input groups */
1247
+ export type Group = JSX.IntrinsicElements["fieldset"];
1248
+ }
1249
+
1250
+ /** `<Field.Legend />` component props */
1251
+ export type Legend = JSX.IntrinsicElements["legend"];
1252
+
1253
+ /** `<Field.Description />` component props */
1254
+ export type Description = JSX.IntrinsicElements["p"];
1255
+
1256
+ /** `<Field.Issue />` component props */
1257
+ export type Issue = JSX.IntrinsicElements["p"];
1258
+
1259
+ /**
1260
+ * `<Field.Control />` component props
1261
+ *
1262
+ * @template T Tag name
1263
+ */
1264
+ export type Control<T extends Tag> = T extends "textarea"
1265
+ ? JSX.IntrinsicElements["textarea"]
1266
+ : T extends "select"
1267
+ ? JSX.IntrinsicElements["select"]
1268
+ : JSX.IntrinsicElements["input"];
1269
+
1270
+ export namespace Control {
1271
+ /**
1272
+ * `<Field.Control />` component props for group input element.
1273
+ *
1274
+ * @template T Tag name
1275
+ * @template V Option values
1276
+ */
1277
+ export type Group<T extends Tag, V extends Options> = Control<T> & {
1278
+ readonly value: V[number];
1279
+ };
1280
+ }
1281
+
1282
+ /** `<Field.Label />` component props */
1283
+ export type Label = JSX.IntrinsicElements["label"];
1284
+
1285
+ export namespace Label {
1286
+ /**
1287
+ * `<Field.Label />` component props for group input element.
1288
+ *
1289
+ * @template V Option values
1290
+ */
1291
+ export type Group<V extends Options> = Label & {
1292
+ readonly value: V[number];
1293
+ };
1294
+ }
1295
+
1296
+ /**
1297
+ * `<Field.Option />` select component props
1298
+ *
1299
+ * @template V Options
1300
+ */
1301
+ export type Option<V extends Options> = JSX.IntrinsicElements["option"] & {
1302
+ /** Option value */
1303
+ readonly value: V[number];
1304
+ };
1305
+
1306
+ export namespace Option {
1307
+ /**
1308
+ * `<Field.Option />` input group component props
1309
+ *
1310
+ * Wrapper for both the `<Label />` and `<Input />` components.
1311
+ *
1312
+ * @template V Options
1313
+ */
1314
+ export type Input<V extends Options> = JSX.IntrinsicElements["div"] & {
1315
+ /** Option value */
1316
+ readonly value: V[number];
1317
+ };
1318
+ }
1319
+ }
1320
+
1321
+ /**
1322
+ * Base Field component object that contains sub-components,
1323
+ * use for fine grained rendering control.
1324
+ *
1325
+ * @template F Field
1326
+ */
1327
+ export type Component<F extends Any> = Readonly<
1328
+ {
1329
+ /**
1330
+ * @param props Description props
1331
+ * @returns Description paragraph, nothing when the field has no description
1332
+ */
1333
+ Description: (props?: Component.Description) => JSX.Element;
1334
+
1335
+ /**
1336
+ * @param props Issue props
1337
+ * @returns Issue container paragraph
1338
+ */
1339
+ Issue: (props?: Component.Issue) => JSX.Element;
1340
+ } & (F extends Instance<any, "select", Field.Type, infer V>
1341
+ ? V extends Options
1342
+ ? // select
1343
+ {
1344
+ /** The select's options */
1345
+ options: V;
1346
+
1347
+ /**
1348
+ * @param props Root props
1349
+ * @returns Root container div
1350
+ */
1351
+ Root: (props?: Component.Root) => JSX.Element;
1352
+
1353
+ /**
1354
+ * @param props Label props
1355
+ * @returns Label element
1356
+ */
1357
+ Label: (props?: Component.Label) => JSX.Element;
1358
+
1359
+ /**
1360
+ * @param props Control props
1361
+ * @returns Control select element
1362
+ */
1363
+ Control: (props?: Component.Control<"select">) => JSX.Element;
1364
+
1365
+ /**
1366
+ * @param props Option props
1367
+ * @returns Select option element
1368
+ */
1369
+ Option: (props: Component.Option<V>) => JSX.Element;
1370
+ }
1371
+ : never
1372
+ : F extends Instance<any, "input", Field.Type, infer V>
1373
+ ? V extends Options
1374
+ ? // radio/checkboxes
1375
+ {
1376
+ /** The group's options */
1377
+ options: V;
1378
+
1379
+ /**
1380
+ * @param props Root props
1381
+ * @returns Root container fieldset
1382
+ */
1383
+ Root: (props?: Component.Root.Group) => JSX.Element;
1384
+
1385
+ /**
1386
+ * @param props Legend element props
1387
+ * @returns Legend element
1388
+ */
1389
+ Legend: (props?: Component.Legend) => JSX.Element;
1390
+
1391
+ /**
1392
+ * @param props Label props including `value`
1393
+ * @returns Label element
1394
+ */
1395
+ Label: (props: Component.Label.Group<V>) => JSX.Element;
1396
+
1397
+ /**
1398
+ * @param props Control props
1399
+ * @returns Control input element
1400
+ */
1401
+ Control: (
1402
+ props?: Component.Control.Group<"input", V>,
1403
+ ) => JSX.Element;
1404
+
1405
+ /**
1406
+ * @param props Option props
1407
+ * @returns Both label and input elements together
1408
+ */
1409
+ Option: (props: Component.Option.Input<V>) => JSX.Element;
1410
+ }
1411
+ : // regular input
1412
+ {
1413
+ /**
1414
+ * @param props Root props
1415
+ * @returns Root container div
1416
+ */
1417
+ Root: (props?: Component.Root) => JSX.Element;
1418
+
1419
+ /**
1420
+ * @param props Label props
1421
+ * @returns Label element
1422
+ */
1423
+ Label: (props?: Component.Label) => JSX.Element;
1424
+
1425
+ /**
1426
+ * @param props Control props
1427
+ * @returns Control input element
1428
+ */
1429
+ Control: (props?: Component.Control<"input">) => JSX.Element;
1430
+ }
1431
+ : // textarea
1432
+ {
1433
+ /**
1434
+ * @param props Root props
1435
+ * @returns Root container div
1436
+ */
1437
+ Root: (props?: Component.Root) => JSX.Element;
1438
+
1439
+ /**
1440
+ * @param props Label props
1441
+ * @returns Label element
1442
+ */
1443
+ Label: (props?: Component.Label) => JSX.Element;
1444
+
1445
+ /**
1446
+ * @param props Control props
1447
+ * @returns Control textarea element
1448
+ */
1449
+ Control: (props?: Component.Control<"textarea">) => JSX.Element;
1450
+ })
1451
+ >;
1452
+
1453
+ /** Any field props */
1454
+ export type Props = Props.Input | Props.Select | Props.Textarea;
1455
+
1456
+ export namespace Props {
1457
+ /**
1458
+ * A field's label and description are what it means, for people and
1459
+ * agents, and not attributes of its control: set them with `label()` and
1460
+ * `describe()`, and the control's attributes with `control()`.
1461
+ */
1462
+ interface Chained {
1463
+ /** Use `field.label(text)` */
1464
+ readonly label?: never;
1465
+
1466
+ /** Use `field.describe(text)` */
1467
+ readonly description?: never;
1468
+ }
1469
+
1470
+ /** Attributes of an `<input>` field's control */
1471
+ export type Input = JSX.IntrinsicElements["input"] & Chained;
1472
+
1473
+ /** Attributes of a `<select>` field's control */
1474
+ export type Select = JSX.IntrinsicElements["select"] & Chained;
1475
+
1476
+ /** Attributes of a `<textarea>` field's control */
1477
+ export type Textarea = JSX.IntrinsicElements["textarea"] & Chained;
1478
+ }
1479
+ }
1480
+
1481
+ /** Field factory functions */
1482
+ export class Field {
1483
+ // this is used instead of the defaults for example "Expected string"
1484
+ // since "string" doesn't make sense to end users
1485
+
1486
+ /**
1487
+ * @template T Input type
1488
+ * @param props Input props
1489
+ * @returns Generic input field
1490
+ */
1491
+ static #input<T extends Field.Type>(
1492
+ props: Field.Props.Input & { type: T },
1493
+ ): Field.Instance<string, "input", T> {
1494
+ return new FieldSchema({ props }, Schema.string(required));
1495
+ }
1496
+
1497
+ /**
1498
+ * @returns Text input field
1499
+ */
1500
+ static text(): Field.Instance<string, "input", "text"> {
1501
+ return Field.#input({ type: "text" });
1502
+ }
1503
+
1504
+ /**
1505
+ * @returns Password input field
1506
+ */
1507
+ static password(): Field.Instance<string, "input", "password"> {
1508
+ return Field.#input({ type: "password" });
1509
+ }
1510
+
1511
+ /**
1512
+ * @returns Search input field
1513
+ */
1514
+ static search(): Field.Instance<string, "input", "search"> {
1515
+ return Field.#input({ type: "search" });
1516
+ }
1517
+
1518
+ /**
1519
+ * @returns Telephone input field
1520
+ */
1521
+ static tel(): Field.Instance<string, "input", "tel"> {
1522
+ return Field.#input({ type: "tel" });
1523
+ }
1524
+
1525
+ /**
1526
+ * @returns Color input field
1527
+ */
1528
+ static color(): Field.Instance<string, "input", "color"> {
1529
+ return Field.#input({ type: "color" });
1530
+ }
1531
+
1532
+ /**
1533
+ * @returns Hidden input field
1534
+ */
1535
+ static hidden(): Field.Instance<string, "input", "hidden"> {
1536
+ return Field.#input({ type: "hidden" });
1537
+ }
1538
+
1539
+ /**
1540
+ * @returns Date input field
1541
+ */
1542
+ static date(): Field.Instance<string, "input", "date"> {
1543
+ return Field.#input({ type: "date" });
1544
+ }
1545
+
1546
+ /**
1547
+ * @returns Datetime input field
1548
+ */
1549
+ static datetime(): Field.Instance<string, "input", "datetime-local"> {
1550
+ return Field.#input({ type: "datetime-local" });
1551
+ }
1552
+
1553
+ /**
1554
+ * @returns Month input field
1555
+ */
1556
+ static month(): Field.Instance<string, "input", "month"> {
1557
+ return Field.#input({ type: "month" });
1558
+ }
1559
+
1560
+ /**
1561
+ * @returns Week input field
1562
+ */
1563
+ static week(): Field.Instance<string, "input", "week"> {
1564
+ return Field.#input({ type: "week" });
1565
+ }
1566
+
1567
+ /**
1568
+ * @returns Time input field
1569
+ */
1570
+ static time(): Field.Instance<string, "input", "time"> {
1571
+ return Field.#input({ type: "time" });
1572
+ }
1573
+
1574
+ /**
1575
+ * Validates email string.
1576
+ *
1577
+ * @param message Issue message when invalid
1578
+ * @returns Email input field
1579
+ */
1580
+ static email(message?: string): Field.Instance<string, "input", "email"> {
1581
+ return Field.#input({ type: "email" }).email(message);
1582
+ }
1583
+
1584
+ /**
1585
+ * Validates parsable URL.
1586
+ *
1587
+ * @param message Issue message when invalid
1588
+ * @returns URL input field
1589
+ */
1590
+ static url(message?: string): Field.Instance<string, "input", "url"> {
1591
+ return Field.#input({ type: "url" }).url(message);
1592
+ }
1593
+
1594
+ /**
1595
+ * @template T Input type, `number` or `range`
1596
+ * @param props Input props
1597
+ * @returns Input field
1598
+ */
1599
+ static #number<T extends "number" | "range">(
1600
+ props: Field.Props.Input & { type: T },
1601
+ ): Field.Instance<number, "input", T> {
1602
+ // registered here rather than as the class loads, which is a side effect
1603
+ // that would keep `Field` in bundles that only use `Form`
1604
+ normalizers.add(Field.#toNumber);
1605
+
1606
+ return new FieldSchema(
1607
+ { props },
1608
+ Schema.number(required).preprocess(Field.#toNumber),
1609
+ );
1610
+ }
1611
+
1612
+ /**
1613
+ * @param value Form entry or stored number
1614
+ * @returns The number to validate
1615
+ */
1616
+ static #toNumber(value: unknown) {
1617
+ // form submissions read numeric controls as strings
1618
+ if (value == null || value === "") return undefined;
1619
+
1620
+ return exact(value);
1621
+ }
1622
+
1623
+ /**
1624
+ * Coerces to number.
1625
+ *
1626
+ * @returns Number input field
1627
+ */
1628
+ static number(): Field.Instance<number, "input", "number"> {
1629
+ return Field.#number({ type: "number" });
1630
+ }
1631
+
1632
+ /**
1633
+ * Coerces to number.
1634
+ *
1635
+ * @returns Range input field
1636
+ */
1637
+ static range(): Field.Instance<number, "input", "range"> {
1638
+ return Field.#number({ type: "range" });
1639
+ }
1640
+
1641
+ /**
1642
+ * - unchecked => key missing => `false`
1643
+ * - checked => key present => `true`
1644
+ *
1645
+ * @returns Checkbox input field
1646
+ */
1647
+ static checkbox(): Field.Instance<boolean, "input", "checkbox"> {
1648
+ return new FieldSchema(
1649
+ { props: { type: "checkbox" } },
1650
+ Schema.boolean(),
1651
+ (formData, name) => formData.has(name),
1652
+ );
1653
+ }
1654
+
1655
+ /**
1656
+ * @returns File input field
1657
+ */
1658
+ static file(): Field.Instance<File, "input", "file"> {
1659
+ return new FieldSchema(
1660
+ { props: { type: "file" } },
1661
+ Schema.instance(File, required),
1662
+ (data, name) => {
1663
+ const value = data.get(name);
1664
+
1665
+ return (chosenFile(value) && value) || undefined;
1666
+ },
1667
+ );
1668
+ }
1669
+
1670
+ /**
1671
+ * @template V Value type
1672
+ * @param options Checkbox options
1673
+ * @returns Checkbox group input field
1674
+ */
1675
+ static checkboxes<const V extends string>(
1676
+ options: readonly [V, ...V[]],
1677
+ ): Field.Instance<V[], "input", "checkbox", readonly [V, ...V[]]> {
1678
+ return new FieldSchema(
1679
+ { options, props: { type: "checkbox" } },
1680
+ Schema.array(Schema.enum(options, choose), choose),
1681
+ readMany,
1682
+ options.length,
1683
+ );
1684
+ }
1685
+
1686
+ /**
1687
+ * @template V Value type
1688
+ * @param options Radio button options
1689
+ * @returns Radio group input field
1690
+ */
1691
+ static radio<const V extends string>(
1692
+ options: readonly [V, ...V[]],
1693
+ ): Field.Instance<V, "input", "radio", readonly [V, ...V[]]> {
1694
+ return new FieldSchema(
1695
+ { options, props: { type: "radio" } },
1696
+ Schema.enum(options, choose),
1697
+ );
1698
+ }
1699
+
1700
+ /**
1701
+ * @returns Textarea field
1702
+ */
1703
+ static textarea(): Field.Instance<string, "textarea"> {
1704
+ return new FieldSchema({ tag: "textarea" }, Schema.string(required));
1705
+ }
1706
+
1707
+ /**
1708
+ * @template V Value type
1709
+ * @param options Select options
1710
+ * @returns Select field
1711
+ */
1712
+ static select<const V extends string>(
1713
+ options: readonly [V, ...V[]],
1714
+ ): Field.Instance<V, "select", Field.Type, readonly [V, ...V[]]> {
1715
+ return new FieldSchema(
1716
+ { tag: "select", options },
1717
+ Schema.enum(options, choose),
1718
+ );
1719
+ }
1720
+ }