@warlock.js/seal 5.19.1 → 5.21.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.
@@ -1,149 +1,149 @@
1
- ---
2
- name: pick-seal-primitive
3
- description: "Picking the right primitive in @warlock.js/seal; use when you need to choose seal primitive."
4
- ---
5
-
6
- # Picking the right primitive
7
-
8
- This is the orientation skill — *which* primitive for *which* job. For the chainable methods on each (`.email()`, `.min()`, `.between()`, etc.), load the matching `*-methods.md` reference file in this skill folder.
9
-
10
- ## Strings
11
-
12
- ```ts
13
- v.string() // type: string — full surface in string-methods.md
14
- v.email() // shorthand for v.string().email()
15
- v.enum(["a", "b"]) // type: "a" | "b" — runs as v.string().oneOf, but the factory overload preserves the literal union
16
- ```
17
-
18
- Reach for `v.string()` for any text input. `v.email()` is just sugar — switch back to `v.string().email().min(...)` when you need extra rules.
19
-
20
- ## Numbers — pick by what you accept
21
-
22
- | Validator | Accepts | When |
23
- |---|---|---|
24
- | `v.number()` | any finite number | accepts both integers and floats |
25
- | `v.int()` | integers only | rejects `1.5` |
26
- | `v.float()` | finite, non-integer | rejects `1` |
27
- | `v.numeric()` | numeric strings + numbers | form/query inputs that arrive as `"42"` — coerces to number |
28
-
29
- All four share the same chain surface (see [`number-methods.md`](./number-methods.md)). Picking is about input acceptance, not chain power.
30
-
31
- ## Booleans & scalars
32
-
33
- ```ts
34
- v.boolean() // type: boolean — adds .accepted() / .declined() for form-style inputs
35
- v.scalar() // type: string | number | boolean — usually a smell pointing at a missing discriminator
36
- ```
37
-
38
- Use `v.scalar()` only when the field truly accepts any of the three primitives. If it's "one of N specific values across types", `v.literal(...)` is cleaner.
39
-
40
- ## Dates
41
-
42
- ```ts
43
- v.date() // type: Date — normalizes strings/timestamps to Date, rich rule surface
44
- v.instanceof(Date) // type: Date — raw instanceof, no normalization, no rules
45
- ```
46
-
47
- `v.date()` is the right tool 99% of the time — it ships `.min/.max/.before/.after/.weekDay/.minAge/...` and a built-in mutator that parses strings. `v.instanceof(Date)` is the escape hatch when you specifically need strict instance identity with zero coercion.
48
-
49
- ## Literals & instances
50
-
51
- ```ts
52
- v.literal("items") // type: "items"
53
- v.literal("draft", "published", "archived") // type: "draft" | "published" | "archived"
54
- v.literal(1, 2, 3) // type: 1 | 2 | 3
55
- v.literal(true) // type: true
56
-
57
- v.instanceof(File) // type: File
58
- v.instanceof(Buffer) // type: Buffer
59
- v.instanceof(MyClass) // type: MyClass
60
- ```
61
-
62
- **`v.literal` vs `v.string().oneOf([...])` vs `v.enum([...])`:**
63
-
64
- - `v.literal("a", "b")` infers as `"a" | "b"` (literal narrowing). **Use this for discriminator fields.**
65
- - `v.string().oneOf(["a", "b"])` infers as `string` (loses literal types). Use when broad type is fine.
66
- - `v.enum(["a", "b"])` runs the same `oneOf` rule at runtime (it builds a `StringValidator().oneOf(...)`), but the `v.enum` factory overload **preserves the literal union** — it infers `"a" | "b"`, not `string`. Pass a TS enum object (`v.enum(Direction)`) and it uses `Object.values`, inferring `Direction[keyof Direction]`.
67
-
68
- `**`v.literal("")` — the empty string is a value, not an absence.** `""` is accepted when it is one of the configured literals, and the field is still required to be *present*:
69
-
70
- ```ts
71
- const decorative = v.object({ decorative: v.literal(true), alt: v.literal("") });
72
-
73
- await v.validate(decorative, { decorative: true, alt: "" }); // valid
74
- await v.validate(decorative, { decorative: true, alt: "text" }); // invalid — not the literal
75
- await v.validate(decorative, { decorative: true }); // invalid — key missing
76
- ```
77
-
78
- That distinction matters wherever "empty" and "absent" mean different things — `alt=""` marks an image as decorative to a screen reader, while a missing `alt` is an authoring mistake. Add `.optional()` only when a missing key really is acceptable; a present value must still match the literal.
79
-
80
- :::note[Fixed in 4.9.2]
81
- Before 4.9.2 `v.literal("")` always failed with *"is required"*, and `.optional()` looked like a workaround while actually disabling the literal check — accepting `""`, `null`, and a missing key alike. `v.literal(0)` and `v.literal(false)` were never affected.
82
- :::
83
-
84
- `v.instanceof(Ctor)` for File/Buffer/Uint8Array/custom classes. Returns `{}` from `toJsonSchema()` (not representable). For OpenAPI `File`, attach `{ type: "string", format: "binary" }` manually after generation.
85
-
86
- ## `v.any` — escape hatch
87
-
88
- ```ts
89
- v.any() // type: any — skips validation entirely
90
- ```
91
-
92
- Reach for it when you genuinely don't care about the shape. Usually a smell — search PRs for it and ask whether a real schema would catch a class of bugs.
93
-
94
- ## Derived: `v.computed` and `v.managed`
95
-
96
- These two **don't validate input** — they produce a value as part of validation.
97
-
98
- ```ts
99
- v.object({
100
- firstName: v.string(),
101
- lastName: v.string(),
102
- fullName: v.computed<string>((data) => `${data.firstName} ${data.lastName}`),
103
- createdAt: v.managed<Date>(() => new Date()),
104
- createdBy: v.managed<string>((context) => context.context?.userId),
105
- });
106
- ```
107
-
108
- - **`v.computed`** runs after sibling validation; callback signature is `(data, context)` — `data` is the validated sibling object. Use for derived values (full name, hash of fields, computed totals). An optional second arg validates the result: `v.computed<string>(cb, v.string().min(3))`.
109
- - **`v.managed`** runs from `SchemaContext` only — callback signature is `(context)`. Caller-supplied extras passed to `validate(schema, data, { context })` land on `context.context`. Use for framework-injected values — timestamps, current user, request id. The callback is optional (`v.managed()`) for values the framework injects without a generator.
110
-
111
- Both are **skipped** when their parent `v.object` generates JSON Schema — they never appear in `properties`, since they're runtime-only and not part of the JSON contract an LLM or external API consumer reads. Calling `.toJsonSchema()` *directly* on a `v.computed` / `v.managed` validator **throws** (it's a programming error — let the parent object skip them).
112
-
113
- ## Quick map — "I need to validate…"
114
-
115
- | Need | Reach for |
116
- |---|---|
117
- | Email | `v.string().email()` or `v.email()` |
118
- | URL | `v.string().url()` |
119
- | UUID | `v.string().uuid()` (see [`string-methods.md`](./string-methods.md)) |
120
- | Number 0–100 | `v.number().between(0, 100)` |
121
- | Positive integer | `v.int().positive()` |
122
- | One of N constants | `v.literal(...values)` |
123
- | One of TS enum values | `v.enum(MyEnum)` |
124
- | Date in the past | `v.date().past()` |
125
- | File upload | `v.instanceof(File)` |
126
- | Class instance (not Date) | `v.instanceof(Ctor)` |
127
- | Discriminated union | see [`@warlock.js/seal/define-structural-shape/SKILL.md`](@warlock.js/seal/define-structural-shape/SKILL.md) |
128
- | Derived value (computed from siblings) | `v.computed<T>(callback)` |
129
- | Framework-injected value | `v.managed<T>(callback)` |
130
- | Free-form / pass-through | `v.any()` (only when you've thought about it) |
131
-
132
- ## Method-surface reference
133
-
134
- Each primitive's full method list lives in a sibling file:
135
-
136
- - [`string-methods.md`](./string-methods.md) — `.email` / `.url` / `.uuid` / `.pattern` / `.startsWith` / `.alpha` / `.trim` / `.slug` / `.mask` / `.base64Encode` / …
137
- - [`number-methods.md`](./number-methods.md) — `.min` / `.max` / `.between` / `.greaterThan` / `.positive` / `.even` / `.multipleOf` / `.minSibling` / `.round` / …
138
- - [`date-methods.md`](./date-methods.md) — `.min` / `.before` / `.after` / `.today` / `.past` / `.future` / `.weekDay` / `.minAge` / `.year` / `.quarter` / `.toISOString` / …
139
- - [`boolean-methods.md`](./boolean-methods.md) — `.accepted` / `.declined` / `.mustBeTrue` / `.mustBeFalse` / `.acceptedIf` / `.declinedWithout` / …
140
-
141
- For cross-cutting modifiers (`.optional`/`.nullable`/`.default`/`.catch`/`.in`/`.oneOf`), see [`@warlock.js/seal/compose-seal-modifiers/SKILL.md`](@warlock.js/seal/compose-seal-modifiers/SKILL.md). For containers (object/array/record/tuple/union), see [`@warlock.js/seal/define-structural-shape/SKILL.md`](@warlock.js/seal/define-structural-shape/SKILL.md).
142
-
143
- ## Things NOT to do
144
-
145
- - Don't `new ObjectValidator()` (or any class) directly — factory returns carry the StandardSchema bridge that bare instantiation loses.
146
- - Don't pick `v.scalar` because "it's flexible". Flexibility at this layer usually means a missing discriminator — try `v.literal` or `v.union` first.
147
- - Don't reach for `v.instanceof(Date)` when `v.date()` works. The latter is purpose-built.
148
- - Don't use `v.string().oneOf(["a", "b"])` for discriminator fields where you need the literal type — use `v.literal("a", "b")`.
149
- - Don't expect `v.computed` / `v.managed` to validate input — they ignore input shape entirely. Reach for them only when *producing* a value.
1
+ ---
2
+ name: pick-seal-primitive
3
+ description: 'Pick the right `v` factory primitive — string / int / literal / date / enum / computed / managed / instanceof / any. Triggers: `v.string`, `v.email`, `v.number`, `v.int`, `v.float`, `v.numeric`, `v.boolean`, `v.scalar`, `v.date`, `v.literal`, `v.enum`, `v.instanceof`, `v.computed`, `v.managed`, `v.any`; "v.string vs v.scalar", "v.literal vs v.enum", "v.date vs v.instanceof(Date)", "what is v.computed"; typical import `import { v } from "@warlock.js/seal"`. Skip: structural shapes — `@warlock.js/seal/define-structural-shape/SKILL.md`; modifiers — `@warlock.js/seal/compose-seal-modifiers/SKILL.md`; competing libs `zod`, `valibot`, `yup`.'
4
+ ---
5
+
6
+ # Picking the right primitive
7
+
8
+ This is the orientation skill — *which* primitive for *which* job. For the chainable methods on each (`.email()`, `.min()`, `.between()`, etc.), load the matching `*-methods.md` reference file in this skill folder.
9
+
10
+ ## Strings
11
+
12
+ ```ts
13
+ v.string() // type: string — full surface in string-methods.md
14
+ v.email() // shorthand for v.string().email()
15
+ v.enum(["a", "b"]) // type: "a" | "b" — runs as v.string().oneOf, but the factory overload preserves the literal union
16
+ ```
17
+
18
+ Reach for `v.string()` for any text input. `v.email()` is just sugar — switch back to `v.string().email().min(...)` when you need extra rules.
19
+
20
+ ## Numbers — pick by what you accept
21
+
22
+ | Validator | Accepts | When |
23
+ |---|---|---|
24
+ | `v.number()` | any finite number | accepts both integers and floats |
25
+ | `v.int()` | integers only | rejects `1.5` |
26
+ | `v.float()` | finite, non-integer | rejects `1` |
27
+ | `v.numeric()` | numeric strings + numbers | form/query inputs that arrive as `"42"` — coerces to number |
28
+
29
+ All four share the same chain surface (see [`number-methods.md`](./number-methods.md)). Picking is about input acceptance, not chain power.
30
+
31
+ ## Booleans & scalars
32
+
33
+ ```ts
34
+ v.boolean() // type: boolean — adds .accepted() / .declined() for form-style inputs
35
+ v.scalar() // type: string | number | boolean — usually a smell pointing at a missing discriminator
36
+ ```
37
+
38
+ Use `v.scalar()` only when the field truly accepts any of the three primitives. If it's "one of N specific values across types", `v.literal(...)` is cleaner.
39
+
40
+ ## Dates
41
+
42
+ ```ts
43
+ v.date() // type: Date — normalizes strings/timestamps to Date, rich rule surface
44
+ v.instanceof(Date) // type: Date — raw instanceof, no normalization, no rules
45
+ ```
46
+
47
+ `v.date()` is the right tool 99% of the time — it ships `.min/.max/.before/.after/.weekDay/.minAge/...` and a built-in mutator that parses strings. `v.instanceof(Date)` is the escape hatch when you specifically need strict instance identity with zero coercion.
48
+
49
+ ## Literals & instances
50
+
51
+ ```ts
52
+ v.literal("items") // type: "items"
53
+ v.literal("draft", "published", "archived") // type: "draft" | "published" | "archived"
54
+ v.literal(1, 2, 3) // type: 1 | 2 | 3
55
+ v.literal(true) // type: true
56
+
57
+ v.instanceof(File) // type: File
58
+ v.instanceof(Buffer) // type: Buffer
59
+ v.instanceof(MyClass) // type: MyClass
60
+ ```
61
+
62
+ **`v.literal` vs `v.string().oneOf([...])` vs `v.enum([...])`:**
63
+
64
+ - `v.literal("a", "b")` infers as `"a" | "b"` (literal narrowing). **Use this for discriminator fields.**
65
+ - `v.string().oneOf(["a", "b"])` infers as `string` (loses literal types). Use when broad type is fine.
66
+ - `v.enum(["a", "b"])` runs the same `oneOf` rule at runtime (it builds a `StringValidator().oneOf(...)`), but the `v.enum` factory overload **preserves the literal union** — it infers `"a" | "b"`, not `string`. Pass a TS enum object (`v.enum(Direction)`) and it uses `Object.values`, inferring `Direction[keyof Direction]`.
67
+
68
+ `**`v.literal("")` — the empty string is a value, not an absence.** `""` is accepted when it is one of the configured literals, and the field is still required to be *present*:
69
+
70
+ ```ts
71
+ const decorative = v.object({ decorative: v.literal(true), alt: v.literal("") });
72
+
73
+ await v.validate(decorative, { decorative: true, alt: "" }); // valid
74
+ await v.validate(decorative, { decorative: true, alt: "text" }); // invalid — not the literal
75
+ await v.validate(decorative, { decorative: true }); // invalid — key missing
76
+ ```
77
+
78
+ That distinction matters wherever "empty" and "absent" mean different things — `alt=""` marks an image as decorative to a screen reader, while a missing `alt` is an authoring mistake. Add `.optional()` only when a missing key really is acceptable; a present value must still match the literal.
79
+
80
+ :::note[Fixed in 4.9.2]
81
+ Before 4.9.2 `v.literal("")` always failed with *"is required"*, and `.optional()` looked like a workaround while actually disabling the literal check — accepting `""`, `null`, and a missing key alike. `v.literal(0)` and `v.literal(false)` were never affected.
82
+ :::
83
+
84
+ `v.instanceof(Ctor)` for File/Buffer/Uint8Array/custom classes. Returns `{}` from `toJsonSchema()` (not representable). For OpenAPI `File`, attach `{ type: "string", format: "binary" }` manually after generation.
85
+
86
+ ## `v.any` — escape hatch
87
+
88
+ ```ts
89
+ v.any() // type: any — skips validation entirely
90
+ ```
91
+
92
+ Reach for it when you genuinely don't care about the shape. Usually a smell — search PRs for it and ask whether a real schema would catch a class of bugs.
93
+
94
+ ## Derived: `v.computed` and `v.managed`
95
+
96
+ These two **don't validate input** — they produce a value as part of validation.
97
+
98
+ ```ts
99
+ v.object({
100
+ firstName: v.string(),
101
+ lastName: v.string(),
102
+ fullName: v.computed<string>((data) => `${data.firstName} ${data.lastName}`),
103
+ createdAt: v.managed<Date>(() => new Date()),
104
+ createdBy: v.managed<string>((context) => context.context?.userId),
105
+ });
106
+ ```
107
+
108
+ - **`v.computed`** runs after sibling validation; callback signature is `(data, context)` — `data` is the validated sibling object. Use for derived values (full name, hash of fields, computed totals). An optional second arg validates the result: `v.computed<string>(cb, v.string().min(3))`.
109
+ - **`v.managed`** runs from `SchemaContext` only — callback signature is `(context)`. Caller-supplied extras passed to `validate(schema, data, { context })` land on `context.context`. Use for framework-injected values — timestamps, current user, request id. The callback is optional (`v.managed()`) for values the framework injects without a generator.
110
+
111
+ Both are **skipped** when their parent `v.object` generates JSON Schema — they never appear in `properties`, since they're runtime-only and not part of the JSON contract an LLM or external API consumer reads. Calling `.toJsonSchema()` *directly* on a `v.computed` / `v.managed` validator **throws** (it's a programming error — let the parent object skip them).
112
+
113
+ ## Quick map — "I need to validate…"
114
+
115
+ | Need | Reach for |
116
+ |---|---|
117
+ | Email | `v.string().email()` or `v.email()` |
118
+ | URL | `v.string().url()` |
119
+ | UUID | `v.string().uuid()` (see [`string-methods.md`](./string-methods.md)) |
120
+ | Number 0–100 | `v.number().between(0, 100)` |
121
+ | Positive integer | `v.int().positive()` |
122
+ | One of N constants | `v.literal(...values)` |
123
+ | One of TS enum values | `v.enum(MyEnum)` |
124
+ | Date in the past | `v.date().past()` |
125
+ | File upload | `v.instanceof(File)` |
126
+ | Class instance (not Date) | `v.instanceof(Ctor)` |
127
+ | Discriminated union | see [`@warlock.js/seal/define-structural-shape/SKILL.md`](@warlock.js/seal/define-structural-shape/SKILL.md) |
128
+ | Derived value (computed from siblings) | `v.computed<T>(callback)` |
129
+ | Framework-injected value | `v.managed<T>(callback)` |
130
+ | Free-form / pass-through | `v.any()` (only when you've thought about it) |
131
+
132
+ ## Method-surface reference
133
+
134
+ Each primitive's full method list lives in a sibling file:
135
+
136
+ - [`string-methods.md`](./string-methods.md) — `.email` / `.url` / `.uuid` / `.pattern` / `.startsWith` / `.alpha` / `.trim` / `.slug` / `.mask` / `.base64Encode` / …
137
+ - [`number-methods.md`](./number-methods.md) — `.min` / `.max` / `.between` / `.greaterThan` / `.positive` / `.even` / `.multipleOf` / `.minSibling` / `.round` / …
138
+ - [`date-methods.md`](./date-methods.md) — `.min` / `.before` / `.after` / `.today` / `.past` / `.future` / `.weekDay` / `.minAge` / `.year` / `.quarter` / `.toISOString` / …
139
+ - [`boolean-methods.md`](./boolean-methods.md) — `.accepted` / `.declined` / `.mustBeTrue` / `.mustBeFalse` / `.acceptedIf` / `.declinedWithout` / …
140
+
141
+ For cross-cutting modifiers (`.optional`/`.nullable`/`.default`/`.catch`/`.in`/`.oneOf`), see [`@warlock.js/seal/compose-seal-modifiers/SKILL.md`](@warlock.js/seal/compose-seal-modifiers/SKILL.md). For containers (object/array/record/tuple/union), see [`@warlock.js/seal/define-structural-shape/SKILL.md`](@warlock.js/seal/define-structural-shape/SKILL.md).
142
+
143
+ ## Things NOT to do
144
+
145
+ - Don't `new ObjectValidator()` (or any class) directly — factory returns carry the StandardSchema bridge that bare instantiation loses.
146
+ - Don't pick `v.scalar` because "it's flexible". Flexibility at this layer usually means a missing discriminator — try `v.literal` or `v.union` first.
147
+ - Don't reach for `v.instanceof(Date)` when `v.date()` works. The latter is purpose-built.
148
+ - Don't use `v.string().oneOf(["a", "b"])` for discriminator fields where you need the literal type — use `v.literal("a", "b")`.
149
+ - Don't expect `v.computed` / `v.managed` to validate input — they ignore input shape entirely. Reach for them only when *producing* a value.