is-kit 1.14.2 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,563 +1,839 @@
1
- // src/core/assert.ts
2
- var DEFAULT_ASSERT_MESSAGE = "Assertion failed";
1
+
2
+ //#region src/core/assert.ts
3
+ const DEFAULT_ASSERT_MESSAGE = "Assertion failed";
3
4
  function assert(fn, value, message) {
4
- if (fn(value)) return;
5
- throw new Error(message ?? DEFAULT_ASSERT_MESSAGE);
5
+ if (fn(value)) return;
6
+ throw new Error(message ?? DEFAULT_ASSERT_MESSAGE);
6
7
  }
7
-
8
- // src/core/define.ts
8
+ //#endregion
9
+ //#region src/core/define.ts
9
10
  function define(fn) {
10
- return (value) => !!fn(value);
11
- }
12
-
13
- // src/utils/own-properties.ts
14
- var hasOwnPropertyKey = (value, key) => Object.hasOwn(value, key);
15
- var hasOwnPropertyKeys = (value, keys) => keys.every((key) => hasOwnPropertyKey(value, key));
16
-
17
- // src/utils/object-tags.ts
18
- var objectToString = Object.prototype.toString;
19
- var OBJECT_TAG_ERROR = "[object Error]";
20
- var getTag = (value) => objectToString.call(value);
21
-
22
- // src/core/object.ts
23
- var BUILTIN_BRAND_SENTINEL = Object.freeze({});
24
- var getIntrinsicGetter = (prototype, key) => {
25
- const getter = Object.getOwnPropertyDescriptor(prototype, key)?.get;
26
- return getter ?? (() => {
27
- throw new TypeError(`Missing intrinsic getter: ${String(key)}`);
28
- });
11
+ return (value) => !!fn(value);
12
+ }
13
+ //#endregion
14
+ //#region src/utils/own-properties.ts
15
+ /**
16
+ * Checks whether an object has an own property key.
17
+ *
18
+ * @param value Object-like value already narrowed by callers.
19
+ * @param key Property key to check.
20
+ * @returns Whether `key` is present directly on `value`.
21
+ */
22
+ const hasOwnPropertyKey = (value, key) => Object.hasOwn(value, key);
23
+ /**
24
+ * Checks whether an object has every requested own property key.
25
+ *
26
+ * @param value Object-like value already narrowed by callers.
27
+ * @param keys Property keys to check.
28
+ * @returns Whether all keys are present directly on `value`.
29
+ */
30
+ const hasOwnPropertyKeys = (value, keys) => keys.every((key) => hasOwnPropertyKey(value, key));
31
+ //#endregion
32
+ //#region src/utils/object-tags.ts
33
+ const objectToString = Object.prototype.toString;
34
+ /**
35
+ * Returns the internal object tag for a value.
36
+ * @param value Value to inspect with `Object.prototype.toString`.
37
+ * @returns Stable built-in tag such as `[object Date]`.
38
+ */
39
+ const getTag = (value) => objectToString.call(value);
40
+ //#endregion
41
+ //#region src/core/object.ts
42
+ const BUILTIN_BRAND_SENTINEL = Object.freeze({});
43
+ const getIntrinsicGetter = (prototype, key) => {
44
+ return Object.getOwnPropertyDescriptor(prototype, key)?.get ?? (() => {
45
+ throw new TypeError(`Missing intrinsic getter: ${String(key)}`);
46
+ });
29
47
  };
