@frankmeza/affirm 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENTS.md +154 -0
  2. package/LICENSE +21 -0
  3. package/README.md +152 -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 +842 -0
  51. package/package.json +75 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/core/errors.ts","../src/core/describe.ts","../src/core/report.ts","../src/core/check-def.ts","../src/core/util/kind.ts","../src/checks/arrays.ts","../src/checks/composition.ts","../src/core/util/deep-equal.ts","../src/checks/equality.ts","../src/checks/nullish.ts","../src/checks/numbers.ts","../src/checks/objects.ts","../src/core/util/standard-schema.ts","../src/checks/runtime-type.ts","../src/checks/size.ts","../src/checks/strings.ts","../src/core/registry.ts","../src/core/evaluate.ts","../src/core/util/levenshtein.ts","../src/core/validate-params.ts","../src/affirm.ts"],"sourcesContent":["import type { AffirmReport } from './report.js'\n\nconst MAX_REASONS = 3\n\n/**\n * Thrown by `affirm.assert` when data fails its checks (design §9). `report` has every failure.\n * The default message lists the first three reasons, then `(+N more)`.\n *\n * @example\n * try {\n * affirm.assert(body, { shape: { email: { matches: /@/ } } })\n * } catch (error) {\n * if (error instanceof AffirmError) return badRequest(error.report.failures)\n * throw error\n * }\n */\nexport class AffirmError extends Error {\n override readonly name = 'AffirmError'\n readonly report: AffirmReport\n\n constructor(report: AffirmReport, message?: string) {\n super(message ?? defaultMessage(report))\n this.report = report\n }\n}\n\nfunction defaultMessage(report: AffirmReport): string {\n const reasons = report.failures.slice(0, MAX_REASONS).map((f) => f.reason)\n const more = report.failures.length - reasons.length\n return `affirm.assert failed: ${reasons.join('; ')}${more > 0 ? ` (+${more} more)` : ''}`\n}\n","/**\n * Describes a value by type and size only, never by content (design §8, D5).\n * Used for `AffirmFailure.received`.\n */\nexport function describe(value: unknown): string {\n if (value === null) return 'null'\n switch (typeof value) {\n case 'undefined':\n return 'undefined'\n case 'string':\n return `string(len ${value.length})`\n case 'number':\n return Number.isNaN(value) ? 'number(NaN)' : 'number'\n case 'boolean':\n case 'bigint':\n case 'symbol':\n return typeof value\n case 'function':\n return 'function'\n }\n if (Array.isArray(value)) return `array(len ${value.length})`\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? 'Date(invalid)' : 'Date'\n if (value instanceof Map) return `Map(size ${value.size})`\n if (value instanceof Set) return `Set(size ${value.size})`\n if (value instanceof RegExp) return 'RegExp'\n const keys = Object.keys(value as object).length\n const proto: unknown = Object.getPrototypeOf(value)\n const name = proto === null || proto === Object.prototype ? 'object' : constructorName(value as object)\n return `${name}{${keys} ${keys === 1 ? 'key' : 'keys'}}`\n}\n\nfunction constructorName(value: object): string {\n const ctor: unknown = (value as { constructor?: unknown }).constructor\n return typeof ctor === 'function' && ctor.name !== '' ? ctor.name : 'object'\n}\n\nconst MAX_STRING_PARAM = 32\nconst MAX_LIST_ITEMS = 5\n\n/**\n * Formats a *param* (authored in code, not data) for `expected`.\n * Short strings and primitives are shown literally; anything else is described.\n */\nexport function formatParam(param: unknown): string {\n switch (typeof param) {\n case 'string':\n return param.length <= MAX_STRING_PARAM ? JSON.stringify(param) : `string(len ${param.length})`\n case 'number':\n return Object.is(param, -0) ? '-0' : String(param)\n case 'bigint':\n return `${param}n`\n case 'boolean':\n case 'undefined':\n return String(param)\n case 'symbol':\n return param.toString()\n case 'function':\n return param.name === '' ? 'function' : param.name\n }\n return param === null ? 'null' : describe(param)\n}\n\nexport function formatList(list: readonly unknown[]): string {\n const shown = list.slice(0, MAX_LIST_ITEMS).map(formatParam)\n const more = list.length - shown.length\n return `[${shown.join(', ')}${more > 0 ? `, … (+${more})` : ''}]`\n}\n","import { describe } from './describe.js'\n\n/** One failed check. Never contains raw values from the checked data (design §8, D5). */\nexport interface AffirmFailure {\n /** The params key that failed, e.g. `'hasMinLength'`. */\n key: string\n /** `''` at the root; `'user.address.zip'`; `'items[2].id'`. */\n path: string\n /** What the check wanted, e.g. `'length >= 3'`, `'not null'`. */\n expected: string\n /** A type description of the value, e.g. `'string(len 2)'`. */\n received: string\n /** One human sentence combining path, expected and received. */\n reason: string\n /** For `anyOf`: the failures of each branch. */\n branches?: AffirmFailure[][]\n}\n\nexport interface AffirmReport {\n ok: boolean\n failures: AffirmFailure[]\n}\n\nexport function makeFailure(key: string, path: string, expected: string, value: unknown): AffirmFailure {\n const received = describe(value)\n const reason = `${path === '' ? '' : `${path}: `}expected ${expected}, received ${received}`\n return { key, path, expected, received, reason }\n}\n\n/** `joinPath('items', 2)` → `'items[2]'`; `joinPath('user', 'zip')` → `'user.zip'`. */\nexport function joinPath(base: string, segment: string | number): string {\n if (typeof segment === 'number') return `${base}[${segment}]`\n return base === '' ? segment : `${base}.${segment}`\n}\n","import type { AffirmParams } from '../types/params.js'\nimport { formatParam } from './describe.js'\nimport { makeFailure, type AffirmFailure } from './report.js'\n\n/** Canonical evaluation phases (design §4 rule 7). Lower runs first. */\nexport const Phase = {\n /** Cheap type / nullish / equality checks. */\n Kind: 0,\n /** Size, number and string checks. */\n Measure: 1,\n /** Structural checks: shape, everyItem, isDeepEqual, … */\n Structural: 2,\n /** User predicates: satisfies. */\n Predicate: 3,\n} as const\nexport type Phase = (typeof Phase)[keyof typeof Phase]\n\nexport type Mode = 'first' | 'all'\n\nexport interface EvalContext {\n /** The params key being evaluated. */\n readonly key: string\n /** Path of the value being checked; `''` at the root. */\n readonly path: string\n /** `'first'` for `affirm()` (short-circuit), `'all'` for `explain()` (collect everything). */\n readonly mode: Mode\n /** Recursion for composite keys: failures of nested params, in the current mode. Params must already be validated. */\n run(value: unknown, params: AffirmParams, path: string): AffirmFailure[]\n /** Pass/fail of nested params, always short-circuiting. For `not` and `someItem`. */\n test(value: unknown, params: AffirmParams): boolean\n}\n\n/** Validates nested params (throws `TypeError`). Passed to composite keys so checks don't import the engine. */\nexport type ValidateNested = (params: unknown, path: string) => void\n\nexport interface CheckDef<Param> {\n readonly phase: Phase\n /**\n * Programmer-error guard (design §4 rule 6). Returns `undefined` when the param is valid,\n * otherwise a description of what was expected, e.g. `'a non-negative integer'`.\n * Composite keys validate their nested params with `validateNested`.\n */\n validateParam(param: unknown, path: string, validateNested: ValidateNested): string | undefined\n /** Returns `[]` on pass. */\n evaluate(value: unknown, param: Param, ctx: EvalContext): AffirmFailure[]\n}\n\n/** A group's runtime object: exactly one `CheckDef` per key of its params interface. */\nexport type CheckGroup<P> = { readonly [K in keyof P]-?: CheckDef<Exclude<P[K], undefined>> }\n\n/** Optional kind gate: if `accepts` fails, one failure is reported and `test` never runs (rule 5, D7). */\ninterface Gate<V> {\n accepts?: (value: unknown) => value is V\n /** Shown as `expected` when the gate fails, e.g. `'a number'`. */\n acceptsLabel?: string\n}\n\nexport interface LeafSpec<P, V> extends Gate<V> {\n phase: Phase\n validateParam: (param: unknown) => string | undefined\n test: (value: V, param: P) => boolean\n expected: (param: P) => string\n}\n\n/** Builds a check from a plain `(value, param) => boolean` test. */\nexport function leaf<P, V = unknown>(spec: LeafSpec<P, V>): CheckDef<P> {\n return {\n phase: spec.phase,\n validateParam: spec.validateParam,\n evaluate(value, param, ctx) {\n if (spec.accepts !== undefined && !spec.accepts(value)) {\n return [makeFailure(ctx.key, ctx.path, spec.acceptsLabel ?? 'a different kind of value', value)]\n }\n return spec.test(value as V, param) ? [] : [makeFailure(ctx.key, ctx.path, spec.expected(param), value)]\n },\n }\n}\n\nexport interface BooleanLeafSpec<V> extends Gate<V> {\n phase: Phase\n test: (value: V) => boolean\n /** `expected` when the param is `true`, e.g. `'null'`. */\n expected: string\n /** `expected` when the param is `false`, e.g. `'not null'`. */\n expectedNot: string\n}\n\n/**\n * Builds a boolean key. Implements D1 once: pass ⇔ `test(value) === param`.\n * The kind gate (if any) runs first and fails for both polarities (D7).\n */\nexport function booleanLeaf<V = unknown>(spec: BooleanLeafSpec<V>): CheckDef<boolean> {\n return {\n phase: spec.phase,\n validateParam: (param) => (typeof param === 'boolean' ? undefined : 'a boolean'),\n evaluate(value, param, ctx) {\n if (spec.accepts !== undefined && !spec.accepts(value)) {\n return [makeFailure(ctx.key, ctx.path, spec.acceptsLabel ?? 'a different kind of value', value)]\n }\n if (spec.test(value as V) === param) return []\n return [makeFailure(ctx.key, ctx.path, param ? spec.expected : spec.expectedNot, value)]\n },\n }\n}\n\nexport interface CompositeSpec<P, V> extends Gate<V> {\n phase: Phase\n validateParam: (param: unknown, path: string, validateNested: ValidateNested) => string | undefined\n /** Called only when the gate passes. Returns `[]` on pass. */\n evaluate: (value: V, param: P, ctx: EvalContext) => AffirmFailure[]\n}\n\n/**\n * Builds a composite key (shape, everyItem, anyOf, …). The kind gate runs first, so a value of the\n * wrong kind produces ONE failure instead of one per child (design §4 rule 7).\n */\nexport function composite<P, V = unknown>(spec: CompositeSpec<P, V>): CheckDef<P> {\n return {\n phase: spec.phase,\n validateParam: spec.validateParam,\n evaluate(value, param, ctx) {\n if (spec.accepts !== undefined && !spec.accepts(value)) {\n return [makeFailure(ctx.key, ctx.path, spec.acceptsLabel ?? 'a different kind of value', value)]\n }\n return spec.evaluate(value as V, param, ctx)\n },\n }\n}\n\n/** `{ isNull: true, hasKey: \"id\" }`: a short rendering of nested params for `expected`. */\nexport function formatParams(params: AffirmParams): string {\n const parts = Object.entries(params)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => `${k}: ${formatParam(v)}`)\n return `{ ${parts.join(', ')} }`\n}\n\n// Shared param validators -------------------------------------------------------------------\n\nexport const anyParam = (): undefined => undefined\n\nexport const arrayParam = (param: unknown): string | undefined =>\n Array.isArray(param) ? undefined : `an array (received ${formatParam(param)})`\n\nexport const functionParam = (param: unknown): string | undefined =>\n typeof param === 'function' ? undefined : `a function (received ${formatParam(param)})`\n\nexport const numberParam = (param: unknown): string | undefined =>\n typeof param === 'number' && !Number.isNaN(param) ? undefined : `a number, not NaN (received ${formatParam(param)})`\n\nexport const nonNegativeIntegerParam = (param: unknown): string | undefined =>\n Number.isInteger(param) && (param as number) >= 0\n ? undefined\n : `a non-negative integer (received ${formatParam(param)})`\n\nexport const stringParam = (param: unknown): string | undefined =>\n typeof param === 'string' ? undefined : `a string (received ${formatParam(param)})`\n\nconst isPropertyKey = (k: unknown): k is PropertyKey =>\n typeof k === 'string' || typeof k === 'number' || typeof k === 'symbol'\n\nexport const propertyKeyParam = (param: unknown): string | undefined =>\n isPropertyKey(param) ? undefined : `a string, number or symbol key (received ${formatParam(param)})`\n\nexport const propertyKeyListParam = (param: unknown): string | undefined =>\n Array.isArray(param) && param.every(isPropertyKey)\n ? undefined\n : `an array of string, number or symbol keys (received ${formatParam(param)})`\n","/** Prototype is `Object.prototype` or `null` (so `Object.create(null)` counts, design Q2). */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nexport function isNumber(value: unknown): value is number {\n return typeof value === 'number'\n}\n\nexport function isDate(value: unknown): value is Date {\n return value instanceof Date\n}\n\n/**\n * Heuristic for \"this is a class/constructor, not a guard function\" so `isType: Date`\n * can be rejected with \"use isInstanceOf\". Catches `class` syntax and capitalised built-ins\n * (`Date`, `Map`, `Error`, …). Arrow functions and lowercase function declarations pass.\n */\nexport function looksLikeConstructor(fn: Function): boolean {\n const source = Function.prototype.toString.call(fn)\n if (/^class[\\s{]/.test(source)) return true\n return /\\{\\s*\\[native code\\]\\s*\\}\\s*$/.test(source) && /^[A-Z]/.test(fn.name)\n}\n\n/** A number other than NaN: the kind gate for every number key (design §5 \"Numbers\"). */\nexport function isNumberNotNaN(value: unknown): value is number {\n return typeof value === 'number' && !Number.isNaN(value)\n}\n\nexport function isString(value: unknown): value is string {\n return typeof value === 'string'\n}\n\n/** Non-null object or array (functions excluded): the kind gate for object keys. */\nexport function isObjectLike(value: unknown): value is object {\n return typeof value === 'object' && value !== null\n}\n\nexport function isArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value)\n}\n\nexport type Measurable = string | readonly unknown[] | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>\n\n/** \"Measurable\" = string, array, Map, Set (design §5 \"Emptiness & size\"). */\nexport function isMeasurable(value: unknown): value is Measurable {\n return typeof value === 'string' || Array.isArray(value) || value instanceof Map || value instanceof Set\n}\n\nexport function sizeOf(value: Measurable): number {\n return typeof value === 'string' || Array.isArray(value) ? value.length : (value as ReadonlySet<unknown>).size\n}\n\n/** Own enumerable keys, string and symbol. */\nexport function ownKeys(value: object): PropertyKey[] {\n return [\n ...Object.keys(value),\n ...Object.getOwnPropertySymbols(value).filter((s) => Object.prototype.propertyIsEnumerable.call(value, s)),\n ]\n}\n","import {\n anyParam,\n arrayParam,\n composite,\n formatParams,\n leaf,\n Phase,\n type CheckGroup,\n type ValidateNested,\n} from '../core/check-def.js'\nimport { formatList, formatParam } from '../core/describe.js'\nimport { joinPath, makeFailure, type AffirmFailure } from '../core/report.js'\nimport { isArray } from '../core/util/kind.js'\nimport type { ArrayParams } from '../types/arrays.js'\nimport type { AffirmParams } from '../types/params.js'\n\n/** Nested item params are validated once, at `items[*]`. */\nconst validateItemParams = (param: unknown, path: string, validateNested: ValidateNested): undefined => {\n validateNested(param, `${path}[*]`)\n return undefined\n}\n\n// Array.prototype.includes uses SameValueZero (design §4 rule 8).\nexport const arrayChecks = {\n contains: leaf<unknown, readonly unknown[]>({\n phase: Phase.Measure,\n validateParam: anyParam,\n accepts: isArray,\n acceptsLabel: 'an array',\n test: (value, item) => value.includes(item),\n expected: (item) => `an array containing ${formatParam(item)}`,\n }),\n\n containsAll: leaf<readonly unknown[], readonly unknown[]>({\n phase: Phase.Measure,\n validateParam: arrayParam,\n accepts: isArray,\n acceptsLabel: 'an array',\n test: (value, items) => items.every((item) => value.includes(item)),\n expected: (items) => `an array containing all of ${formatList(items)}`,\n }),\n\n containsAny: leaf<readonly unknown[], readonly unknown[]>({\n phase: Phase.Measure,\n validateParam: arrayParam,\n accepts: isArray,\n acceptsLabel: 'an array',\n test: (value, items) => items.some((item) => value.includes(item)),\n expected: (items) => `an array containing any of ${formatList(items)}`,\n }),\n\n /** Failures carry the item path: `items[2].id`. Vacuously true on `[]`. */\n everyItem: composite<AffirmParams, readonly unknown[]>({\n phase: Phase.Structural,\n validateParam: validateItemParams,\n accepts: isArray,\n acceptsLabel: 'an array',\n evaluate(value, params, ctx) {\n const failures: AffirmFailure[] = []\n for (let i = 0; i < value.length; i++) {\n failures.push(...ctx.run(value[i], params, joinPath(ctx.path, i)))\n if (ctx.mode === 'first' && failures.length > 0) break\n }\n return failures\n },\n }),\n\n /** One failure when no item passes (per-item failures would just be noise). False on `[]`. */\n someItem: composite<AffirmParams, readonly unknown[]>({\n phase: Phase.Structural,\n validateParam: validateItemParams,\n accepts: isArray,\n acceptsLabel: 'an array',\n evaluate(value, params, ctx) {\n if (value.some((item) => ctx.test(item, params))) return []\n return [makeFailure(ctx.key, ctx.path, `at least one item passing ${formatParams(params)}`, value)]\n },\n }),\n} satisfies CheckGroup<ArrayParams>\n","import { composite, formatParams, functionParam, leaf, Phase, type CheckGroup, type ValidateNested } from '../core/check-def.js'\nimport { makeFailure, type AffirmFailure } from '../core/report.js'\nimport type { CompositionParams } from '../types/composition.js'\nimport type { AffirmParams } from '../types/params.js'\n\nfunction validateBranches(param: unknown, path: string, validateNested: ValidateNested): string | undefined {\n if (!Array.isArray(param) || param.length === 0) return 'a non-empty array of params'\n for (const branch of param) validateNested(branch, path)\n return undefined\n}\n\nexport const compositionChecks = {\n not: composite<AffirmParams>({\n phase: Phase.Structural,\n validateParam: (param, path, validateNested) => {\n validateNested(param, path)\n return undefined\n },\n evaluate(value, params, ctx) {\n return ctx.test(value, params) ? [makeFailure(ctx.key, ctx.path, `not ${formatParams(params)}`, value)] : []\n },\n }),\n\n /**\n * Passes when any branch passes. The failure lists every branch's failures in `branches`\n * (all of them under `explain()`, the first per branch under `affirm()`).\n */\n anyOf: composite<readonly AffirmParams[]>({\n phase: Phase.Structural,\n validateParam: validateBranches,\n evaluate(value, branches, ctx) {\n const branchFailures: AffirmFailure[][] = []\n for (const branch of branches) {\n const failures = ctx.run(value, branch, ctx.path)\n if (failures.length === 0) return []\n branchFailures.push(failures)\n }\n const n = branches.length\n const failure = makeFailure(ctx.key, ctx.path, `any of ${n} ${n === 1 ? 'branch' : 'branches'} to pass`, value)\n return [{ ...failure, branches: branchFailures }]\n },\n }),\n\n satisfies: leaf<(value: unknown) => boolean>({\n phase: Phase.Predicate,\n validateParam: functionParam,\n test: (value, predicate) => predicate(value) === true,\n expected: (predicate) => `${predicate.name || 'predicate'}(value) to return true`,\n }),\n} satisfies CheckGroup<CompositionParams>\n","import { isPlainObject } from './kind.js'\n\n/**\n * Structural equality per design §7.\n * - primitives: `Object.is`, except `+0` equals `-0`\n * - arrays: same length, elementwise\n * - plain objects: same own enumerable string keys, valuewise\n * - Date: same time · RegExp: same source + flags\n * - Map: same size, same keys (SameValueZero), values deep-equal\n * - Set: same size, every member present (SameValueZero; no deep matching of members)\n * - other class instances: reference equality only\n * - cycles: a pair already under comparison counts as equal\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n return eq(a, b, new Map())\n}\n\nfunction eq(a: unknown, b: unknown, seen: Map<object, Set<object>>): boolean {\n if (a === b || Object.is(a, b)) return true\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n\n let partners = seen.get(a)\n if (partners?.has(b)) return true\n if (partners === undefined) seen.set(a, (partners = new Set()))\n partners.add(b)\n\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false\n return a.every((item, i) => eq(item, b[i], seen))\n }\n if (isPlainObject(a) || isPlainObject(b)) {\n if (!isPlainObject(a) || !isPlainObject(b)) return false\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) return false\n return keys.every((key) => Object.hasOwn(b, key) && eq(a[key], b[key], seen))\n }\n if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false\n if (a instanceof Date) return Object.is(a.getTime(), (b as Date).getTime())\n if (a instanceof RegExp) return a.source === (b as RegExp).source && a.flags === (b as RegExp).flags\n if (a instanceof Map) {\n const bm = b as Map<unknown, unknown>\n if (a.size !== bm.size) return false\n for (const [key, value] of a) {\n if (!bm.has(key) || !eq(value, bm.get(key), seen)) return false\n }\n return true\n }\n if (a instanceof Set) {\n const bs = b as Set<unknown>\n if (a.size !== bs.size) return false\n for (const member of a) if (!bs.has(member)) return false\n return true\n }\n return false\n}\n","import { anyParam, arrayParam, leaf, Phase, type CheckGroup } from '../core/check-def.js'\nimport { formatList, formatParam } from '../core/describe.js'\nimport { deepEqual } from '../core/util/deep-equal.js'\nimport type { EqualityParams } from '../types/equality.js'\n\nexport const equalityChecks = {\n is: leaf<unknown>({\n phase: Phase.Kind,\n validateParam: anyParam,\n test: (value, param) => value === param,\n expected: (param) => `=== ${formatParam(param)}`,\n }),\n\n isNot: leaf<unknown>({\n phase: Phase.Kind,\n validateParam: anyParam,\n test: (value, param) => value !== param,\n expected: (param) => `!== ${formatParam(param)}`,\n }),\n\n // Array.prototype.includes uses SameValueZero (rule 8).\n isOneOf: leaf<readonly unknown[]>({\n phase: Phase.Kind,\n validateParam: arrayParam,\n test: (value, list) => list.includes(value),\n expected: (list) => `one of ${formatList(list)}`,\n }),\n\n isNotOneOf: leaf<readonly unknown[]>({\n phase: Phase.Kind,\n validateParam: arrayParam,\n test: (value, list) => !list.includes(value),\n expected: (list) => `none of ${formatList(list)}`,\n }),\n\n isDeepEqual: leaf<unknown>({\n phase: Phase.Structural,\n validateParam: anyParam,\n test: (value, param) => deepEqual(value, param),\n expected: (param) => `deep equal to ${formatParam(param)}`,\n }),\n} satisfies CheckGroup<EqualityParams>\n","import { booleanLeaf, Phase, type CheckGroup } from '../core/check-def.js'\nimport type { NullishParams } from '../types/nullish.js'\n\nexport const nullishChecks = {\n isNull: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => value === null,\n expected: 'null',\n expectedNot: 'not null',\n }),\n\n isUndefined: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => value === undefined,\n expected: 'undefined',\n expectedNot: 'not undefined',\n }),\n\n isNullish: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => value === null || value === undefined,\n expected: 'null or undefined',\n expectedNot: 'not null or undefined',\n }),\n\n isDefined: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => value !== undefined,\n expected: 'defined (not undefined)',\n expectedNot: 'undefined',\n }),\n\n isPresent: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => value !== null && value !== undefined,\n expected: 'present (not null or undefined)',\n expectedNot: 'null or undefined',\n }),\n\n isTruthy: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => Boolean(value),\n expected: 'truthy',\n expectedNot: 'falsy',\n }),\n\n isFalsy: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => !value,\n expected: 'falsy',\n expectedNot: 'truthy',\n }),\n} satisfies CheckGroup<NullishParams>\n","import { booleanLeaf, leaf, numberParam, Phase, type CheckDef, type CheckGroup } from '../core/check-def.js'\nimport { formatParam } from '../core/describe.js'\nimport { isNumberNotNaN } from '../core/util/kind.js'\nimport type { NumberParams } from '../types/numbers.js'\n\nconst NUMBER = 'a number (not NaN)'\n\n/** A comparison key: `value <op> n`. */\nfunction compare(test: (value: number, n: number) => boolean, op: string): CheckDef<number> {\n return leaf<number, number>({\n phase: Phase.Measure,\n validateParam: numberParam,\n accepts: isNumberNotNaN,\n acceptsLabel: NUMBER,\n test,\n expected: (n) => `${op} ${formatParam(n)}`,\n })\n}\n\nfunction validateRange(param: unknown): string | undefined {\n if (\n !Array.isArray(param) ||\n param.length !== 2 ||\n numberParam(param[0]) !== undefined ||\n numberParam(param[1]) !== undefined\n ) {\n return `a [min, max] pair of numbers (received ${formatParam(param)})`\n }\n return param[0] <= param[1] ? undefined : `min <= max (received [${param[0]}, ${param[1]}])`\n}\n\nfunction validateDivisor(param: unknown): string | undefined {\n return Number.isFinite(param) && param !== 0 ? undefined : `a finite non-zero number (received ${formatParam(param)})`\n}\n\nexport const numberChecks = {\n isGreaterThan: compare((v, n) => v > n, '>'),\n isAtLeast: compare((v, n) => v >= n, '>='),\n isLessThan: compare((v, n) => v < n, '<'),\n isAtMost: compare((v, n) => v <= n, '<='),\n\n // D3: inclusive at both ends.\n isBetween: leaf<readonly [number, number], number>({\n phase: Phase.Measure,\n validateParam: validateRange,\n accepts: isNumberNotNaN,\n acceptsLabel: NUMBER,\n test: (value, [min, max]) => value >= min && value <= max,\n expected: ([min, max]) => `between ${formatParam(min)} and ${formatParam(max)} (inclusive)`,\n }),\n\n isPositive: booleanLeaf<number>({\n phase: Phase.Measure,\n accepts: isNumberNotNaN,\n acceptsLabel: NUMBER,\n test: (value) => value > 0,\n expected: '> 0',\n expectedNot: '<= 0',\n }),\n\n isNegative: booleanLeaf<number>({\n phase: Phase.Measure,\n accepts: isNumberNotNaN,\n acceptsLabel: NUMBER,\n test: (value) => value < 0,\n expected: '< 0',\n expectedNot: '>= 0',\n }),\n\n isMultipleOf: leaf<number, number>({\n phase: Phase.Measure,\n validateParam: validateDivisor,\n accepts: isNumberNotNaN,\n acceptsLabel: NUMBER,\n test: (value, n) => value % n === 0,\n expected: (n) => `a multiple of ${formatParam(n)}`,\n }),\n} satisfies CheckGroup<NumberParams>\n","import {\n composite,\n leaf,\n Phase,\n propertyKeyListParam,\n propertyKeyParam,\n type CheckGroup,\n type ValidateNested,\n} from '../core/check-def.js'\nimport { formatList, formatParam } from '../core/describe.js'\nimport { joinPath, type AffirmFailure } from '../core/report.js'\nimport { isObjectLike, isPlainObject, ownKeys } from '../core/util/kind.js'\nimport type { ObjectParams } from '../types/objects.js'\nimport type { AffirmParams } from '../types/params.js'\n\nconst OBJECT = 'an object or array'\n\n/** Own-key comparison treats `0` and `'0'` as the same key, like property access does. */\nconst normalizeKey = (key: PropertyKey): string | symbol => (typeof key === 'symbol' ? key : String(key))\n\nfunction validatePath(param: unknown): string | undefined {\n if (typeof param !== 'string') return `a dot path string (received ${formatParam(param)})`\n if (param.split('.').some((segment) => segment === '')) {\n return `a dot path with no empty segments (received ${formatParam(param)})`\n }\n return undefined\n}\n\nfunction hasOwnPath(value: object, path: string): boolean {\n let current: unknown = value\n for (const segment of path.split('.')) {\n if (!isObjectLike(current) || !Object.hasOwn(current, segment)) return false\n current = (current as Record<string, unknown>)[segment]\n }\n return true\n}\n\nfunction validateShape(param: unknown, path: string, validateNested: ValidateNested): string | undefined {\n if (!isPlainObject(param)) return `an object mapping field names to params (received ${formatParam(param)})`\n if (Object.keys(param).length === 0) return 'at least one field; `shape: {}` would always pass'\n for (const [field, fieldParams] of Object.entries(param)) validateNested(fieldParams, joinPath(path, field))\n return undefined\n}\n\nconst shapeCheck = composite<Readonly<Record<string, AffirmParams>>, object>({\n phase: Phase.Structural,\n validateParam: validateShape,\n accepts: isObjectLike,\n acceptsLabel: OBJECT,\n evaluate(value, shape, ctx) {\n const failures: AffirmFailure[] = []\n for (const [field, fieldParams] of Object.entries(shape)) {\n // Own-key semantics (D2): a missing or inherited field is checked as `undefined`.\n const fieldValue = Object.hasOwn(value, field) ? (value as Record<string, unknown>)[field] : undefined\n failures.push(...ctx.run(fieldValue, fieldParams, joinPath(ctx.path, field)))\n if (ctx.mode === 'first' && failures.length > 0) break\n }\n return failures\n },\n})\n\nexport const objectChecks = {\n shape: shapeCheck,\n\n hasKey: leaf<PropertyKey, object>({\n phase: Phase.Measure,\n validateParam: propertyKeyParam,\n accepts: isObjectLike,\n acceptsLabel: OBJECT,\n test: (value, key) => Object.hasOwn(value, key),\n expected: (key) => `own key ${formatParam(key)}`,\n }),\n\n hasKeys: leaf<readonly PropertyKey[], object>({\n phase: Phase.Measure,\n validateParam: propertyKeyListParam,\n accepts: isObjectLike,\n acceptsLabel: OBJECT,\n test: (value, keys) => keys.every((key) => Object.hasOwn(value, key)),\n expected: (keys) => `own keys ${formatList(keys)}`,\n }),\n\n hasAnyKey: leaf<readonly PropertyKey[], object>({\n phase: Phase.Measure,\n validateParam: propertyKeyListParam,\n accepts: isObjectLike,\n acceptsLabel: OBJECT,\n test: (value, keys) => keys.some((key) => Object.hasOwn(value, key)),\n expected: (keys) => `at least one own key of ${formatList(keys)}`,\n }),\n\n hasOnlyKeys: leaf<readonly PropertyKey[], object>({\n phase: Phase.Measure,\n validateParam: propertyKeyListParam,\n accepts: isObjectLike,\n acceptsLabel: OBJECT,\n test: (value, keys) => {\n const allowed = new Set(keys.map(normalizeKey))\n return ownKeys(value).every((key) => allowed.has(normalizeKey(key)))\n },\n expected: (keys) => `no own keys other than ${formatList(keys)}`,\n }),\n\n hasPath: leaf<string, object>({\n phase: Phase.Measure,\n validateParam: validatePath,\n accepts: isObjectLike,\n acceptsLabel: OBJECT,\n test: hasOwnPath,\n expected: (path) => `own path ${formatParam(path)}`,\n }),\n} satisfies CheckGroup<ObjectParams>\n","// Vendored Standard Schema V1 types (https://standardschema.dev). The spec intends these to be\n// copied rather than depended on (design §10). Type-only; no runtime code from the spec.\n\n/** The Standard Schema interface. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>\n}\n\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1\n /** The vendor name of the schema library. */\n readonly vendor: string\n /** Validates unknown input values. */\n readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output\n /** The non-existent issues. */\n readonly issues?: undefined\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input\n /** The output type of the schema. */\n readonly output: Output\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input']\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output']\n}\n\n// --- affirm's runtime helpers ---------------------------------------------------------------\n\n/**\n * Detects a Standard Schema via its `'~standard'` property. Schemas may be objects (Zod, Valibot)\n * or callable functions (ArkType), so both are accepted.\n */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return false\n const props: unknown = (value as { '~standard'?: unknown })['~standard']\n return (\n typeof props === 'object' &&\n props !== null &&\n (props as { version?: unknown }).version === 1 &&\n typeof (props as { validate?: unknown }).validate === 'function'\n )\n}\n\n/** Runs a schema synchronously. Throws `TypeError` for async schemas (design §4 rule 6, §10). */\nexport function validateSync(schema: StandardSchemaV1, value: unknown): StandardSchemaV1.Result<unknown> {\n const result = schema['~standard'].validate(value)\n if (typeof (result as { then?: unknown }).then === 'function') {\n // Avoid an unhandled rejection from the promise we're discarding.\n ;(result as Promise<unknown>).then(undefined, () => {})\n throw new TypeError(\n `affirm: async schemas are not supported by affirm; validate them before calling affirm (vendor: ${schema['~standard'].vendor})`,\n )\n }\n return result as StandardSchemaV1.Result<unknown>\n}\n","import { booleanLeaf, leaf, Phase, type CheckDef, type CheckGroup, type EvalContext } from '../core/check-def.js'\nimport { formatParam } from '../core/describe.js'\nimport { joinPath, makeFailure, type AffirmFailure } from '../core/report.js'\nimport { isDate, isNumber, isPlainObject, looksLikeConstructor } from '../core/util/kind.js'\nimport { isStandardSchema, validateSync, type StandardSchemaV1 } from '../core/util/standard-schema.js'\nimport type { RuntimeTypeParams, TypeGuard, TypeTag } from '../types/runtime-type.js'\n\nconst TYPE_TAGS: ReadonlySet<string> = new Set<TypeTag>([\n 'string',\n 'number',\n 'boolean',\n 'bigint',\n 'symbol',\n 'function',\n 'object',\n])\n\nfunction validateIsType(param: unknown): string | undefined {\n // Schemas first: ArkType schemas are callable, and would otherwise be taken for guards.\n if (isStandardSchema(param)) return undefined\n if (typeof param === 'string') {\n if (TYPE_TAGS.has(param)) return undefined\n if (param === 'undefined') return `a type tag; use \\`isUndefined: true\\` instead of \\`isType: 'undefined'\\``\n if (param === 'null') return `a type tag; use \\`isNull: true\\` instead of \\`isType: 'null'\\``\n return `one of ${[...TYPE_TAGS].map((t) => `'${t}'`).join(', ')} (received ${formatParam(param)})`\n }\n if (typeof param === 'function') {\n if (looksLikeConstructor(param)) {\n return `a type tag, guard or schema; use \\`isInstanceOf: ${param.name || 'YourClass'}\\` for classes`\n }\n return undefined\n }\n return `a type tag, a type guard function or a Standard Schema (received ${formatParam(param)})`\n}\n\nfunction matchesTag(value: unknown, tag: TypeTag): boolean {\n if (tag === 'object') return typeof value === 'object' && value !== null\n return typeof value === tag\n}\n\ntype PathSegment = PropertyKey | StandardSchemaV1.PathSegment\n\nconst segmentKey = (segment: PathSegment): PropertyKey =>\n typeof segment === 'object' && segment !== null ? segment.key : segment\n\n/** Appends a schema issue path: numbers as `[n]`, strings as `.key`, symbols as `[Symbol(x)]`. */\nfunction appendIssuePath(base: string, path: readonly PathSegment[] | undefined): string {\n let out = base\n for (const segment of path ?? []) {\n const key = segmentKey(segment)\n out = typeof key === 'symbol' ? `${out}[${key.toString()}]` : joinPath(out, key)\n }\n return out\n}\n\n/** The value an issue points at, for `received` (described by type only, D5). */\nfunction valueAt(value: unknown, path: readonly PathSegment[] | undefined): unknown {\n let current = value\n for (const segment of path ?? []) {\n if ((typeof current !== 'object' && typeof current !== 'function') || current === null) return undefined\n current = (current as Record<PropertyKey, unknown>)[segmentKey(segment)]\n }\n return current\n}\n\n/**\n * Maps schema issues to failures (design §10). Issue *messages* are not copied: libraries may put\n * the received value in them (e.g. enum mismatches), and reports must not carry raw values (D5).\n */\nfunction schemaFailures(schema: StandardSchemaV1, value: unknown, ctx: EvalContext): AffirmFailure[] {\n const result = validateSync(schema, value)\n if (result.issues === undefined) return []\n const vendor = schema['~standard'].vendor\n if (result.issues.length === 0) return [makeFailure(ctx.key, ctx.path, `a value accepted by the ${vendor} schema`, value)]\n return result.issues.map((issue) =>\n makeFailure(\n ctx.key,\n appendIssuePath(ctx.path, issue.path),\n `a value accepted by the ${vendor} schema`,\n valueAt(value, issue.path),\n ),\n )\n}\n\nconst isTypeCheck: CheckDef<TypeTag | TypeGuard | StandardSchemaV1> = {\n phase: Phase.Kind,\n validateParam: validateIsType,\n evaluate(value, param, ctx) {\n if (isStandardSchema(param)) return schemaFailures(param, value, ctx)\n if (typeof param === 'string') {\n if (matchesTag(value, param)) return []\n return [makeFailure(ctx.key, ctx.path, param === 'object' ? 'a non-null object' : `typeof ${param}`, value)]\n }\n if (param(value) === true) return []\n return [makeFailure(ctx.key, ctx.path, `${param.name || 'guard'}(value) to return true`, value)]\n },\n}\n\nexport const runtimeTypeChecks = {\n isType: isTypeCheck,\n\n isArray: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => Array.isArray(value),\n expected: 'an array',\n expectedNot: 'not an array',\n }),\n\n isPlainObject: booleanLeaf({\n phase: Phase.Kind,\n test: isPlainObject,\n expected: 'a plain object',\n expectedNot: 'not a plain object',\n }),\n\n isFunction: booleanLeaf({\n phase: Phase.Kind,\n test: (value) => typeof value === 'function',\n expected: 'a function',\n expectedNot: 'not a function',\n }),\n\n isInstanceOf: leaf<abstract new (...args: any) => any>({\n phase: Phase.Kind,\n validateParam: (param) =>\n typeof param === 'function' && param.prototype !== undefined\n ? undefined\n : `a class or constructor (received ${formatParam(param)})`,\n test: (value, ctor) => value instanceof ctor,\n expected: (ctor) => `instance of ${ctor.name || 'the given class'}`,\n }),\n\n isValidDate: booleanLeaf<Date>({\n phase: Phase.Kind,\n accepts: isDate,\n acceptsLabel: 'a Date',\n test: (date) => !Number.isNaN(date.getTime()),\n expected: 'a valid Date',\n expectedNot: 'an invalid Date',\n }),\n\n isInteger: booleanLeaf<number>({\n phase: Phase.Kind,\n accepts: isNumber,\n acceptsLabel: 'a number',\n test: Number.isInteger,\n expected: 'an integer',\n expectedNot: 'a non-integer number',\n }),\n\n isFiniteNumber: booleanLeaf<number>({\n phase: Phase.Kind,\n accepts: isNumber,\n acceptsLabel: 'a number',\n test: Number.isFinite,\n expected: 'a finite number',\n expectedNot: 'a non-finite number (Infinity, -Infinity or NaN)',\n }),\n\n isNaN: booleanLeaf<number>({\n phase: Phase.Kind,\n accepts: isNumber,\n acceptsLabel: 'a number',\n test: Number.isNaN,\n expected: 'NaN',\n expectedNot: 'a number other than NaN',\n }),\n} satisfies CheckGroup<RuntimeTypeParams>\n","import { booleanLeaf, leaf, nonNegativeIntegerParam, Phase, type CheckGroup } from '../core/check-def.js'\nimport { isMeasurable, isPlainObject, isString, sizeOf, type Measurable } from '../core/util/kind.js'\nimport type { SizeParams } from '../types/size.js'\n\nconst MEASURABLE = 'a string, array, Map or Set'\n\n/** isEmpty / isNotEmpty also accept plain objects (own enumerable keys). */\ntype Sizable = Measurable | Record<string, unknown>\nconst isSizable = (value: unknown): value is Sizable => isMeasurable(value) || isPlainObject(value)\nconst sizeOfSizable = (value: Sizable): number =>\n isMeasurable(value) ? sizeOf(value) : Object.keys(value).length\nconst SIZABLE = 'a string, array, Map, Set or plain object'\n\nexport const sizeChecks = {\n isEmpty: booleanLeaf<Sizable>({\n phase: Phase.Measure,\n accepts: isSizable,\n acceptsLabel: SIZABLE,\n test: (value) => sizeOfSizable(value) === 0,\n expected: 'empty',\n expectedNot: 'not empty',\n }),\n\n isNotEmpty: booleanLeaf<Sizable>({\n phase: Phase.Measure,\n accepts: isSizable,\n acceptsLabel: SIZABLE,\n test: (value) => sizeOfSizable(value) > 0,\n expected: 'not empty',\n expectedNot: 'empty',\n }),\n\n isBlank: booleanLeaf<string>({\n phase: Phase.Measure,\n accepts: isString,\n acceptsLabel: 'a string',\n test: (value) => value.trim() === '',\n expected: 'a blank string',\n expectedNot: 'a non-blank string',\n }),\n\n hasLength: leaf<number, Measurable>({\n phase: Phase.Measure,\n validateParam: nonNegativeIntegerParam,\n accepts: isMeasurable,\n acceptsLabel: MEASURABLE,\n test: (value, n) => sizeOf(value) === n,\n expected: (n) => `length === ${n}`,\n }),\n\n hasMinLength: leaf<number, Measurable>({\n phase: Phase.Measure,\n validateParam: nonNegativeIntegerParam,\n accepts: isMeasurable,\n acceptsLabel: MEASURABLE,\n test: (value, n) => sizeOf(value) >= n,\n expected: (n) => `length >= ${n}`,\n }),\n\n hasMaxLength: leaf<number, Measurable>({\n phase: Phase.Measure,\n validateParam: nonNegativeIntegerParam,\n accepts: isMeasurable,\n acceptsLabel: MEASURABLE,\n test: (value, n) => sizeOf(value) <= n,\n expected: (n) => `length <= ${n}`,\n }),\n} satisfies CheckGroup<SizeParams>\n","import { leaf, Phase, stringParam, type CheckGroup } from '../core/check-def.js'\nimport { formatParam } from '../core/describe.js'\nimport { isString } from '../core/util/kind.js'\nimport type { StringParams } from '../types/strings.js'\n\nconst MAX_REGEX_SHOWN = 40\n\nfunction formatRegExp(re: RegExp): string {\n const text = String(re)\n return text.length <= MAX_REGEX_SHOWN ? text : `${text.slice(0, MAX_REGEX_SHOWN)}…`\n}\n\nexport const stringChecks = {\n startsWith: leaf<string, string>({\n phase: Phase.Measure,\n validateParam: stringParam,\n accepts: isString,\n acceptsLabel: 'a string',\n test: (value, prefix) => value.startsWith(prefix),\n expected: (prefix) => `a string starting with ${formatParam(prefix)}`,\n }),\n\n endsWith: leaf<string, string>({\n phase: Phase.Measure,\n validateParam: stringParam,\n accepts: isString,\n acceptsLabel: 'a string',\n test: (value, suffix) => value.endsWith(suffix),\n expected: (suffix) => `a string ending with ${formatParam(suffix)}`,\n }),\n\n includes: leaf<string, string>({\n phase: Phase.Measure,\n validateParam: stringParam,\n accepts: isString,\n acceptsLabel: 'a string',\n test: (value, part) => value.includes(part),\n expected: (part) => `a string including ${formatParam(part)}`,\n }),\n\n matches: leaf<RegExp, string>({\n phase: Phase.Measure,\n validateParam: (param) =>\n param instanceof RegExp ? undefined : `a RegExp (received ${formatParam(param)}); use \\`includes\\` for plain text`,\n accepts: isString,\n acceptsLabel: 'a string',\n test: (value, re) => {\n re.lastIndex = 0 // /g and /y regexes keep state between calls\n return re.test(value)\n },\n expected: (re) => `a string matching ${formatRegExp(re)}`,\n }),\n} satisfies CheckGroup<StringParams>\n","import { arrayChecks } from '../checks/arrays.js'\nimport { compositionChecks } from '../checks/composition.js'\nimport { equalityChecks } from '../checks/equality.js'\nimport { nullishChecks } from '../checks/nullish.js'\nimport { numberChecks } from '../checks/numbers.js'\nimport { objectChecks } from '../checks/objects.js'\nimport { runtimeTypeChecks } from '../checks/runtime-type.js'\nimport { sizeChecks } from '../checks/size.js'\nimport { stringChecks } from '../checks/strings.js'\nimport type { AffirmParams } from '../types/params.js'\nimport type { CheckDef, CheckGroup } from './check-def.js'\n\ntype AnyGroup = Readonly<Record<string, CheckDef<any>>>\ntype UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never\n\n/**\n * Merges group objects into one registry. Throws at module load on a duplicate key,\n * which a plain spread would silently overwrite.\n */\nexport function defineRegistry<const G extends readonly AnyGroup[]>(...groups: G): UnionToIntersection<G[number]> {\n const merged: Record<string, CheckDef<any>> = {}\n for (const group of groups) {\n for (const key of Object.keys(group)) {\n if (Object.hasOwn(merged, key)) throw new Error(`affirm: duplicate check key \\`${key}\\` across groups`)\n merged[key] = group[key]!\n }\n }\n return merged as UnionToIntersection<G[number]>\n}\n\n/** Every check, keyed by params key. Group order here is the tie-breaker within a phase. */\nexport const checks: CheckGroup<AffirmParams> = defineRegistry(\n nullishChecks,\n runtimeTypeChecks,\n equalityChecks,\n sizeChecks,\n numberChecks,\n stringChecks,\n objectChecks,\n arrayChecks,\n compositionChecks,\n)\n\nexport type CheckKey = keyof AffirmParams\n\n/** All keys, sorted by phase (stable, so registry order breaks ties). Design §4 rule 7. */\nexport const KEY_ORDER: readonly CheckKey[] = (Object.keys(checks) as CheckKey[])\n .map((key, index) => ({ key, index, phase: checks[key].phase }))\n .sort((a, b) => a.phase - b.phase || a.index - b.index)\n .map(({ key }) => key)\n\nconst RANK: ReadonlyMap<string, number> = new Map(KEY_ORDER.map((key, i) => [key, i]))\n\nexport function isCheckKey(key: string): key is CheckKey {\n return RANK.has(key)\n}\n\n/** Canonical rank of a key; only call with keys that passed `isCheckKey`. */\nexport function rankOf(key: CheckKey): number {\n return RANK.get(key)!\n}\n","import type { AffirmParams } from '../types/params.js'\nimport type { CheckDef, EvalContext, Mode } from './check-def.js'\nimport { checks, isCheckKey, rankOf, type CheckKey } from './registry.js'\nimport type { AffirmFailure } from './report.js'\n\n/**\n * Runs already-validated params against a value in canonical key order (design §4 rule 7).\n * `'first'` stops at the first failing key; `'all'` collects every failure.\n */\nexport function runParams(value: unknown, params: AffirmParams, path: string, mode: Mode): AffirmFailure[] {\n const keys = (Object.keys(params).filter(isCheckKey) as CheckKey[]).sort((a, b) => rankOf(a) - rankOf(b))\n const failures: AffirmFailure[] = []\n const run = (v: unknown, p: AffirmParams, at: string) => runParams(v, p, at, mode)\n const test = (v: unknown, p: AffirmParams) => runParams(v, p, path, 'first').length === 0\n\n for (const key of keys) {\n const param = params[key]\n if (param === undefined) continue // rule 3\n const ctx: EvalContext = { key, path, mode, run, test }\n const result = (checks[key] as CheckDef<unknown>).evaluate(value, param, ctx)\n if (result.length > 0) {\n failures.push(...result)\n if (mode === 'first') break\n }\n }\n return failures\n}\n","export function levenshtein(a: string, b: string): number {\n if (a === b) return 0\n if (a.length === 0) return b.length\n if (b.length === 0) return a.length\n let prev = Array.from({ length: b.length + 1 }, (_, i) => i)\n for (let i = 1; i <= a.length; i++) {\n const curr = [i]\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n curr[j] = Math.min(prev[j]! + 1, curr[j - 1]! + 1, prev[j - 1]! + cost)\n }\n prev = curr\n }\n return prev[b.length]!\n}\n\n/** Closest candidate by case-insensitive edit distance, or `undefined` if nothing is close enough. */\nexport function closest(input: string, candidates: readonly string[]): string | undefined {\n const needle = input.toLowerCase()\n const limit = Math.max(2, Math.floor(input.length / 3))\n let best: string | undefined\n let bestDistance = Infinity\n for (const candidate of candidates) {\n const d = levenshtein(needle, candidate.toLowerCase())\n if (d < bestDistance) {\n best = candidate\n bestDistance = d\n }\n }\n return bestDistance <= limit ? best : undefined\n}\n","import type { AffirmParams } from '../types/params.js'\nimport { formatParam } from './describe.js'\nimport { checks, isCheckKey, KEY_ORDER } from './registry.js'\nimport { closest } from './util/levenshtein.js'\n\n/**\n * Throws `TypeError` for programmer errors (design §4 rule 6, D4):\n * params that are not an object, empty params `{}`, unknown keys, and wrong param types.\n * Runs over all keys before any evaluation, so a typo can't hide behind a short-circuit.\n * `path` locates nested params (from `shape`, `everyItem`, …) in messages.\n */\nexport function validateParams(params: unknown, path = ''): asserts params is AffirmParams {\n const where = path === '' ? '' : ` at \\`${path}\\``\n if (typeof params !== 'object' || params === null || Array.isArray(params)) {\n throw new TypeError(`affirm: params${where} must be an object of checks, received ${formatParam(params)}`)\n }\n const keys = Object.keys(params)\n if (keys.length === 0) {\n throw new TypeError(`affirm: params${where} are empty; \\`{}\\` would always pass`)\n }\n for (const key of keys) {\n if (!isCheckKey(key)) {\n const suggestion = closest(key, KEY_ORDER)\n const hint = suggestion === undefined ? '' : ` Did you mean \\`${suggestion}\\`?`\n throw new TypeError(`affirm: unknown check \\`${key}\\`${where}.${hint}`)\n }\n const param: unknown = (params as Record<string, unknown>)[key]\n if (param === undefined) continue // rule 3: undefined = skip\n const problem = checks[key].validateParam(param, path, validateParams)\n if (problem !== undefined) {\n throw new TypeError(`affirm: invalid param for \\`${key}\\`${where}: expected ${problem}`)\n }\n }\n}\n","import { AffirmError } from './core/errors.js'\nimport { runParams } from './core/evaluate.js'\nimport type { AffirmReport } from './core/report.js'\nimport { validateParams } from './core/validate-params.js'\nimport type { Affirmed, CanNarrow } from './types/affirmed.js'\nimport type { ParamsCheck } from './types/contradictions.js'\nimport type { AffirmParams } from './types/params.js'\n\n/** Makes the narrowing overload inapplicable (so the boolean one is picked) when narrowing is unsound. */\ntype IfNarrowable<V, P> = CanNarrow<V, P> extends true ? unknown : never\n\n/**\n * Design §6.1. `const P` keeps literal params (`is: 'admin'` narrows to `'admin'`).\n * Declared as an explicit interface so `affirm.assert` can carry an `asserts` signature.\n * Each narrowing signature has a non-narrowing twin for params where narrowing would be unsound\n * (see `CanNarrow`).\n */\nexport interface Affirm {\n /**\n * Checks `value` against named checks and returns `true` when all of them pass (keys combine\n * with AND; use `anyOf` for OR). Narrows `value` in the `if` branch.\n *\n * Data failures return `false`; programmer errors (unknown key, empty params, wrong param type,\n * async schema) throw `TypeError`. Use `affirm.explain` to see why a value failed.\n *\n * Never negate the result (`!affirm(…)`, `affirm(…) === false`): it means \"some check failed, for\n * some reason\", which is too broad to rely on. Use `affirm.assert`, `affirm.explain`, or a positive\n * check for the state you mean. Enforced by the `affirm/no-negated-affirm` lint rule.\n *\n * @example\n * if (affirm(order, { isPresent: true, shape: { total: { isType: 'number', isPositive: true } } })) {\n * order.total // number\n * }\n */\n <V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P> & IfNarrowable<V, P>): value is Affirmed<V, P>\n /**\n * Checks `value` against named checks and returns `true` when all of them pass.\n * (This signature is used when narrowing would be unsound, e.g. `isFalsy` on `string | null`.)\n *\n * @example\n * if (affirm(name, { isFalsy: true })) return 'anonymous'\n */\n <V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P>): boolean\n /**\n * Evaluates every check and reports all failures, with paths like `items[2].id`.\n * Never throws on data failures. Reports describe values by type only (`string(len 2)`),\n * never by content, so they are safe to log.\n *\n * @example\n * const report = affirm.explain(body, { shape: { email: { matches: /@/ } } })\n * if (!report.ok) log.warn(report.failures.map((f) => f.reason))\n */\n explain<const P extends AffirmParams>(value: unknown, params: P & ParamsCheck<P>): AffirmReport\n /**\n * Throws `AffirmError` (with the full report) unless every check passes; afterwards `value`\n * is narrowed for the rest of the scope.\n *\n * @example\n * affirm.assert(config.port, { isInteger: true, isBetween: [1, 65535] }, 'invalid PORT')\n * server.listen(config.port) // number\n */\n assert<V, const P extends AffirmParams>(\n value: V,\n params: P & ParamsCheck<P> & IfNarrowable<V, P>,\n message?: string,\n ): asserts value is Affirmed<V, P>\n /**\n * Throws `AffirmError` (with the full report) unless every check passes.\n * (This signature is used when narrowing would be unsound.)\n *\n * @example\n * affirm.assert(input, { isFalsy: true }, 'expected no input')\n */\n assert<V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P>, message?: string): void\n}\n\nfunction call(value: unknown, params: AffirmParams): boolean {\n validateParams(params)\n return runParams(value, params, '', 'first').length === 0\n}\n\nfunction explain(value: unknown, params: AffirmParams): AffirmReport {\n validateParams(params)\n const failures = runParams(value, params, '', 'all')\n return { ok: failures.length === 0, failures }\n}\n\nfunction assertOrThrow(value: unknown, params: AffirmParams, message?: string): void {\n const report = explain(value, params)\n if (!report.ok) throw new AffirmError(report, message)\n}\n\n// The implementations are plain boolean/void functions; the narrowing lives only in `Affirm`.\n/**\n * Replaces compound data checks with one readable object of named checks.\n * See `AffirmParams` for every key, and `AGENTS.md` for the usage guide.\n *\n * @example\n * import { affirm } from '@frankmeza/affirm'\n *\n * if (affirm(user, { isPresent: true, hasKey: 'email' })) { … }\n * affirm.explain(user, { shape: { email: { matches: /@/ } } }) // { ok, failures }\n * affirm.assert(user, { isPresent: true }) // throws AffirmError, then narrows\n */\nexport const affirm: Affirm = Object.assign(call, { explain, assert: assertOrThrow }) as Affirm\n"],"mappings":";AAEA,IAAM,cAAc;;;;;;;;;;;;;AAcpB,IAAa,cAAb,cAAiC,MAAM;CACnB,OAAO;CAChB;CAET,YAAY,QAAsB,SAAkB;EAClD,MAAM,WAAW,eAAe,MAAM,CAAC;EACvC,KAAK,SAAS;CAChB;AACF;AAEA,SAAS,eAAe,QAA8B;CACpD,MAAM,UAAU,OAAO,SAAS,MAAM,GAAG,WAAW,CAAC,CAAC,KAAK,MAAM,EAAE,MAAM;CACzE,MAAM,OAAO,OAAO,SAAS,SAAS,QAAQ;CAC9C,OAAO,yBAAyB,QAAQ,KAAK,IAAI,IAAI,OAAO,IAAI,MAAM,KAAK,UAAU;AACvF;;;;;;AC1BA,SAAgB,SAAS,OAAwB;CAC/C,IAAI,UAAU,MAAM,OAAO;CAC3B,QAAQ,OAAO,OAAf;EACE,KAAK,aACH,OAAO;EACT,KAAK,UACH,OAAO,cAAc,MAAM,OAAO;EACpC,KAAK,UACH,OAAO,OAAO,MAAM,KAAK,IAAI,gBAAgB;EAC/C,KAAK;EACL,KAAK;EACL,KAAK,UACH,OAAO,OAAO;EAChB,KAAK,YACH,OAAO;CACX;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,aAAa,MAAM,OAAO;CAC3D,IAAI,iBAAiB,MAAM,OAAO,OAAO,MAAM,MAAM,QAAQ,CAAC,IAAI,kBAAkB;CACpF,IAAI,iBAAiB,KAAK,OAAO,YAAY,MAAM,KAAK;CACxD,IAAI,iBAAiB,KAAK,OAAO,YAAY,MAAM,KAAK;CACxD,IAAI,iBAAiB,QAAQ,OAAO;CACpC,MAAM,OAAO,OAAO,KAAK,KAAe,CAAC,CAAC;CAC1C,MAAM,QAAiB,OAAO,eAAe,KAAK;CAElD,OAAO,GADM,UAAU,QAAQ,UAAU,OAAO,YAAY,WAAW,gBAAg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Ae,KAAA,IAAY,KAAK,mBAAmB,WAAW;GAC3E,MAAM,IAAI,UAAU,2BAA2B,IAAI,IAAI,MAAM,GAAG,MAAM;EACxE;EACA,MAAM,QAAkB,OAAmC;EAC3D,IAAI,UAAU,KAAA,GAAW;EACzB,MAAM,UAAU,OAAO,IAAI,CAAC,cAAc,OAAO,MAAM,cAAc;EACrE,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,UAAU,+BAA+B,IAAI,IAAI,MAAM,aAAa,SAAS;CAE3F;AACF;;AC2CA,SAAS,KAAK,OAAgB,QAA+B;CAC3D,eAAe,MAAM;CACrB,OAAO,UAAU,OAAO,QAAQ,IAAI,OAAO,CAAC,CAAC,WAAW;AAC1D;AAEA,SAAS,QAAQ,OAAgB,QAAoC;CACnE,eAAe,MAAM;CACrB,MAAM,WAAW,UAAU,OAAO,QAAQ,IAAI,KAAK;CACnD,OAAO;EAAE,IAAI,SAAS,WAAW;EAAG;CAAS;AAC/C;AAEA,SAAS,cAAc,OAAgB,QAAsB,SAAwB;CACnF,MAAM,SAAS,QAAQ,OAAO,MAAM;CACpC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,YAAY,QAAQ,OAAO;AACvD;;;;;;;;;;;;AAcA,IAAa,SAAiB,OAAO,OAAO,MAAM;CAAE;CAAS,QAAQ;AAAc,CAAC"}
