@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.
- package/AGENTS.md +130 -0
- package/LICENSE +21 -0
- package/README.md +116 -2
- package/dist/affirm.d.ts +79 -0
- package/dist/checks/arrays.d.ts +10 -0
- package/dist/checks/composition.d.ts +10 -0
- package/dist/checks/equality.d.ts +7 -0
- package/dist/checks/nullish.d.ts +9 -0
- package/dist/checks/numbers.d.ts +11 -0
- package/dist/checks/objects.d.ts +9 -0
- package/dist/checks/runtime-type.d.ts +14 -0
- package/dist/checks/size.d.ts +8 -0
- package/dist/checks/strings.d.ts +6 -0
- package/dist/core/check-def.d.ts +93 -0
- package/dist/core/describe.d.ts +11 -0
- package/dist/core/errors.d.ts +18 -0
- package/dist/core/evaluate.d.ts +8 -0
- package/dist/core/registry.d.ts +18 -0
- package/dist/core/report.d.ts +22 -0
- package/dist/core/util/deep-equal.d.ts +12 -0
- package/dist/core/util/kind.d.ts +22 -0
- package/dist/core/util/levenshtein.d.ts +3 -0
- package/dist/core/util/same-value-zero.d.ts +5 -0
- package/dist/core/util/standard-schema.d.ts +62 -0
- package/dist/core/validate-params.d.ts +8 -0
- package/dist/eslint/check-keys.d.ts +7 -0
- package/dist/eslint/const-params.d.ts +2 -0
- package/dist/eslint/guard-naming.d.ts +2 -0
- package/dist/eslint/index.d.ts +29 -0
- package/dist/eslint/no-negated-affirm.d.ts +2 -0
- package/dist/eslint/shared.d.ts +65 -0
- package/dist/eslint.js +734 -0
- package/dist/eslint.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +967 -0
- package/dist/index.js.map +1 -0
- package/dist/types/affirmed.d.ts +55 -0
- package/dist/types/arrays.d.ts +64 -0
- package/dist/types/composition.d.ts +53 -0
- package/dist/types/contradictions.d.ts +90 -0
- package/dist/types/equality.d.ts +65 -0
- package/dist/types/narrowing.d.ts +66 -0
- package/dist/types/nullish.d.ts +80 -0
- package/dist/types/numbers.d.ts +94 -0
- package/dist/types/objects.d.ts +99 -0
- package/dist/types/params.d.ts +14 -0
- package/dist/types/runtime-type.d.ts +129 -0
- package/dist/types/size.d.ts +76 -0
- package/dist/types/strings.d.ts +49 -0
- package/docs/client-usage.md +850 -0
- package/package.json +58 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,967 @@
|
|
|
1
|
+
// src/core/errors.ts
|
|
2
|
+
var MAX_REASONS = 3;
|
|
3
|
+
/**
|
|
4
|
+
* Thrown by `affirm.assert` when data fails its checks (design §9). `report` has every failure.
|
|
5
|
+
* The default message lists the first three reasons, then `(+N more)`.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* try {
|
|
9
|
+
* affirm.assert(body, { shape: { email: { matches: /@/ } } })
|
|
10
|
+
* } catch (error) {
|
|
11
|
+
* if (error instanceof AffirmError) return badRequest(error.report.failures)
|
|
12
|
+
* throw error
|
|
13
|
+
* }
|
|
14
|
+
*/
|
|
15
|
+
var AffirmError = class extends Error {
|
|
16
|
+
name = "AffirmError";
|
|
17
|
+
report;
|
|
18
|
+
constructor(report, message) {
|
|
19
|
+
super(message ?? defaultMessage(report));
|
|
20
|
+
this.report = report;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function defaultMessage(report) {
|
|
24
|
+
const reasons = report.failures.slice(0, MAX_REASONS).map((f) => f.reason);
|
|
25
|
+
const more = report.failures.length - reasons.length;
|
|
26
|
+
return `affirm.assert failed: ${reasons.join("; ")}${more > 0 ? ` (+${more} more)` : ""}`;
|
|
27
|
+
}
|
|
28
|
+
// src/core/describe.ts
|
|
29
|
+
/**
|
|
30
|
+
* Describes a value by type and size only, never by content (design §8, D5).
|
|
31
|
+
* Used for `AffirmFailure.received`.
|
|
32
|
+
*/
|
|
33
|
+
function describe(value) {
|
|
34
|
+
if (value === null) return "null";
|
|
35
|
+
switch (typeof value) {
|
|
36
|
+
case "undefined": return "undefined";
|
|
37
|
+
case "string": return `string(len ${value.length})`;
|
|
38
|
+
case "number": return Number.isNaN(value) ? "number(NaN)" : "number";
|
|
39
|
+
case "boolean":
|
|
40
|
+
case "bigint":
|
|
41
|
+
case "symbol": return typeof value;
|
|
42
|
+
case "function": return "function";
|
|
43
|
+
}
|
|
44
|
+
if (Array.isArray(value)) return `array(len ${value.length})`;
|
|
45
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Date(invalid)" : "Date";
|
|
46
|
+
if (value instanceof Map) return `Map(size ${value.size})`;
|
|
47
|
+
if (value instanceof Set) return `Set(size ${value.size})`;
|
|
48
|
+
if (value instanceof RegExp) return "RegExp";
|
|
49
|
+
const keys = Object.keys(value).length;
|
|
50
|
+
const proto = Object.getPrototypeOf(value);
|
|
51
|
+
return `${proto === null || proto === Object.prototype ? "object" : constructorName(value)}{${keys} ${keys === 1 ? "key" : "keys"}}`;
|
|
52
|
+
}
|
|
53
|
+
function constructorName(value) {
|
|
54
|
+
const ctor = value.constructor;
|
|
55
|
+
return typeof ctor === "function" && ctor.name !== "" ? ctor.name : "object";
|
|
56
|
+
}
|
|
57
|
+
var MAX_STRING_PARAM = 32;
|
|
58
|
+
var MAX_LIST_ITEMS = 5;
|
|
59
|
+
/**
|
|
60
|
+
* Formats a *param* (authored in code, not data) for `expected`.
|
|
61
|
+
* Short strings and primitives are shown literally; anything else is described.
|
|
62
|
+
*/
|
|
63
|
+
function formatParam(param) {
|
|
64
|
+
switch (typeof param) {
|
|
65
|
+
case "string": return param.length <= MAX_STRING_PARAM ? JSON.stringify(param) : `string(len ${param.length})`;
|
|
66
|
+
case "number": return Object.is(param, -0) ? "-0" : String(param);
|
|
67
|
+
case "bigint": return `${param}n`;
|
|
68
|
+
case "boolean":
|
|
69
|
+
case "undefined": return String(param);
|
|
70
|
+
case "symbol": return param.toString();
|
|
71
|
+
case "function": return param.name === "" ? "function" : param.name;
|
|
72
|
+
}
|
|
73
|
+
return param === null ? "null" : describe(param);
|
|
74
|
+
}
|
|
75
|
+
function formatList(list) {
|
|
76
|
+
const shown = list.slice(0, MAX_LIST_ITEMS).map(formatParam);
|
|
77
|
+
const more = list.length - shown.length;
|
|
78
|
+
return `[${shown.join(", ")}${more > 0 ? `, … (+${more})` : ""}]`;
|
|
79
|
+
}
|
|
80
|
+
// src/core/report.ts
|
|
81
|
+
function makeFailure(key, path, expected, value) {
|
|
82
|
+
const received = describe(value);
|
|
83
|
+
return {
|
|
84
|
+
key,
|
|
85
|
+
path,
|
|
86
|
+
expected,
|
|
87
|
+
received,
|
|
88
|
+
reason: `${path === "" ? "" : `${path}: `}expected ${expected}, received ${received}`
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** `joinPath('items', 2)` → `'items[2]'`; `joinPath('user', 'zip')` → `'user.zip'`. */
|
|
92
|
+
function joinPath(base, segment) {
|
|
93
|
+
if (typeof segment === "number") return `${base}[${segment}]`;
|
|
94
|
+
return base === "" ? segment : `${base}.${segment}`;
|
|
95
|
+
}
|
|
96
|
+
// src/core/check-def.ts
|
|
97
|
+
/** Canonical evaluation phases (design §4 rule 7). Lower runs first. */
|
|
98
|
+
var Phase = {
|
|
99
|
+
/** Cheap type / nullish / equality checks. */
|
|
100
|
+
Kind: 0,
|
|
101
|
+
/** Size, number and string checks. */
|
|
102
|
+
Measure: 1,
|
|
103
|
+
/** Structural checks: shape, everyItem, isDeepEqual, … */
|
|
104
|
+
Structural: 2,
|
|
105
|
+
/** User predicates: satisfies. */
|
|
106
|
+
Predicate: 3
|
|
107
|
+
};
|
|
108
|
+
/** Builds a check from a plain `(value, param) => boolean` test. */
|
|
109
|
+
function leaf(spec) {
|
|
110
|
+
return {
|
|
111
|
+
phase: spec.phase,
|
|
112
|
+
validateParam: spec.validateParam,
|
|
113
|
+
evaluate(value, param, ctx) {
|
|
114
|
+
if (spec.accepts !== void 0 && !spec.accepts(value)) return [makeFailure(ctx.key, ctx.path, spec.acceptsLabel ?? "a different kind of value", value)];
|
|
115
|
+
return spec.test(value, param) ? [] : [makeFailure(ctx.key, ctx.path, spec.expected(param), value)];
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Builds a boolean key. Implements D1 once: pass ⇔ `test(value) === param`.
|
|
121
|
+
* The kind gate (if any) runs first and fails for both polarities (D7).
|
|
122
|
+
*/
|
|
123
|
+
function booleanLeaf(spec) {
|
|
124
|
+
return {
|
|
125
|
+
phase: spec.phase,
|
|
126
|
+
validateParam: (param) => typeof param === "boolean" ? void 0 : "a boolean",
|
|
127
|
+
evaluate(value, param, ctx) {
|
|
128
|
+
if (spec.accepts !== void 0 && !spec.accepts(value)) return [makeFailure(ctx.key, ctx.path, spec.acceptsLabel ?? "a different kind of value", value)];
|
|
129
|
+
if (spec.test(value) === param) return [];
|
|
130
|
+
return [makeFailure(ctx.key, ctx.path, param ? spec.expected : spec.expectedNot, value)];
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Builds a composite key (shape, everyItem, anyOf, …). The kind gate runs first, so a value of the
|
|
136
|
+
* wrong kind produces ONE failure instead of one per child (design §4 rule 7).
|
|
137
|
+
*/
|
|
138
|
+
function composite(spec) {
|
|
139
|
+
return {
|
|
140
|
+
phase: spec.phase,
|
|
141
|
+
validateParam: spec.validateParam,
|
|
142
|
+
evaluate(value, param, ctx) {
|
|
143
|
+
if (spec.accepts !== void 0 && !spec.accepts(value)) return [makeFailure(ctx.key, ctx.path, spec.acceptsLabel ?? "a different kind of value", value)];
|
|
144
|
+
return spec.evaluate(value, param, ctx);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/** `{ isNull: true, hasKey: "id" }`: a short rendering of nested params for `expected`. */
|
|
149
|
+
function formatParams(params) {
|
|
150
|
+
return `{ ${Object.entries(params).filter(([, v]) => v !== void 0).map(([k, v]) => `${k}: ${formatParam(v)}`).join(", ")} }`;
|
|
151
|
+
}
|
|
152
|
+
var anyParam = () => void 0;
|
|
153
|
+
var arrayParam = (param) => Array.isArray(param) ? void 0 : `an array (received ${formatParam(param)})`;
|
|
154
|
+
var functionParam = (param) => typeof param === "function" ? void 0 : `a function (received ${formatParam(param)})`;
|
|
155
|
+
var numberParam = (param) => typeof param === "number" && !Number.isNaN(param) ? void 0 : `a number, not NaN (received ${formatParam(param)})`;
|
|
156
|
+
var nonNegativeIntegerParam = (param) => Number.isInteger(param) && param >= 0 ? void 0 : `a non-negative integer (received ${formatParam(param)})`;
|
|
157
|
+
var stringParam = (param) => typeof param === "string" ? void 0 : `a string (received ${formatParam(param)})`;
|
|
158
|
+
var isPropertyKey = (k) => typeof k === "string" || typeof k === "number" || typeof k === "symbol";
|
|
159
|
+
var propertyKeyParam = (param) => isPropertyKey(param) ? void 0 : `a string, number or symbol key (received ${formatParam(param)})`;
|
|
160
|
+
var propertyKeyListParam = (param) => Array.isArray(param) && param.every(isPropertyKey) ? void 0 : `an array of string, number or symbol keys (received ${formatParam(param)})`;
|
|
161
|
+
// src/core/util/kind.ts
|
|
162
|
+
/** Prototype is `Object.prototype` or `null` (so `Object.create(null)` counts, design Q2). */
|
|
163
|
+
function isPlainObject(value) {
|
|
164
|
+
if (typeof value !== "object" || value === null) return false;
|
|
165
|
+
const proto = Object.getPrototypeOf(value);
|
|
166
|
+
return proto === Object.prototype || proto === null;
|
|
167
|
+
}
|
|
168
|
+
function isNumber(value) {
|
|
169
|
+
return typeof value === "number";
|
|
170
|
+
}
|
|
171
|
+
function isDate(value) {
|
|
172
|
+
return value instanceof Date;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Heuristic for "this is a class/constructor, not a guard function" so `isType: Date`
|
|
176
|
+
* can be rejected with "use isInstanceOf". Catches `class` syntax and capitalised built-ins
|
|
177
|
+
* (`Date`, `Map`, `Error`, …). Arrow functions and lowercase function declarations pass.
|
|
178
|
+
*/
|
|
179
|
+
function looksLikeConstructor(fn) {
|
|
180
|
+
const source = Function.prototype.toString.call(fn);
|
|
181
|
+
if (/^class[\s{]/.test(source)) return true;
|
|
182
|
+
return /\{\s*\[native code\]\s*\}\s*$/.test(source) && /^[A-Z]/.test(fn.name);
|
|
183
|
+
}
|
|
184
|
+
/** A number other than NaN: the kind gate for every number key (design §5 "Numbers"). */
|
|
185
|
+
function isNumberNotNaN(value) {
|
|
186
|
+
return typeof value === "number" && !Number.isNaN(value);
|
|
187
|
+
}
|
|
188
|
+
function isString(value) {
|
|
189
|
+
return typeof value === "string";
|
|
190
|
+
}
|
|
191
|
+
/** Non-null object or array (functions excluded): the kind gate for object keys. */
|
|
192
|
+
function isObjectLike(value) {
|
|
193
|
+
return typeof value === "object" && value !== null;
|
|
194
|
+
}
|
|
195
|
+
function isArray(value) {
|
|
196
|
+
return Array.isArray(value);
|
|
197
|
+
}
|
|
198
|
+
/** "Measurable" = string, array, Map, Set (design §5 "Emptiness & size"). */
|
|
199
|
+
function isMeasurable(value) {
|
|
200
|
+
return typeof value === "string" || Array.isArray(value) || value instanceof Map || value instanceof Set;
|
|
201
|
+
}
|
|
202
|
+
function sizeOf(value) {
|
|
203
|
+
return typeof value === "string" || Array.isArray(value) ? value.length : value.size;
|
|
204
|
+
}
|
|
205
|
+
/** Own enumerable keys, string and symbol. */
|
|
206
|
+
function ownKeys(value) {
|
|
207
|
+
return [...Object.keys(value), ...Object.getOwnPropertySymbols(value).filter((s) => Object.prototype.propertyIsEnumerable.call(value, s))];
|
|
208
|
+
}
|
|
209
|
+
// src/checks/arrays.ts
|
|
210
|
+
/** Nested item params are validated once, at `items[*]`. */
|
|
211
|
+
var validateItemParams = (param, path, validateNested) => {
|
|
212
|
+
validateNested(param, `${path}[*]`);
|
|
213
|
+
};
|
|
214
|
+
var arrayChecks = {
|
|
215
|
+
contains: leaf({
|
|
216
|
+
phase: Phase.Measure,
|
|
217
|
+
validateParam: anyParam,
|
|
218
|
+
accepts: isArray,
|
|
219
|
+
acceptsLabel: "an array",
|
|
220
|
+
test: (value, item) => value.includes(item),
|
|
221
|
+
expected: (item) => `an array containing ${formatParam(item)}`
|
|
222
|
+
}),
|
|
223
|
+
containsAll: leaf({
|
|
224
|
+
phase: Phase.Measure,
|
|
225
|
+
validateParam: arrayParam,
|
|
226
|
+
accepts: isArray,
|
|
227
|
+
acceptsLabel: "an array",
|
|
228
|
+
test: (value, items) => items.every((item) => value.includes(item)),
|
|
229
|
+
expected: (items) => `an array containing all of ${formatList(items)}`
|
|
230
|
+
}),
|
|
231
|
+
containsAny: leaf({
|
|
232
|
+
phase: Phase.Measure,
|
|
233
|
+
validateParam: arrayParam,
|
|
234
|
+
accepts: isArray,
|
|
235
|
+
acceptsLabel: "an array",
|
|
236
|
+
test: (value, items) => items.some((item) => value.includes(item)),
|
|
237
|
+
expected: (items) => `an array containing any of ${formatList(items)}`
|
|
238
|
+
}),
|
|
239
|
+
/** Failures carry the item path: `items[2].id`. Vacuously true on `[]`. */
|
|
240
|
+
everyItem: composite({
|
|
241
|
+
phase: Phase.Structural,
|
|
242
|
+
validateParam: validateItemParams,
|
|
243
|
+
accepts: isArray,
|
|
244
|
+
acceptsLabel: "an array",
|
|
245
|
+
evaluate(value, params, ctx) {
|
|
246
|
+
const failures = [];
|
|
247
|
+
for (let i = 0; i < value.length; i++) {
|
|
248
|
+
failures.push(...ctx.run(value[i], params, joinPath(ctx.path, i)));
|
|
249
|
+
if (ctx.mode === "first" && failures.length > 0) break;
|
|
250
|
+
}
|
|
251
|
+
return failures;
|
|
252
|
+
}
|
|
253
|
+
}),
|
|
254
|
+
/** One failure when no item passes (per-item failures would just be noise). False on `[]`. */
|
|
255
|
+
someItem: composite({
|
|
256
|
+
phase: Phase.Structural,
|
|
257
|
+
validateParam: validateItemParams,
|
|
258
|
+
accepts: isArray,
|
|
259
|
+
acceptsLabel: "an array",
|
|
260
|
+
evaluate(value, params, ctx) {
|
|
261
|
+
if (value.some((item) => ctx.test(item, params))) return [];
|
|
262
|
+
return [makeFailure(ctx.key, ctx.path, `at least one item passing ${formatParams(params)}`, value)];
|
|
263
|
+
}
|
|
264
|
+
})
|
|
265
|
+
};
|
|
266
|
+
// src/checks/composition.ts
|
|
267
|
+
function validateBranches(param, path, validateNested) {
|
|
268
|
+
if (!Array.isArray(param) || param.length === 0) return "a non-empty array of params";
|
|
269
|
+
for (const branch of param) validateNested(branch, path);
|
|
270
|
+
}
|
|
271
|
+
var compositionChecks = {
|
|
272
|
+
not: composite({
|
|
273
|
+
phase: Phase.Structural,
|
|
274
|
+
validateParam: (param, path, validateNested) => {
|
|
275
|
+
validateNested(param, path);
|
|
276
|
+
},
|
|
277
|
+
evaluate(value, params, ctx) {
|
|
278
|
+
return ctx.test(value, params) ? [makeFailure(ctx.key, ctx.path, `not ${formatParams(params)}`, value)] : [];
|
|
279
|
+
}
|
|
280
|
+
}),
|
|
281
|
+
/**
|
|
282
|
+
* Passes when any branch passes. The failure lists every branch's failures in `branches`
|
|
283
|
+
* (all of them under `explain()`, the first per branch under `affirm()`).
|
|
284
|
+
*/
|
|
285
|
+
anyOf: composite({
|
|
286
|
+
phase: Phase.Structural,
|
|
287
|
+
validateParam: validateBranches,
|
|
288
|
+
evaluate(value, branches, ctx) {
|
|
289
|
+
const branchFailures = [];
|
|
290
|
+
for (const branch of branches) {
|
|
291
|
+
const failures = ctx.run(value, branch, ctx.path);
|
|
292
|
+
if (failures.length === 0) return [];
|
|
293
|
+
branchFailures.push(failures);
|
|
294
|
+
}
|
|
295
|
+
const n = branches.length;
|
|
296
|
+
return [{
|
|
297
|
+
...makeFailure(ctx.key, ctx.path, `any of ${n} ${n === 1 ? "branch" : "branches"} to pass`, value),
|
|
298
|
+
branches: branchFailures
|
|
299
|
+
}];
|
|
300
|
+
}
|
|
301
|
+
}),
|
|
302
|
+
satisfies: leaf({
|
|
303
|
+
phase: Phase.Predicate,
|
|
304
|
+
validateParam: functionParam,
|
|
305
|
+
test: (value, predicate) => predicate(value) === true,
|
|
306
|
+
expected: (predicate) => `${predicate.name || "predicate"}(value) to return true`
|
|
307
|
+
})
|
|
308
|
+
};
|
|
309
|
+
// src/core/util/deep-equal.ts
|
|
310
|
+
/**
|
|
311
|
+
* Structural equality per design §7.
|
|
312
|
+
* - primitives: `Object.is`, except `+0` equals `-0`
|
|
313
|
+
* - arrays: same length, elementwise
|
|
314
|
+
* - plain objects: same own enumerable string keys, valuewise
|
|
315
|
+
* - Date: same time · RegExp: same source + flags
|
|
316
|
+
* - Map: same size, same keys (SameValueZero), values deep-equal
|
|
317
|
+
* - Set: same size, every member present (SameValueZero; no deep matching of members)
|
|
318
|
+
* - other class instances: reference equality only
|
|
319
|
+
* - cycles: a pair already under comparison counts as equal
|
|
320
|
+
*/
|
|
321
|
+
function deepEqual(a, b) {
|
|
322
|
+
return eq(a, b, /* @__PURE__ */ new Map());
|
|
323
|
+
}
|
|
324
|
+
function eq(a, b, seen) {
|
|
325
|
+
if (a === b || Object.is(a, b)) return true;
|
|
326
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
|
|
327
|
+
let partners = seen.get(a);
|
|
328
|
+
if (partners?.has(b)) return true;
|
|
329
|
+
if (partners === void 0) seen.set(a, partners = /* @__PURE__ */ new Set());
|
|
330
|
+
partners.add(b);
|
|
331
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
332
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
|
333
|
+
return a.every((item, i) => eq(item, b[i], seen));
|
|
334
|
+
}
|
|
335
|
+
if (isPlainObject(a) || isPlainObject(b)) {
|
|
336
|
+
if (!isPlainObject(a) || !isPlainObject(b)) return false;
|
|
337
|
+
const keys = Object.keys(a);
|
|
338
|
+
if (keys.length !== Object.keys(b).length) return false;
|
|
339
|
+
return keys.every((key) => Object.hasOwn(b, key) && eq(a[key], b[key], seen));
|
|
340
|
+
}
|
|
341
|
+
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
|
|
342
|
+
if (a instanceof Date) return Object.is(a.getTime(), b.getTime());
|
|
343
|
+
if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;
|
|
344
|
+
if (a instanceof Map) {
|
|
345
|
+
const bm = b;
|
|
346
|
+
if (a.size !== bm.size) return false;
|
|
347
|
+
for (const [key, value] of a) if (!bm.has(key) || !eq(value, bm.get(key), seen)) return false;
|
|
348
|
+
return true;
|
|
349
|
+
}
|
|
350
|
+
if (a instanceof Set) {
|
|
351
|
+
const bs = b;
|
|
352
|
+
if (a.size !== bs.size) return false;
|
|
353
|
+
for (const member of a) if (!bs.has(member)) return false;
|
|
354
|
+
return true;
|
|
355
|
+
}
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
// src/checks/equality.ts
|
|
359
|
+
var equalityChecks = {
|
|
360
|
+
is: leaf({
|
|
361
|
+
phase: Phase.Kind,
|
|
362
|
+
validateParam: anyParam,
|
|
363
|
+
test: (value, param) => value === param,
|
|
364
|
+
expected: (param) => `=== ${formatParam(param)}`
|
|
365
|
+
}),
|
|
366
|
+
isNot: leaf({
|
|
367
|
+
phase: Phase.Kind,
|
|
368
|
+
validateParam: anyParam,
|
|
369
|
+
test: (value, param) => value !== param,
|
|
370
|
+
expected: (param) => `!== ${formatParam(param)}`
|
|
371
|
+
}),
|
|
372
|
+
isOneOf: leaf({
|
|
373
|
+
phase: Phase.Kind,
|
|
374
|
+
validateParam: arrayParam,
|
|
375
|
+
test: (value, list) => list.includes(value),
|
|
376
|
+
expected: (list) => `one of ${formatList(list)}`
|
|
377
|
+
}),
|
|
378
|
+
isNotOneOf: leaf({
|
|
379
|
+
phase: Phase.Kind,
|
|
380
|
+
validateParam: arrayParam,
|
|
381
|
+
test: (value, list) => !list.includes(value),
|
|
382
|
+
expected: (list) => `none of ${formatList(list)}`
|
|
383
|
+
}),
|
|
384
|
+
isDeepEqual: leaf({
|
|
385
|
+
phase: Phase.Structural,
|
|
386
|
+
validateParam: anyParam,
|
|
387
|
+
test: (value, param) => deepEqual(value, param),
|
|
388
|
+
expected: (param) => `deep equal to ${formatParam(param)}`
|
|
389
|
+
})
|
|
390
|
+
};
|
|
391
|
+
// src/checks/nullish.ts
|
|
392
|
+
var nullishChecks = {
|
|
393
|
+
isNull: booleanLeaf({
|
|
394
|
+
phase: Phase.Kind,
|
|
395
|
+
test: (value) => value === null,
|
|
396
|
+
expected: "null",
|
|
397
|
+
expectedNot: "not null"
|
|
398
|
+
}),
|
|
399
|
+
isUndefined: booleanLeaf({
|
|
400
|
+
phase: Phase.Kind,
|
|
401
|
+
test: (value) => value === void 0,
|
|
402
|
+
expected: "undefined",
|
|
403
|
+
expectedNot: "not undefined"
|
|
404
|
+
}),
|
|
405
|
+
isNullish: booleanLeaf({
|
|
406
|
+
phase: Phase.Kind,
|
|
407
|
+
test: (value) => value === null || value === void 0,
|
|
408
|
+
expected: "null or undefined",
|
|
409
|
+
expectedNot: "not null or undefined"
|
|
410
|
+
}),
|
|
411
|
+
isDefined: booleanLeaf({
|
|
412
|
+
phase: Phase.Kind,
|
|
413
|
+
test: (value) => value !== void 0,
|
|
414
|
+
expected: "defined (not undefined)",
|
|
415
|
+
expectedNot: "undefined"
|
|
416
|
+
}),
|
|
417
|
+
isPresent: booleanLeaf({
|
|
418
|
+
phase: Phase.Kind,
|
|
419
|
+
test: (value) => value !== null && value !== void 0,
|
|
420
|
+
expected: "present (not null or undefined)",
|
|
421
|
+
expectedNot: "null or undefined"
|
|
422
|
+
}),
|
|
423
|
+
isTruthy: booleanLeaf({
|
|
424
|
+
phase: Phase.Kind,
|
|
425
|
+
test: (value) => Boolean(value),
|
|
426
|
+
expected: "truthy",
|
|
427
|
+
expectedNot: "falsy"
|
|
428
|
+
}),
|
|
429
|
+
isFalsy: booleanLeaf({
|
|
430
|
+
phase: Phase.Kind,
|
|
431
|
+
test: (value) => !value,
|
|
432
|
+
expected: "falsy",
|
|
433
|
+
expectedNot: "truthy"
|
|
434
|
+
})
|
|
435
|
+
};
|
|
436
|
+
// src/checks/numbers.ts
|
|
437
|
+
var NUMBER = "a number (not NaN)";
|
|
438
|
+
/** A comparison key: `value <op> n`. */
|
|
439
|
+
function compare(test, op) {
|
|
440
|
+
return leaf({
|
|
441
|
+
phase: Phase.Measure,
|
|
442
|
+
validateParam: numberParam,
|
|
443
|
+
accepts: isNumberNotNaN,
|
|
444
|
+
acceptsLabel: NUMBER,
|
|
445
|
+
test,
|
|
446
|
+
expected: (n) => `${op} ${formatParam(n)}`
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
function validateRange(param) {
|
|
450
|
+
if (!Array.isArray(param) || param.length !== 2 || numberParam(param[0]) !== void 0 || numberParam(param[1]) !== void 0) return `a [min, max] pair of numbers (received ${formatParam(param)})`;
|
|
451
|
+
return param[0] <= param[1] ? void 0 : `min <= max (received [${param[0]}, ${param[1]}])`;
|
|
452
|
+
}
|
|
453
|
+
function validateDivisor(param) {
|
|
454
|
+
return Number.isFinite(param) && param !== 0 ? void 0 : `a finite non-zero number (received ${formatParam(param)})`;
|
|
455
|
+
}
|
|
456
|
+
var numberChecks = {
|
|
457
|
+
isGreaterThan: compare((v, n) => v > n, ">"),
|
|
458
|
+
isAtLeast: compare((v, n) => v >= n, ">="),
|
|
459
|
+
isLessThan: compare((v, n) => v < n, "<"),
|
|
460
|
+
isAtMost: compare((v, n) => v <= n, "<="),
|
|
461
|
+
isBetween: leaf({
|
|
462
|
+
phase: Phase.Measure,
|
|
463
|
+
validateParam: validateRange,
|
|
464
|
+
accepts: isNumberNotNaN,
|
|
465
|
+
acceptsLabel: NUMBER,
|
|
466
|
+
test: (value, [min, max]) => value >= min && value <= max,
|
|
467
|
+
expected: ([min, max]) => `between ${formatParam(min)} and ${formatParam(max)} (inclusive)`
|
|
468
|
+
}),
|
|
469
|
+
isPositive: booleanLeaf({
|
|
470
|
+
phase: Phase.Measure,
|
|
471
|
+
accepts: isNumberNotNaN,
|
|
472
|
+
acceptsLabel: NUMBER,
|
|
473
|
+
test: (value) => value > 0,
|
|
474
|
+
expected: "> 0",
|
|
475
|
+
expectedNot: "<= 0"
|
|
476
|
+
}),
|
|
477
|
+
isNegative: booleanLeaf({
|
|
478
|
+
phase: Phase.Measure,
|
|
479
|
+
accepts: isNumberNotNaN,
|
|
480
|
+
acceptsLabel: NUMBER,
|
|
481
|
+
test: (value) => value < 0,
|
|
482
|
+
expected: "< 0",
|
|
483
|
+
expectedNot: ">= 0"
|
|
484
|
+
}),
|
|
485
|
+
isMultipleOf: leaf({
|
|
486
|
+
phase: Phase.Measure,
|
|
487
|
+
validateParam: validateDivisor,
|
|
488
|
+
accepts: isNumberNotNaN,
|
|
489
|
+
acceptsLabel: NUMBER,
|
|
490
|
+
test: (value, n) => value % n === 0,
|
|
491
|
+
expected: (n) => `a multiple of ${formatParam(n)}`
|
|
492
|
+
})
|
|
493
|
+
};
|
|
494
|
+
// src/checks/objects.ts
|
|
495
|
+
var OBJECT = "an object or array";
|
|
496
|
+
/** Own-key comparison treats `0` and `'0'` as the same key, like property access does. */
|
|
497
|
+
var normalizeKey = (key) => typeof key === "symbol" ? key : String(key);
|
|
498
|
+
function validatePath(param) {
|
|
499
|
+
if (typeof param !== "string") return `a dot path string (received ${formatParam(param)})`;
|
|
500
|
+
if (param.split(".").some((segment) => segment === "")) return `a dot path with no empty segments (received ${formatParam(param)})`;
|
|
501
|
+
}
|
|
502
|
+
function hasOwnPath(value, path) {
|
|
503
|
+
let current = value;
|
|
504
|
+
for (const segment of path.split(".")) {
|
|
505
|
+
if (!isObjectLike(current) || !Object.hasOwn(current, segment)) return false;
|
|
506
|
+
current = current[segment];
|
|
507
|
+
}
|
|
508
|
+
return true;
|
|
509
|
+
}
|
|
510
|
+
function validateShape(param, path, validateNested) {
|
|
511
|
+
if (!isPlainObject(param)) return `an object mapping field names to params (received ${formatParam(param)})`;
|
|
512
|
+
if (Object.keys(param).length === 0) return "at least one field; `shape: {}` would always pass";
|
|
513
|
+
for (const [field, fieldParams] of Object.entries(param)) validateNested(fieldParams, joinPath(path, field));
|
|
514
|
+
}
|
|
515
|
+
var objectChecks = {
|
|
516
|
+
shape: composite({
|
|
517
|
+
phase: Phase.Structural,
|
|
518
|
+
validateParam: validateShape,
|
|
519
|
+
accepts: isObjectLike,
|
|
520
|
+
acceptsLabel: OBJECT,
|
|
521
|
+
evaluate(value, shape, ctx) {
|
|
522
|
+
const failures = [];
|
|
523
|
+
for (const [field, fieldParams] of Object.entries(shape)) {
|
|
524
|
+
const fieldValue = Object.hasOwn(value, field) ? value[field] : void 0;
|
|
525
|
+
failures.push(...ctx.run(fieldValue, fieldParams, joinPath(ctx.path, field)));
|
|
526
|
+
if (ctx.mode === "first" && failures.length > 0) break;
|
|
527
|
+
}
|
|
528
|
+
return failures;
|
|
529
|
+
}
|
|
530
|
+
}),
|
|
531
|
+
hasKey: leaf({
|
|
532
|
+
phase: Phase.Measure,
|
|
533
|
+
validateParam: propertyKeyParam,
|
|
534
|
+
accepts: isObjectLike,
|
|
535
|
+
acceptsLabel: OBJECT,
|
|
536
|
+
test: (value, key) => Object.hasOwn(value, key),
|
|
537
|
+
expected: (key) => `own key ${formatParam(key)}`
|
|
538
|
+
}),
|
|
539
|
+
hasKeys: leaf({
|
|
540
|
+
phase: Phase.Measure,
|
|
541
|
+
validateParam: propertyKeyListParam,
|
|
542
|
+
accepts: isObjectLike,
|
|
543
|
+
acceptsLabel: OBJECT,
|
|
544
|
+
test: (value, keys) => keys.every((key) => Object.hasOwn(value, key)),
|
|
545
|
+
expected: (keys) => `own keys ${formatList(keys)}`
|
|
546
|
+
}),
|
|
547
|
+
hasAnyKey: leaf({
|
|
548
|
+
phase: Phase.Measure,
|
|
549
|
+
validateParam: propertyKeyListParam,
|
|
550
|
+
accepts: isObjectLike,
|
|
551
|
+
acceptsLabel: OBJECT,
|
|
552
|
+
test: (value, keys) => keys.some((key) => Object.hasOwn(value, key)),
|
|
553
|
+
expected: (keys) => `at least one own key of ${formatList(keys)}`
|
|
554
|
+
}),
|
|
555
|
+
hasOnlyKeys: leaf({
|
|
556
|
+
phase: Phase.Measure,
|
|
557
|
+
validateParam: propertyKeyListParam,
|
|
558
|
+
accepts: isObjectLike,
|
|
559
|
+
acceptsLabel: OBJECT,
|
|
560
|
+
test: (value, keys) => {
|
|
561
|
+
const allowed = new Set(keys.map(normalizeKey));
|
|
562
|
+
return ownKeys(value).every((key) => allowed.has(normalizeKey(key)));
|
|
563
|
+
},
|
|
564
|
+
expected: (keys) => `no own keys other than ${formatList(keys)}`
|
|
565
|
+
}),
|
|
566
|
+
hasPath: leaf({
|
|
567
|
+
phase: Phase.Measure,
|
|
568
|
+
validateParam: validatePath,
|
|
569
|
+
accepts: isObjectLike,
|
|
570
|
+
acceptsLabel: OBJECT,
|
|
571
|
+
test: hasOwnPath,
|
|
572
|
+
expected: (path) => `own path ${formatParam(path)}`
|
|
573
|
+
})
|
|
574
|
+
};
|
|
575
|
+
// src/core/util/standard-schema.ts
|
|
576
|
+
/**
|
|
577
|
+
* Detects a Standard Schema via its `'~standard'` property. Schemas may be objects (Zod, Valibot)
|
|
578
|
+
* or callable functions (ArkType), so both are accepted.
|
|
579
|
+
*/
|
|
580
|
+
function isStandardSchema(value) {
|
|
581
|
+
if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
|
|
582
|
+
const props = value["~standard"];
|
|
583
|
+
return typeof props === "object" && props !== null && props.version === 1 && typeof props.validate === "function";
|
|
584
|
+
}
|
|
585
|
+
/** Runs a schema synchronously. Throws `TypeError` for async schemas (design §4 rule 6, §10). */
|
|
586
|
+
function validateSync(schema, value) {
|
|
587
|
+
const result = schema["~standard"].validate(value);
|
|
588
|
+
if (typeof result.then === "function") {
|
|
589
|
+
result.then(void 0, () => {});
|
|
590
|
+
throw new TypeError(`affirm: async schemas are not supported by affirm; validate them before calling affirm (vendor: ${schema["~standard"].vendor})`);
|
|
591
|
+
}
|
|
592
|
+
return result;
|
|
593
|
+
}
|
|
594
|
+
// src/checks/runtime-type.ts
|
|
595
|
+
var TYPE_TAGS = /* @__PURE__ */ new Set([
|
|
596
|
+
"string",
|
|
597
|
+
"number",
|
|
598
|
+
"boolean",
|
|
599
|
+
"bigint",
|
|
600
|
+
"symbol",
|
|
601
|
+
"function",
|
|
602
|
+
"object"
|
|
603
|
+
]);
|
|
604
|
+
function validateIsType(param) {
|
|
605
|
+
if (isStandardSchema(param)) return void 0;
|
|
606
|
+
if (typeof param === "string") {
|
|
607
|
+
if (TYPE_TAGS.has(param)) return void 0;
|
|
608
|
+
if (param === "undefined") return `a type tag; use \`isUndefined: true\` instead of \`isType: 'undefined'\``;
|
|
609
|
+
if (param === "null") return `a type tag; use \`isNull: true\` instead of \`isType: 'null'\``;
|
|
610
|
+
return `one of ${[...TYPE_TAGS].map((t) => `'${t}'`).join(", ")} (received ${formatParam(param)})`;
|
|
611
|
+
}
|
|
612
|
+
if (typeof param === "function") {
|
|
613
|
+
if (looksLikeConstructor(param)) return `a type tag, guard or schema; use \`isInstanceOf: ${param.name || "YourClass"}\` for classes`;
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
return `a type tag, a type guard function or a Standard Schema (received ${formatParam(param)})`;
|
|
617
|
+
}
|
|
618
|
+
function matchesTag(value, tag) {
|
|
619
|
+
if (tag === "object") return typeof value === "object" && value !== null;
|
|
620
|
+
return typeof value === tag;
|
|
621
|
+
}
|
|
622
|
+
var segmentKey = (segment) => typeof segment === "object" && segment !== null ? segment.key : segment;
|
|
623
|
+
/** Appends a schema issue path: numbers as `[n]`, strings as `.key`, symbols as `[Symbol(x)]`. */
|
|
624
|
+
function appendIssuePath(base, path) {
|
|
625
|
+
let out = base;
|
|
626
|
+
for (const segment of path ?? []) {
|
|
627
|
+
const key = segmentKey(segment);
|
|
628
|
+
out = typeof key === "symbol" ? `${out}[${key.toString()}]` : joinPath(out, key);
|
|
629
|
+
}
|
|
630
|
+
return out;
|
|
631
|
+
}
|
|
632
|
+
/** The value an issue points at, for `received` (described by type only, D5). */
|
|
633
|
+
function valueAt(value, path) {
|
|
634
|
+
let current = value;
|
|
635
|
+
for (const segment of path ?? []) {
|
|
636
|
+
if (typeof current !== "object" && typeof current !== "function" || current === null) return void 0;
|
|
637
|
+
current = current[segmentKey(segment)];
|
|
638
|
+
}
|
|
639
|
+
return current;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Maps schema issues to failures (design §10). Issue *messages* are not copied: libraries may put
|
|
643
|
+
* the received value in them (e.g. enum mismatches), and reports must not carry raw values (D5).
|
|
644
|
+
*/
|
|
645
|
+
function schemaFailures(schema, value, ctx) {
|
|
646
|
+
const result = validateSync(schema, value);
|
|
647
|
+
if (result.issues === void 0) return [];
|
|
648
|
+
const vendor = schema["~standard"].vendor;
|
|
649
|
+
if (result.issues.length === 0) return [makeFailure(ctx.key, ctx.path, `a value accepted by the ${vendor} schema`, value)];
|
|
650
|
+
return result.issues.map((issue) => makeFailure(ctx.key, appendIssuePath(ctx.path, issue.path), `a value accepted by the ${vendor} schema`, valueAt(value, issue.path)));
|
|
651
|
+
}
|
|
652
|
+
var runtimeTypeChecks = {
|
|
653
|
+
isType: {
|
|
654
|
+
phase: Phase.Kind,
|
|
655
|
+
validateParam: validateIsType,
|
|
656
|
+
evaluate(value, param, ctx) {
|
|
657
|
+
if (isStandardSchema(param)) return schemaFailures(param, value, ctx);
|
|
658
|
+
if (typeof param === "string") {
|
|
659
|
+
if (matchesTag(value, param)) return [];
|
|
660
|
+
return [makeFailure(ctx.key, ctx.path, param === "object" ? "a non-null object" : `typeof ${param}`, value)];
|
|
661
|
+
}
|
|
662
|
+
if (param(value) === true) return [];
|
|
663
|
+
return [makeFailure(ctx.key, ctx.path, `${param.name || "guard"}(value) to return true`, value)];
|
|
664
|
+
}
|
|
665
|
+
},
|
|
666
|
+
isArray: booleanLeaf({
|
|
667
|
+
phase: Phase.Kind,
|
|
668
|
+
test: (value) => Array.isArray(value),
|
|
669
|
+
expected: "an array",
|
|
670
|
+
expectedNot: "not an array"
|
|
671
|
+
}),
|
|
672
|
+
isPlainObject: booleanLeaf({
|
|
673
|
+
phase: Phase.Kind,
|
|
674
|
+
test: isPlainObject,
|
|
675
|
+
expected: "a plain object",
|
|
676
|
+
expectedNot: "not a plain object"
|
|
677
|
+
}),
|
|
678
|
+
isFunction: booleanLeaf({
|
|
679
|
+
phase: Phase.Kind,
|
|
680
|
+
test: (value) => typeof value === "function",
|
|
681
|
+
expected: "a function",
|
|
682
|
+
expectedNot: "not a function"
|
|
683
|
+
}),
|
|
684
|
+
isInstanceOf: leaf({
|
|
685
|
+
phase: Phase.Kind,
|
|
686
|
+
validateParam: (param) => typeof param === "function" && param.prototype !== void 0 ? void 0 : `a class or constructor (received ${formatParam(param)})`,
|
|
687
|
+
test: (value, ctor) => value instanceof ctor,
|
|
688
|
+
expected: (ctor) => `instance of ${ctor.name || "the given class"}`
|
|
689
|
+
}),
|
|
690
|
+
isValidDate: booleanLeaf({
|
|
691
|
+
phase: Phase.Kind,
|
|
692
|
+
accepts: isDate,
|
|
693
|
+
acceptsLabel: "a Date",
|
|
694
|
+
test: (date) => !Number.isNaN(date.getTime()),
|
|
695
|
+
expected: "a valid Date",
|
|
696
|
+
expectedNot: "an invalid Date"
|
|
697
|
+
}),
|
|
698
|
+
isInteger: booleanLeaf({
|
|
699
|
+
phase: Phase.Kind,
|
|
700
|
+
accepts: isNumber,
|
|
701
|
+
acceptsLabel: "a number",
|
|
702
|
+
test: Number.isInteger,
|
|
703
|
+
expected: "an integer",
|
|
704
|
+
expectedNot: "a non-integer number"
|
|
705
|
+
}),
|
|
706
|
+
isFiniteNumber: booleanLeaf({
|
|
707
|
+
phase: Phase.Kind,
|
|
708
|
+
accepts: isNumber,
|
|
709
|
+
acceptsLabel: "a number",
|
|
710
|
+
test: Number.isFinite,
|
|
711
|
+
expected: "a finite number",
|
|
712
|
+
expectedNot: "a non-finite number (Infinity, -Infinity or NaN)"
|
|
713
|
+
}),
|
|
714
|
+
isNaN: booleanLeaf({
|
|
715
|
+
phase: Phase.Kind,
|
|
716
|
+
accepts: isNumber,
|
|
717
|
+
acceptsLabel: "a number",
|
|
718
|
+
test: Number.isNaN,
|
|
719
|
+
expected: "NaN",
|
|
720
|
+
expectedNot: "a number other than NaN"
|
|
721
|
+
})
|
|
722
|
+
};
|
|
723
|
+
// src/checks/size.ts
|
|
724
|
+
var MEASURABLE = "a string, array, Map or Set";
|
|
725
|
+
var isSizable = (value) => isMeasurable(value) || isPlainObject(value);
|
|
726
|
+
var sizeOfSizable = (value) => isMeasurable(value) ? sizeOf(value) : Object.keys(value).length;
|
|
727
|
+
var SIZABLE = "a string, array, Map, Set or plain object";
|
|
728
|
+
var sizeChecks = {
|
|
729
|
+
isEmpty: booleanLeaf({
|
|
730
|
+
phase: Phase.Measure,
|
|
731
|
+
accepts: isSizable,
|
|
732
|
+
acceptsLabel: SIZABLE,
|
|
733
|
+
test: (value) => sizeOfSizable(value) === 0,
|
|
734
|
+
expected: "empty",
|
|
735
|
+
expectedNot: "not empty"
|
|
736
|
+
}),
|
|
737
|
+
isNotEmpty: booleanLeaf({
|
|
738
|
+
phase: Phase.Measure,
|
|
739
|
+
accepts: isSizable,
|
|
740
|
+
acceptsLabel: SIZABLE,
|
|
741
|
+
test: (value) => sizeOfSizable(value) > 0,
|
|
742
|
+
expected: "not empty",
|
|
743
|
+
expectedNot: "empty"
|
|
744
|
+
}),
|
|
745
|
+
isBlank: booleanLeaf({
|
|
746
|
+
phase: Phase.Measure,
|
|
747
|
+
accepts: isString,
|
|
748
|
+
acceptsLabel: "a string",
|
|
749
|
+
test: (value) => value.trim() === "",
|
|
750
|
+
expected: "a blank string",
|
|
751
|
+
expectedNot: "a non-blank string"
|
|
752
|
+
}),
|
|
753
|
+
hasLength: leaf({
|
|
754
|
+
phase: Phase.Measure,
|
|
755
|
+
validateParam: nonNegativeIntegerParam,
|
|
756
|
+
accepts: isMeasurable,
|
|
757
|
+
acceptsLabel: MEASURABLE,
|
|
758
|
+
test: (value, n) => sizeOf(value) === n,
|
|
759
|
+
expected: (n) => `length === ${n}`
|
|
760
|
+
}),
|
|
761
|
+
hasMinLength: leaf({
|
|
762
|
+
phase: Phase.Measure,
|
|
763
|
+
validateParam: nonNegativeIntegerParam,
|
|
764
|
+
accepts: isMeasurable,
|
|
765
|
+
acceptsLabel: MEASURABLE,
|
|
766
|
+
test: (value, n) => sizeOf(value) >= n,
|
|
767
|
+
expected: (n) => `length >= ${n}`
|
|
768
|
+
}),
|
|
769
|
+
hasMaxLength: leaf({
|
|
770
|
+
phase: Phase.Measure,
|
|
771
|
+
validateParam: nonNegativeIntegerParam,
|
|
772
|
+
accepts: isMeasurable,
|
|
773
|
+
acceptsLabel: MEASURABLE,
|
|
774
|
+
test: (value, n) => sizeOf(value) <= n,
|
|
775
|
+
expected: (n) => `length <= ${n}`
|
|
776
|
+
})
|
|
777
|
+
};
|
|
778
|
+
// src/checks/strings.ts
|
|
779
|
+
var MAX_REGEX_SHOWN = 40;
|
|
780
|
+
function formatRegExp(re) {
|
|
781
|
+
const text = String(re);
|
|
782
|
+
return text.length <= MAX_REGEX_SHOWN ? text : `${text.slice(0, MAX_REGEX_SHOWN)}…`;
|
|
783
|
+
}
|
|
784
|
+
var stringChecks = {
|
|
785
|
+
startsWith: leaf({
|
|
786
|
+
phase: Phase.Measure,
|
|
787
|
+
validateParam: stringParam,
|
|
788
|
+
accepts: isString,
|
|
789
|
+
acceptsLabel: "a string",
|
|
790
|
+
test: (value, prefix) => value.startsWith(prefix),
|
|
791
|
+
expected: (prefix) => `a string starting with ${formatParam(prefix)}`
|
|
792
|
+
}),
|
|
793
|
+
endsWith: leaf({
|
|
794
|
+
phase: Phase.Measure,
|
|
795
|
+
validateParam: stringParam,
|
|
796
|
+
accepts: isString,
|
|
797
|
+
acceptsLabel: "a string",
|
|
798
|
+
test: (value, suffix) => value.endsWith(suffix),
|
|
799
|
+
expected: (suffix) => `a string ending with ${formatParam(suffix)}`
|
|
800
|
+
}),
|
|
801
|
+
includes: leaf({
|
|
802
|
+
phase: Phase.Measure,
|
|
803
|
+
validateParam: stringParam,
|
|
804
|
+
accepts: isString,
|
|
805
|
+
acceptsLabel: "a string",
|
|
806
|
+
test: (value, part) => value.includes(part),
|
|
807
|
+
expected: (part) => `a string including ${formatParam(part)}`
|
|
808
|
+
}),
|
|
809
|
+
matches: leaf({
|
|
810
|
+
phase: Phase.Measure,
|
|
811
|
+
validateParam: (param) => param instanceof RegExp ? void 0 : `a RegExp (received ${formatParam(param)}); use \`includes\` for plain text`,
|
|
812
|
+
accepts: isString,
|
|
813
|
+
acceptsLabel: "a string",
|
|
814
|
+
test: (value, re) => {
|
|
815
|
+
re.lastIndex = 0;
|
|
816
|
+
return re.test(value);
|
|
817
|
+
},
|
|
818
|
+
expected: (re) => `a string matching ${formatRegExp(re)}`
|
|
819
|
+
})
|
|
820
|
+
};
|
|
821
|
+
// src/core/registry.ts
|
|
822
|
+
/**
|
|
823
|
+
* Merges group objects into one registry. Throws at module load on a duplicate key,
|
|
824
|
+
* which a plain spread would silently overwrite.
|
|
825
|
+
*/
|
|
826
|
+
function defineRegistry(...groups) {
|
|
827
|
+
const merged = {};
|
|
828
|
+
for (const group of groups) for (const key of Object.keys(group)) {
|
|
829
|
+
if (Object.hasOwn(merged, key)) throw new Error(`affirm: duplicate check key \`${key}\` across groups`);
|
|
830
|
+
merged[key] = group[key];
|
|
831
|
+
}
|
|
832
|
+
return merged;
|
|
833
|
+
}
|
|
834
|
+
/** Every check, keyed by params key. Group order here is the tie-breaker within a phase. */
|
|
835
|
+
var checks = defineRegistry(nullishChecks, runtimeTypeChecks, equalityChecks, sizeChecks, numberChecks, stringChecks, objectChecks, arrayChecks, compositionChecks);
|
|
836
|
+
/** All keys, sorted by phase (stable, so registry order breaks ties). Design §4 rule 7. */
|
|
837
|
+
var KEY_ORDER = Object.keys(checks).map((key, index) => ({
|
|
838
|
+
key,
|
|
839
|
+
index,
|
|
840
|
+
phase: checks[key].phase
|
|
841
|
+
})).sort((a, b) => a.phase - b.phase || a.index - b.index).map(({ key }) => key);
|
|
842
|
+
var RANK = new Map(KEY_ORDER.map((key, i) => [key, i]));
|
|
843
|
+
function isCheckKey(key) {
|
|
844
|
+
return RANK.has(key);
|
|
845
|
+
}
|
|
846
|
+
/** Canonical rank of a key; only call with keys that passed `isCheckKey`. */
|
|
847
|
+
function rankOf(key) {
|
|
848
|
+
return RANK.get(key);
|
|
849
|
+
}
|
|
850
|
+
// src/core/evaluate.ts
|
|
851
|
+
/**
|
|
852
|
+
* Runs already-validated params against a value in canonical key order (design §4 rule 7).
|
|
853
|
+
* `'first'` stops at the first failing key; `'all'` collects every failure.
|
|
854
|
+
*/
|
|
855
|
+
function runParams(value, params, path, mode) {
|
|
856
|
+
const keys = Object.keys(params).filter(isCheckKey).sort((a, b) => rankOf(a) - rankOf(b));
|
|
857
|
+
const failures = [];
|
|
858
|
+
const run = (v, p, at) => runParams(v, p, at, mode);
|
|
859
|
+
const test = (v, p) => runParams(v, p, path, "first").length === 0;
|
|
860
|
+
for (const key of keys) {
|
|
861
|
+
const param = params[key];
|
|
862
|
+
if (param === void 0) continue;
|
|
863
|
+
const ctx = {
|
|
864
|
+
key,
|
|
865
|
+
path,
|
|
866
|
+
mode,
|
|
867
|
+
run,
|
|
868
|
+
test
|
|
869
|
+
};
|
|
870
|
+
const result = checks[key].evaluate(value, param, ctx);
|
|
871
|
+
if (result.length > 0) {
|
|
872
|
+
failures.push(...result);
|
|
873
|
+
if (mode === "first") break;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return failures;
|
|
877
|
+
}
|
|
878
|
+
// src/core/util/levenshtein.ts
|
|
879
|
+
function levenshtein(a, b) {
|
|
880
|
+
if (a === b) return 0;
|
|
881
|
+
if (a.length === 0) return b.length;
|
|
882
|
+
if (b.length === 0) return a.length;
|
|
883
|
+
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
884
|
+
for (let i = 1; i <= a.length; i++) {
|
|
885
|
+
const curr = [i];
|
|
886
|
+
for (let j = 1; j <= b.length; j++) {
|
|
887
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
888
|
+
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
|
|
889
|
+
}
|
|
890
|
+
prev = curr;
|
|
891
|
+
}
|
|
892
|
+
return prev[b.length];
|
|
893
|
+
}
|
|
894
|
+
/** Closest candidate by case-insensitive edit distance, or `undefined` if nothing is close enough. */
|
|
895
|
+
function closest(input, candidates) {
|
|
896
|
+
const needle = input.toLowerCase();
|
|
897
|
+
const limit = Math.max(2, Math.floor(input.length / 3));
|
|
898
|
+
let best;
|
|
899
|
+
let bestDistance = Infinity;
|
|
900
|
+
for (const candidate of candidates) {
|
|
901
|
+
const d = levenshtein(needle, candidate.toLowerCase());
|
|
902
|
+
if (d < bestDistance) {
|
|
903
|
+
best = candidate;
|
|
904
|
+
bestDistance = d;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
return bestDistance <= limit ? best : void 0;
|
|
908
|
+
}
|
|
909
|
+
// src/core/validate-params.ts
|
|
910
|
+
/**
|
|
911
|
+
* Throws `TypeError` for programmer errors (design §4 rule 6, D4):
|
|
912
|
+
* params that are not an object, empty params `{}`, unknown keys, and wrong param types.
|
|
913
|
+
* Runs over all keys before any evaluation, so a typo can't hide behind a short-circuit.
|
|
914
|
+
* `path` locates nested params (from `shape`, `everyItem`, …) in messages.
|
|
915
|
+
*/
|
|
916
|
+
function validateParams(params, path = "") {
|
|
917
|
+
const where = path === "" ? "" : ` at \`${path}\``;
|
|
918
|
+
if (typeof params !== "object" || params === null || Array.isArray(params)) throw new TypeError(`affirm: params${where} must be an object of checks, received ${formatParam(params)}`);
|
|
919
|
+
const keys = Object.keys(params);
|
|
920
|
+
if (keys.length === 0) throw new TypeError(`affirm: params${where} are empty; \`{}\` would always pass`);
|
|
921
|
+
for (const key of keys) {
|
|
922
|
+
if (!isCheckKey(key)) {
|
|
923
|
+
const suggestion = closest(key, KEY_ORDER);
|
|
924
|
+
const hint = suggestion === void 0 ? "" : ` Did you mean \`${suggestion}\`?`;
|
|
925
|
+
throw new TypeError(`affirm: unknown check \`${key}\`${where}.${hint}`);
|
|
926
|
+
}
|
|
927
|
+
const param = params[key];
|
|
928
|
+
if (param === void 0) continue;
|
|
929
|
+
const problem = checks[key].validateParam(param, path, validateParams);
|
|
930
|
+
if (problem !== void 0) throw new TypeError(`affirm: invalid param for \`${key}\`${where}: expected ${problem}`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
// src/affirm.ts
|
|
934
|
+
function call(value, params) {
|
|
935
|
+
validateParams(params);
|
|
936
|
+
return runParams(value, params, "", "first").length === 0;
|
|
937
|
+
}
|
|
938
|
+
function explain(value, params) {
|
|
939
|
+
validateParams(params);
|
|
940
|
+
const failures = runParams(value, params, "", "all");
|
|
941
|
+
return {
|
|
942
|
+
ok: failures.length === 0,
|
|
943
|
+
failures
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function assertOrThrow(value, params, message) {
|
|
947
|
+
const report = explain(value, params);
|
|
948
|
+
if (!report.ok) throw new AffirmError(report, message);
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Replaces compound data checks with one readable object of named checks.
|
|
952
|
+
* See `AffirmParams` for every key, and `AGENTS.md` for the usage guide.
|
|
953
|
+
*
|
|
954
|
+
* @example
|
|
955
|
+
* import { affirm } from '@frankmeza/affirm'
|
|
956
|
+
*
|
|
957
|
+
* if (affirm(user, { isPresent: true, hasKey: 'email' })) { … }
|
|
958
|
+
* affirm.explain(user, { shape: { email: { matches: /@/ } } }) // { ok, failures }
|
|
959
|
+
* affirm.assert(user, { isPresent: true }) // throws AffirmError, then narrows
|
|
960
|
+
*/
|
|
961
|
+
var affirm = Object.assign(call, {
|
|
962
|
+
explain,
|
|
963
|
+
assert: assertOrThrow
|
|
964
|
+
});
|
|
965
|
+
export { AffirmError, affirm };
|
|
966
|
+
|
|
967
|
+
//# sourceMappingURL=index.js.map
|