30
- var defineIntrinsicBrandGuard = (checkBrand) => define((value) => {
31
- try {
32
- checkBrand(value);
33
- return true;
34
- } catch {
35
- return false;
36
- }
48
+ const defineIntrinsicBrandGuard = (checkBrand) => define((value) => {
49
+ try {
50
+ checkBrand(value);
51
+ return true;
52
+ } catch {
53
+ return false;
54
+ }
37
55
  });
38
- var dateGetTime = Date.prototype.getTime;
39
- var mapHas = Map.prototype.has;
40
- var setHas = Set.prototype.has;
41
- var weakMapHas = WeakMap.prototype.has;
42
- var weakSetHas = WeakSet.prototype.has;
43
- var regExpSource = getIntrinsicGetter(RegExp.prototype, "source");
44
- var arrayBufferByteLength = getIntrinsicGetter(
45
- ArrayBuffer.prototype,
46
- "byteLength"
47
- );
48
- var dataViewBuffer = getIntrinsicGetter(DataView.prototype, "buffer");
49
- var typedArrayName = Object.getOwnPropertyDescriptor(
50
- Object.getPrototypeOf(Uint8Array.prototype),
51
- Symbol.toStringTag
52
- )?.get;
53
- var defineOptionalInstanceGuard = (constructor) => constructor === void 0 ? define(() => false) : define(
54
- (value) => typeof constructor === "function" && value instanceof constructor
55
- );
56
- var isFunction = define(
57
- (value) => typeof value === "function"
58
- );
59
- var isObject = define(
60
- (value) => typeof value === "object" && value !== null
61
- );
62
- var readObjectProperty = (value, key) => {
63
- if (!isObject(value) && !isFunction(value)) return void 0;
64
- return value[key];
56
+ const dateGetTime = Date.prototype.getTime;
57
+ const mapHas = Map.prototype.has;
58
+ const setHas = Set.prototype.has;
59
+ const weakMapHas = WeakMap.prototype.has;
60
+ const weakSetHas = WeakSet.prototype.has;
61
+ const regExpSource = getIntrinsicGetter(RegExp.prototype, "source");
62
+ const arrayBufferByteLength = getIntrinsicGetter(ArrayBuffer.prototype, "byteLength");
63
+ const dataViewBuffer = getIntrinsicGetter(DataView.prototype, "buffer");
64
+ const typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
65
+ const defineOptionalInstanceGuard = (constructor) => constructor === void 0 ? define(() => false) : define((value) => typeof constructor === "function" && value instanceof constructor);
66
+ /**
67
+ * Checks whether a value is a function.
68
+ *
69
+ * @returns Predicate narrowing to a callable value.
70
+ */
71
+ const isFunction = define((value) => typeof value === "function");
72
+ /**
73
+ * Checks for non-null objects (including arrays, dates, etc.).
74
+ *
75
+ * @returns Predicate narrowing to `Record<PropertyKey, unknown>`.
76
+ */
77
+ const isObject = define((value) => typeof value === "object" && value !== null);
78
+ const readObjectProperty = (value, key) => {
79
+ if (!isObject(value) && !isFunction(value)) return void 0;
80
+ return value[key];
65
81
  };
66
- var isPlainObject = define((value) => {
67
- if (!isObject(value)) return false;
68
- const proto = Object.getPrototypeOf(value);
69
- return proto === null || Object.getPrototypeOf(proto) === null;
82
+ /**
83
+ * Checks for plain objects created by object literals or `Object.create(null)`.
84
+ *
85
+ * @returns Predicate narrowing to `Record<string, unknown>`.
86
+ */
87
+ const isPlainObject = define((value) => {
88
+ if (!isObject(value)) return false;
89
+ const proto = Object.getPrototypeOf(value);
90
+ return proto === null || Object.getPrototypeOf(proto) === null;
70
91
  });
71
- var isArray = define(Array.isArray);
72
- var isDate = define((value) => {
73
- try {
74
- return !Number.isNaN(dateGetTime.call(value));
75
- } catch {
76
- return false;
77
- }
92
+ /**
93
+ * Checks whether a value is an array.
94
+ *
95
+ * @returns Predicate narrowing to `readonly unknown[]`.
96
+ */
97
+ const isArray = define(Array.isArray);
98
+ /**
99
+ * Checks whether a value is a valid `Date` instance (not `Invalid Date`).
100
+ *
101
+ * @returns Predicate narrowing to `Date`.
102
+ */
103
+ const isDate = define((value) => {
104
+ try {
105
+ return !Number.isNaN(dateGetTime.call(value));
106
+ } catch {
107
+ return false;
108
+ }
78
109
  });
79
- var isRegExp = defineIntrinsicBrandGuard(
80
- (value) => regExpSource.call(value)
81
- );
82
- var isMap = defineIntrinsicBrandGuard(
83
- (value) => mapHas.call(value, BUILTIN_BRAND_SENTINEL)
84
- );
85
- var isSet = defineIntrinsicBrandGuard(
86
- (value) => setHas.call(value, BUILTIN_BRAND_SENTINEL)
87
- );
88
- var isWeakMap = defineIntrinsicBrandGuard(
89
- (value) => weakMapHas.call(value, BUILTIN_BRAND_SENTINEL)
90
- );
91
- var isWeakSet = defineIntrinsicBrandGuard(
92
- (value) => weakSetHas.call(value, BUILTIN_BRAND_SENTINEL)
93
- );
94
- var isPromiseLike = define(
95
- (value) => isFunction(readObjectProperty(value, "then"))
96
- );
97
- var isIterable = define(
98
- (value) => isFunction(readObjectProperty(value, Symbol.iterator))
99
- );
100
- var isAsyncIterable = define(
101
- (value) => isFunction(readObjectProperty(value, Symbol.asyncIterator))
102
- );
103
- var isArrayBuffer = defineIntrinsicBrandGuard(
104
- (value) => arrayBufferByteLength.call(value)
105
- );
106
- var isDataView = defineIntrinsicBrandGuard(
107
- (value) => dataViewBuffer.call(value)
108
- );
109
- var isTypedArray = define(
110
- (value) => typedArrayName?.call(value) !== void 0
111
- );
112
- var isError = define(
113
- (value) => value instanceof Error || getTag(value) === OBJECT_TAG_ERROR
114
- );
115
- var isURL = defineOptionalInstanceGuard(
116
- typeof URL === "undefined" ? void 0 : URL
117
- );
118
- var isBlob = defineOptionalInstanceGuard(
119
- typeof Blob === "undefined" ? void 0 : Blob
120
- );
121
- var isFile = defineOptionalInstanceGuard(
122
- typeof File === "undefined" ? void 0 : File
123
- );
124
- var isInstanceOf = (constructor) => define((value) => value instanceof constructor);
125
-
126
- // src/core/equals.ts
127
- var guardedBy = (guard) => define((input) => guard(input));
110
+ /**
111
+ * Checks whether a value is a `RegExp`.
112
+ *
113
+ * @returns Predicate narrowing to `RegExp`.
114
+ */
115
+ const isRegExp = defineIntrinsicBrandGuard((value) => regExpSource.call(value));
116
+ /**
117
+ * Checks whether a value is a `Map`.
118
+ *
119
+ * @returns Predicate narrowing to `Map<unknown, unknown>`.
120
+ */
121
+ const isMap = defineIntrinsicBrandGuard((value) => mapHas.call(value, BUILTIN_BRAND_SENTINEL));
122
+ /**
123
+ * Checks whether a value is a `Set`.
124
+ *
125
+ * @returns Predicate narrowing to `Set<unknown>`.
126
+ */
127
+ const isSet = defineIntrinsicBrandGuard((value) => setHas.call(value, BUILTIN_BRAND_SENTINEL));
128
+ /**
129
+ * Checks whether a value is a `WeakMap`.
130
+ *
131
+ * @returns Predicate narrowing to `WeakMap<object, unknown>`.
132
+ */
133
+ const isWeakMap = defineIntrinsicBrandGuard((value) => weakMapHas.call(value, BUILTIN_BRAND_SENTINEL));
134
+ /**
135
+ * Checks whether a value is a `WeakSet`.
136
+ *
137
+ * @returns Predicate narrowing to `WeakSet<object>`.
138
+ */
139
+ const isWeakSet = defineIntrinsicBrandGuard((value) => weakSetHas.call(value, BUILTIN_BRAND_SENTINEL));
140
+ /**
141
+ * Checks whether a value is promise-like (has a `then` function).
142
+ *
143
+ * @returns Predicate narrowing to `PromiseLike<unknown>`.
144
+ */
145
+ const isPromiseLike = define((value) => isFunction(readObjectProperty(value, "then")));
146
+ /**
147
+ * Checks whether a value implements the `Iterable` protocol.
148
+ *
149
+ * @returns Predicate narrowing to `Iterable<unknown>`.
150
+ */
151
+ const isIterable = define((value) => isFunction(readObjectProperty(value, Symbol.iterator)));
152
+ /**
153
+ * Checks whether a value implements the `AsyncIterable` protocol.
154
+ *
155
+ * @returns Predicate narrowing to `AsyncIterable<unknown>`.
156
+ */
157
+ const isAsyncIterable = define((value) => isFunction(readObjectProperty(value, Symbol.asyncIterator)));
158
+ /**
159
+ * Checks whether a value is an `ArrayBuffer`.
160
+ *
161
+ * @returns Predicate narrowing to `ArrayBuffer`.
162
+ */
163
+ const isArrayBuffer = defineIntrinsicBrandGuard((value) => arrayBufferByteLength.call(value));
164
+ /**
165
+ * Checks whether a value is a `DataView`.
166
+ *
167
+ * @returns Predicate narrowing to `DataView`.
168
+ */
169
+ const isDataView = defineIntrinsicBrandGuard((value) => dataViewBuffer.call(value));
170
+ /**
171
+ * Checks whether a value is a typed array view (any `ArrayBufferView` except DataView).
172
+ *
173
+ * @returns Predicate narrowing to `ArrayBufferView`.
174
+ */
175
+ const isTypedArray = define((value) => typedArrayName?.call(value) !== void 0);
176
+ /**
177
+ * Checks whether a value is an `Error` (instance of Error or plain Error object tag).
178
+ *
179
+ * @returns Predicate narrowing to `Error`.
180
+ */
181
+ const isError = define((value) => value instanceof Error || getTag(value) === "[object Error]");
182
+ /**
183
+ * Checks whether a value is a `URL` (in environments with URL available).
184
+ *
185
+ * @returns Predicate narrowing to `URL` when supported; otherwise always false.
186
+ */
187
+ const isURL = defineOptionalInstanceGuard(typeof URL === "undefined" ? void 0 : URL);
188
+ /**
189
+ * Checks whether a value is a `Blob` (in environments with Blob available).
190
+ *
191
+ * @returns Predicate narrowing to `Blob` when supported; otherwise always false.
192
+ */
193
+ const isBlob = defineOptionalInstanceGuard(typeof Blob === "undefined" ? void 0 : Blob);
194
+ /**
195
+ * Checks whether a value is a `File` (in environments with File available).
196
+ *
197
+ * @returns Predicate narrowing to `File` when supported; otherwise always false.
198
+ */
199
+ const isFile = defineOptionalInstanceGuard(typeof File === "undefined" ? void 0 : File);
200
+ /**
201
+ * Creates a guard that checks whether a value is an instance of `constructor`.
202
+ *
203
+ * @param constructor Constructor used as the right-hand side of `instanceof`.
204
+ * @returns Predicate narrowing to `InstanceType<C>`.
205
+ */
206
+ const isInstanceOf = (constructor) => define((value) => value instanceof constructor);
207
+ //#endregion
208
+ //#region src/core/equals.ts
209
+ const guardedBy = (guard) => define((input) => guard(input));
210
+ /**
211
+ * Creates a guard that matches values equal to the provided target using `Object.is` semantics.
212
+ *
213
+ * @param target Target value to compare against.
214
+ * @returns Predicate narrowing to the exact literal type of `target`.
215
+ */
128
216
  function equals(target) {
129
- return define((input) => Object.is(input, target));
217
+ return define((input) => Object.is(input, target));
130
218
  }
131
219
  function equalsBy(guard, selector) {
132
- const matchesGuard = guardedBy(guard);
133
- const createComparator = (selectorFn) => (target) => define((input) => {
134
- if (!matchesGuard(input)) return false;
135
- return Object.is(selectorFn(input), target);
136
- });
137
- if (selector) {
138
- return createComparator(selector);
139
- }
140
- return (selectorFn) => createComparator(selectorFn);
220
+ const matchesGuard = guardedBy(guard);
221
+ const createComparator = (selectorFn) => (target) => define((input) => {
222
+ if (!matchesGuard(input)) return false;
223
+ return Object.is(selectorFn(input), target);
224
+ });
225
+ if (selector) return createComparator(selector);
226
+ return (selectorFn) => createComparator(selectorFn);
141
227
  }
142
228
  function equalsKey(key, target) {
143
- return define((input) => {
144
- return isObject(input) && hasOwnPropertyKey(input, key) && Object.is(input[key], target);
145
- });
229
+ return define((input) => {
230
+ return isObject(input) && hasOwnPropertyKey(input, key) && Object.is(input[key], target);
231
+ });
146
232
  }
147
-
148
- // src/core/key-guards.ts
233
+ //#endregion
234
+ //#region src/core/key-guards.ts
149
235
  function hasKey(key) {
150
- return define(
151
- (input) => isObject(input) && hasOwnPropertyKey(input, key)
152
- );
236
+ return define((input) => isObject(input) && hasOwnPropertyKey(input, key));
153
237
  }
154
238
  function hasKeys(...keys) {
155
- if (keys.length === 0) {
156
- return define(() => false);
157
- }
158
- return define(
159
- (input) => isObject(input) && hasOwnPropertyKeys(input, keys)
160
- );
239
+ if (keys.length === 0) return define(() => false);
240
+ return define((input) => isObject(input) && hasOwnPropertyKeys(input, keys));
161
241
  }
162
242
  function narrowKeyTo(guard, key) {
163
- return (target) => {
164
- const keyEquals = equalsKey(key, target);
165
- return define(
166
- (input) => guard(input) && keyEquals(input)
167
- );
168
- };
169
- }
170
-
171
- // src/core/property-refinement.ts
243
+ return (target) => {
244
+ const keyEquals = equalsKey(key, target);
245
+ return define((input) => guard(input) && keyEquals(input));
246
+ };
247
+ }
248
+ //#endregion
249
+ //#region src/core/property-refinement.ts
250
+ /**
251
+ * Lifts a required-property refinement to its parent object.
252
+ * @param key Single literal key of the required property to refine.
253
+ * @param refinement Refinement applied to the property value.
254
+ * @returns Refinement that preserves the parent type and narrows the property.
255
+ * @example
256
+ * const hasStringValue = refineKey('value', isString);
257
+ */
172
258
  function refineKey(key, refinement) {
173
- return (value) => refinement(value[key]);
174
- }
259
+ return (value) => refinement(value[key]);
260
+ }
261
+ /**
262
+ * Lifts a defined optional-property refinement to its parent object.
263
+ * @param key Single literal key of the optional property to refine when defined.
264
+ * @param refinement Refinement applied only to a defined property value.
265
+ * @returns Refinement that requires and narrows the property.
266
+ * @example
267
+ * const hasDefinedStringLabel = refineDefinedKey('label', isString);
268
+ */
175
269
  function refineDefinedKey(key, refinement) {
176
- return (value) => {
177
- const property = value[key];
178
- return property !== void 0 && refinement(property);
179
- };
180
- }
270
+ return (value) => {
271
+ const property = value[key];
272
+ return property !== void 0 && refinement(property);
273
+ };
274
+ }
275
+ /**
276
+ * Refines one defined own element of a readonly array.
277
+ * @param index Non-negative integer literal identifying the own element.
278
+ * @param refinement Refinement applied only to a defined element.
279
+ * @returns Refinement that narrows the selected index.
280
+ * @example
281
+ * const hasStringAtZero = refineIndex(0, isString);
282
+ */
181
283
  function refineIndex(index, refinement) {
182
- return (value) => {
183
- if (!hasOwnPropertyKey(value, index)) return false;
184
- const element = value[index];
185
- return element !== void 0 && refinement(element);
186
- };
187
- }
188
-
189
- // src/core/lazy.ts
284
+ return (value) => {
285
+ if (!hasOwnPropertyKey(value, index)) return false;
286
+ const element = value[index];
287
+ return element !== void 0 && refinement(element);
288
+ };
289
+ }
290
+ //#endregion
291
+ //#region src/core/lazy.ts
292
+ /**
293
+ * Creates a predicate whose implementation is initialized on first use.
294
+ *
295
+ * The initialized predicate is cached after the factory returns successfully.
296
+ * Circular references in the input value are not detected.
297
+ *
298
+ * @param factory Function that creates the predicate when it is first evaluated.
299
+ * @returns Predicate that delegates to the lazily initialized implementation.
300
+ */
190
301
  function lazy(factory) {
191
- let predicate;
192
- return (value) => {
193
- predicate ??= factory();
194
- return predicate(value);
195
- };
196
- }
197
-
198
- // src/core/logic.ts
302
+ let predicate;
303
+ return (value) => {
304
+ predicate ??= factory();
305
+ return predicate(value);
306
+ };
307
+ }
308
+ //#endregion
309
+ //#region src/core/logic.ts
199
310
  function and(precondition, condition) {
200
- return (input) => !!(precondition(input) && condition(input));
311
+ return (input) => !!(precondition(input) && condition(input));
201
312
  }
202
313
  function andAll(precondition, stepOrSteps, ...remainingSteps) {
203
- const steps = stepOrSteps === void 0 ? remainingSteps : isFunction(stepOrSteps) ? [stepOrSteps, ...remainingSteps] : [...stepOrSteps, ...remainingSteps];
204
- return (input) => {
205
- if (!precondition(input)) return false;
206
- return steps.every((step) => step(input));
207
- };
314
+ const steps = stepOrSteps === void 0 ? remainingSteps : isFunction(stepOrSteps) ? [stepOrSteps, ...remainingSteps] : [...stepOrSteps, ...remainingSteps];
315
+ return (input) => {
316
+ if (!precondition(input)) return false;
317
+ return steps.every((step) => step(input));
318
+ };
208
319
  }
209
320
  function or(...refinements) {
210
- return (input) => refinements.some((refinement) => refinement(input));
321
+ return (input) => refinements.some((refinement) => refinement(input));
211
322
  }
212
323
  function guardIn() {
213
- return (guard) => (input) => guard(input);
324
+ return (guard) => (input) => guard(input);
214
325
  }
215
326
  function not(fn) {
216
- return (input) => !fn(input);
327
+ return (input) => !fn(input);
217
328
  }
218
-
219
- // src/core/nullish.ts
329
+ //#endregion
330
+ //#region src/core/nullish.ts
220
331
  function nullable(fn) {
221
- return (value) => value === null || fn(value);
332
+ return (value) => value === null || fn(value);
222
333
  }
223
334
  function nonNull(fn) {
224
- return (value) => value !== null && fn(value);
335
+ return (value) => value !== null && fn(value);
225
336
  }
226
337
  function nullish(fn) {
227
- return (value) => value === null || value === void 0 || fn(value);
338
+ return (value) => value === null || value === void 0 || fn(value);
228
339
  }
229
340
  function optional(fn) {
230
- return (value) => value === void 0 || fn(value);
341
+ return (value) => value === void 0 || fn(value);
231
342
  }
232
343
  function required(fn) {
233
- return (value) => value !== void 0 && fn(value);
344
+ return (value) => value !== void 0 && fn(value);
234
345
  }
235
-
236
- // src/core/parse.ts
346
+ //#endregion
347
+ //#region src/core/parse.ts
237
348
  function safeParse(fn, value) {
238
- const valid = fn(value);
239
- return valid ? { valid: true, value } : { valid: false };
349
+ return fn(value) ? {
350
+ valid: true,
351
+ value
352
+ } : { valid: false };
240
353
  }
241
354
  function safeParseWith(fn) {
242
- return (value) => safeParse(fn, value);
243
- }
355
+ return (value) => safeParse(fn, value);
356
+ }
357
+ /**
358
+ * Decodes JSON text and validates the decoded value without coercion.
359
+ *
360
+ * @param input JSON text to decode.
361
+ * @param guard Guard used to validate the decoded `unknown` value.
362
+ * @returns The decoded value when valid; `{ valid: false }` for invalid JSON or a guard mismatch.
363
+ */
244
364
  function safeJsonParse(input, guard) {
245
- let value;
246
- try {
247
- value = JSON.parse(input);
248
- } catch {
249
- return { valid: false };
250
- }
251
- return safeParse(guard, value);
252
- }
253
-
254
- // src/core/predicate.ts
255
- var predicateToRefine = (fn) => (value) => fn(value);
256
-
257
- // src/core/primitive.ts
258
- var isString = define((value) => typeof value === "string");
259
- var isNumberPrimitive = define(
260
- (value) => typeof value === "number"
261
- );
262
- var isNaN = define(Number.isNaN);
263
- var isInfiniteNumber = and(
264
- isNumberPrimitive,
265
- predicateToRefine((n) => n === Infinity || n === -Infinity)
266
- );
267
- var isFiniteNumber = predicateToRefine(Number.isFinite);
268
- var isNumber = and(isNumberPrimitive, isFiniteNumber);
269
- var isInteger = define(Number.isInteger);
270
- var isSafeInteger = define(Number.isSafeInteger);
271
- var isPositive = and(
272
- isNumber,
273
- predicateToRefine((n) => n > 0)
274
- );
275
- var isNegative = and(
276
- isNumber,
277
- predicateToRefine((n) => n < 0)
278
- );
279
- var isZero = and(
280
- isNumber,
281
- predicateToRefine((n) => n === 0)
282
- );
283
- var isBoolean = define((value) => typeof value === "boolean");
284
- var isBigInt = define((value) => typeof value === "bigint");
285
- var isSymbol = define((value) => typeof value === "symbol");
286
- var isUndefined = define((value) => value === void 0);
287
- var isNull = define((value) => value === null);
288
- var isNil = (value) => value === null || value === void 0;
289
- var isNotNil = (value) => value !== null && value !== void 0;
290
- var isPrimitive = or(
291
- isString,
292
- isNumberPrimitive,
293
- isBoolean,
294
- isBigInt,
295
- isSymbol,
296
- isUndefined,
297
- isNull
298
- );
299
-
300
- // src/utils/guard-collections.ts
301
- var mapEntries = Map.prototype.entries;
302
- var setValues = Set.prototype.values;
303
- var everyIterableValue = (values, predicate) => {
304
- for (const value of values) {
305
- if (!predicate(value)) return false;
306
- }
307
- return true;
365
+ let value;
366
+ try {
367
+ value = JSON.parse(input);
368
+ } catch {
369
+ return { valid: false };
370
+ }
371
+ return safeParse(guard, value);
372
+ }
373
+ //#endregion
374
+ //#region src/core/predicate.ts
375
+ /**
376
+ * Converts a boolean predicate into a refinement preserving the input type.
377
+ *
378
+ * @param fn Boolean-returning function over a value of type A.
379
+ * @returns Refinement equivalent to the provided predicate.
380
+ */
381
+ const predicateToRefine = (fn) => (value) => fn(value);
382
+ //#endregion
383
+ //#region src/core/primitive.ts
384
+ /**
385
+ * Checks whether a value is a string.
386
+ *
387
+ * @returns Predicate narrowing to `string`.
388
+ */
389
+ const isString = define((value) => typeof value === "string");
390
+ /**
391
+ * Checks whether a value is a number primitive (may include NaN/±Infinity).
392
+ *
393
+ * @returns Predicate narrowing to `number` (primitive-only).
394
+ */
395
+ const isNumberPrimitive = define((value) => typeof value === "number");
396
+ /**
397
+ * Checks whether a value is `NaN`.
398
+ *
399
+ * Equivalent to `Number.isNaN(value)` without coercion.
400
+ * @returns Predicate narrowing to `number` (`NaN` only).
401
+ */
402
+ const isNaN = define(Number.isNaN);
403
+ /**
404
+ * Checks whether a value is an infinite number (±Infinity).
405
+ *
406
+ * @returns Predicate narrowing to `number` (Infinity or -Infinity).
407
+ */
408
+ const isInfiniteNumber = and(isNumberPrimitive, predicateToRefine((n) => n === Infinity || n === -Infinity));
409
+ /**
410
+ * Checks whether a number is finite.
411
+ * @returns Refinement that accepts only finite numbers.
412
+ */
413
+ const isFiniteNumber = predicateToRefine(Number.isFinite);
414
+ /**
415
+ * Checks whether a value is a finite number.
416
+ * @returns Predicate narrowing to finite `number`.
417
+ */
418
+ const isNumber = and(isNumberPrimitive, isFiniteNumber);
419
+ /**
420
+ * Checks whether a value is an integer number.
421
+ *
422
+ * Equivalent to `Number.isInteger(value)`.
423
+ * @returns Predicate narrowing to integer `number`.
424
+ */
425
+ const isInteger = define(Number.isInteger);
426
+ /**
427
+ * Checks whether a value is a safe integer.
428
+ *
429
+ * Equivalent to `Number.isSafeInteger(value)`.
430
+ * @returns Predicate narrowing to safe-integer `number`.
431
+ */
432
+ const isSafeInteger = define(Number.isSafeInteger);
433
+ /**
434
+ * Checks whether a value is a positive finite number (> 0).
435
+ *
436
+ * Uses `isNumber` internally to exclude NaN and ±Infinity.
437
+ * @returns Predicate narrowing to positive `number`.
438
+ */
439
+ const isPositive = and(isNumber, predicateToRefine((n) => n > 0));
440
+ /**
441
+ * Checks whether a value is a negative finite number (< 0).
442
+ *
443
+ * Uses `isNumber` internally to exclude NaN and ±Infinity.
444
+ * Note: `-0` is not considered negative (consistent with `< 0`).
445
+ * @returns Predicate narrowing to negative `number`.
446
+ */
447
+ const isNegative = and(isNumber, predicateToRefine((n) => n < 0));
448
+ /**
449
+ * Checks whether a value is a finite number that equals zero (including `-0`).
450
+ *
451
+ * @returns Predicate narrowing to zero `number`.
452
+ */
453
+ const isZero = and(isNumber, predicateToRefine((n) => n === 0));
454
+ /**
455
+ * Checks whether a value is a boolean.
456
+ *
457
+ * @returns Predicate narrowing to `boolean`.
458
+ */
459
+ const isBoolean = define((value) => typeof value === "boolean");
460
+ /**
461
+ * Checks whether a value is a bigint.
462
+ *
463
+ * @returns Predicate narrowing to `bigint`.
464
+ */
465
+ const isBigInt = define((value) => typeof value === "bigint");
466
+ /**
467
+ * Checks whether a value is a symbol.
468
+ *
469
+ * @returns Predicate narrowing to `symbol`.
470
+ */
471
+ const isSymbol = define((value) => typeof value === "symbol");
472
+ /**
473
+ * Checks whether a value is exactly `undefined`.
474
+ *
475
+ * For reusable nullish checks, use {@link isNil} or compose a named guard with
476
+ * {@link or} once and reuse it.
477
+ *
478
+ * @returns Predicate narrowing to `undefined`.
479
+ * @see isNil
480
+ */
481
+ const isUndefined = define((value) => value === void 0);
482
+ /**
483
+ * Checks whether a value is exactly `null`.
484
+ *
485
+ * For reusable nullish checks, use {@link isNil} or compose a named guard with
486
+ * {@link or} once and reuse it.
487
+ *
488
+ * @returns Predicate narrowing to `null`.
489
+ * @see isNil
490
+ */
491
+ const isNull = define((value) => value === null);
492
+ /**
493
+ * Checks whether a value is `null` or `undefined` (nullish).
494
+ *
495
+ * Prefer this over hand-rolling `isNull(x) || isUndefined(x)`: it is the same
496
+ * check expressed once. To widen an existing guard so it also accepts nullish
497
+ * values, use {@link nullish} instead.
498
+ *
499
+ * @returns Predicate narrowing to `null | undefined`.
500
+ * @example
501
+ * isNil(null); // true
502
+ * isNil(undefined); // true
503
+ * isNil(0); // false
504
+ */
505
+ const isNil = (value) => value === null || value === void 0;
506
+ /**
507
+ * Checks whether a value is neither `null` nor `undefined`.
508
+ *
509
+ * Narrows the input to `NonNullable<T>`, making it useful for removing nullish
510
+ * values with `Array.prototype.filter`.
511
+ *
512
+ * @param value Value to check.
513
+ * @returns `true` when the value is not nullish.
514
+ * @example
515
+ * const values: Array<string | null | undefined> = ['value', null];
516
+ * const presentValues = values.filter(isNotNil); // string[]
517
+ * @see isNil
518
+ */
519
+ const isNotNil = (value) => value !== null && value !== void 0;
520
+ /**
521
+ * Checks whether a value is a JavaScript primitive.
522
+ *
523
+ * Primitives: string, number, boolean, bigint, symbol, undefined, null.
524
+ * Note: `number` here includes NaN and ±Infinity (use `isNumber` for finite only).
525
+ *
526
+ * @returns Predicate narrowing to `Primitive`.
527
+ */
528
+ const isPrimitive = or(isString, isNumberPrimitive, isBoolean, isBigInt, isSymbol, isUndefined, isNull);
529
+ //#endregion
530
+ //#region src/utils/guard-collections.ts
531
+ const mapEntries = Map.prototype.entries;
532
+ const setValues = Set.prototype.values;
533
+ const everyIterableValue = (values, predicate) => {
534
+ for (const value of values) if (!predicate(value)) return false;
535
+ return true;
308
536
  };
309
- var everyKeyValueEntry = (entries, predicate) => {
310
- for (const [key, value] of entries) {
311
- if (!predicate(key, value)) return false;
312
- }
313
- return true;
537
+ const everyKeyValueEntry = (entries, predicate) => {
538
+ for (const [key, value] of entries) if (!predicate(key, value)) return false;
539
+ return true;
314
540
  };
315
- var everyArrayValue = (values, predicate) => everyIterableValue(values, predicate);
316
- var everyTupleValue = (values, predicates) => {
317
- if (values.length !== predicates.length) return false;
318
- for (let index = 0; index < predicates.length; index += 1) {
319
- const predicate = predicates[index];
320
- if (!predicate(values[index])) return false;
321
- }
322
- return true;
541
+ /**
542
+ * Checks whether every array element satisfies the provided predicate.
543
+ *
544
+ * @deprecated Use `Array.prototype.every` for boolean iteration or `arrayOf`
545
+ * for a narrowing guard. This root export will be removed in is-kit v2.
546
+ * @param values Array values to validate.
547
+ * @param predicate Predicate applied to each element.
548
+ * @returns Whether all elements satisfy `predicate`.
549
+ */
550
+ const everyArrayValue = (values, predicate) => everyIterableValue(values, predicate);
551
+ /**
552
+ * Checks whether a tuple matches the provided element predicates in order.
553
+ *
554
+ * @deprecated Use `tupleOf` for a narrowing guard or compare the tuple length
555
+ * and predicates directly. This root export will be removed in is-kit v2.
556
+ * @param values Tuple candidate values.
557
+ * @param predicates Predicates aligned to each tuple index.
558
+ * @returns Whether lengths match and each index passes.
559
+ */
560
+ const everyTupleValue = (values, predicates) => {
561
+ if (values.length !== predicates.length) return false;
562
+ for (let index = 0; index < predicates.length; index += 1) {
563
+ const predicate = predicates[index];
564
+ if (!predicate(values[index])) return false;
565
+ }
566
+ return true;
323
567
  };
324
- var everySetValue = (values, predicate) => everyIterableValue(values, predicate);
325
- var everyBrandedSetValue = (values, predicate) => everyIterableValue(setValues.call(values), predicate);
326
- var everyMapEntry = (values, keyPredicate, valuePredicate) => everyKeyValueEntry(
327
- values,
328
- (key, value) => keyPredicate(key) && valuePredicate(value)
329
- );
330
- var everyBrandedMapEntry = (values, keyPredicate, valuePredicate) => everyKeyValueEntry(
331
- mapEntries.call(values),
332
- (key, value) => keyPredicate(key) && valuePredicate(value)
333
- );
334
- var everyOwnEnumerableEntry = (values, keyPredicate, valuePredicate) => everyIterableValue(
335
- Object.keys(values),
336
- (key) => keyPredicate(key) && valuePredicate(values[key])
337
- );
338
-
339
- // src/core/combinators/array.ts
568
+ /**
569
+ * Checks whether every set value satisfies the provided predicate.
570
+ *
571
+ * @deprecated Use `setOf` for a narrowing guard or iterate the set directly.
572
+ * This root export will be removed in is-kit v2.
573
+ * @param values Set values to validate.
574
+ * @param predicate Predicate applied to each value.
575
+ * @returns Whether all set values satisfy `predicate`.
576
+ */
577
+ const everySetValue = (values, predicate) => everyIterableValue(values, predicate);
578
+ /**
579
+ * Checks built-in Set data without invoking an instance-provided iterator.
580
+ * WHY: A branded Set subclass may override its public iterator and throw.
581
+ */
582
+ const everyBrandedSetValue = (values, predicate) => everyIterableValue(setValues.call(values), predicate);
583
+ /**
584
+ * Checks whether every map entry satisfies the provided key and value predicates.
585
+ *
586
+ * @deprecated Use `mapOf` for a narrowing guard or iterate the map directly.
587
+ * This root export will be removed in is-kit v2.
588
+ * @param values Map values to validate.
589
+ * @param keyPredicate Predicate applied to each key.
590
+ * @param valuePredicate Predicate applied to each value.
591
+ * @returns Whether all keys and values satisfy their predicates.
592
+ */
593
+ const everyMapEntry = (values, keyPredicate, valuePredicate) => everyKeyValueEntry(values, (key, value) => keyPredicate(key) && valuePredicate(value));
594
+ /**
595
+ * Checks built-in Map data without invoking an instance-provided iterator.
596
+ * WHY: A branded Map subclass may override its public iterator and throw.
597
+ */
598
+ const everyBrandedMapEntry = (values, keyPredicate, valuePredicate) => everyKeyValueEntry(mapEntries.call(values), (key, value) => keyPredicate(key) && valuePredicate(value));
599
+ /**
600
+ * Checks whether every own enumerable string key/value pair satisfies the provided predicates.
601
+ *
602
+ * @deprecated Use `recordOf` for a narrowing guard or
603
+ * `Object.entries(value).every(...)` for boolean iteration. This root export
604
+ * will be removed in is-kit v2.
605
+ * @param values Plain object values to validate.
606
+ * @param keyPredicate Predicate applied to each enumerable own string key.
607
+ * @param valuePredicate Predicate applied to each corresponding value.
608
+ * @returns Whether all enumerable entries satisfy their predicates.
609
+ */
610
+ const everyOwnEnumerableEntry = (values, keyPredicate, valuePredicate) => everyIterableValue(Object.keys(values), (key) => keyPredicate(key) && valuePredicate(values[key]));
611
+ //#endregion
612
+ //#region src/core/combinators/array.ts
613
+ /**
614
+ * Validates an array where every element satisfies the provided guard.
615
+ *
616
+ * @param elementGuard Guard applied to each array element.
617
+ * @returns Predicate narrowing to a readonly array of the guarded element type.
618
+ */
340
619
  function arrayOf(elementGuard) {
341
- return define(
342
- (input) => Array.isArray(input) && everyArrayValue(input, elementGuard)
343
- );
344
- }
620
+ return define((input) => Array.isArray(input) && everyArrayValue(input, elementGuard));
621
+ }
622
+ /**
623
+ * Validates a non-empty array where every element satisfies the provided guard.
624
+ *
625
+ * @param elementGuard Guard applied to each array element.
626
+ * @returns Predicate narrowing to a readonly non-empty array of the guarded element type.
627
+ */
345
628
  function nonEmptyArrayOf(elementGuard) {
346
- return define(
347
- (input) => Array.isArray(input) && input.length > 0 && everyArrayValue(input, elementGuard)
348
- );
349
- }
350
-
351
- // src/core/combinators/map.ts
629
+ return define((input) => Array.isArray(input) && input.length > 0 && everyArrayValue(input, elementGuard));
630
+ }
631
+ //#endregion
632
+ //#region src/core/combinators/discriminated-union.ts
633
+ const isDiscriminantValue = (value) => isString(value) || isNumberPrimitive(value) || isSymbol(value) || isBoolean(value);
634
+ const toRuntimeKey = (value) => isSymbol(value) ? value : String(value);
635
+ const assertSafeProtoBranch = (values, guards) => {
636
+ if (!values.includes("__proto__")) return;
637
+ if (hasOwnPropertyKey(guards, "__proto__")) return;
638
+ if (isFunction(Object.getPrototypeOf(guards))) throw new TypeError("Use ['__proto__'] for a discriminatedUnion branch key so it is an own property.");
639
+ };
640
+ const assertBranchKeys = (values, guards) => {
641
+ const keys = /* @__PURE__ */ new Set();
642
+ for (const value of values) {
643
+ const key = toRuntimeKey(value);
644
+ if (keys.has(key)) throw new TypeError(`Duplicate discriminatedUnion discriminant value for ${String(value)}.`);
645
+ keys.add(key);
646
+ if (!hasOwnPropertyKey(guards, key)) throw new TypeError(`Missing discriminatedUnion branch guard for ${String(value)}.`);
647
+ }
648
+ return keys;
649
+ };
650
+ /**
651
+ * Creates an exhaustive guard for a union whose members share a literal discriminant.
652
+ * A tuple of every discriminant value keeps finite coverage explicit at runtime
653
+ * and compile time. Values that coerce to the same object key, such as `1` and
654
+ * `'1'`, are rejected.
655
+ * Use `['__proto__']` for that literal discriminant so it becomes an own map key.
656
+ *
657
+ * @param discriminant Required property that identifies each union member.
658
+ * @param values Finite tuple containing every discriminant value.
659
+ * @param guards Branch guards keyed by the discriminant values.
660
+ * @returns Predicate narrowing to the union accepted by the branch guards.
661
+ */
662
+ function discriminatedUnion() {
663
+ return (discriminant, values, guards) => {
664
+ assertSafeProtoBranch(values, guards);
665
+ const declaredKeys = assertBranchKeys(values, guards);
666
+ return define((input) => {
667
+ if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return false;
668
+ const value = Reflect.get(input, discriminant);
669
+ if (!isDiscriminantValue(value)) return false;
670
+ const key = toRuntimeKey(value);
671
+ if (!declaredKeys.has(key) || !hasOwnPropertyKey(guards, key)) return false;
672
+ const guard = guards[key];
673
+ return guard(input);
674
+ });
675
+ };
676
+ }
677
+ //#endregion
678
+ //#region src/core/combinators/map.ts
679
+ /**
680
+ * Validates a map where every key and value satisfies the provided guards.
681
+ *
682
+ * @param keyGuard Guard applied to each map key.
683
+ * @param valueGuard Guard applied to each map value.
684
+ * @returns Predicate narrowing to a readonly map with guarded key/value types.
685
+ */
352
686
  function mapOf(keyGuard, valueGuard) {
353
- return define(
354
- (input) => isMap(input) && everyBrandedMapEntry(input, keyGuard, valueGuard)
355
- );
687
+ return define((input) => isMap(input) && everyBrandedMapEntry(input, keyGuard, valueGuard));
356
688
  }
357
-
358
- // src/core/combinators/one-of.ts
689
+ //#endregion
690
+ //#region src/core/combinators/one-of.ts
359
691
  function oneOf(...refinements) {
360
- return (input) => refinements.some((refinement) => refinement(input));
361
- }
362
-
363
- // src/core/combinators/one-of-values.ts
364
- var ONE_OF_VALUES_LINEAR_SCAN_MAX = 8;
365
- var isSingleArrayArg = define(
366
- (value) => Array.isArray(value) && value.length === 1 && Array.isArray(value[0])
367
- );
368
- var normalizeValues = (args) => isSingleArrayArg(args) ? args[0] : args;
369
- var createLinearPredicate = (items) => {
370
- return define((input) => {
371
- return items.some((value) => Object.is(value, input));
372
- });
692
+ return (input) => refinements.some((refinement) => refinement(input));
693
+ }
694
+ //#endregion
695
+ //#region src/core/combinators/one-of-values.ts
696
+ const ONE_OF_VALUES_LINEAR_SCAN_MAX = 8;
697
+ const isSingleArrayArg = define((value) => Array.isArray(value) && value.length === 1 && Array.isArray(value[0]));
698
+ const normalizeValues = (args) => isSingleArrayArg(args) ? args[0] : args;
699
+ const createLinearPredicate = (items) => {
700
+ return define((input) => {
701
+ return items.some((value) => Object.is(value, input));
702
+ });
373
703
  };
374
- var createSetPredicate = (items) => {
375
- let hasPositiveZero = false;
376
- let hasNegativeZero = false;
377
- const valueSet = /* @__PURE__ */ new Set();
378
- for (const literalValue of items) {
379
- if (isZero(literalValue)) {
380
- if (Object.is(literalValue, -0)) hasNegativeZero = true;
381
- else hasPositiveZero = true;
382
- } else {
383
- valueSet.add(literalValue);
384
- }
385
- }
386
- return define((input) => {
387
- if (isZero(input)) {
388
- return Object.is(input, -0) ? hasNegativeZero : hasPositiveZero;
389
- }
390
- return valueSet.has(input);
391
- });
704
+ const createSetPredicate = (items) => {
705
+ let hasPositiveZero = false;
706
+ let hasNegativeZero = false;
707
+ const valueSet = /* @__PURE__ */ new Set();
708
+ for (const literalValue of items) if (isZero(literalValue)) {
709
+ if (Object.is(literalValue, -0)) hasNegativeZero = true;
710
+ else hasPositiveZero = true;
711
+ } else valueSet.add(literalValue);
712
+ return define((input) => {
713
+ if (isZero(input)) return Object.is(input, -0) ? hasNegativeZero : hasPositiveZero;
714
+ return valueSet.has(input);
715
+ });
392
716
  };
393
717
  function oneOfValues(...args) {
394
- const items = normalizeValues(args);
395
- return items.length <= ONE_OF_VALUES_LINEAR_SCAN_MAX ? createLinearPredicate(items) : createSetPredicate(items);
396
- }
397
-
398
- // src/core/combinators/record.ts
718
+ const items = normalizeValues(args);
719
+ return items.length <= ONE_OF_VALUES_LINEAR_SCAN_MAX ? createLinearPredicate(items) : createSetPredicate(items);
720
+ }
721
+ //#endregion
722
+ //#region src/core/combinators/record.ts
723
+ /**
724
+ * Validates a record-like object by guarding both keys and values.
725
+ *
726
+ * @param keyFunction Guard for string keys (e.g., specific literal keys pattern).
727
+ * @param valueFunction Guard applied to each value in the record.
728
+ * @returns Predicate narrowing to a readonly record with guarded key/value types.
729
+ */
399
730
  function recordOf(keyFunction, valueFunction) {
400
- return define(
401
- (input) => isPlainObject(input) && everyOwnEnumerableEntry(input, keyFunction, valueFunction)
402
- );
403
- }
404
-
405
- // src/core/combinators/set.ts
731
+ return define((input) => isPlainObject(input) && everyOwnEnumerableEntry(input, keyFunction, valueFunction));
732
+ }
733
+ //#endregion
734
+ //#region src/core/combinators/set.ts
735
+ /**
736
+ * Validates a set where every value satisfies the provided guard.
737
+ *
738
+ * @param valueGuard Guard applied to each set value.
739
+ * @returns Predicate narrowing to a readonly set of the guarded value type.
740
+ */
406
741
  function setOf(valueGuard) {
407
- return define(
408
- (input) => isSet(input) && everyBrandedSetValue(input, valueGuard)
409
- );
410
- }
411
-
412
- // src/core/combinators/struct.ts
413
- var isOptionalSchemaField = define(
414
- // WHY: Optional fields are represented as a small tagged object so `struct`
415
- // can distinguish schema metadata from plain predicate functions up front.
416
- (field) => isObject(field) && field.optional === true && isFunction(field.guard)
417
- );
418
- var hasRequiredKeys = (obj, entries) => (
419
- // WHY: Required fields must be own properties; inherited values should not
420
- // satisfy a schema because `struct` models object payload shape, not prototype chains.
421
- entries.every(
422
- ([key, guard]) => hasOwnPropertyKey(obj, key) && guard(obj[key])
423
- )
424
- );
425
- var hasValidOptionalKeys = (obj, entries) => (
426
- // WHY: Optional keys are validated only when present. Missing keys stay valid
427
- // without forcing callers to encode `undefined` into the value guard.
428
- entries.every(
429
- ([key, guard]) => !hasOwnPropertyKey(obj, key) || guard(obj[key])
430
- )
431
- );
432
- var hasOnlyAllowedKeys = (obj, allowed) => Object.keys(obj).every((key) => allowed.has(key));
742
+ return define((input) => isSet(input) && everyBrandedSetValue(input, valueGuard));
743
+ }
744
+ //#endregion
745
+ //#region src/core/combinators/struct.ts
746
+ const isOptionalSchemaField = define((field) => isObject(field) && field.optional === true && isFunction(field.guard));
747
+ const hasRequiredKeys = (obj, entries) => entries.every(([key, guard]) => hasOwnPropertyKey(obj, key) && guard(obj[key]));
748
+ const hasValidOptionalKeys = (obj, entries) => entries.every(([key, guard]) => !hasOwnPropertyKey(obj, key) || guard(obj[key]));
749
+ const hasOnlyAllowedKeys = (obj, allowed) => Object.keys(obj).every((key) => allowed.has(key));
750
+ /**
751
+ * Marks a struct schema field as optional at the key level.
752
+ *
753
+ * When used inside `struct`, the property may be absent. If the property exists,
754
+ * its value must satisfy the wrapped guard.
755
+ *
756
+ * @param guard Guard used to validate the property value when the key exists.
757
+ * @returns Schema field marker understood by `struct`.
758
+ */
433
759
  function optionalKey(guard) {
434
- return { optional: true, guard };
435
- }
760
+ return {
761
+ optional: true,
762
+ guard
763
+ };
764
+ }
765
+ /**
766
+ * Validates an object against a field-to-guard schema.
767
+ * Keys in the schema are required unless wrapped with `optionalKey`; optionally
768
+ * rejects extra keys when `exact: true`.
769
+ *
770
+ * @param schema Record of property guards.
771
+ * @param options When `{ exact: true }`, disallows own enumerable string-key
772
+ * properties not in `schema`.
773
+ * @returns Predicate that narrows to the inferred struct type.
774
+ */
436
775
  function struct(schema, options) {
437
- const requiredEntries = [];
438
- const optionalEntries = [];
439
- const schemaKeys = [];
440
- for (const key in schema) {
441
- if (!hasOwnPropertyKey(schema, key)) continue;
442
- const field = schema[key];
443
- schemaKeys.push(key);
444
- if (isOptionalSchemaField(field)) {
445
- optionalEntries.push([key, field.guard]);
446
- continue;
447
- }
448
- requiredEntries.push([key, field]);
449
- }
450
- const allowed = options?.exact ? new Set(schemaKeys) : null;
451
- return define((input) => {
452
- if (!isPlainObject(input)) return false;
453
- const obj = input;
454
- if (!hasRequiredKeys(obj, requiredEntries)) return false;
455
- if (!hasValidOptionalKeys(obj, optionalEntries)) return false;
456
- if (!allowed) return true;
457
- return hasOnlyAllowedKeys(obj, allowed);
458
- });
459
- }
460
-
461
- // src/core/combinators/typed-struct.ts
776
+ const requiredEntries = [];
777
+ const optionalEntries = [];
778
+ const schemaKeys = [];
779
+ for (const key in schema) {
780
+ if (!hasOwnPropertyKey(schema, key)) continue;
781
+ const field = schema[key];
782
+ schemaKeys.push(key);
783
+ if (isOptionalSchemaField(field)) {
784
+ optionalEntries.push([key, field.guard]);
785
+ continue;
786
+ }
787
+ requiredEntries.push([key, field]);
788
+ }
789
+ const allowed = options?.exact ? new Set(schemaKeys) : null;
790
+ return define((input) => {
791
+ if (!isPlainObject(input)) return false;
792
+ const obj = input;
793
+ if (!hasRequiredKeys(obj, requiredEntries)) return false;
794
+ if (!hasValidOptionalKeys(obj, optionalEntries)) return false;
795
+ if (!allowed) return true;
796
+ return hasOnlyAllowedKeys(obj, allowed);
797
+ });
798
+ }
799
+ //#endregion
800
+ //#region src/core/combinators/typed-struct.ts
801
+ /**
802
+ * Creates a `struct` builder checked against an existing string-keyed object
803
+ * type. Numeric and symbol properties are excluded from the checked shape and
804
+ * cannot be validated by the resulting guard.
805
+ * Optional target keys must also be declared with `optionalKey` so type drift
806
+ * stays visible when the target type changes.
807
+ *
808
+ * Target-compatible field guards may narrow further than the target field type;
809
+ * the returned predicate preserves those narrower inferred types.
810
+ *
811
+ * @returns Builder that rejects missing, extra, or incompatible struct fields.
812
+ */
462
813
  function typedStruct() {
463
- return (fields, options) => (
464
- // WHY: `typedStruct` keeps `struct` runtime behavior while using the target
465
- // type only to check that hand-written guard fields stay in sync.
466
- struct(fields, options)
467
- );
468
- }
469
-
470
- // src/core/combinators/tuple.ts
814
+ return (fields, options) => struct(fields, options);
815
+ }
816
+ //#endregion
817
+ //#region src/core/combinators/tuple.ts
818
+ /**
819
+ * Validates a fixed-length tuple by applying element-wise guards.
820
+ *
821
+ * @param guards Guards corresponding to each tuple position.
822
+ * @returns Predicate that narrows to a readonly tuple of guarded element types.
823
+ */
471
824
  function tupleOf(...guards) {
472
- return define(
473
- (input) => Array.isArray(input) && everyTupleValue(input, guards)
474
- );
475
- }
476
-
477
- // src/utils/to-boolean-predicates.ts
478
- var toBooleanPredicates = (predicates) => predicates;
479
- export {
480
- and,
481
- andAll,
482
- arrayOf,
483
- assert,
484
- define,
485
- equals,
486
- equalsBy,
487
- equalsKey,
488
- everyArrayValue,
489
- everyMapEntry,
490
- everyOwnEnumerableEntry,
491
- everySetValue,
492
- everyTupleValue,
493
- guardIn,
494
- hasKey,
495
- hasKeys,
496
- isArray,
497
- isArrayBuffer,
498
- isAsyncIterable,
499
- isBigInt,
500
- isBlob,
501
- isBoolean,
502
- isDataView,
503
- isDate,
504
- isError,
505
- isFile,
506
- isFiniteNumber,
507
- isFunction,
508
- isInfiniteNumber,
509
- isInstanceOf,
510
- isInteger,
511
- isIterable,
512
- isMap,
513
- isNaN,
514
- isNegative,
515
- isNil,
516
- isNotNil,
517
- isNull,
518
- isNumber,
519
- isNumberPrimitive,
520
- isObject,
521
- isPlainObject,
522
- isPositive,
523
- isPrimitive,
524
- isPromiseLike,
525
- isRegExp,
526
- isSafeInteger,
527
- isSet,
528
- isString,
529
- isSymbol,
530
- isTypedArray,
531
- isURL,
532
- isUndefined,
533
- isWeakMap,
534
- isWeakSet,
535
- isZero,
536
- lazy,
537
- mapOf,
538
- narrowKeyTo,
539
- nonEmptyArrayOf,
540
- nonNull,
541
- not,
542
- nullable,
543
- nullish,
544
- oneOf,
545
- oneOfValues,
546
- optional,
547
- optionalKey,
548
- or,
549
- predicateToRefine,
550
- recordOf,
551
- refineDefinedKey,
552
- refineIndex,
553
- refineKey,
554
- required,
555
- safeJsonParse,
556
- safeParse,
557
- safeParseWith,
558
- setOf,
559
- struct,
560
- toBooleanPredicates,
561
- tupleOf,
562
- typedStruct
563
- };
825
+ return define((input) => Array.isArray(input) && everyTupleValue(input, guards));
826
+ }
827
+ //#endregion
828
+ //#region src/utils/to-boolean-predicates.ts
829
+ /**
830
+ * Converts predicates to plain boolean predicates for iteration helpers.
831
+ *
832
+ * @deprecated Use the original predicate array directly. This identity helper
833
+ * will no longer be exported from the package root in is-kit v2.
834
+ * @param predicates Predicates to be treated as simple boolean functions.
835
+ * @returns Readonly array of boolean-returning functions.
836
+ */
837
+ const toBooleanPredicates = (predicates) => predicates;
838
+ //#endregion
839
+ export { and, andAll, arrayOf, assert, define, discriminatedUnion, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, refineDefinedKey, refineIndex, refineKey, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };