@frankmeza/affirm 0.0.0-stage → 0.0.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 (51) hide show
  1. package/AGENTS.md +130 -0
  2. package/LICENSE +21 -0
  3. package/README.md +116 -2
  4. package/dist/affirm.d.ts +79 -0
  5. package/dist/checks/arrays.d.ts +10 -0
  6. package/dist/checks/composition.d.ts +10 -0
  7. package/dist/checks/equality.d.ts +7 -0
  8. package/dist/checks/nullish.d.ts +9 -0
  9. package/dist/checks/numbers.d.ts +11 -0
  10. package/dist/checks/objects.d.ts +9 -0
  11. package/dist/checks/runtime-type.d.ts +14 -0
  12. package/dist/checks/size.d.ts +8 -0
  13. package/dist/checks/strings.d.ts +6 -0
  14. package/dist/core/check-def.d.ts +93 -0
  15. package/dist/core/describe.d.ts +11 -0
  16. package/dist/core/errors.d.ts +18 -0
  17. package/dist/core/evaluate.d.ts +8 -0
  18. package/dist/core/registry.d.ts +18 -0
  19. package/dist/core/report.d.ts +22 -0
  20. package/dist/core/util/deep-equal.d.ts +12 -0
  21. package/dist/core/util/kind.d.ts +22 -0
  22. package/dist/core/util/levenshtein.d.ts +3 -0
  23. package/dist/core/util/same-value-zero.d.ts +5 -0
  24. package/dist/core/util/standard-schema.d.ts +62 -0
  25. package/dist/core/validate-params.d.ts +8 -0
  26. package/dist/eslint/check-keys.d.ts +7 -0
  27. package/dist/eslint/const-params.d.ts +2 -0
  28. package/dist/eslint/guard-naming.d.ts +2 -0
  29. package/dist/eslint/index.d.ts +29 -0
  30. package/dist/eslint/no-negated-affirm.d.ts +2 -0
  31. package/dist/eslint/shared.d.ts +65 -0
  32. package/dist/eslint.js +734 -0
  33. package/dist/eslint.js.map +1 -0
  34. package/dist/index.d.ts +5 -0
  35. package/dist/index.js +967 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/types/affirmed.d.ts +55 -0
  38. package/dist/types/arrays.d.ts +64 -0
  39. package/dist/types/composition.d.ts +53 -0
  40. package/dist/types/contradictions.d.ts +90 -0
  41. package/dist/types/equality.d.ts +65 -0
  42. package/dist/types/narrowing.d.ts +66 -0
  43. package/dist/types/nullish.d.ts +80 -0
  44. package/dist/types/numbers.d.ts +94 -0
  45. package/dist/types/objects.d.ts +99 -0
  46. package/dist/types/params.d.ts +14 -0
  47. package/dist/types/runtime-type.d.ts +129 -0
  48. package/dist/types/size.d.ts +76 -0
  49. package/dist/types/strings.d.ts +49 -0
  50. package/docs/client-usage.md +850 -0
  51. package/package.json +58 -4
