is-kit 1.15.3 → 1.16.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/README.md +67 -2
- package/dist/index.d.mts +32 -5
- package/dist/index.d.ts +32 -5
- package/dist/index.js +137 -23
- package/dist/index.mjs +137 -24
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -386,6 +386,10 @@ Use `struct(schema, { exact: true })` when extra own enumerable string keys
|
|
|
386
386
|
should be rejected. Exact mode follows `Object.keys(...)` semantics, so symbol
|
|
387
387
|
keys and non-enumerable properties are outside its key matching.
|
|
388
388
|
|
|
389
|
+
Schemas themselves must use own enumerable string keys. `struct` rejects
|
|
390
|
+
symbol-keyed, non-enumerable, and inherited schema fields so its runtime checks
|
|
391
|
+
match the inferred type.
|
|
392
|
+
|
|
389
393
|
If the property must exist but the value may be `undefined`, use `optional(guard)` instead.
|
|
390
394
|
|
|
391
395
|
### 5. Validate arrays, tuples, maps, sets, and records
|
|
@@ -579,7 +583,13 @@ Use `discriminatedUnion<T>()` with `typedStruct` to keep both the branch
|
|
|
579
583
|
fields and the union coverage aligned with an existing TypeScript type.
|
|
580
584
|
|
|
581
585
|
```ts
|
|
582
|
-
import {
|
|
586
|
+
import {
|
|
587
|
+
discriminatedUnion,
|
|
588
|
+
discriminatedUnionWithFallback,
|
|
589
|
+
isNumber,
|
|
590
|
+
oneOfValues,
|
|
591
|
+
typedStruct
|
|
592
|
+
} from 'is-kit';
|
|
583
593
|
|
|
584
594
|
type Event =
|
|
585
595
|
{ kind: 'click'; x: number; y: number } | { kind: 'scroll'; delta: number };
|
|
@@ -611,6 +621,55 @@ For a `__proto__` discriminant, write the branch as `['__proto__']: guard` (or
|
|
|
611
621
|
use a null-prototype map); the uncomputed object-literal form changes the
|
|
612
622
|
object's prototype instead of creating a branch entry.
|
|
613
623
|
|
|
624
|
+
#### Classify explicit fallback variants
|
|
625
|
+
|
|
626
|
+
Use `discriminatedUnionWithFallback<T>()` when an input may contain future
|
|
627
|
+
discriminant values. Known branches remain exhaustive. An undeclared own
|
|
628
|
+
primitive discriminant instead calls `fallback.create`, which returns payload
|
|
629
|
+
for one canonical fallback tag or `undefined` to mark the input invalid. The
|
|
630
|
+
payload must be an own data-field plain record with an `Object.prototype` or
|
|
631
|
+
null prototype; arrays, dates, functions, class instances, custom prototypes,
|
|
632
|
+
accessor fields, and function fields are rejected so the decoded value always
|
|
633
|
+
matches its object shape. Dictionary
|
|
634
|
+
payload _types_ with broad or patterned index signatures are also unsupported;
|
|
635
|
+
use a finite object shape for each fallback variant.
|
|
636
|
+
|
|
637
|
+
```ts
|
|
638
|
+
const classifyEvent = discriminatedUnionWithFallback<Event>()(
|
|
639
|
+
'kind',
|
|
640
|
+
['click', 'scroll'],
|
|
641
|
+
{
|
|
642
|
+
click: typedStruct<Extract<Event, { kind: 'click' }>>()({
|
|
643
|
+
kind: oneOfValues('click'),
|
|
644
|
+
x: isNumber,
|
|
645
|
+
y: isNumber
|
|
646
|
+
}),
|
|
647
|
+
scroll: typedStruct<Extract<Event, { kind: 'scroll' }>>()({
|
|
648
|
+
kind: oneOfValues('scroll'),
|
|
649
|
+
delta: isNumber
|
|
650
|
+
})
|
|
651
|
+
},
|
|
652
|
+
{
|
|
653
|
+
tag: 'unknown',
|
|
654
|
+
create: (input, originalKind) => ({ input, originalKind })
|
|
655
|
+
}
|
|
656
|
+
);
|
|
657
|
+
|
|
658
|
+
const result = classifyEvent(value);
|
|
659
|
+
if (result.valid) {
|
|
660
|
+
const event = result.value;
|
|
661
|
+
// Event member | { kind: 'unknown'; input: unknown; originalKind: PropertyKey | boolean }
|
|
662
|
+
}
|
|
663
|
+
```
|
|
664
|
+
|
|
665
|
+
The fallback tag must be one literal with a distinct runtime key from every
|
|
666
|
+
known discriminant, so a known `1` also reserves the tag `'1'` (and `true`
|
|
667
|
+
reserves `'true'`). The classifier determines whether a raw discriminant is
|
|
668
|
+
known before converting it to a branch key, then writes the fallback tag after
|
|
669
|
+
creating its payload. A malformed known branch, missing or inherited
|
|
670
|
+
discriminant, non-primitive discriminant, or non-plain fallback payload returns
|
|
671
|
+
`{ valid: false }` without producing a fallback variant.
|
|
672
|
+
|
|
614
673
|
### 12. Narrow object keys
|
|
615
674
|
|
|
616
675
|
Use key helpers when the important part of a value is one property.
|
|
@@ -785,9 +844,15 @@ For detailed API pages and more examples, see:
|
|
|
785
844
|
Start with [How to safely filter null and undefined from arrays in
|
|
786
845
|
TypeScript](https://is-kit.dev/guides/filter-null-and-undefined).
|
|
787
846
|
|
|
847
|
+
## Compatibility
|
|
848
|
+
|
|
849
|
+
is-kit requires Node.js 22 or later. CI validates the packed npm artifact on
|
|
850
|
+
Node.js 22.x and 24.x with native ESM, CommonJS, and strict TypeScript
|
|
851
|
+
NodeNext consumers.
|
|
852
|
+
|
|
788
853
|
## 👨💻 Development
|
|
789
854
|
|
|
790
|
-
Requires Node 22.
|
|
855
|
+
Requires Node 22.23.4 and pnpm 11.2.2.
|
|
791
856
|
|
|
792
857
|
- `pnpm lint`
|
|
793
858
|
- `pnpm build`
|
package/dist/index.d.mts
CHANGED
|
@@ -739,6 +739,22 @@ type MatchingDiscriminantMember<T extends object, K extends DiscriminantKey<T>,
|
|
|
739
739
|
type DiscriminatedUnionGuardMap<T extends object, K extends DiscriminantKey<T>, Values extends DiscriminantValue> = { readonly [Value in Values as DiscriminantMapKey<Value>]: Predicate<MatchingDiscriminantMember<T, K, Value>>; };
|
|
740
740
|
type InvalidGuardDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = { [Value in Values as DiscriminantMapKey<Value>]: G extends Record<DiscriminantMapKey<Value>, infer Guard> ? GuardedOf<Guard> extends Record<K, DiscriminantValue> ? Value extends GuardedOf<Guard>[K] ? never : Value : Value : Value; }[DiscriminantMapKey<Values>];
|
|
741
741
|
type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = [InvalidGuardDiscriminantValues<K, Values, G>] extends [never] ? unknown : never;
|
|
742
|
+
type FallbackDiscriminant<Values extends DiscriminantValue, Value extends DiscriminantValue> = IsFiniteDiscriminantValue<Value> extends true ? IsUnion<Value> extends false ? DiscriminantRuntimeKey<Value> extends DiscriminantRuntimeKey<Values> ? never : unknown : never : never;
|
|
743
|
+
type RuntimePropertyKey<Key extends PropertyKey> = Key extends symbol ? Key : Key extends string | number ? `${Key}` : never;
|
|
744
|
+
type OmitRuntimeKey<Data extends object, Key extends PropertyKey> = { [Property in keyof Data as RuntimePropertyKey<Property> extends RuntimePropertyKey<Key> ? never : Property]: Data[Property]; };
|
|
745
|
+
type InvalidFallbackKey<Key extends PropertyKey> = Key extends unknown ? SinglePropertyKey<Key> extends never ? Key : never : never;
|
|
746
|
+
type InvalidFallbackData<Data extends object> = Data extends unknown ? [InvalidFallbackKey<keyof Data & PropertyKey>] extends [never] ? never : Data : never;
|
|
747
|
+
type FiniteFallbackData<Data extends object> = [InvalidFallbackData<Data>] extends [never] ? unknown : never;
|
|
748
|
+
type FallbackVariant<K extends PropertyKey, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = Data extends unknown ? OmitRuntimeKey<Data, K> & Record<K, Value> : never;
|
|
749
|
+
type FallbackVariantConfig<Values extends DiscriminantValue, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = {
|
|
750
|
+
readonly tag: Value & FallbackDiscriminant<Values, Value>;
|
|
751
|
+
readonly create: (this: void, input: unknown, discriminant: DiscriminantValue) => Data | undefined;
|
|
752
|
+
};
|
|
753
|
+
type Decoder<Output> = (input: unknown) => ParseResult<Output>;
|
|
754
|
+
declare const invalidFallbackClassifier: unique symbol;
|
|
755
|
+
type InvalidFallbackClassifier = {
|
|
756
|
+
readonly [invalidFallbackClassifier]: 'Fallback payloads must have finite property keys.';
|
|
757
|
+
};
|
|
742
758
|
/**
|
|
743
759
|
* Creates an exhaustive guard for a union whose members share a literal discriminant.
|
|
744
760
|
* A tuple of every discriminant value keeps finite coverage explicit at runtime
|
|
@@ -752,6 +768,16 @@ type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends Discrim
|
|
|
752
768
|
* @returns Predicate narrowing to the union accepted by the branch guards.
|
|
753
769
|
*/
|
|
754
770
|
export declare function discriminatedUnion<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>>(discriminant: K, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>) => Predicate<GuardedOf<G[keyof G]>>;
|
|
771
|
+
/**
|
|
772
|
+
* Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
|
|
773
|
+
* Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
|
|
774
|
+
* @param discriminant Required property that identifies each known union member.
|
|
775
|
+
* @param values Finite tuple containing every known discriminant value.
|
|
776
|
+
* @param guards Branch guards keyed by the known discriminant values.
|
|
777
|
+
* @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
|
|
778
|
+
* @returns Decoder that returns a guarded known member or fallback variant when valid.
|
|
779
|
+
*/
|
|
780
|
+
export declare function discriminatedUnionWithFallback<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>, const FallbackValue extends DiscriminantValue, const FallbackData extends Record<PropertyKey, unknown>>(discriminant: K & SinglePropertyKey<K>, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>, fallback: FallbackVariantConfig<Values[number], FallbackValue, FallbackData>) => FiniteFallbackData<FallbackData> extends never ? InvalidFallbackClassifier : Decoder<GuardedOf<G[keyof G]> | FallbackVariant<K, FallbackValue, FallbackData>>;
|
|
755
781
|
//#endregion
|
|
756
782
|
//#region src/core/combinators/map.d.ts
|
|
757
783
|
/**
|
|
@@ -822,16 +848,17 @@ export declare function setOf<VF extends Predicate<unknown>>(valueGuard: VF): Pr
|
|
|
822
848
|
*/
|
|
823
849
|
export declare function optionalKey<G extends Predicate<unknown>>(guard: G): OptionalSchemaField<G>;
|
|
824
850
|
/**
|
|
825
|
-
* Validates an object against a field-to-guard schema with
|
|
826
|
-
* Numeric schema keys are normalized to strings by JavaScript; symbol
|
|
827
|
-
* are not supported. Keys are required unless
|
|
828
|
-
* rejects extra keys when `exact: true`.
|
|
851
|
+
* Validates an object against a field-to-guard schema with own enumerable string
|
|
852
|
+
* keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
|
|
853
|
+
* non-enumerable, and inherited fields are not supported. Keys are required unless
|
|
854
|
+
* wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
|
|
829
855
|
*
|
|
830
856
|
* @param schema Record of string- or numeric-keyed property guards.
|
|
831
857
|
* @param options When `{ exact: true }`, disallows own enumerable string-key
|
|
832
858
|
* properties not in `schema`.
|
|
833
859
|
* @returns Predicate that narrows to the inferred struct type.
|
|
834
|
-
* @throws {TypeError} If `schema` has
|
|
860
|
+
* @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
|
|
861
|
+
* string-keyed fields.
|
|
835
862
|
*/
|
|
836
863
|
export declare function struct<const S extends SchemaShape<S>>(schema: StructSchemaShape<S>, options?: StructOptions): Predicate<InferSchema<S>>;
|
|
837
864
|
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -739,6 +739,22 @@ type MatchingDiscriminantMember<T extends object, K extends DiscriminantKey<T>,
|
|
|
739
739
|
type DiscriminatedUnionGuardMap<T extends object, K extends DiscriminantKey<T>, Values extends DiscriminantValue> = { readonly [Value in Values as DiscriminantMapKey<Value>]: Predicate<MatchingDiscriminantMember<T, K, Value>>; };
|
|
740
740
|
type InvalidGuardDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = { [Value in Values as DiscriminantMapKey<Value>]: G extends Record<DiscriminantMapKey<Value>, infer Guard> ? GuardedOf<Guard> extends Record<K, DiscriminantValue> ? Value extends GuardedOf<Guard>[K] ? never : Value : Value : Value; }[DiscriminantMapKey<Values>];
|
|
741
741
|
type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = [InvalidGuardDiscriminantValues<K, Values, G>] extends [never] ? unknown : never;
|
|
742
|
+
type FallbackDiscriminant<Values extends DiscriminantValue, Value extends DiscriminantValue> = IsFiniteDiscriminantValue<Value> extends true ? IsUnion<Value> extends false ? DiscriminantRuntimeKey<Value> extends DiscriminantRuntimeKey<Values> ? never : unknown : never : never;
|
|
743
|
+
type RuntimePropertyKey<Key extends PropertyKey> = Key extends symbol ? Key : Key extends string | number ? `${Key}` : never;
|
|
744
|
+
type OmitRuntimeKey<Data extends object, Key extends PropertyKey> = { [Property in keyof Data as RuntimePropertyKey<Property> extends RuntimePropertyKey<Key> ? never : Property]: Data[Property]; };
|
|
745
|
+
type InvalidFallbackKey<Key extends PropertyKey> = Key extends unknown ? SinglePropertyKey<Key> extends never ? Key : never : never;
|
|
746
|
+
type InvalidFallbackData<Data extends object> = Data extends unknown ? [InvalidFallbackKey<keyof Data & PropertyKey>] extends [never] ? never : Data : never;
|
|
747
|
+
type FiniteFallbackData<Data extends object> = [InvalidFallbackData<Data>] extends [never] ? unknown : never;
|
|
748
|
+
type FallbackVariant<K extends PropertyKey, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = Data extends unknown ? OmitRuntimeKey<Data, K> & Record<K, Value> : never;
|
|
749
|
+
type FallbackVariantConfig<Values extends DiscriminantValue, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = {
|
|
750
|
+
readonly tag: Value & FallbackDiscriminant<Values, Value>;
|
|
751
|
+
readonly create: (this: void, input: unknown, discriminant: DiscriminantValue) => Data | undefined;
|
|
752
|
+
};
|
|
753
|
+
type Decoder<Output> = (input: unknown) => ParseResult<Output>;
|
|
754
|
+
declare const invalidFallbackClassifier: unique symbol;
|
|
755
|
+
type InvalidFallbackClassifier = {
|
|
756
|
+
readonly [invalidFallbackClassifier]: 'Fallback payloads must have finite property keys.';
|
|
757
|
+
};
|
|
742
758
|
/**
|
|
743
759
|
* Creates an exhaustive guard for a union whose members share a literal discriminant.
|
|
744
760
|
* A tuple of every discriminant value keeps finite coverage explicit at runtime
|
|
@@ -752,6 +768,16 @@ type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends Discrim
|
|
|
752
768
|
* @returns Predicate narrowing to the union accepted by the branch guards.
|
|
753
769
|
*/
|
|
754
770
|
export declare function discriminatedUnion<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>>(discriminant: K, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>) => Predicate<GuardedOf<G[keyof G]>>;
|
|
771
|
+
/**
|
|
772
|
+
* Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
|
|
773
|
+
* Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
|
|
774
|
+
* @param discriminant Required property that identifies each known union member.
|
|
775
|
+
* @param values Finite tuple containing every known discriminant value.
|
|
776
|
+
* @param guards Branch guards keyed by the known discriminant values.
|
|
777
|
+
* @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
|
|
778
|
+
* @returns Decoder that returns a guarded known member or fallback variant when valid.
|
|
779
|
+
*/
|
|
780
|
+
export declare function discriminatedUnionWithFallback<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>, const FallbackValue extends DiscriminantValue, const FallbackData extends Record<PropertyKey, unknown>>(discriminant: K & SinglePropertyKey<K>, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>, fallback: FallbackVariantConfig<Values[number], FallbackValue, FallbackData>) => FiniteFallbackData<FallbackData> extends never ? InvalidFallbackClassifier : Decoder<GuardedOf<G[keyof G]> | FallbackVariant<K, FallbackValue, FallbackData>>;
|
|
755
781
|
//#endregion
|
|
756
782
|
//#region src/core/combinators/map.d.ts
|
|
757
783
|
/**
|
|
@@ -822,16 +848,17 @@ export declare function setOf<VF extends Predicate<unknown>>(valueGuard: VF): Pr
|
|
|
822
848
|
*/
|
|
823
849
|
export declare function optionalKey<G extends Predicate<unknown>>(guard: G): OptionalSchemaField<G>;
|
|
824
850
|
/**
|
|
825
|
-
* Validates an object against a field-to-guard schema with
|
|
826
|
-
* Numeric schema keys are normalized to strings by JavaScript; symbol
|
|
827
|
-
* are not supported. Keys are required unless
|
|
828
|
-
* rejects extra keys when `exact: true`.
|
|
851
|
+
* Validates an object against a field-to-guard schema with own enumerable string
|
|
852
|
+
* keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
|
|
853
|
+
* non-enumerable, and inherited fields are not supported. Keys are required unless
|
|
854
|
+
* wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
|
|
829
855
|
*
|
|
830
856
|
* @param schema Record of string- or numeric-keyed property guards.
|
|
831
857
|
* @param options When `{ exact: true }`, disallows own enumerable string-key
|
|
832
858
|
* properties not in `schema`.
|
|
833
859
|
* @returns Predicate that narrows to the inferred struct type.
|
|
834
|
-
* @throws {TypeError} If `schema` has
|
|
860
|
+
* @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
|
|
861
|
+
* string-keyed fields.
|
|
835
862
|
*/
|
|
836
863
|
export declare function struct<const S extends SchemaShape<S>>(schema: StructSchemaShape<S>, options?: StructOptions): Predicate<InferSchema<S>>;
|
|
837
864
|
//#endregion
|
package/dist/index.js
CHANGED
|
@@ -537,7 +537,6 @@ const isNotNil = (value) => value !== null && value !== void 0;
|
|
|
537
537
|
const isPrimitive = or(isString, isNumberPrimitive, isBoolean, isBigInt, isSymbol, isUndefined, isNull);
|
|
538
538
|
//#endregion
|
|
539
539
|
//#region src/utils/guard-collections.ts
|
|
540
|
-
const arrayValues = Array.prototype.values;
|
|
541
540
|
const mapEntries = Map.prototype.entries;
|
|
542
541
|
const setValues = Set.prototype.values;
|
|
543
542
|
const everyIterableValue = (values, predicate) => {
|
|
@@ -548,6 +547,15 @@ const everyKeyValueEntry = (entries, predicate) => {
|
|
|
548
547
|
for (const [key, value] of entries) if (!predicate(key, value)) return false;
|
|
549
548
|
return true;
|
|
550
549
|
};
|
|
550
|
+
const hasTupleValues = (values, predicates) => {
|
|
551
|
+
if (values.length !== predicates.length) return false;
|
|
552
|
+
for (let index = 0; index < predicates.length; index += 1) {
|
|
553
|
+
const predicate = predicates[index];
|
|
554
|
+
if (!predicate(values[index])) return false;
|
|
555
|
+
}
|
|
556
|
+
return true;
|
|
557
|
+
};
|
|
558
|
+
const hasOwnEnumerableEntries = (values, keyPredicate, valuePredicate) => everyIterableValue(Object.keys(values), (key) => keyPredicate(key) && valuePredicate(values[key]));
|
|
551
559
|
/**
|
|
552
560
|
* Checks whether every array element satisfies the provided predicate.
|
|
553
561
|
*
|
|
@@ -560,9 +568,13 @@ const everyKeyValueEntry = (entries, predicate) => {
|
|
|
560
568
|
const everyArrayValue = (values, predicate) => everyIterableValue(values, predicate);
|
|
561
569
|
/**
|
|
562
570
|
* Checks built-in Array data without invoking an instance-provided iterator.
|
|
563
|
-
* WHY:
|
|
571
|
+
* WHY: Indexed reads preserve hole-as-undefined semantics while avoiding iterator
|
|
572
|
+
* allocation on this hot path. They also bypass iterator overrides on subclasses.
|
|
564
573
|
*/
|
|
565
|
-
const everyBrandedArrayValue = (values, predicate) =>
|
|
574
|
+
const everyBrandedArrayValue = (values, predicate) => {
|
|
575
|
+
for (let index = 0; index < values.length; index += 1) if (!predicate(values[index])) return false;
|
|
576
|
+
return true;
|
|
577
|
+
};
|
|
566
578
|
/**
|
|
567
579
|
* Checks whether a tuple matches the provided element predicates in order.
|
|
568
580
|
*
|
|
@@ -572,14 +584,7 @@ const everyBrandedArrayValue = (values, predicate) => everyIterableValue(arrayVa
|
|
|
572
584
|
* @param predicates Predicates aligned to each tuple index.
|
|
573
585
|
* @returns Whether lengths match and each index passes.
|
|
574
586
|
*/
|
|
575
|
-
const everyTupleValue = (values, predicates) =>
|
|
576
|
-
if (values.length !== predicates.length) return false;
|
|
577
|
-
for (let index = 0; index < predicates.length; index += 1) {
|
|
578
|
-
const predicate = predicates[index];
|
|
579
|
-
if (!predicate(values[index])) return false;
|
|
580
|
-
}
|
|
581
|
-
return true;
|
|
582
|
-
};
|
|
587
|
+
const everyTupleValue = (values, predicates) => hasTupleValues(values, predicates);
|
|
583
588
|
/**
|
|
584
589
|
* Checks whether every set value satisfies the provided predicate.
|
|
585
590
|
*
|
|
@@ -622,7 +627,7 @@ const everyBrandedMapEntry = (values, keyPredicate, valuePredicate) => everyKeyV
|
|
|
622
627
|
* @param valuePredicate Predicate applied to each corresponding value.
|
|
623
628
|
* @returns Whether all enumerable entries satisfy their predicates.
|
|
624
629
|
*/
|
|
625
|
-
const everyOwnEnumerableEntry = (values, keyPredicate, valuePredicate) =>
|
|
630
|
+
const everyOwnEnumerableEntry = (values, keyPredicate, valuePredicate) => hasOwnEnumerableEntries(values, keyPredicate, valuePredicate);
|
|
626
631
|
//#endregion
|
|
627
632
|
//#region src/core/combinators/array.ts
|
|
628
633
|
/**
|
|
@@ -645,8 +650,48 @@ function nonEmptyArrayOf(elementGuard) {
|
|
|
645
650
|
}
|
|
646
651
|
//#endregion
|
|
647
652
|
//#region src/core/combinators/discriminated-union.ts
|
|
653
|
+
function defineFallbackClassifier(classifier) {
|
|
654
|
+
return classifier;
|
|
655
|
+
}
|
|
656
|
+
function createFallbackVariant(fallbackData, discriminant, tag) {
|
|
657
|
+
const fallbackVariant = {};
|
|
658
|
+
const discriminantKey = isSymbol(discriminant) ? discriminant : String(discriminant);
|
|
659
|
+
for (const key of Reflect.ownKeys(fallbackData)) {
|
|
660
|
+
if (key === discriminantKey) continue;
|
|
661
|
+
const descriptor = Object.getOwnPropertyDescriptor(fallbackData, key);
|
|
662
|
+
if (descriptor !== void 0) Object.defineProperty(fallbackVariant, key, descriptor);
|
|
663
|
+
}
|
|
664
|
+
Object.defineProperty(fallbackVariant, discriminantKey, {
|
|
665
|
+
configurable: true,
|
|
666
|
+
enumerable: true,
|
|
667
|
+
value: tag,
|
|
668
|
+
writable: true
|
|
669
|
+
});
|
|
670
|
+
return fallbackVariant;
|
|
671
|
+
}
|
|
648
672
|
const isDiscriminantValue = (value) => isString(value) || isNumberPrimitive(value) || isSymbol(value) || isBoolean(value);
|
|
673
|
+
const isFallbackDataDescriptor = (descriptor) => descriptor !== void 0 && "value" in descriptor && !isFunction(descriptor.value);
|
|
674
|
+
const isFallbackPayload = (value) => {
|
|
675
|
+
if (!isPlainObject(value)) return false;
|
|
676
|
+
const prototype = Object.getPrototypeOf(value);
|
|
677
|
+
if (prototype !== null && prototype !== Object.prototype) return false;
|
|
678
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
679
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
680
|
+
if (!isFallbackDataDescriptor(descriptor)) return false;
|
|
681
|
+
}
|
|
682
|
+
return true;
|
|
683
|
+
};
|
|
649
684
|
const toRuntimeKey = (value) => isSymbol(value) ? value : String(value);
|
|
685
|
+
const assertSafeFallbackTag = (values, tag) => {
|
|
686
|
+
if (!isDiscriminantValue(tag)) throw new TypeError("discriminatedUnion fallback tag must be a string, number, symbol, or boolean.");
|
|
687
|
+
const fallbackKey = toRuntimeKey(tag);
|
|
688
|
+
if (values.some((value) => toRuntimeKey(value) === fallbackKey)) throw new TypeError(`Fallback discriminatedUnion tag collides with a branch value: ${String(tag)}.`);
|
|
689
|
+
};
|
|
690
|
+
const getOwnDiscriminantValue = (input, discriminant) => {
|
|
691
|
+
if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return;
|
|
692
|
+
const value = Reflect.get(input, discriminant);
|
|
693
|
+
return isDiscriminantValue(value) ? value : void 0;
|
|
694
|
+
};
|
|
650
695
|
const assertSafeProtoBranch = (values, guards) => {
|
|
651
696
|
if (!values.includes("__proto__")) return;
|
|
652
697
|
if (hasOwnPropertyKey(guards, "__proto__")) return;
|
|
@@ -679,9 +724,8 @@ function discriminatedUnion() {
|
|
|
679
724
|
assertSafeProtoBranch(values, guards);
|
|
680
725
|
const declaredKeys = assertBranchKeys(values, guards);
|
|
681
726
|
return define((input) => {
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
if (!isDiscriminantValue(value)) return false;
|
|
727
|
+
const value = getOwnDiscriminantValue(input, discriminant);
|
|
728
|
+
if (value === void 0) return false;
|
|
685
729
|
const key = toRuntimeKey(value);
|
|
686
730
|
if (!declaredKeys.has(key) || !hasOwnPropertyKey(guards, key)) return false;
|
|
687
731
|
const guard = guards[key];
|
|
@@ -689,6 +733,44 @@ function discriminatedUnion() {
|
|
|
689
733
|
});
|
|
690
734
|
};
|
|
691
735
|
}
|
|
736
|
+
/**
|
|
737
|
+
* Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
|
|
738
|
+
* Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
|
|
739
|
+
* @param discriminant Required property that identifies each known union member.
|
|
740
|
+
* @param values Finite tuple containing every known discriminant value.
|
|
741
|
+
* @param guards Branch guards keyed by the known discriminant values.
|
|
742
|
+
* @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
|
|
743
|
+
* @returns Decoder that returns a guarded known member or fallback variant when valid.
|
|
744
|
+
*/
|
|
745
|
+
function discriminatedUnionWithFallback() {
|
|
746
|
+
return (discriminant, values, guards, fallback) => {
|
|
747
|
+
assertSafeProtoBranch(values, guards);
|
|
748
|
+
const fallbackTag = fallback.tag;
|
|
749
|
+
const createFallback = fallback.create;
|
|
750
|
+
assertSafeFallbackTag(values, fallbackTag);
|
|
751
|
+
assertBranchKeys(values, guards);
|
|
752
|
+
const declaredValues = new Set(values);
|
|
753
|
+
return defineFallbackClassifier((input) => {
|
|
754
|
+
const value = getOwnDiscriminantValue(input, discriminant);
|
|
755
|
+
if (value === void 0) return { valid: false };
|
|
756
|
+
if (!declaredValues.has(value)) {
|
|
757
|
+
const fallbackData = createFallback(input, value);
|
|
758
|
+
if (fallbackData === void 0 || !isFallbackPayload(fallbackData)) return { valid: false };
|
|
759
|
+
return {
|
|
760
|
+
valid: true,
|
|
761
|
+
value: createFallbackVariant(fallbackData, discriminant, fallbackTag)
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
const key = toRuntimeKey(value);
|
|
765
|
+
if (!hasOwnPropertyKey(guards, key)) return { valid: false };
|
|
766
|
+
const guard = guards[key];
|
|
767
|
+
return guard(input) ? {
|
|
768
|
+
valid: true,
|
|
769
|
+
value: input
|
|
770
|
+
} : { valid: false };
|
|
771
|
+
});
|
|
772
|
+
};
|
|
773
|
+
}
|
|
692
774
|
//#endregion
|
|
693
775
|
//#region src/core/combinators/map.ts
|
|
694
776
|
/**
|
|
@@ -746,7 +828,7 @@ function oneOfValues(...args) {
|
|
|
746
828
|
* @returns Predicate narrowing to a readonly record with guarded key/value types.
|
|
747
829
|
*/
|
|
748
830
|
function recordOf(keyFunction, valueFunction) {
|
|
749
|
-
return define((input) => isPlainObject(input) &&
|
|
831
|
+
return define((input) => isPlainObject(input) && hasOwnEnumerableEntries(input, keyFunction, valueFunction));
|
|
750
832
|
}
|
|
751
833
|
//#endregion
|
|
752
834
|
//#region src/core/combinators/set.ts
|
|
@@ -761,6 +843,36 @@ function setOf(valueGuard) {
|
|
|
761
843
|
}
|
|
762
844
|
//#endregion
|
|
763
845
|
//#region src/core/combinators/struct.ts
|
|
846
|
+
const OBJECT_CONSTRUCTOR_SOURCE = Function.prototype.toString.call(Object);
|
|
847
|
+
const isObjectPrototype = (prototype) => {
|
|
848
|
+
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
849
|
+
return typeof constructor === "function" && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === OBJECT_CONSTRUCTOR_SOURCE;
|
|
850
|
+
};
|
|
851
|
+
const hasOnlyEnumerableOwnStringKeys = (schema) => Object.getOwnPropertyNames(schema).every((key) => Object.prototype.propertyIsEnumerable.call(schema, key));
|
|
852
|
+
const hasInheritedStringKeys = (schema) => {
|
|
853
|
+
let prototype = Object.getPrototypeOf(schema);
|
|
854
|
+
while (prototype !== null && !isObjectPrototype(prototype)) {
|
|
855
|
+
if (Object.getOwnPropertyNames(prototype).some((key) => {
|
|
856
|
+
if (key !== "constructor") return true;
|
|
857
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, key);
|
|
858
|
+
return !(typeof descriptor?.value === "function" && descriptor.value.prototype === prototype);
|
|
859
|
+
})) return true;
|
|
860
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
861
|
+
}
|
|
862
|
+
return false;
|
|
863
|
+
};
|
|
864
|
+
const hasInheritedSymbolKeys = (schema) => {
|
|
865
|
+
let prototype = Object.getPrototypeOf(schema);
|
|
866
|
+
while (prototype !== null && !isObjectPrototype(prototype)) {
|
|
867
|
+
if (Object.getOwnPropertySymbols(prototype).length > 0) return true;
|
|
868
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
869
|
+
}
|
|
870
|
+
return false;
|
|
871
|
+
};
|
|
872
|
+
const assertValidSchemaKeys = (schema) => {
|
|
873
|
+
if (Object.getOwnPropertySymbols(schema).length > 0 || hasInheritedSymbolKeys(schema)) throw new TypeError("struct schema fields cannot use symbol keys");
|
|
874
|
+
if (!hasOnlyEnumerableOwnStringKeys(schema) || hasInheritedStringKeys(schema)) throw new TypeError("struct schema fields must be own enumerable string keys");
|
|
875
|
+
};
|
|
764
876
|
const isOptionalSchemaField = define((field) => isObject(field) && field.optional === true && isFunction(field.guard));
|
|
765
877
|
const hasRequiredKeys = (obj, entries) => entries.every(([key, guard]) => hasOwnPropertyKey(obj, key) && guard(obj[key]));
|
|
766
878
|
const hasValidOptionalKeys = (obj, entries) => entries.every(([key, guard]) => !hasOwnPropertyKey(obj, key) || guard(obj[key]));
|
|
@@ -785,23 +897,24 @@ function optionalKey(guard) {
|
|
|
785
897
|
};
|
|
786
898
|
}
|
|
787
899
|
/**
|
|
788
|
-
* Validates an object against a field-to-guard schema with
|
|
789
|
-
* Numeric schema keys are normalized to strings by JavaScript; symbol
|
|
790
|
-
* are not supported. Keys are required unless
|
|
791
|
-
* rejects extra keys when `exact: true`.
|
|
900
|
+
* Validates an object against a field-to-guard schema with own enumerable string
|
|
901
|
+
* keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
|
|
902
|
+
* non-enumerable, and inherited fields are not supported. Keys are required unless
|
|
903
|
+
* wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
|
|
792
904
|
*
|
|
793
905
|
* @param schema Record of string- or numeric-keyed property guards.
|
|
794
906
|
* @param options When `{ exact: true }`, disallows own enumerable string-key
|
|
795
907
|
* properties not in `schema`.
|
|
796
908
|
* @returns Predicate that narrows to the inferred struct type.
|
|
797
|
-
* @throws {TypeError} If `schema` has
|
|
909
|
+
* @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
|
|
910
|
+
* string-keyed fields.
|
|
798
911
|
*/
|
|
799
912
|
function struct(schema, options) {
|
|
800
913
|
return createStruct(schema, options);
|
|
801
914
|
}
|
|
802
915
|
/** @internal Shared implementation for string-keyed schema builders. */
|
|
803
916
|
function createStruct(schema, options) {
|
|
804
|
-
|
|
917
|
+
assertValidSchemaKeys(schema);
|
|
805
918
|
const requiredEntries = [];
|
|
806
919
|
const optionalEntries = [];
|
|
807
920
|
const schemaKeys = [];
|
|
@@ -853,7 +966,7 @@ function typedStruct() {
|
|
|
853
966
|
* @returns Predicate that narrows to a readonly tuple of guarded element types.
|
|
854
967
|
*/
|
|
855
968
|
function tupleOf(...guards) {
|
|
856
|
-
return define((input) => Array.isArray(input) &&
|
|
969
|
+
return define((input) => Array.isArray(input) && hasTupleValues(input, guards));
|
|
857
970
|
}
|
|
858
971
|
//#endregion
|
|
859
972
|
//#region src/utils/to-boolean-predicates.ts
|
|
@@ -873,6 +986,7 @@ exports.arrayOf = arrayOf;
|
|
|
873
986
|
exports.assert = assert;
|
|
874
987
|
exports.define = define;
|
|
875
988
|
exports.discriminatedUnion = discriminatedUnion;
|
|
989
|
+
exports.discriminatedUnionWithFallback = discriminatedUnionWithFallback;
|
|
876
990
|
exports.equals = equals;
|
|
877
991
|
exports.equalsBy = equalsBy;
|
|
878
992
|
exports.equalsKey = equalsKey;
|
package/dist/index.mjs
CHANGED
|
@@ -536,7 +536,6 @@ const isNotNil = (value) => value !== null && value !== void 0;
|
|
|
536
536
|
const isPrimitive = or(isString, isNumberPrimitive, isBoolean, isBigInt, isSymbol, isUndefined, isNull);
|
|
537
537
|
//#endregion
|
|
538
538
|
//#region src/utils/guard-collections.ts
|
|
539
|
-
const arrayValues = Array.prototype.values;
|
|
540
539
|
const mapEntries = Map.prototype.entries;
|
|
541
540
|
const setValues = Set.prototype.values;
|
|
542
541
|
const everyIterableValue = (values, predicate) => {
|
|
@@ -547,6 +546,15 @@ const everyKeyValueEntry = (entries, predicate) => {
|
|
|
547
546
|
for (const [key, value] of entries) if (!predicate(key, value)) return false;
|
|
548
547
|
return true;
|
|
549
548
|
};
|
|
549
|
+
const hasTupleValues = (values, predicates) => {
|
|
550
|
+
if (values.length !== predicates.length) return false;
|
|
551
|
+
for (let index = 0; index < predicates.length; index += 1) {
|
|
552
|
+
const predicate = predicates[index];
|
|
553
|
+
if (!predicate(values[index])) return false;
|
|
554
|
+
}
|
|
555
|
+
return true;
|
|
556
|
+
};
|
|
557
|
+
const hasOwnEnumerableEntries = (values, keyPredicate, valuePredicate) => everyIterableValue(Object.keys(values), (key) => keyPredicate(key) && valuePredicate(values[key]));
|
|
550
558
|
/**
|
|
551
559
|
* Checks whether every array element satisfies the provided predicate.
|
|
552
560
|
*
|
|
@@ -559,9 +567,13 @@ const everyKeyValueEntry = (entries, predicate) => {
|
|
|
559
567
|
const everyArrayValue = (values, predicate) => everyIterableValue(values, predicate);
|
|
560
568
|
/**
|
|
561
569
|
* Checks built-in Array data without invoking an instance-provided iterator.
|
|
562
|
-
* WHY:
|
|
570
|
+
* WHY: Indexed reads preserve hole-as-undefined semantics while avoiding iterator
|
|
571
|
+
* allocation on this hot path. They also bypass iterator overrides on subclasses.
|
|
563
572
|
*/
|
|
564
|
-
const everyBrandedArrayValue = (values, predicate) =>
|
|
573
|
+
const everyBrandedArrayValue = (values, predicate) => {
|
|
574
|
+
for (let index = 0; index < values.length; index += 1) if (!predicate(values[index])) return false;
|
|
575
|
+
return true;
|
|
576
|
+
};
|
|
565
577
|
/**
|
|
566
578
|
* Checks whether a tuple matches the provided element predicates in order.
|
|
567
579
|
*
|
|
@@ -571,14 +583,7 @@ const everyBrandedArrayValue = (values, predicate) => everyIterableValue(arrayVa
|
|
|
571
583
|
* @param predicates Predicates aligned to each tuple index.
|
|
572
584
|
* @returns Whether lengths match and each index passes.
|
|
573
585
|
*/
|
|
574
|
-
const everyTupleValue = (values, predicates) =>
|
|
575
|
-
if (values.length !== predicates.length) return false;
|
|
576
|
-
for (let index = 0; index < predicates.length; index += 1) {
|
|
577
|
-
const predicate = predicates[index];
|
|
578
|
-
if (!predicate(values[index])) return false;
|
|
579
|
-
}
|
|
580
|
-
return true;
|
|
581
|
-
};
|
|
586
|
+
const everyTupleValue = (values, predicates) => hasTupleValues(values, predicates);
|
|
582
587
|
/**
|
|
583
588
|
* Checks whether every set value satisfies the provided predicate.
|
|
584
589
|
*
|
|
@@ -621,7 +626,7 @@ const everyBrandedMapEntry = (values, keyPredicate, valuePredicate) => everyKeyV
|
|
|
621
626
|
* @param valuePredicate Predicate applied to each corresponding value.
|
|
622
627
|
* @returns Whether all enumerable entries satisfy their predicates.
|
|
623
628
|
*/
|
|
624
|
-
const everyOwnEnumerableEntry = (values, keyPredicate, valuePredicate) =>
|
|
629
|
+
const everyOwnEnumerableEntry = (values, keyPredicate, valuePredicate) => hasOwnEnumerableEntries(values, keyPredicate, valuePredicate);
|
|
625
630
|
//#endregion
|
|
626
631
|
//#region src/core/combinators/array.ts
|
|
627
632
|
/**
|
|
@@ -644,8 +649,48 @@ function nonEmptyArrayOf(elementGuard) {
|
|
|
644
649
|
}
|
|
645
650
|
//#endregion
|
|
646
651
|
//#region src/core/combinators/discriminated-union.ts
|
|
652
|
+
function defineFallbackClassifier(classifier) {
|
|
653
|
+
return classifier;
|
|
654
|
+
}
|
|
655
|
+
function createFallbackVariant(fallbackData, discriminant, tag) {
|
|
656
|
+
const fallbackVariant = {};
|
|
657
|
+
const discriminantKey = isSymbol(discriminant) ? discriminant : String(discriminant);
|
|
658
|
+
for (const key of Reflect.ownKeys(fallbackData)) {
|
|
659
|
+
if (key === discriminantKey) continue;
|
|
660
|
+
const descriptor = Object.getOwnPropertyDescriptor(fallbackData, key);
|
|
661
|
+
if (descriptor !== void 0) Object.defineProperty(fallbackVariant, key, descriptor);
|
|
662
|
+
}
|
|
663
|
+
Object.defineProperty(fallbackVariant, discriminantKey, {
|
|
664
|
+
configurable: true,
|
|
665
|
+
enumerable: true,
|
|
666
|
+
value: tag,
|
|
667
|
+
writable: true
|
|
668
|
+
});
|
|
669
|
+
return fallbackVariant;
|
|
670
|
+
}
|
|
647
671
|
const isDiscriminantValue = (value) => isString(value) || isNumberPrimitive(value) || isSymbol(value) || isBoolean(value);
|
|
672
|
+
const isFallbackDataDescriptor = (descriptor) => descriptor !== void 0 && "value" in descriptor && !isFunction(descriptor.value);
|
|
673
|
+
const isFallbackPayload = (value) => {
|
|
674
|
+
if (!isPlainObject(value)) return false;
|
|
675
|
+
const prototype = Object.getPrototypeOf(value);
|
|
676
|
+
if (prototype !== null && prototype !== Object.prototype) return false;
|
|
677
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
678
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
679
|
+
if (!isFallbackDataDescriptor(descriptor)) return false;
|
|
680
|
+
}
|
|
681
|
+
return true;
|
|
682
|
+
};
|
|
648
683
|
const toRuntimeKey = (value) => isSymbol(value) ? value : String(value);
|
|
684
|
+
const assertSafeFallbackTag = (values, tag) => {
|
|
685
|
+
if (!isDiscriminantValue(tag)) throw new TypeError("discriminatedUnion fallback tag must be a string, number, symbol, or boolean.");
|
|
686
|
+
const fallbackKey = toRuntimeKey(tag);
|
|
687
|
+
if (values.some((value) => toRuntimeKey(value) === fallbackKey)) throw new TypeError(`Fallback discriminatedUnion tag collides with a branch value: ${String(tag)}.`);
|
|
688
|
+
};
|
|
689
|
+
const getOwnDiscriminantValue = (input, discriminant) => {
|
|
690
|
+
if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return;
|
|
691
|
+
const value = Reflect.get(input, discriminant);
|
|
692
|
+
return isDiscriminantValue(value) ? value : void 0;
|
|
693
|
+
};
|
|
649
694
|
const assertSafeProtoBranch = (values, guards) => {
|
|
650
695
|
if (!values.includes("__proto__")) return;
|
|
651
696
|
if (hasOwnPropertyKey(guards, "__proto__")) return;
|
|
@@ -678,9 +723,8 @@ function discriminatedUnion() {
|
|
|
678
723
|
assertSafeProtoBranch(values, guards);
|
|
679
724
|
const declaredKeys = assertBranchKeys(values, guards);
|
|
680
725
|
return define((input) => {
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
if (!isDiscriminantValue(value)) return false;
|
|
726
|
+
const value = getOwnDiscriminantValue(input, discriminant);
|
|
727
|
+
if (value === void 0) return false;
|
|
684
728
|
const key = toRuntimeKey(value);
|
|
685
729
|
if (!declaredKeys.has(key) || !hasOwnPropertyKey(guards, key)) return false;
|
|
686
730
|
const guard = guards[key];
|
|
@@ -688,6 +732,44 @@ function discriminatedUnion() {
|
|
|
688
732
|
});
|
|
689
733
|
};
|
|
690
734
|
}
|
|
735
|
+
/**
|
|
736
|
+
* Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
|
|
737
|
+
* Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
|
|
738
|
+
* @param discriminant Required property that identifies each known union member.
|
|
739
|
+
* @param values Finite tuple containing every known discriminant value.
|
|
740
|
+
* @param guards Branch guards keyed by the known discriminant values.
|
|
741
|
+
* @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
|
|
742
|
+
* @returns Decoder that returns a guarded known member or fallback variant when valid.
|
|
743
|
+
*/
|
|
744
|
+
function discriminatedUnionWithFallback() {
|
|
745
|
+
return (discriminant, values, guards, fallback) => {
|
|
746
|
+
assertSafeProtoBranch(values, guards);
|
|
747
|
+
const fallbackTag = fallback.tag;
|
|
748
|
+
const createFallback = fallback.create;
|
|
749
|
+
assertSafeFallbackTag(values, fallbackTag);
|
|
750
|
+
assertBranchKeys(values, guards);
|
|
751
|
+
const declaredValues = new Set(values);
|
|
752
|
+
return defineFallbackClassifier((input) => {
|
|
753
|
+
const value = getOwnDiscriminantValue(input, discriminant);
|
|
754
|
+
if (value === void 0) return { valid: false };
|
|
755
|
+
if (!declaredValues.has(value)) {
|
|
756
|
+
const fallbackData = createFallback(input, value);
|
|
757
|
+
if (fallbackData === void 0 || !isFallbackPayload(fallbackData)) return { valid: false };
|
|
758
|
+
return {
|
|
759
|
+
valid: true,
|
|
760
|
+
value: createFallbackVariant(fallbackData, discriminant, fallbackTag)
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
const key = toRuntimeKey(value);
|
|
764
|
+
if (!hasOwnPropertyKey(guards, key)) return { valid: false };
|
|
765
|
+
const guard = guards[key];
|
|
766
|
+
return guard(input) ? {
|
|
767
|
+
valid: true,
|
|
768
|
+
value: input
|
|
769
|
+
} : { valid: false };
|
|
770
|
+
});
|
|
771
|
+
};
|
|
772
|
+
}
|
|
691
773
|
//#endregion
|
|
692
774
|
//#region src/core/combinators/map.ts
|
|
693
775
|
/**
|
|
@@ -745,7 +827,7 @@ function oneOfValues(...args) {
|
|
|
745
827
|
* @returns Predicate narrowing to a readonly record with guarded key/value types.
|
|
746
828
|
*/
|
|
747
829
|
function recordOf(keyFunction, valueFunction) {
|
|
748
|
-
return define((input) => isPlainObject(input) &&
|
|
830
|
+
return define((input) => isPlainObject(input) && hasOwnEnumerableEntries(input, keyFunction, valueFunction));
|
|
749
831
|
}
|
|
750
832
|
//#endregion
|
|
751
833
|
//#region src/core/combinators/set.ts
|
|
@@ -760,6 +842,36 @@ function setOf(valueGuard) {
|
|
|
760
842
|
}
|
|
761
843
|
//#endregion
|
|
762
844
|
//#region src/core/combinators/struct.ts
|
|
845
|
+
const OBJECT_CONSTRUCTOR_SOURCE = Function.prototype.toString.call(Object);
|
|
846
|
+
const isObjectPrototype = (prototype) => {
|
|
847
|
+
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
848
|
+
return typeof constructor === "function" && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === OBJECT_CONSTRUCTOR_SOURCE;
|
|
849
|
+
};
|
|
850
|
+
const hasOnlyEnumerableOwnStringKeys = (schema) => Object.getOwnPropertyNames(schema).every((key) => Object.prototype.propertyIsEnumerable.call(schema, key));
|
|
851
|
+
const hasInheritedStringKeys = (schema) => {
|
|
852
|
+
let prototype = Object.getPrototypeOf(schema);
|
|
853
|
+
while (prototype !== null && !isObjectPrototype(prototype)) {
|
|
854
|
+
if (Object.getOwnPropertyNames(prototype).some((key) => {
|
|
855
|
+
if (key !== "constructor") return true;
|
|
856
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, key);
|
|
857
|
+
return !(typeof descriptor?.value === "function" && descriptor.value.prototype === prototype);
|
|
858
|
+
})) return true;
|
|
859
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
860
|
+
}
|
|
861
|
+
return false;
|
|
862
|
+
};
|
|
863
|
+
const hasInheritedSymbolKeys = (schema) => {
|
|
864
|
+
let prototype = Object.getPrototypeOf(schema);
|
|
865
|
+
while (prototype !== null && !isObjectPrototype(prototype)) {
|
|
866
|
+
if (Object.getOwnPropertySymbols(prototype).length > 0) return true;
|
|
867
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
868
|
+
}
|
|
869
|
+
return false;
|
|
870
|
+
};
|
|
871
|
+
const assertValidSchemaKeys = (schema) => {
|
|
872
|
+
if (Object.getOwnPropertySymbols(schema).length > 0 || hasInheritedSymbolKeys(schema)) throw new TypeError("struct schema fields cannot use symbol keys");
|
|
873
|
+
if (!hasOnlyEnumerableOwnStringKeys(schema) || hasInheritedStringKeys(schema)) throw new TypeError("struct schema fields must be own enumerable string keys");
|
|
874
|
+
};
|
|
763
875
|
const isOptionalSchemaField = define((field) => isObject(field) && field.optional === true && isFunction(field.guard));
|
|
764
876
|
const hasRequiredKeys = (obj, entries) => entries.every(([key, guard]) => hasOwnPropertyKey(obj, key) && guard(obj[key]));
|
|
765
877
|
const hasValidOptionalKeys = (obj, entries) => entries.every(([key, guard]) => !hasOwnPropertyKey(obj, key) || guard(obj[key]));
|
|
@@ -784,23 +896,24 @@ function optionalKey(guard) {
|
|
|
784
896
|
};
|
|
785
897
|
}
|
|
786
898
|
/**
|
|
787
|
-
* Validates an object against a field-to-guard schema with
|
|
788
|
-
* Numeric schema keys are normalized to strings by JavaScript; symbol
|
|
789
|
-
* are not supported. Keys are required unless
|
|
790
|
-
* rejects extra keys when `exact: true`.
|
|
899
|
+
* Validates an object against a field-to-guard schema with own enumerable string
|
|
900
|
+
* keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
|
|
901
|
+
* non-enumerable, and inherited fields are not supported. Keys are required unless
|
|
902
|
+
* wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
|
|
791
903
|
*
|
|
792
904
|
* @param schema Record of string- or numeric-keyed property guards.
|
|
793
905
|
* @param options When `{ exact: true }`, disallows own enumerable string-key
|
|
794
906
|
* properties not in `schema`.
|
|
795
907
|
* @returns Predicate that narrows to the inferred struct type.
|
|
796
|
-
* @throws {TypeError} If `schema` has
|
|
908
|
+
* @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
|
|
909
|
+
* string-keyed fields.
|
|
797
910
|
*/
|
|
798
911
|
function struct(schema, options) {
|
|
799
912
|
return createStruct(schema, options);
|
|
800
913
|
}
|
|
801
914
|
/** @internal Shared implementation for string-keyed schema builders. */
|
|
802
915
|
function createStruct(schema, options) {
|
|
803
|
-
|
|
916
|
+
assertValidSchemaKeys(schema);
|
|
804
917
|
const requiredEntries = [];
|
|
805
918
|
const optionalEntries = [];
|
|
806
919
|
const schemaKeys = [];
|
|
@@ -852,7 +965,7 @@ function typedStruct() {
|
|
|
852
965
|
* @returns Predicate that narrows to a readonly tuple of guarded element types.
|
|
853
966
|
*/
|
|
854
967
|
function tupleOf(...guards) {
|
|
855
|
-
return define((input) => Array.isArray(input) &&
|
|
968
|
+
return define((input) => Array.isArray(input) && hasTupleValues(input, guards));
|
|
856
969
|
}
|
|
857
970
|
//#endregion
|
|
858
971
|
//#region src/utils/to-boolean-predicates.ts
|
|
@@ -866,4 +979,4 @@ function tupleOf(...guards) {
|
|
|
866
979
|
*/
|
|
867
980
|
const toBooleanPredicates = (predicates) => predicates;
|
|
868
981
|
//#endregion
|
|
869
|
-
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 };
|
|
982
|
+
export { and, andAll, arrayOf, assert, define, discriminatedUnion, discriminatedUnionWithFallback, 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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "is-kit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.1",
|
|
4
4
|
"description": "Zero-dependency TypeScript runtime validation toolkit for composable type guards and natural type narrowing.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
"test:package": "node tests/package-smoke.mjs",
|
|
23
23
|
"test:package:vlt": "node tests/vlt-package-smoke.mjs",
|
|
24
24
|
"bench:core": "node bench/core-workloads.mjs",
|
|
25
|
+
"bench:array-traversal": "node bench/array-traversal.mjs",
|
|
25
26
|
"lint": "oxlint .",
|
|
26
27
|
"format": "oxfmt .",
|
|
27
28
|
"format:check": "oxfmt --check .",
|
|
@@ -59,6 +60,9 @@
|
|
|
59
60
|
"homepage": "https://is-kit.dev/",
|
|
60
61
|
"author": "nyaomaru",
|
|
61
62
|
"license": "MIT",
|
|
63
|
+
"engines": {
|
|
64
|
+
"node": ">=22"
|
|
65
|
+
},
|
|
62
66
|
"packageManager": "pnpm@11.2.2",
|
|
63
67
|
"devDependencies": {
|
|
64
68
|
"@types/jest": "^30.0.0",
|