@@ -0,0 +1,55 @@
1
+ import type { ArrayInfos } from './arrays.js';
2
+ import type { CompositionInfos } from './composition.js';
3
+ import type { EqualityInfos } from './equality.js';
4
+ import type { ExactOf, NarrowOf, NarrowTo, Refined } from './narrowing.js';
5
+ import type { NullishInfos } from './nullish.js';
6
+ import type { AffirmParams } from './params.js';
7
+ import type { NumberInfos } from './numbers.js';
8
+ import type { ObjectInfos } from './objects.js';
9
+ import type { RuntimeTypeInfos } from './runtime-type.js';
10
+ import type { SizeInfos } from './size.js';
11
+ import type { StringInfos } from './strings.js';
12
+ /** Every group's key infos, concatenated. */
13
+ type AllInfos<P> = [
14
+ ...EqualityInfos<P>,
15
+ ...NullishInfos<P>,
16
+ ...RuntimeTypeInfos<P>,
17
+ ...SizeInfos<P>,
18
+ ...NumberInfos<P>,
19
+ ...StringInfos<P>,
20
+ ...ObjectInfos<P>,
21
+ ...ArrayInfos<P>,
22
+ ...CompositionInfos<P>
23
+ ];
24
+ /** What P narrows to on its own (before combining with the input type). */
25
+ export type Narrow<P> = NarrowOf<AllInfos<P>>;
26
+ /** `true` when every present key is exact, so the `else` branch may exclude `Narrow<P>`. */
27
+ export type IsExact<P> = ExactOf<AllInfos<P>>;
28
+ type Result<V, P> = NarrowTo<V, Narrow<P>>;
29
+ /**
30
+ * `false` when narrowing would be unsound: refined params whose result can be `null` or `undefined`.
31
+ * `null & Refined` reduces to `never`, so the brand would silently drop `null` from the `if` branch
32
+ * (`isFalsy: true` on `string | null` would claim `string`); leaving `null` unbranded would wrongly
33
+ * drop it from the `else` branch. TypeScript predicates can't express either side soundly, so these
34
+ * calls fall back to a plain `boolean` (design §6.3 fallback).
35
+ */
36
+ export type CanNarrow<V, P> = IsExact<P> extends true ? true : null extends Result<V, P> ? false : undefined extends Result<V, P> ? false : true;
37
+ /**
38
+ * The type of `value` after `affirm(value, params)` returns `true` (design §6.3).
39
+ * Export it to name a narrowed type, e.g. in a helper's return type.
40
+ * Exact params: plain narrowed type, and the `else` branch excludes it.
41
+ * Otherwise: narrowed type `& Refined`, and the `else` branch keeps everything.
42
+ * (When `CanNarrow` is false, `affirm` returns a plain boolean; this type then omits the brand.)
43
+ *
44
+ * @example
45
+ * type ValidOrder = Affirmed<unknown, { shape: { total: { isType: 'number' } } }> // { total: number } & Refined
46
+ */
47
+ export type Affirmed<V, P> = IsExact<P> extends true ? Result<V, P> : CanNarrow<V, P> extends true ? Result<V, P> & Refined : Result<V, P>;
48
+ /**
49
+ * `Narrow` / `IsExact` for nested params (shape fields, everyItem, anyOf branches).
50
+ * Stops recursion when the nested params are the wide `AffirmParams` type (e.g. a params variable,
51
+ * or the constraint TypeScript checks the signature against), which would otherwise recurse forever.
52
+ */
53
+ export type NarrowNested<P> = AffirmParams extends P ? unknown : Narrow<P>;
54
+ export type IsExactNested<P> = AffirmParams extends P ? false : IsExact<P>;
55
+ export {};
@@ -0,0 +1,64 @@
1
+ import type { NarrowNested } from './affirmed.js';
2
+ import type { ParamInfo, ParamOf, Refine } from './narrowing.js';
3
+ import type { AffirmParams } from './params.js';
4
+ export interface ArrayParams {
5
+ /**
6
+ * Value is an array that includes this item. Arrays only: for substrings use `includes`.
7
+ *
8
+ * Passes when the value is an array and includes the item (SameValueZero: like `===`, but `NaN`
9
+ * matches `NaN`). Objects match by reference. Narrows to the array type (refined).
10
+ *
11
+ * @example
12
+ * affirm(user.roles, { contains: 'admin' })
13
+ */
14
+ contains?: unknown;
15
+ /**
16
+ * Value is an array that includes every one of these items.
17
+ *
18
+ * Passes when the value is an array and includes each item (SameValueZero). `[]` always passes.
19
+ * Narrows to the array type (refined).
20
+ *
21
+ * @example
22
+ * affirm(grantedScopes, { containsAll: ['read', 'write'] })
23
+ */
24
+ containsAll?: readonly unknown[];
25
+ /**
26
+ * Value is an array that includes at least one of these items.
27
+ *
28
+ * Passes when the value is an array and includes any item (SameValueZero). `[]` never passes.
29
+ * Narrows to the array type (refined).
30
+ *
31
+ * @example
32
+ * affirm(user.roles, { containsAny: ['admin', 'owner'] })
33
+ */
34
+ containsAny?: readonly unknown[];
35
+ /**
36
+ * Value is an array whose every item passes these params.
37
+ *
38
+ * Passes when the value is an array and each item passes. `[]` passes (vacuously true). Failures
39
+ * report the item path, e.g. `items[2].id`. Narrows the element type (refined).
40
+ *
41
+ * @example
42
+ * affirm(order.items, { isNotEmpty: true, everyItem: { shape: { qty: { isInteger: true, isAtLeast: 1 } } } })
43
+ */
44
+ everyItem?: AffirmParams;
45
+ /**
46
+ * Value is an array where at least one item passes these params.
47
+ *
48
+ * Passes when the value is an array and any item passes. `[]` fails. Reports one failure, not one
49
+ * per item. Narrows to the array type (refined).
50
+ *
51
+ * @example
52
+ * affirm(addresses, { someItem: { shape: { isDefault: { is: true } } } })
53
+ */
54
+ someItem?: AffirmParams;
55
+ }
56
+ type ArrayInfo<V> = ParamInfo<V, Refine<readonly unknown[]>>;
57
+ export type ArrayInfos<P> = [
58
+ ArrayInfo<ParamOf<P, 'contains'>>,
59
+ ArrayInfo<ParamOf<P, 'containsAll'>>,
60
+ ArrayInfo<ParamOf<P, 'containsAny'>>,
61
+ ParamInfo<ParamOf<P, 'everyItem'>, Refine<readonly NarrowNested<ParamOf<P, 'everyItem'>>[]>>,
62
+ ArrayInfo<ParamOf<P, 'someItem'>>
63
+ ];
64
+ export {};
@@ -0,0 +1,53 @@
1
+ import type { IsExactNested, NarrowNested } from './affirmed.js';
2
+ import type { Exact, ParamInfo, ParamOf, Refine } from './narrowing.js';
3
+ import type { AffirmParams } from './params.js';
4
+ import type { TypeGuard } from './runtime-type.js';
5
+ export interface CompositionParams {
6
+ /**
7
+ * Value fails these params.
8
+ *
9
+ * Passes when the nested params fail. The nested keys combine with AND, so
10
+ * `not: { a, b }` means "not (a and b)". Does not narrow.
11
+ *
12
+ * @example
13
+ * affirm(username, { not: { isOneOf: ['admin', 'root'] } })
14
+ */
15
+ not?: AffirmParams;
16
+ /**
17
+ * Value passes at least one of these param branches: the only way to express OR.
18
+ *
19
+ * Passes when any branch passes. Must be non-empty. On failure, the report lists each branch's
20
+ * failures in `branches`. Narrows to the union of the branches' narrowing; exact when every
21
+ * branch is exact.
22
+ *
23
+ * @example
24
+ * if (affirm(note, { anyOf: [{ isNull: true }, { isType: 'string' }] })) { note } // string | null
25
+ */
26
+ anyOf?: readonly AffirmParams[];
27
+ /**
28
+ * Value satisfies this predicate. The escape hatch, always run last.
29
+ *
30
+ * Passes when the predicate returns exactly `true`. Use it for prototype getters, cross-field
31
+ * rules and anything the other keys can't express. Errors thrown by the predicate propagate.
32
+ * A type guard narrows to its type (refined); a plain predicate does not narrow.
33
+ *
34
+ * @example
35
+ * affirm(range, { satisfies: (r) => isRange(r) && r.min <= r.max }) // the param is `unknown`: guard first
36
+ */
37
+ satisfies?: ((value: unknown) => boolean) | TypeGuard;
38
+ }
39
+ /** Union of each branch's narrowing; exact only when every branch is exact (design §6.3). */
40
+ type AnyOfInfo<V> = ParamInfo<V, V extends readonly unknown[] ? false extends {
41
+ [I in keyof V]: IsExactNested<V[I]>;
42
+ }[number] ? Refine<{
43
+ [I in keyof V]: NarrowNested<V[I]>;
44
+ }[number]> : Exact<{
45
+ [I in keyof V]: NarrowNested<V[I]>;
46
+ }[number]> : Refine>;
47
+ type SatisfiesInfo<V> = ParamInfo<V, V extends TypeGuard<infer T> ? Refine<T> : Refine>;
48
+ export type CompositionInfos<P> = [
49
+ ParamInfo<ParamOf<P, 'not'>, Refine>,
50
+ AnyOfInfo<ParamOf<P, 'anyOf'>>,
51
+ SatisfiesInfo<ParamOf<P, 'satisfies'>>
52
+ ];
53
+ export {};
@@ -0,0 +1,90 @@
1
+ import type { AffirmParams } from './params.js';
2
+ /** Everything the call signature intersects with P, applied at every nesting level. */
3
+ export type ParamsCheck<P> = AffirmParams extends P ? unknown : NoUnknownKeys<P> & NoContradictions<P> & Nested<P>;
4
+ /**
5
+ * Unknown keys. Generic inference skips excess-property checks, so `{ isNull: true, isTypo: 1 }`
6
+ * would otherwise type-check (it still throws at runtime). Shown on the key itself:
7
+ * `… not assignable to type '{ __affirmError: "unknown check 'isTypo'" }'`.
8
+ */
9
+ export type NoUnknownKeys<P> = {
10
+ [K in Exclude<keyof P, keyof AffirmParams>]: {
11
+ __affirmError: `unknown check '${K & string}'`;
12
+ };
13
+ };
14
+ /** Applies `ParamsCheck` inside composite keys: shape fields, everyItem, someItem, not, anyOf branches. */
15
+ type Nested<P> = ('shape' extends keyof P ? P['shape'] extends object ? {
16
+ shape: {
17
+ [F in keyof P['shape']]: ParamsCheck<P['shape'][F]>;
18
+ };
19
+ } : unknown : unknown) & ('everyItem' extends keyof P ? {
20
+ everyItem: ParamsCheck<P['everyItem']>;
21
+ } : unknown) & ('someItem' extends keyof P ? {
22
+ someItem: ParamsCheck<P['someItem']>;
23
+ } : unknown) & ('not' extends keyof P ? {
24
+ not: ParamsCheck<P['not']>;
25
+ } : unknown) & ('anyOf' extends keyof P ? (P['anyOf'] extends readonly unknown[] ? {
26
+ anyOf: Branches<P['anyOf']>;
27
+ } : unknown) : unknown);
28
+ /** Homomorphic over the tuple type parameter, so it maps elements, not array methods. */
29
+ type Branches<T extends readonly unknown[]> = {
30
+ [I in keyof T]: ParamsCheck<T[I]>;
31
+ };
32
+ /**
33
+ * Resolves to `unknown` when P has no contradiction, or `{ __affirmError: '<message>' }` for the
34
+ * first one found. Shown at the call site as `Property '__affirmError' is missing in type …`.
35
+ */
36
+ export type NoContradictions<P> = ToCheck<FirstMessage<[
37
+ Clash<P, 'isNull', ['isTruthy', 'isPresent', 'isUndefined']>,
38
+ TagClash<P, 'isNull'>,
39
+ Clash<P, 'isUndefined', ['isTruthy', 'isPresent', 'isDefined']>,
40
+ TagClash<P, 'isUndefined'>,
41
+ Clash<P, 'isNullish', ['isPresent']>,
42
+ Clash<P, 'isTruthy', ['isFalsy']>,
43
+ Clash<P, 'isEmpty', ['isNotEmpty']>,
44
+ EmptyVsMinLength<P>,
45
+ ArrayVsTag<P>,
46
+ KindClash<P, 'string', NumberKeys, 'a number key'>,
47
+ KindClash<P, 'number', StringKeys, 'a string key'>,
48
+ MinOverMax<P>
49
+ ]>>;
50
+ type ToCheck<M> = [M] extends [never] ? unknown : {
51
+ __affirmError: M;
52
+ };
53
+ /** Keys that only pass for numbers (any value, since gated keys fail both polarities, D7). */
54
+ type NumberKeys = 'isGreaterThan' | 'isAtLeast' | 'isLessThan' | 'isAtMost' | 'isBetween' | 'isPositive' | 'isNegative' | 'isMultipleOf' | 'isInteger' | 'isFiniteNumber' | 'isNaN';
55
+ /** Keys that only pass for strings. */
56
+ type StringKeys = 'startsWith' | 'endsWith' | 'includes' | 'matches' | 'isBlank';
57
+ /** `true` when key K is present with the literal value `true`. */
58
+ type IsTrue<P, K extends PropertyKey> = K extends keyof P ? ([P[K]] extends [true] ? true : false) : false;
59
+ /** `true` when key K is present and not `undefined`. */
60
+ type IsSet<P, K extends PropertyKey> = K extends keyof P ? ([P[K]] extends [undefined] ? false : true) : false;
61
+ /** The `isType` tag, if `isType` is a tag literal (guards and schemas are not checked: they may allow null). */
62
+ type Tag<P> = 'isType' extends keyof P ? (P['isType'] extends string ? P['isType'] : never) : never;
63
+ /** First key of Ks that is `true` in P. */
64
+ type FirstTrue<P, Ks extends readonly string[]> = Ks extends readonly [infer K extends string, ...infer R extends string[]] ? IsTrue<P, K> extends true ? K : FirstTrue<P, R> : never;
65
+ /** `A: true` together with any of `Others: true`. */
66
+ type Clash<P, A extends string, Others extends readonly string[]> = IsTrue<P, A> extends true ? FirstTrue<P, Others> extends infer K extends string ? `\`${A}: true\` contradicts \`${K}: true\`` : never : never;
67
+ /** `isNull: true` / `isUndefined: true` with an `isType` tag. */
68
+ type TagClash<P, A extends string> = IsTrue<P, A> extends true ? [Tag<P>] extends [never] ? never : `\`${A}: true\` contradicts \`isType: '${Tag<P>}'\`` : never;
69
+ /** `isEmpty: true` with a literal `hasMinLength` of 1 or more. */
70
+ type EmptyVsMinLength<P> = IsTrue<P, 'isEmpty'> extends true ? 'hasMinLength' extends keyof P ? P['hasMinLength'] extends number ? number extends P['hasMinLength'] ? never : P['hasMinLength'] extends 0 ? never : `\`isEmpty: true\` contradicts \`hasMinLength: ${P['hasMinLength']}\`` : never : never : never;
71
+ /** `isArray: true` with an `isType` tag other than `'object'`. */
72
+ type ArrayVsTag<P> = IsTrue<P, 'isArray'> extends true ? [Tag<P>] extends [never] ? never : Tag<P> extends 'object' ? never : `\`isArray: true\` contradicts \`isType: '${Tag<P>}'\`` : never;
73
+ /** `isType: T` with a key that only passes for a different kind. */
74
+ type KindClash<P, T extends string, Keys extends string, Label extends string> = Tag<P> extends T ? [Tag<P>] extends [never] ? never : FirstSet<P, Keys> extends infer K extends string ? `\`isType: '${T}'\` contradicts \`${K}\` (${Label})` : never : never;
75
+ type FirstSet<P, Keys extends string> = Keys extends unknown ? (IsSet<P, Keys> extends true ? Keys : never) : never;
76
+ /** Literal `hasMinLength` greater than literal `hasMaxLength`. */
77
+ type MinOverMax<P> = 'hasMinLength' extends keyof P ? 'hasMaxLength' extends keyof P ? P['hasMinLength'] extends number ? P['hasMaxLength'] extends number ? GreaterThan<P['hasMinLength'], P['hasMaxLength']> extends true ? `\`hasMinLength: ${P['hasMinLength']}\` is greater than \`hasMaxLength: ${P['hasMaxLength']}\`` : never : never : never : never : never;
78
+ /** First non-never entry of a tuple of messages. */
79
+ type FirstMessage<T extends readonly unknown[]> = T extends readonly [infer H, ...infer R] ? [H] extends [never] ? FirstMessage<R> : H : never;
80
+ type Digits<N extends number> = number extends N ? never : `${N}` extends `${infer S}` ? S extends `${string}${'.' | 'e' | '-'}${string}` ? never : S : never;
81
+ type Length<S extends string, Acc extends unknown[] = []> = S extends `${string}${infer R}` ? Length<R, [...Acc, 0]> : Acc;
82
+ type LongerThan<A extends unknown[], B extends unknown[]> = A extends [...B, unknown, ...unknown[]] ? true : false;
83
+ type DigitGreater<A extends string, B extends string> = A extends B ? false : '0123456789' extends `${string}${B}${string}${A}${string}` ? true : false;
84
+ /** Same-length digit strings, compared left to right. */
85
+ type DigitsGreater<A extends string, B extends string> = A extends `${infer a}${infer ra}` ? B extends `${infer b}${infer rb}` ? a extends b ? DigitsGreater<ra, rb> : DigitGreater<a, b> : false : false;
86
+ export type GreaterThan<A extends number, B extends number> = [Digits<A>, Digits<B>] extends [
87
+ infer DA extends string,
88
+ infer DB extends string
89
+ ] ? [DA] extends [never] ? false : [DB] extends [never] ? false : LongerThan<Length<DA>, Length<DB>> extends true ? true : LongerThan<Length<DB>, Length<DA>> extends true ? false : DigitsGreater<DA, DB> : false;
90
+ export {};
@@ -0,0 +1,65 @@
1
+ import type { Exact, IsLiteral, ParamInfo, ParamOf, Refine } from './narrowing.js';
2
+ export interface EqualityParams {
3
+ /**
4
+ * Value is exactly this value.
5
+ *
6
+ * Passes when `value === param`. Objects compare by reference; use `isDeepEqual` for structure.
7
+ * Narrows to the param's type. Exact for literal params, so the `else` branch excludes it.
8
+ *
9
+ * @example
10
+ * if (affirm(role, { is: 'admin' })) { role } // role: 'admin'
11
+ */
12
+ is?: unknown;
13
+ /**
14
+ * Value is not this value.
15
+ *
16
+ * Passes when `value !== param`. Does not narrow.
17
+ *
18
+ * @example
19
+ * affirm(status, { isNot: 'deleted' })
20
+ */
21
+ isNot?: unknown;
22
+ /**
23
+ * Value is one of the listed values.
24
+ *
25
+ * Passes when the list includes the value (SameValueZero: like `===`, but `NaN` matches `NaN`).
26
+ * `[]` never passes. Narrows to the union of the elements; exact when they are all literals.
27
+ *
28
+ * @example
29
+ * if (affirm(size, { isOneOf: ['s', 'm', 'l'] })) { size } // size: 's' | 'm' | 'l'
30
+ */
31
+ isOneOf?: readonly unknown[];
32
+ /**
33
+ * Value is none of the listed values.
34
+ *
35
+ * Passes when the list does not include the value (SameValueZero). `[]` always passes. Does not narrow.
36
+ *
37
+ * @example
38
+ * affirm(username, { isNotOneOf: ['admin', 'root'] })
39
+ */
40
+ isNotOneOf?: readonly unknown[];
41
+ /**
42
+ * Value is structurally equal to this value.
43
+ *
44
+ * Passes when both have the same type and contents: arrays elementwise, plain objects by own
45
+ * enumerable keys, Dates by time, RegExps by source and flags, Maps by keys and deep values,
46
+ * Sets by members (not deep). Other class instances compare by reference. Does not narrow.
47
+ *
48
+ * @example
49
+ * affirm(config.retry, { isDeepEqual: { attempts: 3, backoff: 'exponential' } })
50
+ */
51
+ isDeepEqual?: unknown;
52
+ }
53
+ /** `is` narrows to the param's type; exact only for literal params (design §5). */
54
+ type IsInfo<V> = ParamInfo<V, IsLiteral<V> extends true ? Exact<V> : Refine<V>>;
55
+ type IsOneOfInfo<V> = ParamInfo<V, V extends readonly unknown[] ? (IsLiteral<V[number]> extends true ? Exact<V[number]> : Refine<V[number]>) : Refine>;
56
+ /** No narrowing: `ParamInfo<V, Refine>` skips when absent, otherwise refined with `n: unknown`. */
57
+ type NoNarrow<V> = ParamInfo<V, Refine>;
58
+ export type EqualityInfos<P> = [
59
+ IsInfo<ParamOf<P, 'is'>>,
60
+ NoNarrow<ParamOf<P, 'isNot'>>,
61
+ IsOneOfInfo<ParamOf<P, 'isOneOf'>>,
62
+ NoNarrow<ParamOf<P, 'isNotOneOf'>>,
63
+ NoNarrow<ParamOf<P, 'isDeepEqual'>>
64
+ ];
65
+ export {};
@@ -0,0 +1,66 @@
1
+ declare const refined: unique symbol;
2
+ /**
3
+ * Phantom brand added when any key is *refined* (not exact). No real type is assignable to it,
4
+ * so TypeScript cannot exclude anything in the `else` branch, while the `if` branch still gets
5
+ * the narrowed type (`string & Refined` is usable anywhere a `string` is).
6
+ *
7
+ * `{}` and `object` are *assignable* to this all-optional type, but narrowing uses the strict
8
+ * subtype relation, under which they are not subtypes, so `else` branches keep them too.
9
+ * Covered by the "{} and object constituents" type test.
10
+ */
11
+ export interface Refined {
12
+ readonly [refined]?: never;
13
+ }
14
+ export interface KeyInfo {
15
+ readonly n: unknown;
16
+ readonly e: boolean;
17
+ }
18
+ /** Key absent or `undefined`: no narrowing, does not affect exactness. */
19
+ export type Skip = {
20
+ n: unknown;
21
+ e: true;
22
+ };
23
+ /** Narrows to `N`, and failing the check means the value is not an `N`. */
24
+ export type Exact<N> = {
25
+ n: N;
26
+ e: true;
27
+ };
28
+ /** Narrows to `N` in the `if` branch only. */
29
+ export type Refine<N = unknown> = {
30
+ n: N;
31
+ e: false;
32
+ };
33
+ /** The param for key `K`, or `undefined` when P doesn't have it. */
34
+ export type ParamOf<P, K extends PropertyKey> = K extends keyof P ? P[K] : undefined;
35
+ /**
36
+ * Boolean keys (D1). `T` is the info for `true`, `F` for `false`.
37
+ * A non-literal `boolean` (or `boolean | undefined`) param can't be narrowed on.
38
+ */
39
+ export type BoolInfo<V, T extends KeyInfo, F extends KeyInfo> = [V] extends [undefined] ? Skip : [V] extends [true] ? T : [V] extends [false] ? F : Refine;
40
+ /** Guards the common case for non-boolean keys: absent → Skip, maybe-undefined → Refine. */
41
+ export type ParamInfo<V, Info extends KeyInfo> = [V] extends [undefined] ? Skip : undefined extends V ? Refine : Info;
42
+ /** `true` when T is a union of unit types (string/number/bigint/boolean literals, null, unique symbols). */
43
+ export type IsLiteral<T> = [T] extends [never] ? false : (T extends unknown ? IsUnit<T> : never) extends true ? true : false;
44
+ type IsUnit<T> = T extends null ? true : T extends string ? string extends T ? false : true : T extends number ? number extends T ? false : true : T extends bigint ? bigint extends T ? false : true : T extends boolean ? true : T extends symbol ? symbol extends T ? false : true : false;
45
+ export type IsUnion<T, U = T> = (T extends unknown ? ([U] extends [T] ? false : true) : never) extends false ? false : true;
46
+ /**
47
+ * Narrows V by C the way TypeScript narrows a union with a type guard:
48
+ * keep constituents of V that are subtypes of C, replace constituents that C refines,
49
+ * drop unrelated constituents; if nothing is related, fall back to `V & C`.
50
+ * (A plain `V & C` leaves artefacts like `string & readonly unknown[]` in unions.)
51
+ */
52
+ type Filter<V, C> = V extends unknown ? (C extends unknown ? (V extends C ? V : C extends V ? C : never) : never) : never;
53
+ export type NarrowTo<V, C> = [Filter<V, C>] extends [never] ? V & C : Filter<V, C>;
54
+ /**
55
+ * Every info's `n`, combined with `NarrowTo` (so `string` + `Measurable` gives `string`,
56
+ * not `string & (string | readonly unknown[] | …)`).
57
+ * Tail-recursive (accumulator) so TypeScript doesn't count each of the ~50 keys against the
58
+ * instantiation depth limit, which nested params would otherwise hit.
59
+ */
60
+ export type NarrowOf<T extends readonly KeyInfo[], Acc = unknown> = T extends readonly [
61
+ infer H extends KeyInfo,
62
+ ...infer R extends readonly KeyInfo[]
63
+ ] ? NarrowOf<R, NarrowTo<Acc, H['n']>> : Acc;
64
+ /** `true` only when every info is exact. */
65
+ export type ExactOf<T extends readonly KeyInfo[]> = false extends T[number]['e'] ? false : true;
66
+ export {};