@@ -0,0 +1,850 @@
1
+ # Using `affirm` in a client project
2
+
3
+ This guide shows how to use `affirm` in application code that depends on it, such as API handlers, config loading, fetch responses, form input and array filtering. It is written for AI coding agents that generate that code, and for the people who review it.
4
+
5
+ [`AGENTS.md`](../AGENTS.md) is the short reference. This document goes deeper into the parts of the API that generated code uses most, and into the mistakes that compile but do the wrong thing. Every behaviour and error message quoted here was checked against the current source with `strict: true`: types on TypeScript 5.9 to 7.0, lint rules on ESLint 9 and 10.
6
+
7
+ ---
8
+
9
+ ## 1. Setup
10
+
11
+ The package is ESM-only and is not published. Build it, then depend on it locally:
12
+
13
+ ```sh
14
+ # in the affirm repo
15
+ pnpm build
16
+ ```
17
+
18
+ ```jsonc
19
+ // client package.json
20
+ "dependencies": {
21
+ "@frankmeza/affirm": "link:../affirm"
22
+ }
23
+ ```
24
+
25
+ ```ts
26
+ import { affirm, AffirmError, type AffirmParams, type Affirmed, type AffirmReport, type AffirmFailure } from '@frankmeza/affirm'
27
+ ```
28
+
29
+ `affirm` has no runtime dependencies. For narrowing to work, the client's `tsconfig.json` needs `"strict": true`, or at least `strictNullChecks`.
30
+
31
+ **Requirements: TypeScript 5.9 or later** (declared as an optional peer dependency, so package managers warn about older versions). This is not cosmetic. On 5.8 and earlier, `affirm`'s types fail to resolve, and with the usual `skipLibCheck: true` nothing reports it. Narrowing then goes silently wrong: the `if` branch narrows nothing, and every `else` branch becomes `never`, so code that runs on real data type-checks as unreachable.
32
+
33
+ ### ESLint plugin (required)
34
+
35
+ `@frankmeza/affirm/eslint` catches the usage mistakes TypeScript can't: negated checks (§9), guards that hide `affirm` under another name (§9), and params that lose their exact values (§8.1). It needs ESLint 9 or 10 with a flat config. `eslint` is an optional peer dependency, so projects that don't lint don't install it.
36
+
37
+ A complete setup for a TypeScript project:
38
+
39
+ ```js
40
+ // eslint.config.js
41
+ import affirm from '@frankmeza/affirm/eslint'
42
+ import tsParser from '@typescript-eslint/parser'
43
+
44
+ export default [
45
+ {
46
+ files: ['**/*.ts'],
47
+ languageOptions: {
48
+ parser: tsParser,
49
+ // Optional type information: lets affirm/const-params follow lists imported from other files (§8.1).
50
+ parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
51
+ },
52
+ },
53
+ affirm.configs.recommended,
54
+ {
55
+ settings: { affirm: { guards: '^isValid' } }, // strongly recommended: catches negated guards across files (§9)
56
+ linterOptions: { reportUnusedDisableDirectives: 'error' },
57
+ },
58
+ ]
59
+ ```
60
+
61
+ `affirm.configs.recommended` sets no `files`, so it applies to everything ESLint lints. `.ts` files still need the TypeScript parser, as above.
62
+
63
+ **The rules**, all `error` in `recommended`:
64
+
65
+ | Rule | Catches | Fix |
66
+ | --- | --- | --- |
67
+ | `affirm/no-negated-affirm` | `!affirm(…)`, `=== false`, and negation through variables, `&&` / `\|\|`, same-file wrappers, and (with `guards`) guards from other files | Editor suggestion for `if (!affirm(…)) throw …` → `affirm.assert(…)` |
68
+ | `affirm/guard-naming` | With `guards`: a function returning `affirm(…)` whose name doesn't match the pattern, or a non-guard whose name does. Does nothing without `guards` | None (renaming crosses files) |
69
+ | `affirm/const-params` | TypeScript files: params or lists used in params declared without `as const`, or typed as `AffirmParams` | `eslint --fix` adds `as const`; a suggestion instead when the variable has other uses or a type annotation |
70
+
71
+ **Settings**, shared by all rules under `settings.affirm`:
72
+
73
+ | Setting | Default | Meaning |
74
+ | --- | --- | --- |
75
+ | `guards` | none | A regular expression (as a string) naming every guard built on `affirm`, e.g. `'^isValid'`. Turns on `guard-naming` and the cross-file guard check (§9) |
76
+ | `guardModules` | `[]` | Import prefixes that are your own code, for path aliases such as `['@/']`. Relative imports always count; packages never do |
77
+ | `sources` | `['@frankmeza/affirm']` | Modules that export `affirm`, if your project re-exports it (`['@frankmeza/affirm', '@/lib/affirm']`) |
78
+
79
+ The rules recognise `affirm` however it's imported: aliased (`import { affirm as check }`) or as a namespace (`ns.affirm(…)`). An unrelated function that happens to be called `affirm` is ignored.
80
+
81
+ **What lint can and can't see.** ESLint checks one file at a time and, by default, without type information:
82
+
83
+ | Situation | Without type information | With `projectService` |
84
+ | --- | --- | --- |
85
+ | Negated `affirm()` in any form within a file | ✓ | ✓ |
86
+ | Negated guard imported from another file | ✓ with `guards` | ✓ with `guards` |
87
+ | Params object without `as const`, declared in any file | ✓ (recognised by its keys) | ✓ |
88
+ | List used in params, declared in the same file | ✓ | ✓ |
89
+ | List imported from another file (`isOneOf: ROLES`) | ✗ (convention: declare it `as const`) | ✓ (reported at the use) |
90
+ | JavaScript files | `no-negated-affirm` and `guard-naming` only | n/a |
91
+
92
+ Type-aware linting is slower, and `typescript-eslint` currently supports TypeScript up to 6.0 (it needs TypeScript's JavaScript API, which 7.0 doesn't have). Without it, every rule still works; only the imported-list check is skipped.
93
+
94
+ **Exceptions.** Disable a rule for one line only, with a reason after `--`: `// eslint-disable-next-line affirm/no-negated-affirm -- legacy handler: only null reaches here`. Never disable a rule for a whole file. With `reportUnusedDisableDirectives: 'error'` (as above), stale exceptions get flagged (§9).
95
+
96
+ ---
97
+
98
+ ## 2. Which entry point to use
99
+
100
+ | Situation | Use | Returns |
101
+ | --- | --- | --- |
102
+ | Branch on data that passes (`if`, `filter`, ternaries) | `affirm(value, params)` | `boolean`; narrows `value` in the `if` branch. **Never negated** (§9) |
103
+ | Data must be valid or the program can't go on (config, invariants, trusted internal data) | `affirm.assert(value, params, message?)` | `void`; throws `AffirmError`; narrows `value` for the rest of the scope |
104
+ | You need to tell someone *why* it failed (400 responses, form errors, logs) | `affirm.explain(value, params)` | `{ ok, failures }`; never throws on bad data |
105
+
106
+ Rules of thumb:
107
+
108
+ - **Default to `affirm()`.** It stops at the first failure, so it is the cheapest.
109
+ - **Use `explain()` only where the failure details are used.** It runs every check and collects every failure.
110
+ - **Use `assert()` where a failure is a bug or a fatal misconfiguration**, not where bad input is expected. Don't wrap `assert` in `try/catch` to get a boolean. Use `affirm()` instead.
111
+ - **Handle the failure path with `explain()` or `assert()`, never with `!affirm()`** (§9).
112
+
113
+ `explain` does not narrow. To get both the report and narrowing, call `explain`, handle `!report.ok`, then call `affirm.assert` (see §5.1). It can't fail at that point, and it narrows the rest of the scope. Alternatively, catch `AffirmError` from `assert` (see §6.3).
114
+
115
+ ---
116
+
117
+ ## 3. The rules that decide whether generated code is correct
118
+
119
+ Read these before writing any params. Most bugs in generated `affirm` code break one of them.
120
+
121
+ 1. **Value first, params second.** `affirm(value, { … })`, never `affirm({ value, … })`.
122
+ 2. **Keys combine with AND.** The only OR is `anyOf: [{ … }, { … }]`.
123
+ 3. **An omitted key, or one set to `undefined`, is skipped.** This allows conditional params: `{ hasMinLength: strict ? 8 : undefined }`.
124
+ 4. **`true` asserts, `false` asserts the negation.** `isNull: false` means "not null". It never means "don't check".
125
+ 5. **No coercion.** `'10'` fails `isGreaterThan: 5`. `42` fails `hasMinLength: 1`. Parse first, then check.
126
+ 6. **The wrong kind of value fails both polarities.** `isPositive: false` means "a number that is not positive", so `'x'` fails it. The same goes for `isInteger`, `isFiniteNumber`, `isNaN`, `isBlank`, `isEmpty`, `isNotEmpty` and `isValidDate`. To say "not a positive number, or not a number at all", use `not: { isPositive: true }`.
127
+ 7. **Bad data returns `false`; mistakes in params throw `TypeError`.** Params are validated on every call, before any check runs, so a typo throws even when the value would have failed earlier. Never catch these errors. Fix the params.
128
+ 8. **Own keys only.** `shape`, `hasKey`, `hasKeys`, `hasAnyKey`, `hasOnlyKeys` and `hasPath` use `Object.hasOwn`. Getters on a class prototype are invisible to them, so use `satisfies` or `isInstanceOf` for class instances.
129
+ 9. **Evaluation order is fixed, not object-key order.** Type and nullish checks run first, then size, number and string checks, then structural checks (`shape`, `everyItem`, `isDeepEqual`, …), and `satisfies` runs last. You don't need to order keys defensively, and a `satisfies` predicate only runs after every other key has passed (under `affirm()`; under `explain()` it always runs).
130
+ 10. **Never negate `affirm()`.** `!affirm(…)`, `affirm(…) === false`, a negated variable holding its result, and a negated same-file wrapper (`!isOrder(x)`) are lint errors. Don't negate imported guards built on `affirm` either. The negation means "some check failed, for some reason", which is too broad to build on. Use `assert`, `explain`, or a positive check for the state you mean (§9).
131
+
132
+ ---
133
+
134
+ ## 4. The keys generated code uses most
135
+
136
+ ### 4.1 Presence and nullish
137
+
138
+ ```ts
139
+ affirm(x, { isPresent: true }) // x !== null && x !== undefined
140
+ affirm(x, { isDefined: true }) // x !== undefined (null passes!)
141
+ affirm(x, { isNullish: true }) // x === null || x === undefined
142
+ affirm(x, { isNull: false }) // x !== null (undefined passes)
143
+ ```
144
+
145
+ - **`isPresent` is almost always what you want** for "has a value". `isDefined` lets `null` through.
146
+ - `isTruthy` / `isFalsy` treat `0`, `''` and `NaN` as falsy. Don't use them for "has a value" on numbers or strings that may legitimately be `0` or `''`.
147
+ - These keys are **exact**, so they narrow both branches (see §7).
148
+
149
+ ### 4.2 Runtime type
150
+
151
+ ```ts
152
+ affirm(x, { isType: 'string' }) // typeof x === 'string'
153
+ affirm(x, { isType: 'number' }) // typeof; NaN and Infinity pass! Add isFiniteNumber
154
+ affirm(x, { isType: 'object' }) // non-null object, ARRAYS INCLUDED
155
+ affirm(x, { isPlainObject: true }) // {} literal / JSON object / Object.create(null); not arrays, not class instances
156
+ affirm(x, { isArray: true })
157
+ affirm(x, { isInstanceOf: URL }) // classes go here, never in isType
158
+ affirm(x, { isValidDate: true }) // a Date whose getTime() is not NaN
159
+ affirm(x, { isInteger: true }) // Number.isInteger (implies number)
160
+ affirm(x, { isFiniteNumber: true }) // Number.isFinite (implies number)
161
+ ```
162
+
163
+ - `isType` accepts exactly `'string' | 'number' | 'boolean' | 'bigint' | 'symbol' | 'function' | 'object'`, a type guard, or a **synchronous** Standard Schema (Zod, Valibot, ArkType).
164
+ - `isType: 'null'` and `isType: 'undefined'` throw: use `isNull` / `isUndefined`. `isType: SomeClass` throws: use `isInstanceOf`.
165
+ - To accept "a JSON object", write `isPlainObject: true`, not `isType: 'object'`, which also accepts arrays, `Date`s and `Map`s.
166
+ - To accept "a real number", write `isFiniteNumber: true`. It already implies `number`.
167
+
168
+ ### 4.3 Strings
169
+
170
+ ```ts
171
+ affirm(name, { isType: 'string', isBlank: false }) // the "required text field" idiom
172
+ affirm(slug, { matches: /^[a-z0-9-]+$/, hasMaxLength: 64 })
173
+ affirm(url, { startsWith: 'https://' })
174
+ affirm(text, { includes: 'TODO' }) // substring, strings only
175
+ ```
176
+
177
+ - `isBlank: true` means the string is empty or whitespace only. `isBlank: false` means "a string with at least one non-whitespace character". It fails on non-strings, so it already implies `isType: 'string'`. Writing both is still clearer for readers and costs nothing.
178
+ - `matches` requires a `RegExp`. A string param throws. `lastIndex` is reset before each test, so `/g` regexes are safe to reuse.
179
+ - `hasLength` / `hasMinLength` / `hasMaxLength` count UTF-16 code units (`.length`), not characters or bytes.
180
+ - Anchor your regexes (`^…$`). `matches: /\d+/` passes on `'abc1'`.
181
+
182
+ ### 4.4 Numbers
183
+
184
+ ```ts
185
+ affirm(qty, { isInteger: true, isAtLeast: 1 })
186
+ affirm(price, { isFiniteNumber: true, isAtLeast: 0 })
187
+ affirm(port, { isInteger: true, isBetween: [1, 65535] }) // inclusive on both ends
188
+ affirm(pct, { isGreaterThan: 0, isLessThan: 100 }) // exclusive bounds
189
+ affirm(cents, { isMultipleOf: 5 })
190
+ ```
191
+
192
+ - Every number key fails on `NaN` and on non-numbers, including numeric strings.
193
+ - `isBetween` is **inclusive**. For exclusive bounds, combine `isGreaterThan` and `isLessThan`.
194
+ - `isPositive` means `> 0`. Zero is not positive. For "zero or more", use `isAtLeast: 0`.
195
+ - `bigint` is not supported by the number keys.
196
+
197
+ ### 4.5 Equality and enums
198
+
199
+ ```ts
200
+ affirm(status, { isOneOf: ['draft', 'published', 'archived'] })
201
+ affirm(role, { is: 'admin' })
202
+ affirm(role, { isNotOneOf: ['root', 'system'] })
203
+ affirm(config, { isDeepEqual: { mode: 'strict', retries: 3 } })
204
+ ```
205
+
206
+ - `is` uses `===`, and `isOneOf` uses SameValueZero (`NaN` matches `NaN`). Objects compare by reference. Use `isDeepEqual` to compare structure.
207
+ - With literal params written inline, `isOneOf` narrows to the literal union (`'draft' | 'published' | 'archived'`). If you hoist the list into a variable, add `as const` or the narrowing widens to `string` (§8.1). `affirm/const-params` flags it, and `eslint --fix` adds `as const`.
208
+
209
+ ### 4.6 Objects: `shape` is the workhorse
210
+
211
+ `shape` checks named fields, each with its own params. This is how most generated code validates objects.
212
+
213
+ ```ts
214
+ const ok = affirm(body, {
215
+ isPlainObject: true,
216
+ shape: {
217
+ email: { isType: 'string', matches: /^[^@\s]+@[^@\s]+$/ },
218
+ age: { isInteger: true, isBetween: [13, 130] },
219
+ role: { isOneOf: ['admin', 'member'] },
220
+ },
221
+ })
222
+ ```
223
+
224
+ What `shape` does:
225
+
226
+ - **A missing field is checked as `undefined`.** So `shape: { email: { isType: 'string' } }` already requires `email` to be present. You don't need `hasKey: 'email'` as well.
227
+ - **It only checks the fields you list.** Extra fields pass. To reject unknown fields, add `hasOnlyKeys: [...]`.
228
+ - **It accepts arrays as well as objects**, and fails on `null` / primitives with a single failure (`expected an object or array, received null`). Add `isPlainObject: true` when arrays must be rejected.
229
+ - **Fields nest without limit**: `shape: { user: { shape: { address: { shape: { zip: {...} } } } } }`.
230
+
231
+ Optional and nullable fields:
232
+
233
+ ```ts
234
+ shape: {
235
+ // optional: may be missing / undefined
236
+ nickname: { anyOf: [{ isUndefined: true }, { isType: 'string', hasMaxLength: 20 }] },
237
+ // nullable: present but may be null
238
+ middleName: { anyOf: [{ isNull: true }, { isType: 'string' }] },
239
+ // optional AND nullable
240
+ bio: { anyOf: [{ isNullish: true }, { isType: 'string' }] },
241
+ }
242
+ ```
243
+
244
+ Do not write `nickname: { isType: 'string' }` for an optional field. A missing field is `undefined`, so the check fails.
245
+
246
+ Other object keys:
247
+
248
+ ```ts
249
+ affirm(x, { hasKey: 'id' }) // own key exists (value may be undefined)
250
+ affirm(x, { hasKeys: ['id', 'name'] }) // all of them
251
+ affirm(x, { hasAnyKey: ['email', 'phone'] }) // at least one
252
+ affirm(x, { hasOnlyKeys: ['page', 'limit'] }) // no others (does NOT require these to be present)
253
+ affirm(x, { hasPath: 'user.address.zip' }) // every segment exists; numeric segments index arrays: 'items.0.id'
254
+ affirm(x, { isNotEmpty: true }) // a plain object with ≥ 1 own enumerable key
255
+ ```
256
+
257
+ Prefer `shape` over `hasKey` / `hasPath` when you also care about the field's value. `hasKey: 'x'` passes when `x` is present but `undefined`.
258
+
259
+ ### 4.7 Arrays: `everyItem` and friends
260
+
261
+ ```ts
262
+ affirm(order.items, {
263
+ isNotEmpty: true, // everyItem alone passes on []
264
+ everyItem: {
265
+ shape: {
266
+ sku: { isType: 'string', isBlank: false },
267
+ qty: { isInteger: true, isAtLeast: 1 },
268
+ },
269
+ },
270
+ })
271
+
272
+ affirm(tags, { isArray: true, hasMaxLength: 10, everyItem: { isType: 'string' } })
273
+ affirm(roles, { contains: 'admin' }) // one item, SameValueZero
274
+ affirm(roles, { containsAll: ['read', 'write'] })
275
+ affirm(roles, { containsAny: ['admin', 'owner'] })
276
+ affirm(users, { someItem: { shape: { isOwner: { is: true } } } }) // false on []
277
+ ```
278
+
279
+ - **`everyItem` passes on an empty array.** Add `isNotEmpty: true` (or `hasMinLength: 1`) when at least one item is required.
280
+ - **`contains*` are for arrays and `includes` is for strings.** Using the wrong one fails rather than throwing, which makes it a silent bug. Watch for it.
281
+ - `contains` compares with SameValueZero, so `contains: { id: 1 }` never matches a different object. Use `someItem: { isDeepEqual: { id: 1 } }` or `someItem: { shape: { id: { is: 1 } } }`.
282
+ - Failure paths include the index: `items[1].qty`.
283
+
284
+ ### 4.8 Composition: `anyOf`, `not`, `satisfies`
285
+
286
+ ```ts
287
+ // OR
288
+ affirm(id, { anyOf: [{ isType: 'string', isBlank: false }, { isInteger: true, isAtLeast: 1 }] })
289
+
290
+ // NOT. The nested keys AND together first: not (a AND b)
291
+ affirm(username, { not: { isOneOf: ['admin', 'root'] } })
292
+
293
+ // Cross-field rules. The predicate receives `unknown`, so guard inside it
294
+ const rangeFields = { shape: { min: { isFiniteNumber: true }, max: { isFiniteNumber: true } } } as const
295
+ affirm(range, {
296
+ ...rangeFields,
297
+ satisfies: (r: unknown) => affirm(r, rangeFields) && r.min <= r.max, // annotate `r`: see §8.2
298
+ })
299
+ ```
300
+
301
+ - `satisfies` runs last. Under `affirm()`, it only runs once every other key in the same params has passed. Under `affirm.explain()`, every key runs, including `satisfies` on malformed input. Always guard inside the predicate rather than casting: a cast like `(r as Range).min` throws on `null` under `explain()`.
302
+ - The predicate must return exactly `true`. Truthy values such as `1` or `'yes'` fail.
303
+ - Errors thrown inside `satisfies` propagate to the caller. They are not turned into failures.
304
+ - `anyOf: []`, `shape: {}` and `{}` throw because they would always pass.
305
+
306
+ ### 4.9 Existing schemas (Zod / Valibot / ArkType)
307
+
308
+ ```ts
309
+ import { z } from 'zod'
310
+ const Order = z.object({ id: z.string(), total: z.number().positive() })
311
+
312
+ if (affirm(body, { isType: Order })) {
313
+ body.total // number
314
+ }
315
+ ```
316
+
317
+ - **Sync schemas only.** A schema whose `validate` returns a Promise (`z.string().refine(async …)`) throws `TypeError`.
318
+ - **Validation only, no transformation.** `affirm` never returns the parsed value, so `.transform()`, `.default()` and coercion have no effect. Narrowing uses the schema's *input* type. If you need the transformed output, call `Order.parse(body)` yourself.
319
+ - Schema issue messages are **not** copied into reports, because they can contain raw values. Each issue becomes a failure at the issue's path, with `expected: 'a value accepted by the zod schema'`.
320
+
321
+ ---
322
+
323
+ ## 5. Recipes by client-code scenario
324
+
325
+ ### 5.1 HTTP handler: validate a request body and return 400 with reasons
326
+
327
+ ```ts
328
+ import { affirm } from '@frankmeza/affirm'
329
+
330
+ const createUserParams = {
331
+ isPlainObject: true,
332
+ hasOnlyKeys: ['email', 'name', 'age', 'role'],
333
+ shape: {
334
+ email: { isType: 'string', matches: /^[^@\s]+@[^@\s]+$/, hasMaxLength: 254 },
335
+ name: { isType: 'string', isBlank: false, hasMaxLength: 100 },
336
+ age: { anyOf: [{ isUndefined: true }, { isInteger: true, isBetween: [13, 130] }] },
337
+ role: { isOneOf: ['admin', 'member'] },
338
+ },
339
+ } as const
340
+
341
+ export async function createUser(req: Request): Promise<Response> {
342
+ const body: unknown = await req.json()
343
+
344
+ const report = affirm.explain(body, createUserParams)
345
+ if (!report.ok) {
346
+ return Response.json({ errors: report.failures.map((f) => ({ field: f.path, message: f.reason })) }, { status: 400 })
347
+ }
348
+
349
+ // explain() does not narrow. assert() can't fail here, and narrows `body` from now on.
350
+ affirm.assert(body, createUserParams)
351
+
352
+ return Response.json(await db.users.insert({ email: body.email, name: body.name, role: body.role }))
353
+ }
354
+ ```
355
+
356
+ ### 5.2 Startup config: fail fast with `assert`
357
+
358
+ ```ts
359
+ import { affirm } from '@frankmeza/affirm'
360
+
361
+ affirm.assert(process.env.DATABASE_URL, { isType: 'string', startsWith: 'postgres://' }, 'DATABASE_URL must be a postgres:// URL')
362
+ affirm.assert(process.env.PORT, { isType: 'string', matches: /^\d{2,5}$/ }, 'PORT must be numeric')
363
+
364
+ const port = Number(process.env.PORT)
365
+ affirm.assert(port, { isInteger: true, isBetween: [1, 65535] }, 'PORT out of range')
366
+
367
+ // Both env vars are narrowed to `string` from here on.
368
+ ```
369
+
370
+ Note the order: env vars are strings, so check the string, convert it, then check the number. Rule 5 applies: `isBetween` on the raw `'8080'` fails.
371
+
372
+ ### 5.3 Fetch response from a third-party API
373
+
374
+ ```ts
375
+ const orderPayload = {
376
+ isPlainObject: true,
377
+ shape: {
378
+ id: { isType: 'string' },
379
+ status: { isOneOf: ['pending', 'shipped', 'delivered'] },
380
+ items: { isArray: true, everyItem: { shape: { sku: { isType: 'string' }, qty: { isInteger: true } } } },
381
+ },
382
+ } as const
383
+
384
+ async function fetchOrder(id: string) {
385
+ const res = await fetch(`https://api.example.com/orders/${id}`)
386
+ const data: unknown = await res.json()
387
+
388
+ if (affirm(data, orderPayload)) {
389
+ data.status // 'pending' | 'shipped' | 'delivered'
390
+ data.items // readonly { sku: string; qty: number }[]
391
+ return data
392
+ }
393
+
394
+ // Only pay for explain() on the failure path.
395
+ logger.warn('unexpected order payload', { failures: affirm.explain(data, orderPayload).failures }) // safe to log: no raw values
396
+ return null
397
+ }
398
+ ```
399
+
400
+ Hoist params that are used more than once into an `as const` constant (§8.1) instead of repeating them.
401
+
402
+ ### 5.4 Form validation: one error message per field
403
+
404
+ `explain()` reports every failing key, so one field can produce several failures (for example `age` failing both `isInteger` and `isBetween`). Keep the first failure per path:
405
+
406
+ ```ts
407
+ function fieldErrors(report: AffirmReport): Record<string, string> {
408
+ const errors: Record<string, string> = {}
409
+ for (const f of report.failures) errors[f.path] ??= f.reason
410
+ return errors
411
+ }
412
+ ```
413
+
414
+ `reason` is written for developers (`age: expected an integer, received number`). For end-user copy, map on `f.path` and `f.key` to your own messages:
415
+
416
+ ```ts
417
+ const messages: Record<string, string> = {
418
+ 'email:matches': 'Enter a valid email address',
419
+ 'name:isBlank': 'Name is required',
420
+ 'age:isBetween': 'You must be at least 13',
421
+ }
422
+ const text = messages[`${f.path}:${f.key}`] ?? 'Invalid value'
423
+ ```
424
+
425
+ ### 5.5 Filtering arrays
426
+
427
+ An inline arrow works directly: TypeScript infers the type predicate, including for refined checks.
428
+
429
+ ```ts
430
+ const raw: unknown[] = await loadRows()
431
+
432
+ const names = raw.filter((r) => affirm(r, { isType: 'string', isBlank: false }))
433
+ // (string & Refined)[]: usable anywhere string[] is
434
+
435
+ const users = raw.filter((r) => affirm(r, { shape: { id: { isType: 'string' } } }))
436
+ // ({ id: string } & Refined)[]
437
+
438
+ const present = maybeNames.filter((n) => affirm(n, { isPresent: true }))
439
+ // string[] (exact check, so no Refined marker)
440
+ ```
441
+
442
+ For a reusable guard, name its type with `Affirmed`, and its function with your `guards` pattern (`'^isValid'` here; §1, §9). That way `!isValidOrder(x)` is caught even in files that import it:
443
+
444
+ ```ts
445
+ const orderParams = { shape: { id: { isType: 'string' }, total: { isFiniteNumber: true } } } as const
446
+ type ValidOrder = Affirmed<unknown, typeof orderParams>
447
+
448
+ export function isValidOrder(v: unknown): v is ValidOrder {
449
+ return affirm(v, orderParams)
450
+ }
451
+
452
+ const orders = rows.filter(isValidOrder) // ValidOrder[]
453
+ ```
454
+
455
+ ### 5.6 Narrowing a typed value (not `unknown`)
456
+
457
+ `affirm` works on values that are already typed, and keeps the existing type:
458
+
459
+ ```ts
460
+ function greet(user: User | null) {
461
+ if (affirm(user, { isNull: true })) return 'Hello, guest' // a positive check for the state you mean (§9)
462
+ user // User (isNull is exact, so the code after the early return is narrowed)
463
+
464
+ if (affirm(user.nickname, { isType: 'string', isBlank: false })) {
465
+ return `Hi, ${user.nickname}` // string
466
+ }
467
+ return `Hello, ${user.name}`
468
+ }
469
+ ```
470
+
471
+ With a typed input, `shape` keeps the original type instead of building a new one. On `User | null`, `{ shape: { id: { isType: 'string' } } }` narrows to `User & Refined`.
472
+
473
+ ### 5.7 Building params conditionally
474
+
475
+ `undefined` means skip, so you can build params with ternaries:
476
+
477
+ ```ts
478
+ function passwordParams(strict: boolean) {
479
+ return {
480
+ isType: 'string',
481
+ hasMinLength: strict ? 12 : 8,
482
+ matches: strict ? /[^A-Za-z0-9]/ : undefined, // only in strict mode
483
+ } as const
484
+ }
485
+ ```
486
+
487
+ Never use `false` to mean "skip" a boolean key, because `false` is an assertion too (rule 4). A common slip:
488
+
489
+ ```ts
490
+ { isBlank: !allowBlank } // ✗ when allowBlank is true this is `isBlank: true`: it REQUIRES a blank string
491
+ { isBlank: allowBlank ? undefined : false } // ✓ skip when blanks are allowed, otherwise require non-blank
492
+ ```
493
+
494
+ ---
495
+
496
+ ## 6. Reports and errors in detail
497
+
498
+ ### 6.1 `AffirmReport` / `AffirmFailure`
499
+
500
+ ```ts
501
+ interface AffirmReport { ok: boolean; failures: AffirmFailure[] }
502
+
503
+ interface AffirmFailure {
504
+ key: string // the params key that failed: 'isBetween'
505
+ path: string // '' at the root, 'email', 'items[1].qty', 'user.address.zip'
506
+ expected: string // 'between 13 and 130 (inclusive)'
507
+ received: string // a description of the value's type, never the value: 'number', 'string(len 4)', 'array(len 2)', 'object{3 keys}', 'null'
508
+ reason: string // `${path}: expected ${expected}, received ${received}`
509
+ branches?: AffirmFailure[][] // anyOf only: each branch's failures
510
+ }
511
+ ```
512
+
513
+ Real output for the §5.1-style params against `{ email: 'nope', age: 12.5, role: 'owner', items: [{ sku: 'A', qty: 1 }, { sku: ' ', qty: 0 }], nickname: 42 }`:
514
+
515
+ ```text
516
+ email: expected a string matching /^[^@\s]+@[^@\s]+$/, received string(len 4)
517
+ age: expected an integer, received number
518
+ age: expected between 13 and 130 (inclusive), received number
519
+ role: expected one of ["admin", "member"], received string(len 5)
520
+ items[1].sku: expected a non-blank string, received string(len 1)
521
+ items[1].qty: expected >= 1, received number
522
+ nickname: expected any of 2 branches to pass, received number
523
+ ```
524
+
525
+ The `nickname` failure's `branches` holds `[[isUndefined failure], [isType failure, hasMaxLength failure]]`. The top-level `reason` of an `anyOf` failure is generic, so look in `branches` if you need to say which alternative came closest.
526
+
527
+ ### 6.2 Logging safety
528
+
529
+ `received` never contains the checked value, so reports are safe to log even when the data holds PII. **Params can appear**, though: short string params are quoted in `expected` (`=== "admin"`, `one of ["admin", "member"]`). Don't put secrets in params. For example, never write `affirm(token, { is: process.env.API_KEY })`, because the key would end up in `expected`.
530
+
531
+ ### 6.3 `AffirmError`
532
+
533
+ ```ts
534
+ try {
535
+ affirm.assert(body, createUserParams)
536
+ } catch (error) {
537
+ if (error instanceof AffirmError) return badRequest(error.report.failures)
538
+ throw error
539
+ }
540
+ ```
541
+
542
+ - `error.name === 'AffirmError'` and `error.report` is the full `AffirmReport`.
543
+ - The default message is `affirm.assert failed: ` followed by the first three reasons and `(+N more)`. If you pass a `message` argument, it replaces the default message entirely, and the details remain in `error.report`.
544
+ - Use `instanceof AffirmError` to tell data failures apart from `TypeError`s (mistakes in params) and anything else.
545
+
546
+ ### 6.4 Mistakes that throw `TypeError`
547
+
548
+ These are bugs in the params, not in the data. The messages are designed to tell you how to fix them:
549
+
550
+ ```text
551
+ affirm: unknown check `isTypo`. Did you mean `isType`?
552
+ affirm: unknown check `hasMinLenght`. Did you mean `hasMinLength`?
553
+ affirm: params are empty; `{}` would always pass
554
+ affirm: invalid param for `matches`: expected a RegExp (received "abc"); use `includes` for plain text
555
+ affirm: invalid param for `isType`: expected a type tag; use `isNull: true` instead of `isType: 'null'`
556
+ affirm: invalid param for `isType`: expected a type tag, guard or schema; use `isInstanceOf: Map` for classes
557
+ ```
558
+
559
+ Other cases that throw: `hasMinLength: -1` or `hasMinLength: '3'`, `isBetween: [10, 1]`, `isMultipleOf: 0`, `anyOf: []`, `shape: {}`, and async schemas.
560
+
561
+ Most of these are also **compile errors** (§7.3), so they rarely reach runtime in TypeScript code. They do when params are built from untyped data or cast with `as any`.
562
+
563
+ ---
564
+
565
+ ## 7. Type narrowing: what you can rely on
566
+
567
+ ### 7.1 Exact vs refined
568
+
569
+ - **Exact checks narrow both branches.** These are `isNull`, `isUndefined`, `isNullish`, `isDefined`, `isPresent`, `isType` with a primitive tag (not `'object'`) or a type guard, `isArray: true`, `isFunction: true`, `is` / `isOneOf` with literal params, and `anyOf` when every branch is exact.
570
+
571
+ ```ts
572
+ declare const s: string | null
573
+ if (affirm(s, { isPresent: true })) { s /* string */ } else { s /* null */ }
574
+ ```
575
+
576
+ - **Refined checks narrow only the `if` branch.** That is every other key. The `if` branch gets `T & Refined`, and the `else` branch keeps the full type, because a string can fail `hasMinLength: 3` and still be a string.
577
+
578
+ ```ts
579
+ declare const x: string | number
580
+ if (affirm(x, { isType: 'string', hasMinLength: 3 })) { x /* string & Refined */ } else { x /* string | number */ }
581
+ ```
582
+
583
+ `Refined` is a phantom marker. `string & Refined` can be assigned to `string`, passed to functions, returned and stored. Ignore it, and don't write it in your own type annotations. Use `Affirmed<…>` when you need to name the type.
584
+
585
+ The consequence for generated code: put the code that relies on a refined narrowing **inside** `if (affirm(…)) { … }`, or use `affirm.assert`, which narrows the rest of the scope. Don't reach for a negated guard clause; that is banned (§9).
586
+
587
+ ```ts
588
+ affirm.assert(x, { isType: 'string', isBlank: false })
589
+ x // string & Refined ✓
590
+ ```
591
+
592
+ ### 7.2 When `affirm` returns a plain `boolean`
593
+
594
+ If a refined check's narrowed type could still include `null` or `undefined`, TypeScript can't express the narrowing soundly, so `affirm` falls back to `boolean` and does not narrow:
595
+
596
+ ```ts
597
+ declare const name: string | undefined
598
+ if (affirm(name, { isFalsy: true })) { name /* still string | undefined */ }
599
+ ```
600
+
601
+ To get narrowing, split the check: `affirm(x, { isPresent: true }) && affirm(x, { … })`.
602
+
603
+ ### 7.3 Compile-time errors you will see
604
+
605
+ Unknown keys (at any depth) and contradictions show up as **"No overload matches this call."** The useful part is the `__affirmError` text further down the error:
606
+
607
+ ```text
608
+ Property '__affirmError' is missing … { __affirmError: "`isNull: true` contradicts `isPresent: true`" }
609
+ Property '__affirmError' is missing … { __affirmError: "`isType: 'string'` contradicts `isPositive` (a number key)" }
610
+ ```
611
+
612
+ Other detected contradictions include `hasMinLength` greater than `hasMaxLength`, `isEmpty` with `isNotEmpty`, `isArray: true` with a non-`'object'` `isType` tag, and `isTruthy` with `isFalsy`. Contradictions are checked inside each nested params object, but not across `anyOf` branches.
613
+
614
+ ### 7.4 What each common pattern narrows to (on `unknown`)
615
+
616
+ | Params | `if` branch type |
617
+ | --- | --- |
618
+ | `{ isType: 'string' }` | `string` |
619
+ | `{ isType: 'string', isBlank: false }` | `string & Refined` |
620
+ | `{ isOneOf: ['a', 'b'] }` (inline) | `'a' \| 'b'` |
621
+ | `{ isArray: true }` | `readonly unknown[]` |
622
+ | `{ isArray: true, everyItem: { isType: 'string' } }` | `readonly string[] & Refined` |
623
+ | `{ isPlainObject: true }` | `Record<string, unknown> & Refined` |
624
+ | `{ hasKey: 'id' }` | `Record<'id', unknown> & Refined` |
625
+ | `{ hasPath: 'a.b' }` | `{ a: { b: unknown } } & Refined` |
626
+ | `{ shape: { id: { isType: 'string' }, n: { isOneOf: [1, 2] } } }` | `{ id: string; n: 1 \| 2 } & Refined` |
627
+ | `{ shape: { x: { anyOf: [{ isUndefined: true }, { isType: 'string' }] } } }` | `{ x: string \| undefined } & Refined` |
628
+ | `{ isInstanceOf: Map }` | `Map<unknown, unknown> & Refined` |
629
+ | `{ isType: isUuid }` (a guard) | the guard's type |
630
+ | `{ isType: ZodSchema }` | the schema's input type `& Refined` |
631
+ | `{ satisfies: namedGuard }` | the guard's type `& Refined` |
632
+
633
+ ---
634
+
635
+ ## 8. Pitfalls that compile but are wrong
636
+
637
+ ### 8.1 Hoisted params need `as const` (enforced, autofixable)
638
+
639
+ Inline params get literal types automatically. Params stored in a variable do not. TypeScript widens them where they are declared (`'a'` → `string`, `true` → `boolean`), before `affirm` ever sees them, so `affirm` can't recover the exact values. The runtime check still compares the exact strings; only the narrowing is lost:
640
+
641
+ ```ts
642
+ const p = { isType: 'string', hasMinLength: 3 }
643
+ affirm(x, p)
644
+ // ✗ compile error: Type 'string' is not assignable to type '… | TypeTag | undefined'
645
+
646
+ const q = { isOneOf: ['a', 'b'] }
647
+ affirm(x, q) // compiles, but narrows to `string & Refined`, not 'a' | 'b'
648
+
649
+ const r = { isType: 'string', hasMinLength: 3, isOneOf: ['a', 'b'] } as const // ✓
650
+ const s = { isType: 'string' } as const satisfies AffirmParams // ✓ and checked where it is declared
651
+ ```
652
+
653
+ **Don't annotate params as `AffirmParams`** (`const p: AffirmParams = { … }`), and don't cast them (`{ … } as AffirmParams`). The literal types are lost and nothing narrows. Use `as const`, or `as const satisfies AffirmParams`.
654
+
655
+ **The `affirm/const-params` lint rule enforces this** in TypeScript files (§1). It follows every variable that ends up in params:
656
+ - params passed to `affirm()`, `affirm.assert()` or `affirm.explain()`;
657
+ - pieces inside params (`isOneOf: roles`, `shape: { id: idParams }`, `...baseParams`), including pieces of other hoisted params.
658
+
659
+ `eslint --fix` adds `as const` at the declaration (before any `satisfies`). It only autofixes when the variable is used purely as params, so making it read-only can't break anything. If the variable is also used elsewhere (`roles.push(…)`), you get the same fix as an editor suggestion to apply after checking. Typed declarations get a suggestion to switch to `as const satisfies <Type>`.
660
+
661
+ ```ts
662
+ const roles = ['admin', 'member'] // ✗ affirm/const-params: params `roles` need `as const` … (autofix adds it)
663
+ affirm(user.role, { isOneOf: roles })
664
+ ```
665
+
666
+ **Params exported to other files are covered too.** ESLint checks one file at a time, so the rule also recognises params by their keys where they are declared, whether or not that file calls `affirm`. An object literal counts as params when every key is a check name and at least one key, here or in its nested params, is distinctive (an `isX` / `hasX` check, `containsAll`, `everyItem`, …):
667
+
668
+ ```ts
669
+ // params.ts (no affirm() call in this file)
670
+ export const orderParams = { isPlainObject: true, shape: { … } } // ✗ recognised by its keys; autofix adds `as const`
671
+ export const manifest = { matches: ['<all_urls>'] } // ✓ `matches` alone is an ordinary word, not params
672
+ export const ROLES = ['admin', 'member'] // not recognised: a bare list has no keys
673
+ ```
674
+
675
+ **Bare lists exported from another file need type information.** In `isOneOf: ROLES` where `ROLES` is imported, a list has no keys to recognise. With type-aware linting (§1), the rule asks TypeScript where `ROLES` is declared and reports the use when that declaration is a literal without `as const` (or with a type annotation such as `: string[]`):
676
+
677
+ ```text
678
+ affirm: `ROLES` is used in params here, but it is declared without `as const` in src/roles.ts:1, so TypeScript
679
+ widened its values ('a' → string) before affirm() sees them, and narrowing is silently lost. Fix that declaration: `= … as const`.
680
+ ```
681
+
682
+ This works through re-exports and namespace imports (`R.ROLES`). ESLint can only fix the file it is linting, so this one has no autofix; the message says where to add `as const`. Values without a literal to fix are skipped: `loadRoles()`, `let`, and declarations from packages. Without type information, write lists used in params `as const` where they're declared.
683
+
684
+ ### 8.2 Inline functions in params need an annotated parameter
685
+
686
+ If **any** function written inline in the params has an unannotated parameter, narrowing is switched off for the **whole call**. That covers `satisfies`, `isType` guards, and functions nested inside `shape`, `everyItem` and `anyOf`. The call still compiles and still checks correctly at runtime. Only the types are lost.
687
+
688
+ ```ts
689
+ affirm(x, { isType: 'string', satisfies: (v) => v !== 'x' }) // ✗ x stays `unknown`
690
+ affirm(x, { isType: 'string', satisfies: (v: unknown) => v !== 'x' }) // ✓ x: string & Refined
691
+
692
+ affirm(x, { satisfies: (v): v is Date => v instanceof Date }) // ✗ no narrowing
693
+ affirm(x, { isType: (v): v is Date => v instanceof Date }) // ✗ no narrowing either
694
+ affirm(x, { satisfies: (v: unknown): v is Date => v instanceof Date }) // ✓ Date & Refined
695
+
696
+ const isDate = (v: unknown): v is Date => v instanceof Date
697
+ affirm(x, { satisfies: isDate }) // ✓ named functions are always fine
698
+ ```
699
+
700
+ The rule: **write `(v: unknown) =>` for every inline function in params**, or use a named function.
701
+
702
+ Why this happens: an unannotated arrow makes TypeScript infer the params type in two passes. In the first pass, the narrowing overload's soundness gate (§7.2) sees a not-yet-inferred `P`, so TypeScript rejects that overload and uses the plain-`boolean` one instead.
703
+
704
+ ### 8.3 Don't destructure `assert`
705
+
706
+ ```ts
707
+ const { assert } = affirm
708
+ assert(x, { isType: 'string' })
709
+ // ✗ TS2775: Assertions require every name in the call target to be declared with an explicit type annotation.
710
+ ```
711
+
712
+ Always call it as `affirm.assert(…)`. The same applies to re-exporting it under another name: `export const check = affirm.assert` loses the assertion signature unless you annotate it with `Affirm['assert']`.
713
+
714
+ ### 8.4 Silent failures from using the wrong kind of key
715
+
716
+ Each of these compiles and always returns `false`:
717
+
718
+ | Wrong | Right |
719
+ | --- | --- |
720
+ | `affirm(tags, { includes: 'x' })` on an array | `contains: 'x'` |
721
+ | `affirm(text, { contains: 'x' })` on a string | `includes: 'x'` |
722
+ | `affirm(req.query.page, { isInteger: true })` (query values are strings) | `matches: /^\d+$/`, then `Number()` and check again |
723
+ | `affirm(input, { isEmpty: true })` meaning "null or empty" | `anyOf: [{ isNullish: true }, { isEmpty: true }]` |
724
+ | `affirm(maybe, { isPositive: false })` meaning "not a positive number, or not a number" | `not: { isPositive: true }` |
725
+ | `affirm(obj, { hasMinLength: 1 })` on a plain object | `isNotEmpty: true` (size keys other than `isEmpty` / `isNotEmpty` don't accept plain objects) |
726
+ | `affirm(user, { shape: { name: { isType: 'string' } } })` on a class instance with a `get name()` | `isInstanceOf: User`, or `satisfies` |
727
+ | `shape: { nickname: { isType: 'string' } }` for an optional field | `anyOf: [{ isUndefined: true }, { isType: 'string' }]` |
728
+
729
+ ### 8.5 Things `affirm` deliberately doesn't do
730
+
731
+ - **No parsing, coercion, trimming or defaults.** `affirm` never changes the value. Parse first (`Number(…)`, `new Date(…)`, a schema's `.parse`), then check the result.
732
+ - **No async.** Await first, then check.
733
+ - **No custom messages per key.** Map `path` / `key` to your own messages (§5.4).
734
+ - **No `bigint` comparisons.** `isGreaterThan` and the other number keys need a `number`.
735
+
736
+ ---
737
+
738
+ ## 9. Never negate `affirm()`
739
+
740
+ ### What is banned
741
+
742
+ ```ts
743
+ if (!affirm(value, params)) { … } // ✗
744
+ if (!(affirm(value, params))) { … } // ✗
745
+ if (affirm(value, params) === false) … // ✗ also `== false`, `!== true`, `!= true`
746
+ if (!(x != null && affirm(x, params))) … // ✗ negating an && / || that contains affirm()
747
+
748
+ const ok = affirm(value, params) // also `let` / `var` if never reassigned, and `affirm(a, p) && affirm(b, q)`
749
+ if (!ok) { … } // ✗ a negated stored result
750
+
751
+ const isOrder = (v: unknown) => affirm(v, orderParams)
752
+ if (!isOrder(x)) { … } // ✗ a negated wrapper (a same-file function whose whole body returns affirm())
753
+ ```
754
+
755
+ The `affirm/no-negated-affirm` lint rule (§1) reports each of these as an error and quotes the attempted code:
756
+
757
+ ```text
758
+ affirm: `!affirm(body, createUserParams)` is not allowed. Negating affirm() is true when any
759
+ check fails for any reason, so it tells you nothing reliable about the value. Use
760
+ affirm.assert(value, params) to stop on bad data, affirm.explain(value, params) to handle
761
+ failures by reason, or a positive check for the state you mean (e.g. `isNullish: true`).
762
+ ```
763
+
764
+ ### Why
765
+
766
+ `affirm(value, params)` answers one precise question: "does `value` pass **every one** of these checks?" A `true` result describes one well-defined set of values, and TypeScript narrows to it.
767
+
768
+ Its negation is everything else. Take `!affirm(order, { isPlainObject: true, shape: { total: { isFiniteNumber: true, isPositive: true } } })`. It is true when `order` is `null`, a string, an array, an object without `total`, a `total` of `'12'`, `NaN`, `0` or `-5`. Those are very different situations, and code written under the negation:
769
+
770
+ - **can't rely on anything about the value.** The check is a thin gate made of many narrow conditions, and negating it throws all of them away at once;
771
+ - **can't say what was wrong**, so the failure is handled blindly (a generic error, a silent `return null`, a wrong default);
772
+ - **gets no type information** for refined checks, because TypeScript can't describe "any value except a valid one".
773
+
774
+ This mostly bites in generated code. A negated guard clause (`if (!affirm(…)) return`) looks tidy, but the branch it guards is the vaguest part of the program.
775
+
776
+ ### What to write instead
777
+
778
+ | You want to… | Write |
779
+ | --- | --- |
780
+ | Stop on bad data (a bug, a fatal misconfiguration) | `affirm.assert(value, params, 'message')`. It throws `AffirmError` with the full report and narrows `value` afterwards. |
781
+ | Reject bad input with reasons (HTTP 400s, form errors) | `const report = affirm.explain(value, params); if (!report.ok) return badRequest(report.failures)`, then `affirm.assert(value, params)` to narrow (§5.1). |
782
+ | Fall back quietly | Put the main path in the positive branch: `if (affirm(value, params)) return use(value)`, then `return fallback`. |
783
+ | Handle a specific state such as "missing" | Check that state positively: `if (affirm(user, { isNull: true })) return guest()`. Exact checks narrow the code after an early return (§7.1). |
784
+ | Exclude a specific value inside a check | Use the `not:` key: `affirm(role, { isType: 'string', not: { isOneOf: ['root'] } })`. It negates one named sub-check, not the whole gate, so it's allowed. |
785
+
786
+ When `if (!affirm(…)) throw new X('message')` is flagged, the rule offers an editor suggestion to replace it with `affirm.assert(…, 'message')`. It's a suggestion, not an autofix, because the thrown error becomes an `AffirmError`.
787
+
788
+ ### Guards built on `affirm` follow the same rule
789
+
790
+ A reusable guard such as `isValidOrder(v)` (§5.5) is `affirm` under another name, so `!isValidOrder(v)` is exactly as broad as `!affirm(v, params)`. Use guards in the positive branch, or call `affirm.assert` / `affirm.explain` with their params.
791
+
792
+ ESLint checks one file at a time, so in the file that *imports* `isValidOrder`, nothing says it wraps `affirm`. The `guards` setting (§1) closes that gap with a **naming contract**:
793
+
794
+ - **`affirm/guard-naming`** (where guards are defined): every named function whose whole body returns `affirm(…)` must match the pattern, and no other function defined in the project may match it.
795
+ - **`affirm/no-negated-affirm`** (where guards are used): a negated call to any function matching the pattern is reported, wherever it was imported from.
796
+
797
+ ```ts
798
+ // guards.ts
799
+ export const isValidOrder = (v: unknown) => affirm(v, orderParams) // ✓ matches '^isValid'
800
+ export const checkUser = (v: unknown) => affirm(v, userParams) // ✗ guard-naming: must match '^isValid'
801
+ export function isValidEmail(s: string) { return s.includes('@') } // ✗ guard-naming: '^isValid' is reserved for guards
802
+
803
+ // handler.ts
804
+ import { isValidOrder } from './guards'
805
+ if (!isValidOrder(body)) return null // ✗ no-negated-affirm, even across files
806
+ ```
807
+
808
+ The two halves cover each other: a guard can't escape the pattern, and nothing that isn't a guard can match it. Two limits remain:
809
+ - Inline callbacks (`.filter((r) => affirm(r, p))`) have no name, so they aren't checked. They aren't reusable either.
810
+ - **Only your own code counts as a guard.** A negated call is checked against the pattern when the function is defined in the same file, imported from a relative path (`./guards`), or imported from a prefix listed in `guardModules`. Anything imported from a package is ignored, so `validator.isValidPhoneNumber(x)` or `import { isValidUrl } from 'url-kit'` never trips the rule. If you import your own guards through a path alias (`@/guards`), list the alias in `guardModules` (§1), or those guards are treated like a package and go unchecked.
811
+
812
+ Without `guards`, same-file wrappers are still caught. For imported guards it is then a convention only.
813
+
814
+ ### Escape hatch
815
+
816
+ If a negation really is precise in context (for example, legacy code where you know only `null` reaches the branch), disable the rule for that line **and write the reason** after `--`:
817
+
818
+ ```ts
819
+ // eslint-disable-next-line affirm/no-negated-affirm -- legacy handler: only null reaches this branch
820
+ if (!affirm(x, params)) return // ✗ allowed only with the disable comment above
821
+ ```
822
+
823
+ That keeps each exception deliberate, visible in review, and searchable (`grep -r "no-negated-affirm --"`). Never disable the rule for a whole file or project. Turn on `linterOptions: { reportUnusedDisableDirectives: 'error' }` so that stale disable comments get cleaned up.
824
+
825
+ ### Allowed, with care
826
+
827
+ - **`!report.ok`** from `affirm.explain` is fine. It is the recommended form, because the failures are right there to use.
828
+ - **`if (affirm(…)) { … } else { … }`** is allowed. Be aware that the `else` branch is just as broad as `!affirm`: treat it as "not valid, reason unknown". If the `else` needs the reason, use `explain`.
829
+
830
+ ---
831
+
832
+ ## 10. Checklist for reviewing generated `affirm` code
833
+
834
+ - [ ] Value first, params second.
835
+ - [ ] Lint is set up as in §1: `affirm.configs.recommended`, `settings.affirm.guards`, and `projectService` where the TypeScript version allows it.
836
+ - [ ] No negated `affirm()`: no `!affirm(…)`, `=== false`, `!ok`, or `!isSomeGuard(x)` for a guard built on `affirm`. Failure paths use `assert`, `explain` or a positive check.
837
+ - [ ] Every reusable guard built on `affirm` is named by the `guards` pattern, and nothing else is.
838
+ - [ ] Any `eslint-disable` for an `affirm/*` rule covers one line and has a reason after `--`.
839
+ - [ ] Optional fields use `anyOf: [{ isUndefined: true }, …]`. Nullable fields use `isNull`. Fields that can be both use `isNullish`.
840
+ - [ ] `isPlainObject: true` is present when arrays must be rejected (`shape` and `isType: 'object'` accept arrays).
841
+ - [ ] `everyItem` is paired with `isNotEmpty: true` when an empty array is invalid.
842
+ - [ ] No `includes` on arrays and no `contains` on strings.
843
+ - [ ] Numeric checks run on numbers, not on numeric strings from env vars, query strings or form fields.
844
+ - [ ] `isFiniteNumber` or `isInteger` is used instead of bare `isType: 'number'` when `NaN` / `Infinity` must be rejected.
845
+ - [ ] Hoisted params, and lists used in params (`isOneOf: ROLES`), use `as const` where they're declared, even in other files. They're never annotated or cast as `AffirmParams` (`affirm/const-params`; `eslint --fix` adds it).
846
+ - [ ] Every inline function in params annotates its parameter: `(v: unknown) =>`.
847
+ - [ ] `affirm.assert` is called as a method, never destructured.
848
+ - [ ] `explain()` is used only where its failures are used, and `affirm()` everywhere else.
849
+ - [ ] No `try/catch` around `affirm()` / `explain()`. `TypeError`s are bugs to fix.
850
+ - [ ] No secrets in params.