ovr 6.1.0 → 6.2.1

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 (43) hide show
  1. package/dist/LICENSE.md +2 -0
  2. package/dist/app/index.d.ts.map +1 -1
  3. package/dist/app/index.js +13 -9
  4. package/dist/context/index.d.ts +33 -9
  5. package/dist/context/index.d.ts.map +1 -1
  6. package/dist/context/index.js +61 -17
  7. package/dist/cookie/index.d.ts +1 -1
  8. package/dist/cookie/index.d.ts.map +1 -1
  9. package/dist/cookie/index.js +2 -2
  10. package/dist/index.d.ts +4 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -2
  13. package/dist/middleware/index.d.ts +12 -3
  14. package/dist/middleware/index.d.ts.map +1 -1
  15. package/dist/multipart/index.d.ts +5 -0
  16. package/dist/multipart/index.d.ts.map +1 -1
  17. package/dist/multipart/index.js +20 -22
  18. package/dist/render/index.d.ts +1 -0
  19. package/dist/render/index.d.ts.map +1 -1
  20. package/dist/render/index.js +6 -4
  21. package/dist/route/index.d.ts +143 -42
  22. package/dist/route/index.d.ts.map +1 -1
  23. package/dist/route/index.js +94 -42
  24. package/dist/schema/index.d.ts +1286 -0
  25. package/dist/schema/index.d.ts.map +1 -0
  26. package/dist/schema/index.js +1321 -0
  27. package/dist/trie/index.d.ts.map +1 -1
  28. package/dist/trie/index.js +8 -2
  29. package/dist/util/index.d.ts +113 -19
  30. package/dist/util/index.d.ts.map +1 -1
  31. package/dist/util/index.js +111 -35
  32. package/package.json +4 -1
  33. package/src/app/index.ts +13 -12
  34. package/src/context/index.ts +104 -25
  35. package/src/cookie/index.ts +3 -3
  36. package/src/index.ts +4 -3
  37. package/src/middleware/index.ts +19 -8
  38. package/src/multipart/index.ts +23 -24
  39. package/src/render/index.ts +7 -4
  40. package/src/route/index.ts +336 -95
  41. package/src/schema/index.ts +2798 -0
  42. package/src/trie/index.ts +12 -2
  43. package/src/util/index.ts +142 -36
@@ -0,0 +1,2798 @@
1
+ import { Fragment, type JSX, jsx } from "../jsx/index.js";
2
+ import { Multipart } from "../multipart/index.js";
3
+ import { Checksum, Codec, Size } from "../util/index.js";
4
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
5
+
6
+ export namespace Schema {
7
+ /**
8
+ * `Schema.parse` function type
9
+ *
10
+ * @template O Parse output
11
+ * @param value Unknown value to parse
12
+ * @param path Optional issue path (internal)
13
+ * @returns Parse result containing data or issues
14
+ */
15
+ export type Parse<O> = (value: unknown, path?: Issue.Path) => Parse.Result<O>;
16
+
17
+ export namespace Parse {
18
+ /**
19
+ * Valid result type.
20
+ *
21
+ * @template O Parse output
22
+ */
23
+ export interface Valid<O> {
24
+ /** Valid parsed data */
25
+ data: O;
26
+
27
+ issues?: never;
28
+ }
29
+
30
+ /** Invalid result type. */
31
+ export interface Invalid extends InstanceType<
32
+ typeof Schema.AggregateIssue
33
+ > {
34
+ data?: never;
35
+ }
36
+
37
+ /**
38
+ * `Schema.parse` result containing `data` or invalid metadata.
39
+ *
40
+ * @template O Parse output
41
+ * @template M Extra invalid result metadata
42
+ * @template V Extra valid result metadata
43
+ */
44
+ export type Result<O, M extends object = {}, V extends object = {}> =
45
+ | (Valid<O> & V)
46
+ | (Invalid & M);
47
+
48
+ /**
49
+ * Type of constructor input (path is required).
50
+ *
51
+ * @template O Parse output
52
+ * @param value Unknown value to parse
53
+ * @param path Issue path (internal)
54
+ * @returns Parse result containing data or issues
55
+ */
56
+ export type Constructor<O> = (
57
+ value: unknown,
58
+ path: Issue.Path,
59
+ ) => Result<O>;
60
+ }
61
+
62
+ /**
63
+ * Infer Output type of a schema or shape.
64
+ *
65
+ * @template S Schema or shape type to infer from
66
+ */
67
+ export type Infer<S> =
68
+ S extends Schema<infer Output>
69
+ ? // regular schema
70
+ Output
71
+ : S extends Object.Shape
72
+ ? // infer value of each schema (value) in the shape
73
+ { [K in keyof S]: Infer<S[K]> }
74
+ : S extends any[]
75
+ ? // array - better zod compat
76
+ Infer<S[number]>[]
77
+ : never;
78
+
79
+ /** Schema.Issue type */
80
+ export type Issue = InstanceType<typeof Schema.Issue>;
81
+
82
+ export namespace Issue {
83
+ /** Issue path representation. */
84
+ export type Path = (string | number)[];
85
+
86
+ /** Non-empty list of issues */
87
+ export type List = readonly [Issue, ...Issue[]];
88
+ }
89
+
90
+ // this is to improve inferred type performance to help ts infer objects
91
+ /**
92
+ * Object schema with extend capability.
93
+ *
94
+ * @template S Object shape type
95
+ */
96
+ export type Object<
97
+ S extends Object.Shape,
98
+ M extends Object.Mode = "strip",
99
+ > = ObjectSchema<S, M>;
100
+
101
+ export namespace Object {
102
+ /** Object schema shape. */
103
+ export type Shape = Record<string, Schema<unknown>>;
104
+
105
+ /** Object parsing mode. */
106
+ export type Mode = "strip" | "strict" | "loose";
107
+
108
+ /**
109
+ * Object output type by mode.
110
+ *
111
+ * @template S Object shape
112
+ * @template M Object mode
113
+ */
114
+ export type Output<
115
+ S extends Shape,
116
+ M extends Mode = "strip",
117
+ > = M extends "loose"
118
+ ? Schema.Infer<S> & Record<string, unknown>
119
+ : Schema.Infer<S>;
120
+ }
121
+ }
122
+
123
+ /** Shared shape types for `Shape` related runtime methods. */
124
+ namespace ShapeUtil {
125
+ /**
126
+ * Shape key name string.
127
+ *
128
+ * @template S Record-like shape
129
+ */
130
+ export type Name<S extends Record<string, unknown>> = Extract<
131
+ keyof S,
132
+ string
133
+ >;
134
+
135
+ /**
136
+ * Merge two shapes where `B` overrides `A`.
137
+ *
138
+ * @template A Base shape
139
+ * @template B Extra shape
140
+ */
141
+ export type Extend<
142
+ A extends Record<string, unknown>,
143
+ B extends Record<string, unknown>,
144
+ > = globalThis.Omit<A, keyof B> & B;
145
+ }
146
+
147
+ /** Shared runtime shape operations used by object and form schema methods. */
148
+ class ShapeUtil {
149
+ /**
150
+ * Merge two record-like shapes where `extra` keys override `shape`.
151
+ *
152
+ * @template S Base shape
153
+ * @template E Extra shape
154
+ * @param shape Base shape
155
+ * @param extra Extra values to merge
156
+ * @returns Merged shape
157
+ */
158
+ static extend<
159
+ S extends Record<string, unknown>,
160
+ E extends Record<string, unknown>,
161
+ >(shape: S, extra: E): ShapeUtil.Extend<S, E> {
162
+ return { ...shape, ...extra } as ShapeUtil.Extend<S, E>;
163
+ }
164
+
165
+ /**
166
+ * Pick keys from a record-like shape.
167
+ *
168
+ * @template S Shape
169
+ * @template N Selected key names
170
+ * @param shape Source shape
171
+ * @param names Non-empty list of keys to include
172
+ * @returns Picked shape
173
+ */
174
+ static pick<S extends Record<string, unknown>, N extends ShapeUtil.Name<S>>(
175
+ shape: S,
176
+ names: readonly [N, ...N[]],
177
+ ): Pick<S, N> {
178
+ const out: Record<string, unknown> = {};
179
+
180
+ for (const name of names) {
181
+ if (name in shape) out[name] = shape[name];
182
+ }
183
+
184
+ return out as Pick<S, N>;
185
+ }
186
+
187
+ /**
188
+ * Omit keys from a record-like shape.
189
+ *
190
+ * @template S Shape
191
+ * @template N Removed key names
192
+ * @param shape Source shape
193
+ * @param names Non-empty list of keys to remove
194
+ * @returns Omitted shape
195
+ */
196
+ static omit<S extends Record<string, unknown>, N extends ShapeUtil.Name<S>>(
197
+ shape: S,
198
+ names: readonly [N, ...N[]],
199
+ ): Omit<S, N> {
200
+ const remove = new Set<string>(names);
201
+ const out: Record<string, unknown> = {};
202
+
203
+ for (const [name, value] of Object.entries(shape)) {
204
+ if (!remove.has(name)) out[name] = value;
205
+ }
206
+
207
+ return out as Omit<S, N>;
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Minimal schema validator geared around parsing form data like
213
+ * multipart `FormData` and `URLSearchParams`.
214
+ *
215
+ * Implements Standard Schema v1 via the `~standard` property (sync validate).
216
+ *
217
+ * @template Output Output type after parsing
218
+ */
219
+ export class Schema<Output> implements StandardSchemaV1<unknown, Output> {
220
+ /** Email regular expression */
221
+ static readonly #emailRegex =
222
+ /^(?!\.)(?!.*\.\.)([a-z0-9_'+\-\.]*)[a-z0-9_'+\-]@([a-z0-9][a-z0-9\-]*\.)+[a-z]{2,}$/i;
223
+
224
+ /** Validation issue produced during parsing. */
225
+ static readonly Issue = class Issue extends Error {
226
+ /** Expected type/value. */
227
+ readonly expected: string;
228
+
229
+ /** Path to the invalid value. */
230
+ readonly path: Schema.Issue.Path;
231
+
232
+ /**
233
+ * @param expected Expected value
234
+ * @param path Path to the invalid value
235
+ * @param message Issue message
236
+ */
237
+ constructor(expected: unknown, path: Schema.Issue.Path, message?: string) {
238
+ const exp = String(expected);
239
+
240
+ super(message ?? `Expected ${exp}`);
241
+
242
+ this.name = "Schema.Issue";
243
+ this.expected = exp;
244
+ this.path = path;
245
+ }
246
+
247
+ /**
248
+ * @returns `Schema.Issue(path): message`
249
+ */
250
+ override toString() {
251
+ let path = "";
252
+
253
+ for (const segment of this.path) {
254
+ path +=
255
+ typeof segment === "number"
256
+ ? `[${segment}]`
257
+ : `${path ? "." : path}${segment}`;
258
+ }
259
+
260
+ return `${this.name}${path ? `(${path})` : ""}: ${this.message}`;
261
+ }
262
+
263
+ toJSON() {
264
+ return { ...this, message: this.message };
265
+ }
266
+ };
267
+
268
+ /** AggregateIssue containing at least one Schema.Issue */
269
+ static readonly AggregateIssue = class AggregateIssue extends AggregateError {
270
+ /** Non-empty tuple of issues */
271
+ readonly issues: Schema.Issue.List;
272
+
273
+ /** User submitted / sanitized values */
274
+ readonly values?: Form.Value.Map;
275
+
276
+ /**
277
+ * Create a new AggregateIssue.
278
+ *
279
+ * Coerces issues into a non-empty tuple.
280
+ *
281
+ * @param issues Issues
282
+ * @param values Received values
283
+ */
284
+ constructor([first, ...rest]: Schema.Issue[], values?: Form.Value.Map) {
285
+ if (!first) throw new TypeError("AggregateIssue must have an issue.");
286
+
287
+ const issues: Schema.Issue.List = [first, ...rest];
288
+ const name = "Schema.AggregateIssue";
289
+ const count = issues.length;
290
+
291
+ super(issues, `${name}(${count})\n${issues.join("\n")}`);
292
+
293
+ this.name = name;
294
+ this.issues = issues;
295
+ this.values = values;
296
+ }
297
+
298
+ override toString() {
299
+ // prevents name being in the default twice since it's
300
+ // already in the message
301
+ return this.message;
302
+ }
303
+
304
+ toJSON() {
305
+ return { ...this, message: this.message };
306
+ }
307
+ };
308
+
309
+ readonly "~standard": StandardSchemaV1.Props<unknown, Output> = {
310
+ version: 1,
311
+ vendor: "ovr",
312
+ validate: (value) => {
313
+ const result = this.parse(value);
314
+
315
+ return result.issues ? result : { value: result.data };
316
+ },
317
+ };
318
+
319
+ /**
320
+ * Parse and validate an unknown value.
321
+ *
322
+ * @param value Unknown value to parse
323
+ * @param path Optional issue path (internal)
324
+ * @returns Parse result containing data or issues
325
+ */
326
+ parse: Schema.Parse<Output>;
327
+
328
+ /**
329
+ * Construct a new schema - used internally.
330
+ *
331
+ * Use static methods on `Schema` to make a new schema.
332
+ *
333
+ * @param parse Parse function that validates and transforms input
334
+ */
335
+ constructor(parse: Schema.Parse.Constructor<Output>) {
336
+ this.parse = (value, path = []) => parse(value, path);
337
+ }
338
+
339
+ /**
340
+ * @internal Required for Field to override and return a `Field` instance
341
+ * from the chained methods instead of a `Schema`
342
+ * @template O Output type of the new schema
343
+ * @param parse Parse function that validates and transforms input
344
+ * @returns New schema instance based on the current instance
345
+ */
346
+ derive<O>(parse: Schema.Parse.Constructor<O>) {
347
+ return new Schema<O>(parse);
348
+ }
349
+
350
+ /**
351
+ * @template T Field tag name
352
+ * @template U Field input type attribute
353
+ * @template V Field option values
354
+ * @returns Optional field
355
+ */
356
+ optional<
357
+ T extends Field.Tag,
358
+ U extends Field.Type,
359
+ V extends Field.Values | undefined,
360
+ >(
361
+ this: Field.Instance<Output, T, U, V>,
362
+ ): Field.Instance<Output | undefined, T, U, V>;
363
+ /**
364
+ * @returns Optional schema
365
+ */
366
+ optional(this: Schema<Output>): Schema<Output | undefined>;
367
+ optional(this: Schema<Output>) {
368
+ return this.derive((v, path) => {
369
+ if (v === undefined) return { data: v as Output | undefined };
370
+
371
+ return this.parse(v, path);
372
+ });
373
+ }
374
+
375
+ /**
376
+ * @template T Field tag name
377
+ * @template U Field input type attribute
378
+ * @template V Field option values
379
+ * @returns Nullable field
380
+ */
381
+ nullable<
382
+ T extends Field.Tag,
383
+ U extends Field.Type,
384
+ V extends Field.Values | undefined,
385
+ >(
386
+ this: Field.Instance<Output, T, U, V>,
387
+ ): Field.Instance<Output | null, T, U, V>;
388
+ /**
389
+ * @returns Nullable schema
390
+ */
391
+ nullable(this: Schema<Output>): Schema<Output | null>;
392
+ nullable(this: Schema<Output>) {
393
+ return this.derive((v, path) => {
394
+ if (v === null) return { data: v as Output | null };
395
+
396
+ return this.parse(v, path);
397
+ });
398
+ }
399
+
400
+ /**
401
+ * @template T Field tag name
402
+ * @template U Field input type attribute
403
+ * @template V Field option values
404
+ * @returns Nullish field
405
+ */
406
+ nullish<
407
+ T extends Field.Tag,
408
+ U extends Field.Type,
409
+ V extends Field.Values | undefined,
410
+ >(
411
+ this: Field.Instance<Output, T, U, V>,
412
+ ): Field.Instance<Output | null | undefined, T, U, V>;
413
+ /**
414
+ * @returns Nullish schema
415
+ */
416
+ nullish(this: Schema<Output>): Schema<Output | null | undefined>;
417
+ nullish(this: Schema<Output>) {
418
+ return this.derive((v, path) => {
419
+ if (v == null) return { data: v as Output | null | undefined };
420
+
421
+ return this.parse(v, path);
422
+ });
423
+ }
424
+
425
+ /**
426
+ * @template T Field tag name
427
+ * @template U Field input type attribute
428
+ * @template V Field option values
429
+ * @param value Default value to use when input is undefined
430
+ * @returns Field with default
431
+ */
432
+ default<
433
+ T extends Field.Tag,
434
+ U extends Field.Type,
435
+ V extends Field.Values | undefined,
436
+ >(
437
+ this: Field.Instance<Output, T, U, V>,
438
+ value: Output,
439
+ ): Field.Instance<Output, T, U, V>;
440
+ /**
441
+ * @param value Default value to use when input is undefined
442
+ * @returns Schema with default
443
+ */
444
+ default(this: Schema<Output>, value: Output): Schema<Output>;
445
+ default(this: Schema<Output>, value: Output) {
446
+ return this.derive((v, path) => {
447
+ if (v === undefined) return { data: value };
448
+
449
+ return this.parse(v, path);
450
+ });
451
+ }
452
+
453
+ /**
454
+ * @template T Field tag name
455
+ * @template U Field input type attribute
456
+ * @template V Field option values
457
+ * @param fn Preprocess function to run before parsing
458
+ * @returns Schema that preprocesses input before parsing
459
+ */
460
+ preprocess<
461
+ T extends Field.Tag,
462
+ U extends Field.Type,
463
+ V extends Field.Values | undefined,
464
+ >(
465
+ this: Field.Instance<Output, T, U, V>,
466
+ fn: (value: unknown) => unknown,
467
+ ): Field.Instance<Output, T, U, V>;
468
+ /**
469
+ * @param fn Preprocess function to run before parsing
470
+ * @returns Schema that preprocesses input before parsing
471
+ */
472
+ preprocess(
473
+ this: Schema<Output>,
474
+ fn: (value: unknown) => unknown,
475
+ ): Schema<Output>;
476
+ preprocess(this: Schema<Output>, fn: (value: unknown) => unknown) {
477
+ return this.derive((v, path) => this.parse(fn(v), path));
478
+ }
479
+
480
+ /**
481
+ * @template O Output type after transformation
482
+ * @template T Field tag name
483
+ * @template U Field input type attribute
484
+ * @template V Field option values
485
+ * @param fn Transform function to apply to parsed output
486
+ * @returns Transformed field
487
+ */
488
+ transform<
489
+ O,
490
+ T extends Field.Tag,
491
+ U extends Field.Type,
492
+ V extends Field.Values | undefined,
493
+ >(
494
+ this: Field.Instance<Output, T, U, V>,
495
+ fn: (value: Output) => O,
496
+ ): Field.Instance<O, T, U, V>;
497
+ /**
498
+ * @template O Output type after transformation
499
+ * @param fn Transform function to apply to parsed output
500
+ * @returns Transformed schema
501
+ */
502
+ transform<O>(this: Schema<Output>, fn: (value: Output) => O): Schema<O>;
503
+ transform<O>(this: Schema<Output>, fn: (value: Output) => O) {
504
+ return this.derive((v, path) => {
505
+ const out = this.parse(v, path);
506
+
507
+ return out.issues ? out : { data: fn(out.data) };
508
+ });
509
+ }
510
+
511
+ /**
512
+ * @template O Output type after pipe
513
+ * @template T Field tag name
514
+ * @template U Field input type attribute
515
+ * @template V Field option values
516
+ * @param next Schema to validate the result with
517
+ * @returns Piped field
518
+ */
519
+ pipe<
520
+ O,
521
+ T extends Field.Tag,
522
+ U extends Field.Type,
523
+ V extends Field.Values | undefined,
524
+ >(
525
+ this: Field.Instance<Output, T, U, V>,
526
+ next: Schema<O>,
527
+ ): Field.Instance<O, T, U, V>;
528
+ /**
529
+ * @template O Output type after pipe
530
+ * @param next Schema to validate the result with
531
+ * @returns Piped schema
532
+ */
533
+ pipe<O>(this: Schema<Output>, next: Schema<O>): Schema<O>;
534
+ pipe<O>(this: Schema<Output>, next: Schema<O>) {
535
+ return this.derive((v, path) => {
536
+ const result = this.parse(v, path);
537
+
538
+ return result.issues ? result : next.parse(result.data, path);
539
+ });
540
+ }
541
+
542
+ /**
543
+ * Parse a JSON string and validate the parsed value with the provided schema.
544
+ *
545
+ * @template O Output type
546
+ * @template T Field tag name
547
+ * @template U Field input type attribute
548
+ * @template V Field option values
549
+ * @param schema Schema to validate the parsed JSON value with
550
+ * @param message Issue message when invalid
551
+ * @returns Parsed JSON field
552
+ */
553
+ json<
554
+ O,
555
+ T extends Field.Tag,
556
+ U extends Field.Type,
557
+ V extends Field.Values | undefined,
558
+ >(
559
+ this: Field.Instance<string, T, U, V>,
560
+ schema: Schema<O>,
561
+ message?: string,
562
+ ): Field.Instance<O, T, U, V>;
563
+ /**
564
+ * Parse a JSON string and validate the parsed value with the provided schema.
565
+ *
566
+ * @template O Output type
567
+ * @param schema Schema to validate the parsed JSON value with
568
+ * @param message Issue message when invalid
569
+ * @returns Parsed JSON schema
570
+ */
571
+ json<O>(this: Schema<string>, schema: Schema<O>, message?: string): Schema<O>;
572
+ json<O>(this: Schema<string>, schema: Schema<O>, message?: string) {
573
+ return this.derive((v, path) => {
574
+ const result = this.parse(v, path);
575
+ if (result.issues) return result;
576
+
577
+ let data: unknown;
578
+
579
+ try {
580
+ data = JSON.parse(result.data);
581
+ } catch {
582
+ return new Schema.AggregateIssue([
583
+ new Schema.Issue("JSON", path, message),
584
+ ]);
585
+ }
586
+
587
+ return schema.parse(data, path);
588
+ });
589
+ }
590
+
591
+ /**
592
+ * Validate an input is a valid email string using
593
+ * [Reasonable Email Regex by Colin McDonnell](https://colinhacks.com/essays/reasonable-email-regex).
594
+ *
595
+ * @template T Field tag name
596
+ * @template U Field input type attribute
597
+ * @template V Field option values
598
+ * @param message Issue message when invalid
599
+ * @returns Email field
600
+ */
601
+ email<
602
+ T extends Field.Tag,
603
+ U extends Field.Type,
604
+ V extends Field.Values | undefined,
605
+ >(
606
+ this: Field.Instance<string, T, U, V>,
607
+ message?: string,
608
+ ): Field.Instance<string, T, U, V>;
609
+ /**
610
+ * Validate an input is a valid email string using
611
+ * [Reasonable Email Regex by Colin McDonnell](https://colinhacks.com/essays/reasonable-email-regex).
612
+ *
613
+ * @param message Issue message when invalid
614
+ * @returns Email schema
615
+ */
616
+ email(this: Schema<string>, message?: string): Schema<string>;
617
+ email(this: Schema<string>, message = "Expected email") {
618
+ return this.refine((s) => Schema.#emailRegex.test(s), message);
619
+ }
620
+
621
+ /**
622
+ * Validate an input is a valid URL string.
623
+ *
624
+ * @template T Field tag name
625
+ * @template U Field input type attribute
626
+ * @template V Field option values
627
+ * @param message Issue message when invalid
628
+ * @returns URL field
629
+ */
630
+ url<
631
+ T extends Field.Tag,
632
+ U extends Field.Type,
633
+ V extends Field.Values | undefined,
634
+ >(
635
+ this: Field.Instance<string, T, U, V>,
636
+ message?: string,
637
+ ): Field.Instance<string, T, U, V>;
638
+ /**
639
+ * Validate an input is a valid URL string.
640
+ *
641
+ * @param message Issue message when invalid
642
+ * @returns URL schema
643
+ */
644
+ url(this: Schema<string>, message?: string): Schema<string>;
645
+ url(this: Schema<string>, message = "Expected URL") {
646
+ return this.refine(URL.canParse, message);
647
+ }
648
+
649
+ /**
650
+ * Validate an input is a safe integer.
651
+ *
652
+ * @template T Field tag name
653
+ * @template U Field input type attribute
654
+ * @template V Field option values
655
+ * @param message Issue message when invalid
656
+ * @returns Integer field
657
+ */
658
+ int<
659
+ T extends Field.Tag,
660
+ U extends Field.Type,
661
+ V extends Field.Values | undefined,
662
+ >(
663
+ this: Field.Instance<number, T, U, V>,
664
+ message?: string,
665
+ ): Field.Instance<number, T, U, V>;
666
+ /**
667
+ * Validate an input is a safe integer.
668
+ *
669
+ * @param message Issue message when invalid
670
+ * @returns Integer schema
671
+ */
672
+ int(this: Schema<number>, message?: string): Schema<number>;
673
+ int(this: Schema<number>, message = "Expected integer") {
674
+ return this.refine(Number.isSafeInteger, message);
675
+ }
676
+
677
+ /**
678
+ * Validate an input is greater than or equal to the minimum.
679
+ *
680
+ * For strings, this validates minimum length.
681
+ *
682
+ * @template T Field tag name
683
+ * @template U Field input type attribute
684
+ * @template V Field option values
685
+ * @param value Minimum value or length
686
+ * @param message Issue message when invalid
687
+ * @returns Refined field
688
+ */
689
+ min<
690
+ T extends Field.Tag,
691
+ U extends Field.Type,
692
+ V extends Field.Values | undefined,
693
+ >(
694
+ this: Field.Instance<string, T, U, V>,
695
+ value: number,
696
+ message?: string,
697
+ ): Field.Instance<string, T, U, V>;
698
+ /**
699
+ * Validate an input is greater than or equal to the minimum.
700
+ *
701
+ * @template T Field tag name
702
+ * @template U Field input type attribute
703
+ * @template V Field option values
704
+ * @param value Minimum value
705
+ * @param message Issue message when invalid
706
+ * @returns Refined field
707
+ */
708
+ min<
709
+ T extends Field.Tag,
710
+ U extends Field.Type,
711
+ V extends Field.Values | undefined,
712
+ >(
713
+ this: Field.Instance<number, T, U, V>,
714
+ value: number,
715
+ message?: string,
716
+ ): Field.Instance<number, T, U, V>;
717
+ /**
718
+ * Validate an input is greater than or equal to the minimum.
719
+ *
720
+ * @template T Field tag name
721
+ * @template U Field input type attribute
722
+ * @template V Field option values
723
+ * @param value Minimum value
724
+ * @param message Issue message when invalid
725
+ * @returns Refined field
726
+ */
727
+ min<
728
+ T extends Field.Tag,
729
+ U extends Field.Type,
730
+ V extends Field.Values | undefined,
731
+ >(
732
+ this: Field.Instance<bigint, T, U, V>,
733
+ value: bigint,
734
+ message?: string,
735
+ ): Field.Instance<bigint, T, U, V>;
736
+ /**
737
+ * Validate an input is greater than or equal to the minimum.
738
+ *
739
+ * For strings, this validates minimum length.
740
+ *
741
+ * @param value Minimum value or length
742
+ * @param message Issue message when invalid
743
+ * @returns Refined schema
744
+ */
745
+ min(this: Schema<string>, value: number, message?: string): Schema<string>;
746
+ /**
747
+ * Validate an input is greater than or equal to the minimum.
748
+ *
749
+ * @param value Minimum value
750
+ * @param message Issue message when invalid
751
+ * @returns Refined schema
752
+ */
753
+ min(this: Schema<number>, value: number, message?: string): Schema<number>;
754
+ /**
755
+ * Validate an input is greater than or equal to the minimum.
756
+ *
757
+ * @param value Minimum value
758
+ * @param message Issue message when invalid
759
+ * @returns Refined schema
760
+ */
761
+ min(this: Schema<bigint>, value: bigint, message?: string): Schema<bigint>;
762
+ min(
763
+ this: Schema<string | number | bigint>,
764
+ value: number | bigint,
765
+ message = `Expected minimum ${String(value)}`,
766
+ ) {
767
+ return this.refine((next) => {
768
+ return typeof next === "string"
769
+ ? next.length >= (value as number)
770
+ : next >= (value as number | bigint);
771
+ }, message);
772
+ }
773
+
774
+ /**
775
+ * Validate an input is less than or equal to the maximum.
776
+ *
777
+ * For strings, this validates maximum length.
778
+ *
779
+ * @template T Field tag name
780
+ * @template U Field input type attribute
781
+ * @template V Field option values
782
+ * @param value Maximum value or length
783
+ * @param message Issue message when invalid
784
+ * @returns Refined field
785
+ */
786
+ max<
787
+ T extends Field.Tag,
788
+ U extends Field.Type,
789
+ V extends Field.Values | undefined,
790
+ >(
791
+ this: Field.Instance<string, T, U, V>,
792
+ value: number,
793
+ message?: string,
794
+ ): Field.Instance<string, T, U, V>;
795
+ /**
796
+ * Validate an input is less than or equal to the maximum.
797
+ *
798
+ * @template T Field tag name
799
+ * @template U Field input type attribute
800
+ * @template V Field option values
801
+ * @param value Maximum value
802
+ * @param message Issue message when invalid
803
+ * @returns Refined field
804
+ */
805
+ max<
806
+ T extends Field.Tag,
807
+ U extends Field.Type,
808
+ V extends Field.Values | undefined,
809
+ >(
810
+ this: Field.Instance<number, T, U, V>,
811
+ value: number,
812
+ message?: string,
813
+ ): Field.Instance<number, T, U, V>;
814
+ /**
815
+ * Validate an input is less than or equal to the maximum.
816
+ *
817
+ * @template T Field tag name
818
+ * @template U Field input type attribute
819
+ * @template V Field option values
820
+ * @param value Maximum value
821
+ * @param message Issue message when invalid
822
+ * @returns Refined field
823
+ */
824
+ max<
825
+ T extends Field.Tag,
826
+ U extends Field.Type,
827
+ V extends Field.Values | undefined,
828
+ >(
829
+ this: Field.Instance<bigint, T, U, V>,
830
+ value: bigint,
831
+ message?: string,
832
+ ): Field.Instance<bigint, T, U, V>;
833
+ /**
834
+ * Validate an input is less than or equal to the maximum.
835
+ *
836
+ * For strings, this validates maximum length.
837
+ *
838
+ * @param value Maximum value or length
839
+ * @param message Issue message when invalid
840
+ * @returns Refined schema
841
+ */
842
+ max(this: Schema<string>, value: number, message?: string): Schema<string>;
843
+ /**
844
+ * Validate an input is less than or equal to the maximum.
845
+ *
846
+ * @param value Maximum value
847
+ * @param message Issue message when invalid
848
+ * @returns Refined schema
849
+ */
850
+ max(this: Schema<number>, value: number, message?: string): Schema<number>;
851
+ /**
852
+ * Validate an input is less than or equal to the maximum.
853
+ *
854
+ * @param value Maximum value
855
+ * @param message Issue message when invalid
856
+ * @returns Refined schema
857
+ */
858
+ max(this: Schema<bigint>, value: bigint, message?: string): Schema<bigint>;
859
+ max(
860
+ this: Schema<string | number | bigint>,
861
+ value: number | bigint,
862
+ message = `Expected maximum ${String(value)}`,
863
+ ) {
864
+ return this.refine((next) => {
865
+ return typeof next === "string"
866
+ ? next.length <= (value as number)
867
+ : next <= (value as number | bigint);
868
+ }, message);
869
+ }
870
+
871
+ /**
872
+ * @template T Field tag name
873
+ * @template U Field input type attribute
874
+ * @template V Field option values
875
+ * @param check Validation function that returns `false` to fail
876
+ * @param message Issue message when invalid
877
+ * @returns Refined field
878
+ */
879
+ refine<
880
+ T extends Field.Tag,
881
+ U extends Field.Type,
882
+ V extends Field.Values | undefined,
883
+ >(
884
+ this: Field.Instance<Output, T, U, V>,
885
+ check: (value: Output) => boolean,
886
+ message: string,
887
+ ): Field.Instance<Output, T, U, V>;
888
+ /**
889
+ * @param check Validation function that returns `false` to fail
890
+ * @param message Issue message when invalid
891
+ * @returns Refined schema
892
+ */
893
+ refine(
894
+ this: Schema<Output>,
895
+ check: (value: Output) => boolean,
896
+ message: string,
897
+ ): Schema<Output>;
898
+ refine(
899
+ this: Schema<Output>,
900
+ check: (value: Output) => boolean,
901
+ message: string,
902
+ ) {
903
+ return this.derive((v, path) => {
904
+ const out = this.parse(v, path);
905
+
906
+ return out.issues || check(out.data)
907
+ ? out
908
+ : new Schema.AggregateIssue([
909
+ new Schema.Issue("refine", path, message),
910
+ ]);
911
+ });
912
+ }
913
+
914
+ /**
915
+ * Accepts any value and presents the data as `unknown`.
916
+ *
917
+ * @returns Unknown schema
918
+ */
919
+ static unknown() {
920
+ return new Schema((v) => ({ data: v }));
921
+ }
922
+
923
+ /**
924
+ * Validate an input is a string.
925
+ *
926
+ * @param message Issue message when invalid
927
+ * @returns String schema
928
+ */
929
+ static string(message?: string) {
930
+ return new Schema((v, path) => {
931
+ return typeof v === "string"
932
+ ? { data: v }
933
+ : new Schema.AggregateIssue([
934
+ new Schema.Issue("string", path, message),
935
+ ]);
936
+ });
937
+ }
938
+
939
+ /**
940
+ * Validate an input is a `true` or `false` boolean.
941
+ *
942
+ * @param message Issue message when invalid
943
+ * @returns Boolean schema
944
+ */
945
+ static boolean(message?: string) {
946
+ return new Schema((v, path) => {
947
+ return typeof v === "boolean"
948
+ ? { data: v }
949
+ : new Schema.AggregateIssue([
950
+ new Schema.Issue("boolean", path, message),
951
+ ]);
952
+ });
953
+ }
954
+
955
+ /**
956
+ * Validate an input is a number.
957
+ *
958
+ * Rejects non-finite values like `NaN` and `Infinity`.
959
+ *
960
+ * @param message Issue message when invalid
961
+ * @returns Number schema
962
+ */
963
+ static number(message?: string) {
964
+ return new Schema((v, path) => {
965
+ return Number.isFinite(v) // isFinite checks type
966
+ ? { data: v as number }
967
+ : new Schema.AggregateIssue([
968
+ new Schema.Issue("number", path, message),
969
+ ]);
970
+ });
971
+ }
972
+
973
+ /**
974
+ * Validate an input is a big integer.
975
+ *
976
+ * @param message Issue message when invalid
977
+ * @returns Big integer schema
978
+ */
979
+ static bigint(message?: string) {
980
+ return new Schema((v, path) => {
981
+ return typeof v === "bigint"
982
+ ? { data: v }
983
+ : new Schema.AggregateIssue([
984
+ new Schema.Issue("bigint", path, message),
985
+ ]);
986
+ });
987
+ }
988
+
989
+ /**
990
+ * @template L Literal type
991
+ * @param literal Exact value to match
992
+ * @param message Issue message when invalid
993
+ * @returns Literal schema
994
+ */
995
+ static literal<const L>(literal: L, message?: string) {
996
+ return new Schema((v, path) => {
997
+ return v === literal
998
+ ? { data: literal }
999
+ : new Schema.AggregateIssue([new Schema.Issue(literal, path, message)]);
1000
+ });
1001
+ }
1002
+
1003
+ /**
1004
+ * Validates that the input is strictly equal (`===`) to one of the allowed
1005
+ * values.
1006
+ *
1007
+ * @template A Allowed type
1008
+ * @param allowed Allowed values
1009
+ * @param message Issue message when invalid
1010
+ * @returns Enum schema
1011
+ */
1012
+ static enum<const A extends readonly [unknown, ...unknown[]]>(
1013
+ allowed: A,
1014
+ message?: string,
1015
+ ) {
1016
+ return new Schema<A[number]>((v, path) => {
1017
+ for (const a of allowed) {
1018
+ if (v === a) return { data: a };
1019
+ }
1020
+
1021
+ return new Schema.AggregateIssue([
1022
+ new Schema.Issue(
1023
+ allowed.map((v) => JSON.stringify(v)).join(" | "),
1024
+ path,
1025
+ message,
1026
+ ),
1027
+ ]);
1028
+ });
1029
+ }
1030
+
1031
+ /**
1032
+ * Tries each schema in order and returns the first successfully parsed result.
1033
+ *
1034
+ * @template S Schemas type
1035
+ * @param schemas Schemas to try in order
1036
+ * @returns Union schema
1037
+ */
1038
+ static union<
1039
+ const S extends readonly [Schema<unknown>, ...Schema<unknown>[]],
1040
+ >(schemas: S) {
1041
+ return new Schema((v, path) => {
1042
+ const issues: Schema.Issue[] = [];
1043
+
1044
+ for (const schema of schemas) {
1045
+ const result = schema.parse(v, path);
1046
+
1047
+ if (!result.issues) {
1048
+ // return as soon as one passes
1049
+ return result as Schema.Parse.Result<Schema.Infer<S[number]>>;
1050
+ }
1051
+
1052
+ issues.push(...result.issues);
1053
+ }
1054
+
1055
+ return new Schema.AggregateIssue(issues);
1056
+ });
1057
+ }
1058
+
1059
+ /**
1060
+ * Validates an input is an instance of the constructor.
1061
+ *
1062
+ * @template O Output type
1063
+ * @param constructor Constructor to validate the input is an instance of
1064
+ * @param message Issue message when invalid
1065
+ * @returns Validated instance
1066
+ */
1067
+ static instance<O>(constructor: new (...args: any[]) => O, message?: string) {
1068
+ return new Schema((v, path) =>
1069
+ v instanceof constructor
1070
+ ? { data: v }
1071
+ : new Schema.AggregateIssue([
1072
+ new Schema.Issue(constructor.name, path, message),
1073
+ ]),
1074
+ );
1075
+ }
1076
+
1077
+ /**
1078
+ * Validates that the input is an array and parses each item.
1079
+ *
1080
+ * @template O Output type
1081
+ * @param schema Schema for each array item
1082
+ * @param message Issue message when invalid
1083
+ * @returns Array schema
1084
+ */
1085
+ static array<O>(schema: Schema<O>, message?: string) {
1086
+ return new Schema((v, path) => {
1087
+ if (!Array.isArray(v)) {
1088
+ return new Schema.AggregateIssue([
1089
+ new Schema.Issue("Array", path, message),
1090
+ ]);
1091
+ }
1092
+
1093
+ const data: O[] = [];
1094
+ const issues: Schema.Issue[] = [];
1095
+
1096
+ for (let i = 0; i < v.length; i++) {
1097
+ const result = schema.parse(v[i], [...path, i]);
1098
+
1099
+ if (result.issues) {
1100
+ issues.push(...result.issues);
1101
+ } else {
1102
+ data.push(result.data);
1103
+ }
1104
+ }
1105
+
1106
+ if (issues.length) return new Schema.AggregateIssue(issues);
1107
+
1108
+ return { data };
1109
+ });
1110
+ }
1111
+
1112
+ /**
1113
+ * Validates each key in the shape and returns a new object of parsed outputs.
1114
+ *
1115
+ * @template S Object shape type
1116
+ * @param shape Object shape with schemas for each key
1117
+ * @returns Object schema
1118
+ */
1119
+ static object<S extends Schema.Object.Shape = {}>(
1120
+ shape: S = {} as S,
1121
+ ): Schema.Object<S> {
1122
+ return new ObjectSchema(shape, "strip");
1123
+ }
1124
+ }
1125
+
1126
+ /**
1127
+ * Runtime object schema that validates plain objects and supports shape helpers.
1128
+ *
1129
+ * @template Shape Object shape type
1130
+ * @template Mode Object parsing mode
1131
+ */
1132
+ class ObjectSchema<
1133
+ Shape extends Schema.Object.Shape,
1134
+ Mode extends Schema.Object.Mode = "strip",
1135
+ > extends Schema<Schema.Object.Output<Shape, Mode>> {
1136
+ /** Object shape definitions. */
1137
+ readonly shape: Shape;
1138
+
1139
+ /** Object parsing mode. */
1140
+ readonly #mode: Mode;
1141
+
1142
+ /**
1143
+ * Create a new object schema validator.
1144
+ *
1145
+ * @param shape Object shape
1146
+ * @param mode Object parsing mode
1147
+ */
1148
+ constructor(shape: Shape, mode: Mode = "strip" as Mode) {
1149
+ super((value, path) => {
1150
+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
1151
+ return new Schema.AggregateIssue([new Schema.Issue("Object", path)]);
1152
+ }
1153
+
1154
+ const data: Record<string, unknown> = {};
1155
+ const issues: Schema.Issue[] = [];
1156
+
1157
+ for (const [name, schema] of Object.entries(shape)) {
1158
+ const result = schema.parse((value as Record<string, unknown>)[name], [
1159
+ ...path,
1160
+ name,
1161
+ ]);
1162
+
1163
+ if (result.issues) {
1164
+ issues.push(...result.issues);
1165
+ } else {
1166
+ data[name] = result.data;
1167
+ }
1168
+ }
1169
+
1170
+ if (mode !== "strip") {
1171
+ const names = new Set(Object.keys(shape));
1172
+
1173
+ for (const [name, next] of Object.entries(
1174
+ value as Record<string, unknown>,
1175
+ )) {
1176
+ if (!names.has(name)) {
1177
+ if (mode === "strict") {
1178
+ issues.push(
1179
+ new Schema.Issue("never", [...path, name], "Unexpected key"),
1180
+ );
1181
+ } else {
1182
+ data[name] = next;
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+
1188
+ return issues.length
1189
+ ? new Schema.AggregateIssue(issues)
1190
+ : ({ data } as { data: Schema.Object.Output<Shape, Mode> });
1191
+ });
1192
+
1193
+ this.shape = shape;
1194
+ this.#mode = mode;
1195
+ }
1196
+
1197
+ /**
1198
+ * Merge `extra` into the current shape.
1199
+ *
1200
+ * @template E Extra shape type
1201
+ * @param extra Extra shape or object schema to merge
1202
+ * @returns New object schema with the merged shape
1203
+ */
1204
+ extend<E extends Schema.Object.Shape>(
1205
+ extra: E,
1206
+ ): Schema.Object<ShapeUtil.Extend<Shape, E>, Mode>;
1207
+ extend<E extends Schema.Object.Shape>(
1208
+ extra: Schema.Object<E>,
1209
+ ): Schema.Object<ShapeUtil.Extend<Shape, E>, Mode>;
1210
+ extend(extra: Schema.Object.Shape | Schema.Object<any>) {
1211
+ return new ObjectSchema(
1212
+ ShapeUtil.extend(
1213
+ this.shape,
1214
+ extra instanceof ObjectSchema ? extra.shape : extra,
1215
+ ),
1216
+ this.#mode,
1217
+ );
1218
+ }
1219
+
1220
+ /**
1221
+ * Keep only selected field names.
1222
+ *
1223
+ * @template N Selected key names
1224
+ * @param names Non-empty list of key names to keep
1225
+ * @returns New object schema with only selected keys
1226
+ */
1227
+ pick<N extends ShapeUtil.Name<Shape>>(
1228
+ names: readonly [N, ...N[]],
1229
+ ): Schema.Object<Pick<Shape, N>, Mode> {
1230
+ return new ObjectSchema(ShapeUtil.pick(this.shape, names), this.#mode);
1231
+ }
1232
+
1233
+ /**
1234
+ * Remove selected field names.
1235
+ *
1236
+ * @template N Removed key names
1237
+ * @param names Non-empty list of key names to remove
1238
+ * @returns New object schema without selected keys
1239
+ */
1240
+ omit<N extends ShapeUtil.Name<Shape>>(
1241
+ names: readonly [N, ...N[]],
1242
+ ): Schema.Object<Omit<Shape, N>, Mode> {
1243
+ return new ObjectSchema(ShapeUtil.omit(this.shape, names), this.#mode);
1244
+ }
1245
+
1246
+ /**
1247
+ * Reject unknown keys during parsing.
1248
+ *
1249
+ * @returns New object schema in strict mode
1250
+ */
1251
+ strict(): Schema.Object<Shape, "strict"> {
1252
+ return new ObjectSchema(this.shape, "strict");
1253
+ }
1254
+
1255
+ /**
1256
+ * Preserve unknown keys during parsing.
1257
+ *
1258
+ * @returns New object schema in loose mode
1259
+ */
1260
+ loose(): Schema.Object<Shape, "loose"> {
1261
+ return new ObjectSchema(this.shape, "loose");
1262
+ }
1263
+ }
1264
+
1265
+ export namespace Form {
1266
+ /** Form field shape. */
1267
+ export type Shape = Record<string, Field.Any>;
1268
+
1269
+ /** Persisted form value */
1270
+ export type Value = string | number | boolean | string[];
1271
+
1272
+ export namespace Value {
1273
+ /**
1274
+ * Value map by field name.
1275
+ *
1276
+ * @template S Shape type
1277
+ */
1278
+ export type Map<S extends Shape = Shape> = Partial<
1279
+ Record<ShapeUtil.Name<S>, Value>
1280
+ >;
1281
+ }
1282
+
1283
+ /**
1284
+ * Encoded form state.
1285
+ *
1286
+ * @template S Shape type to infer value keys from
1287
+ */
1288
+ export interface State<S extends Shape = Shape> {
1289
+ /** Form id generated using the field names */
1290
+ readonly id: string;
1291
+
1292
+ /** Non-empty list of validation issues */
1293
+ readonly issues?: Schema.Issue.List;
1294
+
1295
+ /** Map of field names to possible values */
1296
+ readonly values?: Value.Map<S>;
1297
+ }
1298
+
1299
+ export namespace Parse {
1300
+ /**
1301
+ * Field names that are not marked to stream as multipart parts.
1302
+ *
1303
+ * @template S Form shape
1304
+ */
1305
+ type NonStreamNames<S extends Shape> = {
1306
+ [K in keyof S]-?: S[K] extends Field.Instance<any, any, any, any, infer P>
1307
+ ? P extends true
1308
+ ? never
1309
+ : K
1310
+ : never;
1311
+ }[keyof S];
1312
+
1313
+ /**
1314
+ * Parsed data shape with streamed `stream()` fields removed.
1315
+ *
1316
+ * @template S Form shape
1317
+ */
1318
+ type NonStreamShape<S extends Shape> = Pick<S, NonStreamNames<S>>;
1319
+
1320
+ /**
1321
+ * Parsed form data output.
1322
+ *
1323
+ * @template S Form shape
1324
+ */
1325
+ export type Data<S extends Shape> = Schema.Infer<NonStreamShape<S>>;
1326
+
1327
+ /**
1328
+ * Form parse result.
1329
+ *
1330
+ * @template S Form shape
1331
+ * @template M Extra invalid result metadata
1332
+ */
1333
+ export type Result<
1334
+ S extends Shape,
1335
+ M extends object = {},
1336
+ > = Schema.Parse.Result<
1337
+ Data<S>,
1338
+ {
1339
+ /** Encoded URL search param field state */
1340
+ readonly search: Result.Search;
1341
+
1342
+ /** Invalid parses do not expose remaining multipart parts */
1343
+ readonly stream?: never;
1344
+ } & M,
1345
+ {
1346
+ /** Rest of the multipart parts to stream */
1347
+ readonly stream?: AsyncGenerator<Multipart.Part>;
1348
+ }
1349
+ >;
1350
+
1351
+ export namespace Result {
1352
+ /** Form search params iterable */
1353
+ export type Search = [[(typeof Form.params)[1], string]] | undefined;
1354
+ }
1355
+ }
1356
+ }
1357
+
1358
+ /**
1359
+ * Form schema with JSX rendering capabilities.
1360
+ *
1361
+ * Parses `FormData` or `URLSearchParams` and generates form field
1362
+ * components.
1363
+ *
1364
+ * @template Shape Form field shape type
1365
+ */
1366
+ export class Form<Shape extends Form.Shape = Form.Shape> {
1367
+ /** Query param keys ordered as `[return, form]`. */
1368
+ static readonly params = ["_return", "_form"] as const;
1369
+
1370
+ /** Maximum encoded state size in bytes. */
1371
+ static readonly #maxStateBytes = 4 * Size.kb;
1372
+
1373
+ /** Maximum serialized size for a single persisted value. */
1374
+ static readonly #maxValueChars = 512;
1375
+
1376
+ /** Schema used to validate persisted form values. */
1377
+ static readonly #valueSchema = Schema.union([
1378
+ Schema.string(),
1379
+ Schema.number(),
1380
+ Schema.boolean(),
1381
+ Schema.array(Schema.string()),
1382
+ ]);
1383
+
1384
+ /** Form id. */
1385
+ readonly #id: string;
1386
+
1387
+ /** Field definitions. */
1388
+ readonly shape: Shape;
1389
+
1390
+ /** Field names in definition order. */
1391
+ readonly names: ShapeUtil.Name<Shape>[];
1392
+
1393
+ /** Maximum expected multipart parts derived from field cardinality. */
1394
+ readonly parts: number;
1395
+
1396
+ /**
1397
+ * Create a new form schema validator.
1398
+ *
1399
+ * @param shape Form fields
1400
+ */
1401
+ constructor(shape: Shape) {
1402
+ this.shape = shape;
1403
+ this.names = Object.keys(this.shape) as ShapeUtil.Name<Shape>[];
1404
+ this.#id = Checksum.djb2(this.names.join());
1405
+ this.parts = Object.values(this.shape).reduce(
1406
+ (sum, field) => sum + field.parts,
1407
+ 0,
1408
+ );
1409
+ }
1410
+
1411
+ /**
1412
+ * Merge `extra` into the current fields.
1413
+ *
1414
+ * @template E Extra field shape type
1415
+ * @param extra Extra fields or form schema to merge
1416
+ * @returns New form schema with merged fields
1417
+ */
1418
+ extend: {
1419
+ <E extends Form.Shape>(extra: E): Form<ShapeUtil.Extend<Shape, E>>;
1420
+ <E extends Form.Shape>(extra: Form<E>): Form<ShapeUtil.Extend<Shape, E>>;
1421
+ (extra: Form<any>): Form<ShapeUtil.Extend<Shape, Form.Shape>>;
1422
+ } = (extra: Form.Shape | Form<any>) =>
1423
+ Form.from(
1424
+ ShapeUtil.extend(this.shape, extra instanceof Form ? extra.shape : extra),
1425
+ );
1426
+
1427
+ /**
1428
+ * Keep only selected field names.
1429
+ *
1430
+ * @template N Selected field names
1431
+ * @param names Non-empty list of field names to keep
1432
+ * @returns New form schema with only selected fields
1433
+ */
1434
+ pick = <N extends ShapeUtil.Name<Shape>>(names: readonly [N, ...N[]]) =>
1435
+ Form.from(ShapeUtil.pick(this.shape, names));
1436
+
1437
+ /**
1438
+ * Remove selected field names.
1439
+ *
1440
+ * @template N Field names to remove
1441
+ * @param names Non-empty list of field names to remove
1442
+ * @returns New form schema without selected fields
1443
+ */
1444
+ omit = <N extends ShapeUtil.Name<Shape>>(names: readonly [N, ...N[]]) =>
1445
+ Form.from(ShapeUtil.omit(this.shape, names));
1446
+
1447
+ /**
1448
+ * @param name Unexpected form field name
1449
+ * @param path Parent path
1450
+ * @returns Schema issue for unexpected form field names
1451
+ */
1452
+ #unexpected(name: string, path: Schema.Issue.Path = []) {
1453
+ return new Schema.Issue(
1454
+ "known form data name",
1455
+ [...path, name],
1456
+ "Unexpected form data name",
1457
+ );
1458
+ }
1459
+
1460
+ /**
1461
+ * Sanitizes render-state values by removing unsupported or oversized entries.
1462
+ *
1463
+ * @param values Candidate values to keep
1464
+ * @param persist When `true`, only allow fields marked with `.persist()`
1465
+ * @returns Sanitized values
1466
+ */
1467
+ #sanitize(values?: Record<string, unknown>, persist = true) {
1468
+ const sanitized: Form.Value.Map<Shape> = {};
1469
+
1470
+ if (values) {
1471
+ for (const [name, value] of Object.entries(values)) {
1472
+ const field = this.shape[name];
1473
+
1474
+ if (
1475
+ field &&
1476
+ field.type !== "file" &&
1477
+ (!persist || FieldSchema.persisted(field)) &&
1478
+ value != null
1479
+ ) {
1480
+ const result = Form.#valueSchema.parse(value);
1481
+
1482
+ if (
1483
+ !result.issues &&
1484
+ JSON.stringify(result.data).length <= Form.#maxValueChars
1485
+ ) {
1486
+ sanitized[name as ShapeUtil.Name<Shape>] = result.data;
1487
+ }
1488
+ }
1489
+ }
1490
+
1491
+ if (Object.keys(sanitized).length) return sanitized;
1492
+ }
1493
+ }
1494
+
1495
+ /**
1496
+ * Decode form state from input.
1497
+ *
1498
+ * @param stateInput Current page URL
1499
+ */
1500
+ #decode(stateInput?: URL): Form.State<Shape> | undefined {
1501
+ if (stateInput) {
1502
+ const values = this.#sanitize(
1503
+ this.names.reduce<Record<string, unknown>>((data, name) => {
1504
+ if (stateInput.searchParams.has(name)) {
1505
+ const value = FieldSchema.read(
1506
+ this.shape[name]!,
1507
+ stateInput.searchParams,
1508
+ name,
1509
+ );
1510
+
1511
+ if (value != null) data[name] = value;
1512
+ }
1513
+
1514
+ return data;
1515
+ }, {}),
1516
+ false,
1517
+ );
1518
+ const encoded = stateInput.searchParams.get(Form.params[1]);
1519
+
1520
+ if (encoded && encoded.length <= Form.#maxStateBytes * 2) {
1521
+ try {
1522
+ const result = Schema.string()
1523
+ .json(
1524
+ Schema.object({
1525
+ id: Schema.literal(this.#id),
1526
+ issues: Schema.array(
1527
+ Schema.object({
1528
+ expected: Schema.string(),
1529
+ path: Schema.array(
1530
+ Schema.union([Schema.string(), Schema.number()]),
1531
+ ),
1532
+ message: Schema.string(),
1533
+ }).transform(
1534
+ (issue) =>
1535
+ new Schema.Issue(
1536
+ issue.expected,
1537
+ issue.path,
1538
+ issue.message,
1539
+ ),
1540
+ ),
1541
+ ).optional(),
1542
+ values: Schema.object(
1543
+ this.names.reduce<Schema.Object.Shape>((shape, name) => {
1544
+ shape[name] = Form.#valueSchema.optional();
1545
+
1546
+ return shape;
1547
+ }, {}),
1548
+ ).optional(),
1549
+ }),
1550
+ )
1551
+ .parse(Codec.decode(Codec.Base64Url.decode(encoded)));
1552
+
1553
+ if (result.data?.id === this.#id) {
1554
+ const current = this.#sanitize(result.data.values);
1555
+
1556
+ return {
1557
+ ...(result.data as Form.State<Shape>),
1558
+ values:
1559
+ (values || current) &&
1560
+ ({ ...values, ...current } as Form.Value.Map<Shape>),
1561
+ };
1562
+ }
1563
+ } catch {}
1564
+ }
1565
+
1566
+ return values && { id: this.#id, values };
1567
+ }
1568
+ }
1569
+
1570
+ /**
1571
+ * Parse and validate form data.
1572
+ *
1573
+ * @param source FormData, URLSearchParams, or Multipart to parse
1574
+ * @param path Internal path reference
1575
+ * @returns Parsed result
1576
+ */
1577
+ parse = async (
1578
+ source: FormData | URLSearchParams | Multipart,
1579
+ path: Schema.Issue.Path = [],
1580
+ ): Promise<Form.Parse.Result<Shape>> => {
1581
+ const data: Record<string, unknown> = {};
1582
+ const issues: Schema.Issue[] = [];
1583
+ const values: Record<string, unknown> = {};
1584
+ let form: FormData | URLSearchParams;
1585
+ let stream: AsyncGenerator<Multipart.Part> | undefined;
1586
+
1587
+ if (source instanceof Multipart) {
1588
+ form = new FormData();
1589
+ const iter = source[Symbol.asyncIterator]();
1590
+
1591
+ let current: IteratorResult<Multipart.Part>;
1592
+
1593
+ while ((current = await iter.next()) && !current.done) {
1594
+ const part = current.value;
1595
+
1596
+ if (part.name) {
1597
+ const field = this.shape[part.name];
1598
+
1599
+ if (!field) {
1600
+ issues.push(this.#unexpected(part.name, path));
1601
+ } else if (field.streaming) {
1602
+ // expose current and rest of the parts to the user
1603
+ stream = (async function* () {
1604
+ try {
1605
+ // have to yield the current part first
1606
+ // this is why the multipart can't be passed directly
1607
+ yield part;
1608
+
1609
+ let next: IteratorResult<Multipart.Part>;
1610
+
1611
+ while ((next = await iter.next()) && !next.done) {
1612
+ yield next.value;
1613
+ }
1614
+ } finally {
1615
+ try {
1616
+ await iter.return?.();
1617
+ } catch {}
1618
+ }
1619
+ })();
1620
+
1621
+ break;
1622
+ } else {
1623
+ form.append(part.name, await part.value());
1624
+ }
1625
+ }
1626
+ }
1627
+ } else if (source instanceof FormData) {
1628
+ form = source;
1629
+
1630
+ for (const name of new Set(source.keys())) {
1631
+ if (!this.shape[name]) issues.push(this.#unexpected(name, path));
1632
+ }
1633
+ } else {
1634
+ // allow passthrough for URLSearchParams
1635
+ form = source;
1636
+ }
1637
+
1638
+ for (const [name, field] of Object.entries(this.shape)) {
1639
+ if (!field.streaming) {
1640
+ const value = FieldSchema.read(field, form, name);
1641
+ const result = field.parse(value, [...path, name]);
1642
+
1643
+ if (result.issues) {
1644
+ issues.push(...result.issues);
1645
+ } else {
1646
+ data[name] = result.data;
1647
+ }
1648
+
1649
+ if (FieldSchema.persisted(field) && value != null) {
1650
+ values[name] = value;
1651
+ }
1652
+ }
1653
+ }
1654
+
1655
+ if (issues.length) {
1656
+ const result = new Schema.AggregateIssue(issues, this.#sanitize(values));
1657
+ let search: Form.Parse.Result.Search;
1658
+
1659
+ if (result.values) {
1660
+ // trim persisted values until the encoded state fits
1661
+ for (let i = this.names.length; i >= 0; i--) {
1662
+ // skip on the first time - try to encode everything first
1663
+ if (i !== this.names.length) delete result.values[this.names[i]!];
1664
+
1665
+ const state = Codec.encode(
1666
+ JSON.stringify({
1667
+ issues: result.issues,
1668
+ id: this.#id,
1669
+ ...(Object.keys(result.values).length
1670
+ ? { values: result.values }
1671
+ : {}),
1672
+ } satisfies Form.State),
1673
+ );
1674
+
1675
+ if (state.byteLength <= Form.#maxStateBytes) {
1676
+ search = [[Form.params[1], Codec.Base64Url.encode(state)]];
1677
+ break;
1678
+ }
1679
+ }
1680
+ } else {
1681
+ // fall back to issues-only state when nothing persisted.
1682
+ const state = Codec.encode(
1683
+ JSON.stringify({
1684
+ issues: result.issues,
1685
+ id: this.#id,
1686
+ } satisfies Form.State),
1687
+ );
1688
+
1689
+ if (state.byteLength <= Form.#maxStateBytes) {
1690
+ search = [[Form.params[1], Codec.Base64Url.encode(state)]];
1691
+ }
1692
+ }
1693
+
1694
+ if (stream) {
1695
+ // invalid result does not expose streamed parts, drain
1696
+ try {
1697
+ for await (const _ of stream);
1698
+ } catch {}
1699
+ }
1700
+
1701
+ return Object.assign(result, { search });
1702
+ }
1703
+
1704
+ return { data: data as Form.Parse.Data<Shape>, stream };
1705
+ };
1706
+
1707
+ /**
1708
+ * Render a single form field.
1709
+ *
1710
+ * @param props Component props
1711
+ * @example
1712
+ *
1713
+ * ```tsx
1714
+ * <User.Field name="username" />
1715
+ * ```
1716
+ */
1717
+ Field = (props: Field.Component.Props<Shape>) =>
1718
+ this.shape[props.name]!.render({
1719
+ ...props,
1720
+ state: this.#decode(props.state),
1721
+ });
1722
+
1723
+ /**
1724
+ * Render all form fields.
1725
+ *
1726
+ * @param props Component props
1727
+ * @example
1728
+ *
1729
+ * ```tsx
1730
+ * <User.Fields />
1731
+ * ```
1732
+ */
1733
+ Fields = (
1734
+ props: // partial because name is not required
1735
+ Partial<Field.Component.Props<Shape>> = {},
1736
+ ) => {
1737
+ const state = this.#decode(props.state); // pulled out to not call each map iteration
1738
+
1739
+ return this.names.map((name) =>
1740
+ this.shape[name]!.render({ ...props, name, state }),
1741
+ );
1742
+ };
1743
+
1744
+ /**
1745
+ * Access bound sub-components for a field.
1746
+ *
1747
+ * @template N Type of the form field name
1748
+ * @param props Field component props
1749
+ * @example
1750
+ *
1751
+ * ```tsx
1752
+ * const Radio = User.component({ name: "radio" });
1753
+ *
1754
+ * <Radio.Label />
1755
+ * <Radio.Control />
1756
+ * ```
1757
+ */
1758
+ component = <N extends ShapeUtil.Name<Shape>>(
1759
+ props: { name: N } & Field.Component.Props<Shape>,
1760
+ ): Field.Component<Shape[N]> =>
1761
+ this.shape[props.name]!.component({
1762
+ ...props,
1763
+ state: this.#decode(props.state),
1764
+ });
1765
+
1766
+ /**
1767
+ * Create a Form from a shape or use another Form.
1768
+ *
1769
+ * @template S Form field shape type
1770
+ * @param shape Form fields
1771
+ */
1772
+ static from<S extends Form.Shape>(shape: S | Form<S>): Form<S> {
1773
+ return shape instanceof Form ? shape : new Form(shape);
1774
+ }
1775
+ }
1776
+
1777
+ /**
1778
+ * Represents a form field with parsing logic and rendering metadata.
1779
+ *
1780
+ * @template Output Output type of the field
1781
+ * @template Tag Tag name
1782
+ * @template Type Input type
1783
+ * @template Values Persisted field value type
1784
+ * @template Stream If the field should be streamed as a part
1785
+ */
1786
+ class FieldSchema<
1787
+ Output = unknown,
1788
+ Tag extends Field.Tag = "input",
1789
+ Type extends Field.Type = Field.Type,
1790
+ Values extends Field.Values | undefined = undefined,
1791
+ Stream extends boolean | undefined = undefined,
1792
+ > extends Schema<Output> {
1793
+ /** Read the value from form data */
1794
+ readonly #read: Field.Read;
1795
+
1796
+ /** Field type */
1797
+ readonly type: Type;
1798
+
1799
+ // tag and values are public so emitted .d.ts preserves
1800
+ // field discriminants for correct types
1801
+ /** Field tag */
1802
+ readonly tag: Tag;
1803
+
1804
+ /** Field values */
1805
+ readonly values: Values;
1806
+
1807
+ /** Maximum expected multipart part count for this field name. */
1808
+ readonly parts: number;
1809
+
1810
+ /** If the field should be streamed as a part */
1811
+ readonly streaming?: Stream;
1812
+
1813
+ /** If the field should persist invalid-state values. */
1814
+ readonly #persist: boolean;
1815
+
1816
+ /** Field options */
1817
+ readonly #options: Field.Options<Values, Tag>;
1818
+
1819
+ /**
1820
+ * Create a new field.
1821
+ *
1822
+ * @param options Field options
1823
+ * @param parse How to validate the input
1824
+ * @param read How to read the form data
1825
+ * @param parts Maximum expected multipart parts for this field
1826
+ * @param stream If this field should be streamed as a multipart part
1827
+ * @param persist If this field should persist invalid state values
1828
+ */
1829
+ constructor(
1830
+ options: Field.Options<Values, Tag>,
1831
+ parse: Schema<Output> | Schema.Parse.Constructor<Output>,
1832
+ // default to a single value, treating blank as missing
1833
+ read: Field.Read = (data, name) => data.get(name) || undefined,
1834
+ parts = 1,
1835
+ stream?: Stream,
1836
+ persist = false,
1837
+ ) {
1838
+ super(parse instanceof Schema ? parse.parse : parse);
1839
+
1840
+ this.#options = options;
1841
+ this.tag = (options.tag ?? "input") as Tag;
1842
+ this.values = options.values as Values;
1843
+ this.#read = read;
1844
+ this.type = options.props?.type as Type;
1845
+ this.parts = parts;
1846
+ this.streaming = stream;
1847
+ this.#persist = persist;
1848
+ }
1849
+
1850
+ /**
1851
+ * @param field Field instance
1852
+ * @param data Form data source
1853
+ * @param name HTML name attribute
1854
+ * @returns Raw field input
1855
+ */
1856
+ static read(
1857
+ field: Field.Any,
1858
+ data: FormData | URLSearchParams,
1859
+ name: string,
1860
+ ) {
1861
+ return field.#read(data, name);
1862
+ }
1863
+
1864
+ /**
1865
+ * Stream this field as a multipart request `Part`.
1866
+ *
1867
+ * @returns Part field
1868
+ */
1869
+ stream(): Field.Instance<Output, Tag, Type, Values, true> {
1870
+ return new FieldSchema<Output, Tag, Type, Values, true>(
1871
+ this.#options,
1872
+ this.parse,
1873
+ this.#read,
1874
+ this.parts,
1875
+ true,
1876
+ this.#persist,
1877
+ );
1878
+ }
1879
+
1880
+ /**
1881
+ * Persist this field in the encoded invalid form state.
1882
+ *
1883
+ * Use this for non-sensitive values that should refill after an invalid
1884
+ * redirect.
1885
+ *
1886
+ * @returns Field that persists submitted values across invalid redirects
1887
+ */
1888
+ persist<
1889
+ U extends Tag extends "input" ? Exclude<Type, "password" | "file"> : Type,
1890
+ >(
1891
+ this: Field.Instance<Output, Tag, U, Values, Stream>,
1892
+ ): Field.Instance<Output, Tag, U, Values, Stream>;
1893
+ persist() {
1894
+ return new FieldSchema<Output, Tag, Type, Values, Stream>(
1895
+ this.#options,
1896
+ this.parse,
1897
+ this.#read,
1898
+ this.parts,
1899
+ this.streaming,
1900
+ true,
1901
+ );
1902
+ }
1903
+
1904
+ /**
1905
+ * Derive a new Field from the current instance type.
1906
+ *
1907
+ * @template O Output type of the new Field
1908
+ * @param parse Parse function that validates and transforms input
1909
+ * @returns New `Field` instance
1910
+ */
1911
+ override derive<O>(
1912
+ parse: Schema.Parse.Constructor<O>,
1913
+ ): Field.Instance<O, Tag, Type, Values, Stream> {
1914
+ return new FieldSchema<O, Tag, Type, Values, Stream>(
1915
+ this.#options,
1916
+ parse,
1917
+ this.#read,
1918
+ this.parts,
1919
+ this.streaming,
1920
+ this.#persist,
1921
+ );
1922
+ }
1923
+
1924
+ /**
1925
+ * @template S Form shape type
1926
+ * @param props Field control props
1927
+ * @returns Field component with sub-components
1928
+ */
1929
+ component<S extends Form.Shape>(
1930
+ props: Field.Component.Props<S, false>,
1931
+ ): Field.Component<this>;
1932
+ component<S extends Form.Shape>({
1933
+ state,
1934
+ ...props
1935
+ }: Field.Component.Props<S, false>): unknown {
1936
+ const value = state?.values?.[props.name];
1937
+ const issue = state?.issues?.find((i) => i.path[0] === props.name);
1938
+ const issueId = issue && `${props.name}-issue`;
1939
+ const hidden = this.type === "hidden";
1940
+ const { label = props.name, ...control } = {
1941
+ id: props.name,
1942
+ autofocus: issue && state?.issues?.[0] === issue,
1943
+ "aria-invalid": issue && "true",
1944
+ "aria-describedby": issueId,
1945
+ ...this.#options.props,
1946
+ ...props,
1947
+ };
1948
+
1949
+ const Issue = (data: Field.Component.Issue = {}) =>
1950
+ issue && // render nothing if no issue
1951
+ !hidden &&
1952
+ jsx("p", {
1953
+ id: issueId,
1954
+ children: issue.message,
1955
+ "data-issue": issue && state!.issues!.indexOf(issue), // issue index starting from 0
1956
+ ...data,
1957
+ });
1958
+
1959
+ if (this.values && this.tag !== "select") {
1960
+ // radio/checkboxes
1961
+ // make multiple ids for the group so all don't have the same id
1962
+ const groupId = (value: string) =>
1963
+ `${control.name}-${value}`.toLowerCase();
1964
+
1965
+ const Control = (
1966
+ data: Field.Component.Control.Group<"input", Field.Values>,
1967
+ ) =>
1968
+ jsx(this.tag, {
1969
+ ...control,
1970
+ id: groupId(data.value),
1971
+ // autofocus only the first input in the group
1972
+ autofocus: control.autofocus && data.value === this.values?.[0],
1973
+ checked: Array.isArray(value)
1974
+ ? value.includes(data.value) // checkboxes
1975
+ : value === data.value, // radio
1976
+ ...data,
1977
+ });
1978
+
1979
+ const Label = ({
1980
+ value,
1981
+ ...rest
1982
+ }: Field.Component.Label.Group<Field.Values>) =>
1983
+ jsx("label", { for: groupId(value), children: value, ...rest });
1984
+
1985
+ return {
1986
+ Issue,
1987
+ Label,
1988
+ Control,
1989
+ Root: (data: Field.Component.Root = {}) => jsx("fieldset", data),
1990
+ Option: ({
1991
+ value,
1992
+ ...rest
1993
+ }: Field.Component.Option.Input<Field.Values>) =>
1994
+ jsx("div", {
1995
+ children: [Control({ value }), Label({ value })],
1996
+ ...rest,
1997
+ }),
1998
+ Legend: (data: Field.Component.Legend = {}) =>
1999
+ jsx("legend", { children: label, ...data }),
2000
+ ...this,
2001
+ };
2002
+ }
2003
+
2004
+ return {
2005
+ Issue,
2006
+ Root: (data: Field.Component.Root = {}) =>
2007
+ hidden ? Fragment(data) : jsx("div", data),
2008
+ Label: (data: Field.Component.Label = {}) =>
2009
+ !hidden && jsx("label", { for: control.id, children: label, ...data }),
2010
+ Control: (data?: Field.Component.Control<Tag>) => {
2011
+ const attrs = { ...control, ...data };
2012
+
2013
+ if (value !== undefined) {
2014
+ if (this.tag === "textarea") {
2015
+ attrs.children = value;
2016
+ } else if (this.tag === "input") {
2017
+ if (this.type === "checkbox") {
2018
+ attrs.checked = value;
2019
+ } else {
2020
+ attrs.value = value;
2021
+ }
2022
+ }
2023
+ }
2024
+
2025
+ return jsx(this.tag, attrs);
2026
+ },
2027
+ Option:
2028
+ // select
2029
+ this.values &&
2030
+ ((data: Field.Component.Option<Field.Values>) =>
2031
+ jsx("option", {
2032
+ children: data.value,
2033
+ selected: Array.isArray(value)
2034
+ ? value.includes(data.value) // multiselect
2035
+ : value === data.value,
2036
+ ...data,
2037
+ })),
2038
+ ...this,
2039
+ };
2040
+ }
2041
+
2042
+ /**
2043
+ * @template S Form shape type
2044
+ * @param props Field control props
2045
+ * @returns Input group component
2046
+ */
2047
+ #Group<S extends Form.Shape>(
2048
+ this: FieldSchema<Output, "input", "radio" | "checkbox", Field.Values>,
2049
+ props: Field.Component.Props<S, false>,
2050
+ ) {
2051
+ const c = this.component(props);
2052
+
2053
+ return c.Root({
2054
+ children: [
2055
+ // @ts-expect-error - `#Group` runs for grouped inputs, includes `Legend` with label
2056
+ c.Legend(),
2057
+ this.values.map((value: string) => {
2058
+ return jsx("div", {
2059
+ children: [c.Control({ value }), c.Label({ value })],
2060
+ });
2061
+ }),
2062
+ c.Issue(),
2063
+ ],
2064
+ });
2065
+ }
2066
+
2067
+ /**
2068
+ * @template S Form shape type
2069
+ * @param props Field control props
2070
+ * @returns Select component
2071
+ */
2072
+ #Select<S extends Form.Shape>(
2073
+ this: FieldSchema<Output, "select", Type, Field.Values>,
2074
+ props: Field.Component.Props<S, false>,
2075
+ ) {
2076
+ const c = this.component(props);
2077
+
2078
+ return c.Root({
2079
+ children: [
2080
+ c.Label(),
2081
+ c.Control({
2082
+ children: this.values.map((value: string) => c.Option({ value })),
2083
+ }),
2084
+ c.Issue(),
2085
+ ],
2086
+ });
2087
+ }
2088
+
2089
+ /**
2090
+ * @template S Form shape type
2091
+ * @param props Field control props
2092
+ * @returns Default input component
2093
+ */
2094
+ #Input<S extends Form.Shape>(props: Field.Component.Props<S, false>) {
2095
+ const c = this.component(props);
2096
+
2097
+ return c.Root({ children: [c.Label(), c.Control(), c.Issue()] });
2098
+ }
2099
+
2100
+ /**
2101
+ * @template S Form shape type
2102
+ * @param props Field control props including `name` of the field to render
2103
+ * @returns Component that renders the HTML field with default structure
2104
+ */
2105
+ render<S extends Form.Shape>(props: Field.Component.Props<S, false>) {
2106
+ if (this.values) {
2107
+ if (this.tag === "select") return this.#Select(props);
2108
+
2109
+ return this.#Group(props);
2110
+ }
2111
+
2112
+ return this.#Input(props);
2113
+ }
2114
+
2115
+ /**
2116
+ * @param field Field definition
2117
+ * @returns `true` when the field persists invalid-state values
2118
+ */
2119
+ static persisted(field: Field.Any) {
2120
+ return field.#persist;
2121
+ }
2122
+ }
2123
+
2124
+ export namespace Field {
2125
+ /**
2126
+ * Base options to create a Field.
2127
+ *
2128
+ * @template V Type of the values for group inputs
2129
+ * @template T Tag name
2130
+ */
2131
+ export interface Options<
2132
+ V extends Values | undefined = undefined,
2133
+ T extends Tag = Tag,
2134
+ > {
2135
+ /**
2136
+ * Tag name.
2137
+ *
2138
+ * @default "input"
2139
+ */
2140
+ readonly tag?: T;
2141
+
2142
+ /** Values are used for group inputs */
2143
+ readonly values?: V;
2144
+
2145
+ /** Field props */
2146
+ readonly props?: Props;
2147
+ }
2148
+
2149
+ /**
2150
+ * Raw field value before schema parsing.
2151
+ *
2152
+ * Single-value fields read one entry, multi-value fields read all entries,
2153
+ * and checkboxes read presence.
2154
+ */
2155
+ export type Input =
2156
+ | FormDataEntryValue
2157
+ | FormDataEntryValue[]
2158
+ | boolean
2159
+ | undefined;
2160
+
2161
+ /**
2162
+ * @param data FormData or URLSearchParams
2163
+ * @param name HTML name attribute
2164
+ * @returns Resolved value read from the form data
2165
+ */
2166
+ export type Read = (data: FormData | URLSearchParams, name: string) => Input;
2167
+
2168
+ /** Form field tag name */
2169
+ export type Tag = "input" | "textarea" | "select";
2170
+
2171
+ /** `<input type=...>` */
2172
+ export type Type = JSX.IntrinsicElements["input"]["type"];
2173
+
2174
+ /** Value type for select and radio options */
2175
+ export type Values = readonly [string, ...string[]];
2176
+
2177
+ /** Field instance type */
2178
+ export type Instance<
2179
+ Output = unknown,
2180
+ Tag extends Field.Tag = "input",
2181
+ Type extends Field.Type = Field.Type,
2182
+ Values extends Field.Values | undefined = undefined,
2183
+ Stream extends boolean | undefined = undefined,
2184
+ > = FieldSchema<Output, Tag, Type, Values, Stream>;
2185
+
2186
+ /** Any field - `<input type=...>` / `<select>` / `<textarea>` */
2187
+ export type Any = Instance<
2188
+ any,
2189
+ Tag,
2190
+ Type,
2191
+ Values | undefined,
2192
+ boolean | undefined
2193
+ >;
2194
+
2195
+ /**
2196
+ * Obtain the tag name of a field.
2197
+ *
2198
+ * @template F Field
2199
+ */
2200
+ export type TagOf<F extends Any> =
2201
+ F extends Instance<any, infer T, Field.Type, Field.Values | undefined>
2202
+ ? T
2203
+ : Tag;
2204
+
2205
+ export namespace Component {
2206
+ /**
2207
+ * Component props available to users to pass into the
2208
+ * constructed `<Field />` component.
2209
+ *
2210
+ * @template S Form shape type
2211
+ * @template I `true` the state is a `URL`, `false` is just `State`
2212
+ */
2213
+ export type Props<S extends Form.Shape, I extends boolean = true> = {
2214
+ /** Field name attribute */
2215
+ readonly name: ShapeUtil.Name<S>;
2216
+
2217
+ /** Form state */
2218
+ readonly state?: I extends true ? URL : Form.State<S>;
2219
+ } & Field.Props;
2220
+
2221
+ /** Root element for the Field component */
2222
+ export type Root = JSX.IntrinsicElements["div"];
2223
+
2224
+ export namespace Root {
2225
+ /** Root for input groups */
2226
+ export type Group = JSX.IntrinsicElements["fieldset"];
2227
+ }
2228
+
2229
+ /** `<Field.Legend />` component props */
2230
+ export type Legend = JSX.IntrinsicElements["legend"];
2231
+
2232
+ /** `<Field.Issue />` component props */
2233
+ export type Issue = JSX.IntrinsicElements["p"];
2234
+
2235
+ /**
2236
+ * `<Field.Control />` component props
2237
+ *
2238
+ * @template T Tag name
2239
+ */
2240
+ export type Control<T extends Tag> = T extends "textarea"
2241
+ ? JSX.IntrinsicElements["textarea"]
2242
+ : T extends "select"
2243
+ ? JSX.IntrinsicElements["select"]
2244
+ : JSX.IntrinsicElements["input"];
2245
+
2246
+ export namespace Control {
2247
+ /**
2248
+ * `<Field.Control />` component props for group input element.
2249
+ *
2250
+ * @template T Tag name
2251
+ * @template V Option values
2252
+ */
2253
+ export type Group<T extends Tag, V extends Values> = Control<T> & {
2254
+ readonly value: V[number];
2255
+ };
2256
+ }
2257
+
2258
+ /** `<Field.Label />` component props */
2259
+ export type Label = JSX.IntrinsicElements["label"];
2260
+
2261
+ export namespace Label {
2262
+ /**
2263
+ * `<Field.Label />` component props for group input element.
2264
+ *
2265
+ * @template V Option values
2266
+ */
2267
+ export type Group<V extends Values> = Label & {
2268
+ readonly value: V[number];
2269
+ };
2270
+ }
2271
+
2272
+ /**
2273
+ * `<Field.Option />` select component props
2274
+ *
2275
+ * @template V Values
2276
+ */
2277
+ export type Option<V extends Values> = JSX.IntrinsicElements["option"] & {
2278
+ /** Option value */
2279
+ readonly value: V[number];
2280
+ };
2281
+
2282
+ export namespace Option {
2283
+ /**
2284
+ * `<Field.Option />` input group component props
2285
+ *
2286
+ * Wrapper for both the `<Label />` and `<Input />` components.
2287
+ *
2288
+ * @template V Values
2289
+ */
2290
+ export type Input<V extends Values> = JSX.IntrinsicElements["div"] & {
2291
+ /** Option value */
2292
+ readonly value: V[number];
2293
+ };
2294
+ }
2295
+ }
2296
+
2297
+ /**
2298
+ * Base Field component object that contains sub-components,
2299
+ * use for fine grained rendering control.
2300
+ *
2301
+ * @template F Field
2302
+ */
2303
+ export type Component<F extends Any> = Readonly<
2304
+ {
2305
+ /**
2306
+ * @param props Issue props
2307
+ * @returns Issue container paragraph
2308
+ */
2309
+ Issue: (props?: Component.Issue) => JSX.Element;
2310
+ } & (F extends Instance<any, "select", Field.Type, infer V>
2311
+ ? V extends Values
2312
+ ? // select
2313
+ {
2314
+ /** Select option values */
2315
+ values: V;
2316
+
2317
+ /**
2318
+ * @param props Root props
2319
+ * @returns Root container div
2320
+ */
2321
+ Root: (props?: Component.Root) => JSX.Element;
2322
+
2323
+ /**
2324
+ * @param props Label props
2325
+ * @returns Label element
2326
+ */
2327
+ Label: (props?: Component.Label) => JSX.Element;
2328
+
2329
+ /**
2330
+ * @param props Control props
2331
+ * @returns Control select element
2332
+ */
2333
+ Control: (props?: Component.Control<"select">) => JSX.Element;
2334
+
2335
+ /**
2336
+ * @param props Option props
2337
+ * @returns Select option element
2338
+ */
2339
+ Option: (props: Component.Option<V>) => JSX.Element;
2340
+ }
2341
+ : never
2342
+ : F extends Instance<any, "input", Field.Type, infer V>
2343
+ ? V extends Values
2344
+ ? // radio/checkboxes
2345
+ {
2346
+ /** Input group values */
2347
+ values: V;
2348
+
2349
+ /**
2350
+ * @param props Root props
2351
+ * @returns Root container fieldset
2352
+ */
2353
+ Root: (props?: Component.Root.Group) => JSX.Element;
2354
+
2355
+ /**
2356
+ * @param props Legend element props
2357
+ * @returns Legend element
2358
+ */
2359
+ Legend: (props?: Component.Legend) => JSX.Element;
2360
+
2361
+ /**
2362
+ * @param props Label props including `value`
2363
+ * @returns Label element
2364
+ */
2365
+ Label: (props: Component.Label.Group<V>) => JSX.Element;
2366
+
2367
+ /**
2368
+ * @param props Control props
2369
+ * @returns Control input element
2370
+ */
2371
+ Control: (
2372
+ props?: Component.Control.Group<"input", V>,
2373
+ ) => JSX.Element;
2374
+
2375
+ /**
2376
+ * @param props Option props
2377
+ * @returns Both label and input elements together
2378
+ */
2379
+ Option: (props: Component.Option.Input<V>) => JSX.Element;
2380
+ }
2381
+ : // regular input
2382
+ {
2383
+ /**
2384
+ * @param props Root props
2385
+ * @returns Root container div
2386
+ */
2387
+ Root: (props?: Component.Root) => JSX.Element;
2388
+
2389
+ /**
2390
+ * @param props Label props
2391
+ * @returns Label element
2392
+ */
2393
+ Label: (props?: Component.Label) => JSX.Element;
2394
+
2395
+ /**
2396
+ * @param props Control props
2397
+ * @returns Control input element
2398
+ */
2399
+ Control: (props?: Component.Control<"input">) => JSX.Element;
2400
+ }
2401
+ : // textarea
2402
+ {
2403
+ /**
2404
+ * @param props Root props
2405
+ * @returns Root container div
2406
+ */
2407
+ Root: (props?: Component.Root) => JSX.Element;
2408
+
2409
+ /**
2410
+ * @param props Label props
2411
+ * @returns Label element
2412
+ */
2413
+ Label: (props?: Component.Label) => JSX.Element;
2414
+
2415
+ /**
2416
+ * @param props Control props
2417
+ * @returns Control textarea element
2418
+ */
2419
+ Control: (props?: Component.Control<"textarea">) => JSX.Element;
2420
+ })
2421
+ >;
2422
+
2423
+ /** Any field props */
2424
+ export type Props = Props.Input | Props.Select | Props.Textarea;
2425
+
2426
+ export namespace Props {
2427
+ /** Extra props in addition to HTML attributes */
2428
+ interface Meta {
2429
+ /** Field label */
2430
+ readonly label?: string;
2431
+ }
2432
+
2433
+ /** Props for `<input>` fields */
2434
+ export type Input = Meta & JSX.IntrinsicElements["input"];
2435
+
2436
+ /** Props for `<select>` fields */
2437
+ export type Select = Meta & JSX.IntrinsicElements["select"];
2438
+
2439
+ /** Props for `<textarea>` fields */
2440
+ export type Textarea = Meta & JSX.IntrinsicElements["textarea"];
2441
+ }
2442
+ }
2443
+
2444
+ /** Field factory functions */
2445
+ export class Field {
2446
+ // this is used instead of the defaults for example "Expected string"
2447
+ // since "string" doesn't make sense to end users
2448
+ /** Default message for required field values. */
2449
+ static readonly #required = "Required field";
2450
+
2451
+ /**
2452
+ * @param value Raw form entry
2453
+ * @returns `true` when the file input contains a real file value
2454
+ */
2455
+ static #nonEmptyFile(value: FormDataEntryValue | null) {
2456
+ return value instanceof File && (value.name !== "" || value.size > 0);
2457
+ }
2458
+
2459
+ /**
2460
+ * @param data Form data
2461
+ * @param name HTML name attribute
2462
+ * @returns Field values or `undefined` when missing
2463
+ */
2464
+ static #readMany(data: FormData | URLSearchParams, name: string) {
2465
+ const value = data.getAll(name);
2466
+
2467
+ return value.length ? value : undefined;
2468
+ }
2469
+
2470
+ /**
2471
+ * @param props Input props
2472
+ * @returns Generic input field
2473
+ */
2474
+ static #input<T extends Field.Type>(
2475
+ props: Field.Props.Input & { type: T },
2476
+ ): Field.Instance<string, "input", T> {
2477
+ return new FieldSchema({ props }, Schema.string(Field.#required));
2478
+ }
2479
+
2480
+ /**
2481
+ * @param props Input props
2482
+ * @returns Text input field
2483
+ */
2484
+ static text(
2485
+ props?: Field.Props.Input,
2486
+ ): Field.Instance<string, "input", "text"> {
2487
+ return Field.#input({ ...props, type: "text" });
2488
+ }
2489
+
2490
+ /**
2491
+ * @param props Input props
2492
+ * @returns Password input field
2493
+ */
2494
+ static password(
2495
+ props?: Field.Props.Input,
2496
+ ): Field.Instance<string, "input", "password"> {
2497
+ return Field.#input({ ...props, type: "password" });
2498
+ }
2499
+
2500
+ /**
2501
+ * @param props Input props
2502
+ * @returns Search input field
2503
+ */
2504
+ static search(
2505
+ props?: Field.Props.Input,
2506
+ ): Field.Instance<string, "input", "search"> {
2507
+ return Field.#input({ ...props, type: "search" });
2508
+ }
2509
+
2510
+ /**
2511
+ * @param props Input props
2512
+ * @returns Telephone input field
2513
+ */
2514
+ static tel(
2515
+ props?: Field.Props.Input,
2516
+ ): Field.Instance<string, "input", "tel"> {
2517
+ return Field.#input({ ...props, type: "tel" });
2518
+ }
2519
+
2520
+ /**
2521
+ * @param props Input props
2522
+ * @returns Color input field
2523
+ */
2524
+ static color(
2525
+ props?: Field.Props.Input,
2526
+ ): Field.Instance<string, "input", "color"> {
2527
+ return Field.#input({ ...props, type: "color" });
2528
+ }
2529
+
2530
+ /**
2531
+ * @param props Input props
2532
+ * @returns Hidden input field
2533
+ */
2534
+ static hidden(
2535
+ props?: Field.Props.Input,
2536
+ ): Field.Instance<string, "input", "hidden"> {
2537
+ return Field.#input({ ...props, type: "hidden" });
2538
+ }
2539
+
2540
+ /**
2541
+ * @param props Input props
2542
+ * @returns Date input field
2543
+ */
2544
+ static date(
2545
+ props?: Field.Props.Input,
2546
+ ): Field.Instance<string, "input", "date"> {
2547
+ return Field.#input({ ...props, type: "date" });
2548
+ }
2549
+
2550
+ /**
2551
+ * @param props Input props
2552
+ * @returns Datetime input field
2553
+ */
2554
+ static datetime(
2555
+ props?: Field.Props.Input,
2556
+ ): Field.Instance<string, "input", "datetime-local"> {
2557
+ return Field.#input({ ...props, type: "datetime-local" });
2558
+ }
2559
+
2560
+ /**
2561
+ * @param props Input props
2562
+ * @returns Month input field
2563
+ */
2564
+ static month(
2565
+ props?: Field.Props.Input,
2566
+ ): Field.Instance<string, "input", "month"> {
2567
+ return Field.#input({ ...props, type: "month" });
2568
+ }
2569
+
2570
+ /**
2571
+ * @param props Input props
2572
+ * @returns Week input field
2573
+ */
2574
+ static week(
2575
+ props?: Field.Props.Input,
2576
+ ): Field.Instance<string, "input", "week"> {
2577
+ return Field.#input({ ...props, type: "week" });
2578
+ }
2579
+
2580
+ /**
2581
+ * @param props Input props
2582
+ * @returns Time input field
2583
+ */
2584
+ static time(
2585
+ props?: Field.Props.Input,
2586
+ ): Field.Instance<string, "input", "time"> {
2587
+ return Field.#input({ ...props, type: "time" });
2588
+ }
2589
+
2590
+ /**
2591
+ * Validates email string.
2592
+ *
2593
+ * @param props Input props
2594
+ * @param message Issue message when invalid
2595
+ * @returns Email input field
2596
+ */
2597
+ static email(
2598
+ props?: Field.Props.Input,
2599
+ message?: string,
2600
+ ): Field.Instance<string, "input", "email"> {
2601
+ return new FieldSchema(
2602
+ { props: { ...props, type: "email" } },
2603
+ Schema.string(Field.#required).email(message),
2604
+ );
2605
+ }
2606
+
2607
+ /**
2608
+ * Validates parsable URL.
2609
+ *
2610
+ * @param props Input props
2611
+ * @param message Issue message when invalid
2612
+ * @returns URL input field
2613
+ */
2614
+ static url(
2615
+ props?: Field.Props.Input,
2616
+ message?: string,
2617
+ ): Field.Instance<string, "input", "url"> {
2618
+ return new FieldSchema(
2619
+ { props: { ...props, type: "url" } },
2620
+ Schema.string(Field.#required).url(message),
2621
+ );
2622
+ }
2623
+
2624
+ /**
2625
+ * @param props Input props
2626
+ * @returns Input field
2627
+ */
2628
+ static #number<T extends "number" | "range">(
2629
+ props: Field.Props.Input & { type: T },
2630
+ ): Field.Instance<number, "input", T> {
2631
+ return new FieldSchema(
2632
+ { props },
2633
+ Schema.number(Field.#required).preprocess((value) =>
2634
+ // form submissions read numeric controls as strings
2635
+ value == null || value === "" ? undefined : Number(value),
2636
+ ),
2637
+ );
2638
+ }
2639
+
2640
+ /**
2641
+ * Coerces to number.
2642
+ *
2643
+ * @param props Input props
2644
+ * @returns Number input field
2645
+ */
2646
+ static number(
2647
+ props?: Field.Props.Input,
2648
+ ): Field.Instance<number, "input", "number"> {
2649
+ return Field.#number({ ...props, type: "number" });
2650
+ }
2651
+
2652
+ /**
2653
+ * Coerces to number.
2654
+ *
2655
+ * @param props Input props
2656
+ * @returns Range input field
2657
+ */
2658
+ static range(
2659
+ props?: Field.Props.Input,
2660
+ ): Field.Instance<number, "input", "range"> {
2661
+ return Field.#number({ ...props, type: "range" });
2662
+ }
2663
+
2664
+ /**
2665
+ * - unchecked => key missing => `false`
2666
+ * - checked => key present => `true`
2667
+ *
2668
+ * @param props Input props
2669
+ * @returns Checkbox input field
2670
+ */
2671
+ static checkbox(
2672
+ props?: Field.Props.Input,
2673
+ ): Field.Instance<boolean, "input", "checkbox"> {
2674
+ return new FieldSchema(
2675
+ { props: { ...props, type: "checkbox" } },
2676
+ Schema.boolean(),
2677
+ (formData, name) => formData.has(name),
2678
+ );
2679
+ }
2680
+
2681
+ /**
2682
+ * @param props Input props
2683
+ * @returns File input field
2684
+ */
2685
+ static file(
2686
+ props?: Field.Props.Input,
2687
+ ): Field.Instance<File, "input", "file"> {
2688
+ return new FieldSchema(
2689
+ { props: { ...props, type: "file" } },
2690
+ Schema.instance(File, Field.#required),
2691
+ (data, name) => {
2692
+ const value = data.get(name);
2693
+
2694
+ return (Field.#nonEmptyFile(value) && value) || undefined;
2695
+ },
2696
+ );
2697
+ }
2698
+
2699
+ /**
2700
+ * @param props Input props
2701
+ * @returns Multiple file input field
2702
+ */
2703
+ static files(
2704
+ props?: Field.Props.Input,
2705
+ ): Field.Instance<File[], "input", "file"> {
2706
+ return new FieldSchema(
2707
+ { props: { ...props, type: "file", multiple: true } },
2708
+ Schema.array(Schema.instance(File, Field.#required), Field.#required),
2709
+ (data, name) => {
2710
+ const value = data.getAll(name).filter(Field.#nonEmptyFile);
2711
+
2712
+ return value.length ? value : undefined;
2713
+ },
2714
+ Infinity,
2715
+ );
2716
+ }
2717
+
2718
+ /**
2719
+ * @template V Value type
2720
+ * @param values Checkbox values
2721
+ * @param props Input props
2722
+ * @returns Checkbox group input field
2723
+ */
2724
+ static checkboxes<const V extends string>(
2725
+ values: readonly [V, ...V[]],
2726
+ props?: Field.Props.Input,
2727
+ ): Field.Instance<V[], "input", "checkbox", readonly [V, ...V[]]> {
2728
+ return new FieldSchema(
2729
+ { values, props: { ...props, type: "checkbox" } },
2730
+ Schema.array(Schema.enum(values, Field.#required), Field.#required),
2731
+ Field.#readMany,
2732
+ values.length,
2733
+ );
2734
+ }
2735
+
2736
+ /**
2737
+ * @template V Value type
2738
+ * @param values Radio button values
2739
+ * @param props Input props
2740
+ * @returns Radio group input field
2741
+ */
2742
+ static radio<const V extends string>(
2743
+ values: readonly [V, ...V[]],
2744
+ props?: Field.Props.Input,
2745
+ ): Field.Instance<V, "input", "radio", readonly [V, ...V[]]> {
2746
+ return new FieldSchema(
2747
+ { values, props: { ...props, type: "radio" } },
2748
+ Schema.enum(values, Field.#required),
2749
+ );
2750
+ }
2751
+
2752
+ /**
2753
+ * @param props Textarea props
2754
+ * @returns Textarea field
2755
+ */
2756
+ static textarea(
2757
+ props?: Field.Props.Textarea,
2758
+ ): Field.Instance<string, "textarea"> {
2759
+ return new FieldSchema(
2760
+ { tag: "textarea", props },
2761
+ Schema.string(Field.#required),
2762
+ );
2763
+ }
2764
+
2765
+ /**
2766
+ * @template V Value type
2767
+ * @param values Select options
2768
+ * @param props Select props
2769
+ * @returns Select field
2770
+ */
2771
+ static select<const V extends string>(
2772
+ values: readonly [V, ...V[]],
2773
+ props?: Field.Props.Select,
2774
+ ): Field.Instance<V, "select", Field.Type, readonly [V, ...V[]]> {
2775
+ return new FieldSchema(
2776
+ { tag: "select", values, props },
2777
+ Schema.enum(values, Field.#required),
2778
+ );
2779
+ }
2780
+
2781
+ /**
2782
+ * @template V Value type
2783
+ * @param values Select options
2784
+ * @param props Select props
2785
+ * @returns Multi-select field
2786
+ */
2787
+ static multiselect<const V extends string>(
2788
+ values: readonly [V, ...V[]],
2789
+ props?: Field.Props.Select,
2790
+ ): Field.Instance<V[], "select", Field.Type, readonly [V, ...V[]]> {
2791
+ return new FieldSchema(
2792
+ { tag: "select", values, props: { ...props, multiple: true } },
2793
+ Schema.array(Schema.enum(values, Field.#required), Field.#required),
2794
+ Field.#readMany,
2795
+ values.length,
2796
+ );
2797
+ }
2798
+ }