@duplojs/utils 1.4.50 → 1.4.52

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.
@@ -18,7 +18,21 @@ const Positive = base.createConstraint("positive", base$1.Number, min.checkerNum
18
18
  * {@include clean/Negative/index.md}
19
19
  */
20
20
  const Negative = base.createConstraint("negative", base$1.Number, max.checkerNumberMax(-1));
21
+ /**
22
+ * {@include clean/NumberMin/index.md}
23
+ */
24
+ function NumberMin(value) {
25
+ return base.createConstraint(`number-min-${value}`, base$1.Number, min.checkerNumberMin(value));
26
+ }
27
+ /**
28
+ * {@include clean/NumberMax/index.md}
29
+ */
30
+ function NumberMax(value) {
31
+ return base.createConstraint(`number-max-${value}`, base$1.Number, max.checkerNumberMax(value));
32
+ }
21
33
 
22
34
  exports.Int = Int;
23
35
  exports.Negative = Negative;
36
+ exports.NumberMax = NumberMax;
37
+ exports.NumberMin = NumberMin;
24
38
  exports.Positive = Positive;
@@ -1,5 +1,6 @@
1
1
  import { type GetConstraint } from "../base";
2
2
  import * as DDataParser from "../../../dataParser";
3
+ import { type OnlyLiteralNumber } from "../../../common";
3
4
  /**
4
5
  * Constraint handler that validates integer numbers.
5
6
  *
@@ -87,3 +88,63 @@ export type Positive = GetConstraint<typeof Positive>;
87
88
  */
88
89
  export declare const Negative: import("..").ConstraintHandler<"negative", number, readonly [DDataParser.DataParserCheckerNumberMax]>;
89
90
  export type Negative = GetConstraint<typeof Negative>;
91
+ /**
92
+ * Constraint factory that validates numbers greater than or equal to a minimum.
93
+ *
94
+ * **Supported call styles:**
95
+ * - Classic: `NumberMin(min)` -> returns a constraint handler
96
+ *
97
+ * Creates a constraint handler for `C.Number` that enforces a value greater than or equal to `min`. Use it to validate inputs and to constrain NewTypes with a minimum value requirement.
98
+ *
99
+ * ```ts
100
+ * const AdultMin = C.NumberMin(18);
101
+ *
102
+ * const result = AdultMin.create(18);
103
+ *
104
+ * if (E.isRight(result)) {
105
+ * // result: E.Right<"createConstrainedType", C.ConstrainedType<"number-min-18", 18>>
106
+ * }
107
+ *
108
+ * const age = AdultMin.createOrThrow(20);
109
+ * // age: C.ConstrainedType<"number-min-18", 20>
110
+ *
111
+ * AdultMin.is(age); // type guard
112
+ * ```
113
+ *
114
+ * @see https://utils.duplojs.dev/en/v1/api/clean/constraints
115
+ *
116
+ * @namespace C
117
+ *
118
+ */
119
+ export declare function NumberMin<GenericValue extends number>(value: GenericValue & OnlyLiteralNumber<GenericValue>): import("..").ConstraintHandler<`number-min-${GenericValue & OnlyLiteralNumber<GenericValue>}`, number, readonly [DDataParser.DataParserCheckerNumberMin]>;
120
+ export type NumberMin<GenericValue extends number> = ReturnType<typeof NumberMin<GenericValue>>;
121
+ /**
122
+ * Constraint factory that validates numbers less than or equal to a maximum.
123
+ *
124
+ * **Supported call styles:**
125
+ * - Classic: `NumberMax(max)` -> returns a constraint handler
126
+ *
127
+ * Creates a constraint handler for `C.Number` that enforces a value less than or equal to `max`. Use it to validate inputs and to constrain NewTypes with a maximum value requirement.
128
+ *
129
+ * ```ts
130
+ * const PercentMax = C.NumberMax(100);
131
+ *
132
+ * const result = PercentMax.create(100);
133
+ *
134
+ * if (E.isRight(result)) {
135
+ * // result: E.Right<"createConstrainedType", C.ConstrainedType<"number-max-100", 100>>
136
+ * }
137
+ *
138
+ * const value = PercentMax.createOrThrow(80);
139
+ * // value: C.ConstrainedType<"number-max-100", 80>
140
+ *
141
+ * PercentMax.is(value); // type guard
142
+ * ```
143
+ *
144
+ * @see https://utils.duplojs.dev/en/v1/api/clean/constraints
145
+ *
146
+ * @namespace C
147
+ *
148
+ */
149
+ export declare function NumberMax<GenericValue extends number>(value: GenericValue & OnlyLiteralNumber<GenericValue>): import("..").ConstraintHandler<`number-max-${GenericValue & OnlyLiteralNumber<GenericValue>}`, number, readonly [DDataParser.DataParserCheckerNumberMax]>;
150
+ export type NumberMax<GenericValue extends number> = ReturnType<typeof NumberMax<GenericValue>>;
@@ -16,5 +16,17 @@ const Positive = createConstraint("positive", Number, checkerNumberMin(1));
16
16
  * {@include clean/Negative/index.md}
17
17
  */
18
18
  const Negative = createConstraint("negative", Number, checkerNumberMax(-1));
19
+ /**
20
+ * {@include clean/NumberMin/index.md}
21
+ */
22
+ function NumberMin(value) {
23
+ return createConstraint(`number-min-${value}`, Number, checkerNumberMin(value));
24
+ }
25
+ /**
26
+ * {@include clean/NumberMax/index.md}
27
+ */
28
+ function NumberMax(value) {
29
+ return createConstraint(`number-max-${value}`, Number, checkerNumberMax(value));
30
+ }
19
31
 
20
- export { Int, Negative, Positive };
32
+ export { Int, Negative, NumberMax, NumberMin, Positive };
@@ -4,6 +4,8 @@ var base = require('../base.cjs');
4
4
  var base$1 = require('../../primitive/base.cjs');
5
5
  var email = require('../../../dataParser/parsers/string/checkers/email.cjs');
6
6
  var url = require('../../../dataParser/parsers/string/checkers/url.cjs');
7
+ var min = require('../../../dataParser/parsers/string/checkers/min.cjs');
8
+ var max = require('../../../dataParser/parsers/string/checkers/max.cjs');
7
9
 
8
10
  /**
9
11
  * {@include clean/Email/index.md}
@@ -13,6 +15,20 @@ const Email = base.createConstraint("email", base$1.String, email.checkerEmail()
13
15
  * {@include clean/Url/index.md}
14
16
  */
15
17
  const Url = base.createConstraint("url", base$1.String, url.checkerUrl());
18
+ /**
19
+ * {@include clean/StringMin/index.md}
20
+ */
21
+ function StringMin(value) {
22
+ return base.createConstraint(`string-min-${value}`, base$1.String, min.checkerStringMin(value));
23
+ }
24
+ /**
25
+ * {@include clean/StringMax/index.md}
26
+ */
27
+ function StringMax(value) {
28
+ return base.createConstraint(`string-max-${value}`, base$1.String, max.checkerStringMax(value));
29
+ }
16
30
 
17
31
  exports.Email = Email;
32
+ exports.StringMax = StringMax;
33
+ exports.StringMin = StringMin;
18
34
  exports.Url = Url;
@@ -1,5 +1,6 @@
1
1
  import { type GetConstraint } from "../base";
2
2
  import * as DDataParser from "../../../dataParser";
3
+ import { type OnlyLiteralNumber } from "../../../common";
3
4
  /**
4
5
  * Constraint handler that validates an email string.
5
6
  *
@@ -58,3 +59,63 @@ export type Email = GetConstraint<typeof Email>;
58
59
  */
59
60
  export declare const Url: import("..").ConstraintHandler<"url", string, readonly [DDataParser.DataParserCheckerUrl]>;
60
61
  export type Url = GetConstraint<typeof Url>;
62
+ /**
63
+ * Constraint factory that validates strings with a minimum length.
64
+ *
65
+ * **Supported call styles:**
66
+ * - Classic: `StringMin(min)` -> returns a constraint handler
67
+ *
68
+ * Creates a constraint handler for `C.String` that enforces a length greater than or equal to `min`. Use it to validate inputs and to constrain NewTypes with a minimum length requirement.
69
+ *
70
+ * ```ts
71
+ * const UsernameMin = C.StringMin(3);
72
+ *
73
+ * const result = UsernameMin.create("Ada");
74
+ *
75
+ * if (E.isRight(result)) {
76
+ * // result: E.Right<"createConstrainedType", C.ConstrainedType<"string-min-3", "Ada">>
77
+ * }
78
+ *
79
+ * const username = UsernameMin.createOrThrow("Eve");
80
+ * // username: C.ConstrainedType<"string-min-3", "Eve">
81
+ *
82
+ * UsernameMin.is(username); // type guard
83
+ * ```
84
+ *
85
+ * @see https://utils.duplojs.dev/en/v1/api/clean/constraints
86
+ *
87
+ * @namespace C
88
+ *
89
+ */
90
+ export declare function StringMin<GenericValue extends number>(value: GenericValue & OnlyLiteralNumber<GenericValue>): import("..").ConstraintHandler<`string-min-${GenericValue & OnlyLiteralNumber<GenericValue>}`, string, readonly [DDataParser.DataParserCheckerStringMin]>;
91
+ export type StringMin<GenericValue extends number> = GetConstraint<ReturnType<typeof StringMin<GenericValue>>>;
92
+ /**
93
+ * Constraint factory that validates strings with a maximum length.
94
+ *
95
+ * **Supported call styles:**
96
+ * - Classic: `StringMax(max)` -> returns a constraint handler
97
+ *
98
+ * Creates a constraint handler for `C.String` that enforces a length less than or equal to `max`. Use it to validate inputs and to constrain NewTypes with a maximum length requirement.
99
+ *
100
+ * ```ts
101
+ * const TitleMax = C.StringMax(10);
102
+ *
103
+ * const result = TitleMax.create("Hello");
104
+ *
105
+ * if (E.isRight(result)) {
106
+ * // result: E.Right<"createConstrainedType", C.ConstrainedType<"string-max-10", "Hello">>
107
+ * }
108
+ *
109
+ * const title = TitleMax.createOrThrow("World");
110
+ * // title: C.ConstrainedType<"string-max-10", "World">
111
+ *
112
+ * TitleMax.is(title); // type guard
113
+ * ```
114
+ *
115
+ * @see https://utils.duplojs.dev/en/v1/api/clean/constraints
116
+ *
117
+ * @namespace C
118
+ *
119
+ */
120
+ export declare function StringMax<GenericValue extends number>(value: GenericValue & OnlyLiteralNumber<GenericValue>): import("..").ConstraintHandler<`string-max-${GenericValue & OnlyLiteralNumber<GenericValue>}`, string, readonly [DDataParser.DataParserCheckerStringMax]>;
121
+ export type StringMax<GenericValue extends number> = GetConstraint<ReturnType<typeof StringMax<GenericValue>>>;
@@ -2,6 +2,8 @@ import { createConstraint } from '../base.mjs';
2
2
  import { String } from '../../primitive/base.mjs';
3
3
  import { checkerEmail } from '../../../dataParser/parsers/string/checkers/email.mjs';
4
4
  import { checkerUrl } from '../../../dataParser/parsers/string/checkers/url.mjs';
5
+ import { checkerStringMin } from '../../../dataParser/parsers/string/checkers/min.mjs';
6
+ import { checkerStringMax } from '../../../dataParser/parsers/string/checkers/max.mjs';
5
7
 
6
8
  /**
7
9
  * {@include clean/Email/index.md}
@@ -11,5 +13,17 @@ const Email = createConstraint("email", String, checkerEmail());
11
13
  * {@include clean/Url/index.md}
12
14
  */
13
15
  const Url = createConstraint("url", String, checkerUrl());
16
+ /**
17
+ * {@include clean/StringMin/index.md}
18
+ */
19
+ function StringMin(value) {
20
+ return createConstraint(`string-min-${value}`, String, checkerStringMin(value));
21
+ }
22
+ /**
23
+ * {@include clean/StringMax/index.md}
24
+ */
25
+ function StringMax(value) {
26
+ return createConstraint(`string-max-${value}`, String, checkerStringMax(value));
27
+ }
14
28
 
15
- export { Email, Url };
29
+ export { Email, StringMax, StringMin, Url };
@@ -1,2 +1,3 @@
1
1
  export * from "./base";
2
2
  export * from "./defaultConstraint";
3
+ export * from "./set";
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+
3
+ var kind = require('../kind.cjs');
4
+ var base = require('./base.cjs');
5
+ var kind$1 = require('../../common/kind.cjs');
6
+ var flatMap = require('../../array/flatMap.cjs');
7
+ var coalescing = require('../../array/coalescing.cjs');
8
+ var pipe = require('../../common/pipe.cjs');
9
+ var map = require('../../array/map.cjs');
10
+ var entry = require('../../object/entry.cjs');
11
+ var errorKindNamespace = require('../../common/errorKindNamespace.cjs');
12
+ var is = require('../../either/left/is.cjs');
13
+ var unwrap = require('../../common/unwrap.cjs');
14
+ var create = require('../../either/left/create.cjs');
15
+ var create$1 = require('../../either/right/create.cjs');
16
+ var wrapValue = require('../../common/wrapValue.cjs');
17
+ var fromEntries = require('../../object/fromEntries.cjs');
18
+
19
+ const constraintsSetHandlerKind = kind.createCleanKind("constraints-set-handler");
20
+ class CreateConstraintsSetError extends kind$1.kindHeritage("create-constraint-set-error", errorKindNamespace.createErrorKind("create-constraint-set-error"), Error) {
21
+ data;
22
+ dataParserError;
23
+ constructor(data, dataParserError) {
24
+ super({}, ["Error when create constrained type with set."]);
25
+ this.data = data;
26
+ this.dataParserError = dataParserError;
27
+ }
28
+ }
29
+ /**
30
+ * {@include clean/createConstraintsSet/index.md}
31
+ */
32
+ function createConstraintsSet(primitiveHandler, constraint) {
33
+ const constraints = coalescing.coalescing(constraint);
34
+ const checkers = flatMap.flatMap(constraints, ({ checkers }) => checkers);
35
+ const dataParserWithCheckers = primitiveHandler
36
+ .dataParser
37
+ .addChecker(...checkers);
38
+ const constraintKindValue = pipe.pipe(constraints, map.map(({ name }) => entry.entry(name, null)), fromEntries.fromEntries);
39
+ const wrappedConstraints = pipe.pipe(constraints, map.map((constrain) => entry.entry(constrain.name, constrain)), fromEntries.fromEntries);
40
+ function getConstraint(name) {
41
+ return wrappedConstraints[name];
42
+ }
43
+ function create$2(data) {
44
+ const result = dataParserWithCheckers.parse(unwrap.unwrap(data));
45
+ if (is.isLeft(result)) {
46
+ return create.left("createConstraintsSetError", unwrap.unwrap(result));
47
+ }
48
+ else if (base.constrainedTypeKind.has(data)) {
49
+ return create$1.right("createConstraintsSet", base.constrainedTypeKind.addTo(data, {
50
+ ...base.constrainedTypeKind.getValue(data),
51
+ ...constraintKindValue,
52
+ }));
53
+ }
54
+ else {
55
+ return create$1.right("createConstraintsSet", base.constrainedTypeKind.setTo(wrapValue.wrapValue(unwrap.unwrap(result)), constraintKindValue));
56
+ }
57
+ }
58
+ function createOrThrow(data) {
59
+ const result = create$2(data);
60
+ if (is.isLeft(result)) {
61
+ throw new CreateConstraintsSetError(data, unwrap.unwrap(result));
62
+ }
63
+ else {
64
+ return unwrap.unwrap(result);
65
+ }
66
+ }
67
+ function is$1(input) {
68
+ if (!base.constrainedTypeKind.has(input)) {
69
+ return false;
70
+ }
71
+ // eslint-disable-next-line @typescript-eslint/prefer-for-of
72
+ for (let index = 0; index < constraints.length; index++) {
73
+ if (!constraints[index].is(input)) {
74
+ return false;
75
+ }
76
+ }
77
+ return true;
78
+ }
79
+ return constraintsSetHandlerKind.setTo({
80
+ primitiveHandler,
81
+ constrains: constraints,
82
+ getConstraint,
83
+ create: create$2,
84
+ createOrThrow,
85
+ createWithUnknown: create$2,
86
+ createWithUnknownOrThrow: createOrThrow,
87
+ is: is$1,
88
+ });
89
+ }
90
+
91
+ exports.CreateConstraintsSetError = CreateConstraintsSetError;
92
+ exports.constraintsSetHandlerKind = constraintsSetHandlerKind;
93
+ exports.createConstraintsSet = createConstraintsSet;
@@ -0,0 +1,144 @@
1
+ import { type Kind, type WrappedValue, type UnionToIntersection } from "../..";
2
+ import { type GetConstraint, type ConstraintHandler } from "../constraint";
3
+ import { type Primitive, type EligiblePrimitive, type PrimitiveHandler } from "../primitive";
4
+ import * as DEither from "../../either";
5
+ import * as DArray from "../../array";
6
+ import type * as DDataParser from "../../dataParser";
7
+ export declare const constraintsSetHandlerKind: import("../..").KindHandler<import("../..").KindDefinition<"@DuplojsUtilsClean/constraints-set-handler", unknown>>;
8
+ export interface ConstraintsSetHandler<GenericPrimitiveValue extends EligiblePrimitive = EligiblePrimitive, GenericConstrainsHandler extends readonly ConstraintHandler[] = readonly []> extends Kind<typeof constraintsSetHandlerKind.definition> {
9
+ /**
10
+ * The primitive handler used to validate and wrap values (e.g. `C.String`, `C.Number`).
11
+ *
12
+ */
13
+ readonly primitiveHandler: PrimitiveHandler<GenericPrimitiveValue>;
14
+ /**
15
+ * The list of constraint handlers applied by this set.
16
+ *
17
+ */
18
+ readonly constrains: GenericConstrainsHandler;
19
+ /**
20
+ * Creates a constrained value and returns an Either.
21
+ *
22
+ * ```ts
23
+ * const result = UsernameConstraints.create("Ada");
24
+ *
25
+ * if (E.isRight(result)) {
26
+ * // result: E.Right<"createConstraintsSet", C.Primitive<"Ada"> & C.GetConstraints<typeof UsernameConstraints>>
27
+ * }
28
+ * ```
29
+ *
30
+ */
31
+ create<const GenericInput extends GenericPrimitiveValue>(data: GenericInput): (DEither.Right<"createConstraintsSet", (Primitive<GenericInput> & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>)> | DEither.Left<"createConstraintsSetError", DDataParser.DataParserError>);
32
+ create<GenericPrimitive extends Primitive<GenericPrimitiveValue>>(data: GenericPrimitive): (DEither.Right<"createConstraintsSet", (GenericPrimitive & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>)> | DEither.Left<"createConstraintsSetError", DDataParser.DataParserError>);
33
+ /**
34
+ * Creates a constrained value and throws on error. Works with raw values or primitives.
35
+ *
36
+ * ```ts
37
+ * const value = UsernameConstraints.createOrThrow("Nova");
38
+ * // value: C.Primitive<"Nova"> & C.GetConstraints<typeof UsernameConstraints>
39
+ *
40
+ * const primitive = C.String.createOrThrow("Kit");
41
+ * UsernameConstraints.create(primitive);
42
+ * ```
43
+ *
44
+ */
45
+ createOrThrow<const GenericInput extends GenericPrimitiveValue>(data: GenericInput): (Primitive<GenericInput> & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>);
46
+ createOrThrow<GenericPrimitive extends Primitive<GenericPrimitiveValue>>(data: GenericPrimitive): (GenericPrimitive & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>);
47
+ /**
48
+ * Creates a constrained value from an unknown input and returns an Either.
49
+ *
50
+ * ```ts
51
+ * const unknownValue: unknown = "Sam";
52
+ * const maybe = UsernameConstraints.createWithUnknown(unknownValue);
53
+ * ```
54
+ *
55
+ */
56
+ createWithUnknown<GenericInput extends unknown>(data: GenericInput): (DEither.Right<"createConstraintsSet", (Primitive<GenericPrimitiveValue> & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>)> | DEither.Left<"createConstraintsSetError", DDataParser.DataParserError>);
57
+ /**
58
+ * Creates a constrained value from an unknown input and throws on error.
59
+ *
60
+ * ```ts
61
+ * const strictValue = UsernameConstraints.createWithUnknownOrThrow(unknownValue);
62
+ * ```
63
+ *
64
+ */
65
+ createWithUnknownOrThrow<GenericInput extends unknown>(data: GenericInput): (Primitive<GenericPrimitiveValue> & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>);
66
+ /**
67
+ * Checks if a value satisfies all constraints of the set (type guard).
68
+ *
69
+ * ```ts
70
+ * UsernameConstraints.is(value); // type guard
71
+ * ```
72
+ *
73
+ */
74
+ is<GenericInput extends WrappedValue>(input: GenericInput): input is Extract<GenericInput, (Primitive<GenericPrimitiveValue> & UnionToIntersection<GenericConstrainsHandler[number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never>)>;
75
+ /**
76
+ * Returns a constraint handler by name from the constraints set.
77
+ *
78
+ * ```ts
79
+ * const constraint = UsernameConstraints.getConstraint("string-max-16");
80
+ * constraint.createOrThrow("hello");
81
+ * ```
82
+ *
83
+ */
84
+ getConstraint<GenericConstraintName extends GenericConstrainsHandler[number]["name"]>(name: GenericConstraintName): Extract<GenericConstrainsHandler[number], ConstraintHandler<GenericConstraintName>>;
85
+ }
86
+ declare const CreateConstraintsSetError_base: new (params: {
87
+ "@DuplojsUtilsError/create-constraint-set-error"?: unknown;
88
+ }, parentParams: readonly [message?: string | undefined, options?: ErrorOptions | undefined]) => Error & Kind<import("../..").KindDefinition<"create-constraint-set-error", unknown>, unknown> & Kind<import("../..").KindDefinition<"@DuplojsUtilsError/create-constraint-set-error", unknown>, unknown>;
89
+ export declare class CreateConstraintsSetError extends CreateConstraintsSetError_base {
90
+ data: unknown;
91
+ dataParserError: DDataParser.DataParserError;
92
+ constructor(data: unknown, dataParserError: DDataParser.DataParserError);
93
+ }
94
+ /**
95
+ * Creates a constraints set handler to apply multiple constraints to a primitive.
96
+ *
97
+ * **Supported call styles:**
98
+ * - Classic: `createConstraintsSet(primitiveHandler, constraints)` -> returns a handler
99
+ *
100
+ * A constraints set validates input with the primitive DataParser, applies all constraint checkers, and tags the value with each constraint name. Use it to compose multiple constraints once and reuse the handler.
101
+ *
102
+ * ```ts
103
+ * const UsernameConstraints = C.createConstraintsSet(
104
+ * C.String,
105
+ * [C.StringMin(3), C.StringMax(16)],
106
+ * );
107
+ *
108
+ * const result = UsernameConstraints.create("Ada");
109
+ *
110
+ * if (E.isRight(result)) {
111
+ * // result: E.Right<"createConstraintsSet", C.Primitive<"Ada"> & C.GetConstraints<typeof UsernameConstraints>>
112
+ * }
113
+ *
114
+ * const value = UsernameConstraints.createOrThrow("Nova");
115
+ * // value: C.Primitive<"Nova"> & C.GetConstraints<typeof UsernameConstraints>
116
+ *
117
+ * const primitive = C.String.createOrThrow("Kit");
118
+ * UsernameConstraints.create(primitive);
119
+ *
120
+ * const unknownValue: unknown = "Sam";
121
+ * const maybe = UsernameConstraints.createWithUnknown(unknownValue);
122
+ * const strictValue = UsernameConstraints.createWithUnknownOrThrow(unknownValue);
123
+ *
124
+ * UsernameConstraints.is(value); // type guard
125
+ *
126
+ * const constraint = UsernameConstraints.getConstraint("string-max-16");
127
+ * constraint.createOrThrow("hello");
128
+ * ```
129
+ *
130
+ * @remarks
131
+ * - You can pass a single constraint handler or a tuple of constraints.
132
+ * - The handler accepts both raw values and primitives.
133
+ *
134
+ * @see https://utils.duplojs.dev/en/v1/api/clean/constraints
135
+ *
136
+ * @namespace C
137
+ *
138
+ */
139
+ export declare function createConstraintsSet<GenericPrimitiveValue extends EligiblePrimitive, const GenericConstrainHandler extends (ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, GenericPrimitiveValue>[]> | readonly [
140
+ ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, GenericPrimitiveValue>[]>,
141
+ ...ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, GenericPrimitiveValue>[]>[]
142
+ ]) = never>(primitiveHandler: PrimitiveHandler<GenericPrimitiveValue>, constraint: GenericConstrainHandler): ConstraintsSetHandler<GenericPrimitiveValue, DArray.ArrayCoalescing<GenericConstrainHandler>>;
143
+ export type GetConstraints<GenericHandler extends ConstraintsSetHandler<string, readonly any[]>> = Extract<GenericHandler extends any ? UnionToIntersection<GenericHandler["constrains"][number] extends infer InferredConstraint ? InferredConstraint extends ConstraintHandler ? GetConstraint<InferredConstraint> : never : never> : never, any>;
144
+ export {};
@@ -0,0 +1,89 @@
1
+ import { createCleanKind } from '../kind.mjs';
2
+ import { constrainedTypeKind } from './base.mjs';
3
+ import { kindHeritage } from '../../common/kind.mjs';
4
+ import { flatMap } from '../../array/flatMap.mjs';
5
+ import { coalescing } from '../../array/coalescing.mjs';
6
+ import { pipe } from '../../common/pipe.mjs';
7
+ import { map } from '../../array/map.mjs';
8
+ import { entry } from '../../object/entry.mjs';
9
+ import { createErrorKind } from '../../common/errorKindNamespace.mjs';
10
+ import { isLeft } from '../../either/left/is.mjs';
11
+ import { unwrap } from '../../common/unwrap.mjs';
12
+ import { left } from '../../either/left/create.mjs';
13
+ import { right } from '../../either/right/create.mjs';
14
+ import { wrapValue } from '../../common/wrapValue.mjs';
15
+ import { fromEntries } from '../../object/fromEntries.mjs';
16
+
17
+ const constraintsSetHandlerKind = createCleanKind("constraints-set-handler");
18
+ class CreateConstraintsSetError extends kindHeritage("create-constraint-set-error", createErrorKind("create-constraint-set-error"), Error) {
19
+ data;
20
+ dataParserError;
21
+ constructor(data, dataParserError) {
22
+ super({}, ["Error when create constrained type with set."]);
23
+ this.data = data;
24
+ this.dataParserError = dataParserError;
25
+ }
26
+ }
27
+ /**
28
+ * {@include clean/createConstraintsSet/index.md}
29
+ */
30
+ function createConstraintsSet(primitiveHandler, constraint) {
31
+ const constraints = coalescing(constraint);
32
+ const checkers = flatMap(constraints, ({ checkers }) => checkers);
33
+ const dataParserWithCheckers = primitiveHandler
34
+ .dataParser
35
+ .addChecker(...checkers);
36
+ const constraintKindValue = pipe(constraints, map(({ name }) => entry(name, null)), fromEntries);
37
+ const wrappedConstraints = pipe(constraints, map((constrain) => entry(constrain.name, constrain)), fromEntries);
38
+ function getConstraint(name) {
39
+ return wrappedConstraints[name];
40
+ }
41
+ function create(data) {
42
+ const result = dataParserWithCheckers.parse(unwrap(data));
43
+ if (isLeft(result)) {
44
+ return left("createConstraintsSetError", unwrap(result));
45
+ }
46
+ else if (constrainedTypeKind.has(data)) {
47
+ return right("createConstraintsSet", constrainedTypeKind.addTo(data, {
48
+ ...constrainedTypeKind.getValue(data),
49
+ ...constraintKindValue,
50
+ }));
51
+ }
52
+ else {
53
+ return right("createConstraintsSet", constrainedTypeKind.setTo(wrapValue(unwrap(result)), constraintKindValue));
54
+ }
55
+ }
56
+ function createOrThrow(data) {
57
+ const result = create(data);
58
+ if (isLeft(result)) {
59
+ throw new CreateConstraintsSetError(data, unwrap(result));
60
+ }
61
+ else {
62
+ return unwrap(result);
63
+ }
64
+ }
65
+ function is(input) {
66
+ if (!constrainedTypeKind.has(input)) {
67
+ return false;
68
+ }
69
+ // eslint-disable-next-line @typescript-eslint/prefer-for-of
70
+ for (let index = 0; index < constraints.length; index++) {
71
+ if (!constraints[index].is(input)) {
72
+ return false;
73
+ }
74
+ }
75
+ return true;
76
+ }
77
+ return constraintsSetHandlerKind.setTo({
78
+ primitiveHandler,
79
+ constrains: constraints,
80
+ getConstraint,
81
+ create,
82
+ createOrThrow,
83
+ createWithUnknown: create,
84
+ createWithUnknownOrThrow: createOrThrow,
85
+ is,
86
+ });
87
+ }
88
+
89
+ export { CreateConstraintsSetError, constraintsSetHandlerKind, createConstraintsSet };
@@ -10,6 +10,7 @@ var unwrapEntity = require('./unwrapEntity.cjs');
10
10
  var base = require('./constraint/base.cjs');
11
11
  var number = require('./constraint/defaultConstraint/number.cjs');
12
12
  var string = require('./constraint/defaultConstraint/string.cjs');
13
+ var set = require('./constraint/set.cjs');
13
14
  var base$1 = require('./primitive/base.cjs');
14
15
  var equal = require('./primitive/operations/equal.cjs');
15
16
  var add = require('./primitive/operations/number/add.cjs');
@@ -63,9 +64,16 @@ exports.constraintHandlerKind = base.constraintHandlerKind;
63
64
  exports.createConstraint = base.createConstraint;
64
65
  exports.Int = number.Int;
65
66
  exports.Negative = number.Negative;
67
+ exports.NumberMax = number.NumberMax;
68
+ exports.NumberMin = number.NumberMin;
66
69
  exports.Positive = number.Positive;
67
70
  exports.Email = string.Email;
71
+ exports.StringMax = string.StringMax;
72
+ exports.StringMin = string.StringMin;
68
73
  exports.Url = string.Url;
74
+ exports.CreateConstraintsSetError = set.CreateConstraintsSetError;
75
+ exports.constraintsSetHandlerKind = set.constraintsSetHandlerKind;
76
+ exports.createConstraintsSet = set.createConstraintsSet;
69
77
  exports.BigInt = base$1.BigInt;
70
78
  exports.Boolean = base$1.Boolean;
71
79
  exports.CreatePrimitiveError = base$1.CreatePrimitiveError;
@@ -6,8 +6,9 @@ export { createUseCase, useCaseHandlerKind, useCaseInstances } from './useCase.m
6
6
  export { createFlag, flagKind } from './flag.mjs';
7
7
  export { unwrapEntity } from './unwrapEntity.mjs';
8
8
  export { CreateConstrainedTypeError, constrainedTypeKind, constraintHandlerKind, createConstraint } from './constraint/base.mjs';
9
- export { Int, Negative, Positive } from './constraint/defaultConstraint/number.mjs';
10
- export { Email, Url } from './constraint/defaultConstraint/string.mjs';
9
+ export { Int, Negative, NumberMax, NumberMin, Positive } from './constraint/defaultConstraint/number.mjs';
10
+ export { Email, StringMax, StringMin, Url } from './constraint/defaultConstraint/string.mjs';
11
+ export { CreateConstraintsSetError, constraintsSetHandlerKind, createConstraintsSet } from './constraint/set.mjs';
11
12
  export { BigInt, Boolean, CreatePrimitiveError, Date, Number, String, Time, primitiveHandlerKind } from './primitive/base.mjs';
12
13
  export { equal } from './primitive/operations/equal.mjs';
13
14
  export { add } from './primitive/operations/number/add.mjs';
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  var kind = require('./kind.cjs');
4
- var base = require('./constraint/base.cjs');
5
4
  var kind$1 = require('../common/kind.cjs');
6
5
  var flatMap = require('../array/flatMap.cjs');
7
6
  var coalescing = require('../array/coalescing.cjs');
@@ -12,6 +11,7 @@ var errorKindNamespace = require('../common/errorKindNamespace.cjs');
12
11
  var is = require('../either/left/is.cjs');
13
12
  var unwrap = require('../common/unwrap.cjs');
14
13
  var create = require('../either/left/create.cjs');
14
+ var base = require('./constraint/base.cjs');
15
15
  var create$1 = require('../either/right/create.cjs');
16
16
  var wrapValue = require('../common/wrapValue.cjs');
17
17
  var fromEntries = require('../object/fromEntries.cjs');
@@ -33,12 +33,16 @@ class CreateNewTypeError extends kind$1.kindHeritage("create-new-type-error", er
33
33
  * {@include clean/createNewType/index.md}
34
34
  */
35
35
  function createNewType(name, dataParser, constraint) {
36
- const constrains = coalescing.coalescing(constraint ?? []);
37
- const checkers = flatMap.flatMap(constrains, ({ checkers }) => checkers);
36
+ const constraints = coalescing.coalescing(constraint ?? []);
37
+ const checkers = flatMap.flatMap(constraints, ({ checkers }) => checkers);
38
38
  const dataParserWithCheckers = constraint
39
39
  ? dataParser.addChecker(...checkers)
40
40
  : dataParser;
41
- const constraintKindValue = pipe.pipe(constrains, map.map(({ name }) => entry.entry(name, null)), fromEntries.fromEntries);
41
+ const constraintKindValue = pipe.pipe(constraints, map.map(({ name }) => entry.entry(name, null)), fromEntries.fromEntries);
42
+ const wrappedConstraints = pipe.pipe(constraints, map.map((constrain) => entry.entry(constrain.name, constrain)), fromEntries.fromEntries);
43
+ function getConstraint(name) {
44
+ return wrappedConstraints[name];
45
+ }
42
46
  function create$2(data) {
43
47
  const result = dataParserWithCheckers.parse(unwrap.unwrap(data));
44
48
  if (is.isLeft(result)) {
@@ -69,8 +73,8 @@ function createNewType(name, dataParser, constraint) {
69
73
  return false;
70
74
  }
71
75
  // eslint-disable-next-line @typescript-eslint/prefer-for-of
72
- for (let index = 0; index < constrains.length; index++) {
73
- if (!constrains[index].is(input)) {
76
+ for (let index = 0; index < constraints.length; index++) {
77
+ if (!constraints[index].is(input)) {
74
78
  return false;
75
79
  }
76
80
  }
@@ -79,7 +83,8 @@ function createNewType(name, dataParser, constraint) {
79
83
  return newTypeHandlerKind.setTo({
80
84
  name,
81
85
  dataParser: dataParserWithCheckers,
82
- constrains,
86
+ constrains: constraints,
87
+ getConstraint,
83
88
  create: create$2,
84
89
  createOrThrow,
85
90
  createWithUnknown: create$2,
@@ -6,11 +6,11 @@ import * as DArray from "../array";
6
6
  import type * as DDataParser from "../dataParser";
7
7
  import { type DataParserContainTransform } from "./types";
8
8
  export declare const newTypeKind: import("..").KindHandler<import("..").KindDefinition<"@DuplojsUtilsClean/new-type", string>>;
9
- type _NewType<GenericName extends string, GenericValue extends unknown, GenericConstrainName extends string> = (Kind<typeof newTypeKind.definition, GenericName> & Kind<typeof constrainedTypeKind.definition, Record<GenericConstrainName, unknown>> & WrappedValue<GenericValue>);
10
- export interface NewType<GenericName extends string = string, GenericValue extends unknown = unknown, GenericConstrainName extends string = never> extends _NewType<GenericName, GenericValue, GenericConstrainName> {
9
+ type _NewType<GenericName extends string, GenericValue extends unknown, GenericConstraintsName extends string> = (Kind<typeof newTypeKind.definition, GenericName> & Kind<typeof constrainedTypeKind.definition, Record<GenericConstraintsName, unknown>> & WrappedValue<GenericValue>);
10
+ export interface NewType<GenericName extends string = string, GenericValue extends unknown = unknown, GenericConstraintsName extends string = never> extends _NewType<GenericName, GenericValue, GenericConstraintsName> {
11
11
  }
12
12
  export declare const newTypeHandlerKind: import("..").KindHandler<import("..").KindDefinition<"@DuplojsUtilsClean/new-type-handler", unknown>>;
13
- export interface NewTypeHandler<GenericName extends string = string, GenericValue extends unknown = unknown, GenericConstrainHandler extends readonly ConstraintHandler[] = readonly []> extends Kind<typeof newTypeHandlerKind.definition> {
13
+ export interface NewTypeHandler<GenericName extends string = string, GenericValue extends unknown = unknown, GenericConstraintsHandler extends readonly ConstraintHandler[] = readonly []> extends Kind<typeof newTypeHandlerKind.definition> {
14
14
  /**
15
15
  * The NewType name used as the brand (for example "userId").
16
16
  *
@@ -25,7 +25,7 @@ export interface NewTypeHandler<GenericName extends string = string, GenericValu
25
25
  * The list of constraints applied to this NewType.
26
26
  *
27
27
  */
28
- readonly constrains: GenericConstrainHandler;
28
+ readonly constrains: GenericConstraintsHandler;
29
29
  /**
30
30
  * Creates a NewType value and returns an Either.
31
31
  *
@@ -34,8 +34,8 @@ export interface NewTypeHandler<GenericName extends string = string, GenericValu
34
34
  * ```
35
35
  *
36
36
  */
37
- create<const GenericData extends GenericValue>(data: GenericData): (DEither.Right<"createNewType", NewType<GenericName, GenericData, GenericConstrainHandler[number]["name"]>> | DEither.Left<"createNewTypeError", DDataParser.DataParserError>);
38
- create<GenericPrimitive extends Primitive<Extract<GenericValue, EligiblePrimitive>>>(data: GenericPrimitive): (DEither.Right<"createNewType", (GenericPrimitive & NewType<GenericName, Unwrap<GenericPrimitive>, GenericConstrainHandler[number]["name"]>)> | DEither.Left<"createNewTypeError", DDataParser.DataParserError>);
37
+ create<const GenericInput extends GenericValue>(data: GenericInput): (DEither.Right<"createNewType", NewType<GenericName, GenericInput, GenericConstraintsHandler[number]["name"]>> | DEither.Left<"createNewTypeError", DDataParser.DataParserError>);
38
+ create<GenericPrimitive extends Primitive<Extract<GenericValue, EligiblePrimitive>>>(data: GenericPrimitive): (DEither.Right<"createNewType", (GenericPrimitive & NewType<GenericName, Unwrap<GenericPrimitive>, GenericConstraintsHandler[number]["name"]>)> | DEither.Left<"createNewTypeError", DDataParser.DataParserError>);
39
39
  /**
40
40
  * Creates a NewType value and throws on error. Works with raw values or primitives.
41
41
  *
@@ -50,8 +50,8 @@ export interface NewTypeHandler<GenericName extends string = string, GenericValu
50
50
  * ```
51
51
  *
52
52
  */
53
- createOrThrow<const GenericData extends GenericValue>(data: GenericData): NewType<GenericName, GenericData, GenericConstrainHandler[number]["name"]>;
54
- createOrThrow<GenericPrimitive extends Primitive<Extract<GenericValue, EligiblePrimitive>>>(data: GenericPrimitive): (GenericPrimitive & NewType<GenericName, Unwrap<GenericPrimitive>, GenericConstrainHandler[number]["name"]>);
53
+ createOrThrow<const GenericData extends GenericValue>(data: GenericData): NewType<GenericName, GenericData, GenericConstraintsHandler[number]["name"]>;
54
+ createOrThrow<GenericPrimitive extends Primitive<Extract<GenericValue, EligiblePrimitive>>>(data: GenericPrimitive): (GenericPrimitive & NewType<GenericName, Unwrap<GenericPrimitive>, GenericConstraintsHandler[number]["name"]>);
55
55
  /**
56
56
  * Creates a NewType value from an unknown input and returns an Either.
57
57
  *
@@ -65,7 +65,7 @@ export interface NewTypeHandler<GenericName extends string = string, GenericValu
65
65
  * ```
66
66
  *
67
67
  */
68
- createWithUnknown<GenericData extends unknown>(data: GenericData): (DEither.Right<"createNewType", NewType<GenericName, GenericValue, GenericConstrainHandler[number]["name"]>> | DEither.Left<"createNewTypeError", DDataParser.DataParserError>);
68
+ createWithUnknown<GenericInput extends unknown>(data: GenericInput): (DEither.Right<"createNewType", NewType<GenericName, GenericValue, GenericConstraintsHandler[number]["name"]>> | DEither.Left<"createNewTypeError", DDataParser.DataParserError>);
69
69
  /**
70
70
  * Creates a NewType value from an unknown input and throws on error.
71
71
  *
@@ -74,7 +74,7 @@ export interface NewTypeHandler<GenericName extends string = string, GenericValu
74
74
  * ```
75
75
  *
76
76
  */
77
- createWithUnknownOrThrow<GenericData extends unknown>(data: GenericData): NewType<GenericName, GenericValue, GenericConstrainHandler[number]["name"]>;
77
+ createWithUnknownOrThrow<GenericInput extends unknown>(data: GenericInput): NewType<GenericName, GenericValue, GenericConstraintsHandler[number]["name"]>;
78
78
  /**
79
79
  * Checks if a value is a NewType of this handler (type guard).
80
80
  *
@@ -83,7 +83,17 @@ export interface NewTypeHandler<GenericName extends string = string, GenericValu
83
83
  * ```
84
84
  *
85
85
  */
86
- is<GenericInput extends WrappedValue>(input: GenericInput): input is Extract<GenericInput, NewType<GenericName, GenericValue, GenericConstrainHandler[number]["name"]>>;
86
+ is<GenericInput extends WrappedValue>(input: GenericInput): input is Extract<GenericInput, NewType<GenericName, GenericValue, GenericConstraintsHandler[number]["name"]>>;
87
+ /**
88
+ * Returns a constraint handler by name from the NewType constraints list.
89
+ *
90
+ * ```ts
91
+ * const constraint = UserId.getConstraint("positive");
92
+ * constraint.createOrThrow(1);
93
+ * ```
94
+ *
95
+ */
96
+ getConstraint<GenericConstraintName extends GenericConstraintsHandler[number]["name"]>(name: GenericConstraintName): Extract<GenericConstraintsHandler[number], ConstraintHandler<GenericConstraintName>>;
87
97
  }
88
98
  declare const CreateNewTypeError_base: new (params: {
89
99
  "@DuplojsUtilsError/create-new-type-error"?: unknown;
@@ -137,9 +147,9 @@ export declare class CreateNewTypeError extends CreateNewTypeError_base {
137
147
  * @namespace C
138
148
  *
139
149
  */
140
- export declare function createNewType<GenericName extends string, GenericDataParser extends DDataParser.DataParser, const GenericConstrainHandler extends (ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, DDataParser.Output<GenericDataParser>>[]> | readonly [
150
+ export declare function createNewType<GenericName extends string, GenericDataParser extends DDataParser.DataParser, const GenericConstraintsHandler extends (ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, DDataParser.Output<GenericDataParser>>[]> | readonly [
141
151
  ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, DDataParser.Output<GenericDataParser>>[]>,
142
152
  ...ConstraintHandler<string, EligiblePrimitive, readonly DDataParser.DataParserChecker<DDataParser.DataParserCheckerDefinition, DDataParser.Output<GenericDataParser>>[]>[]
143
- ]) = never>(name: GenericName, dataParser: GenericDataParser & DataParserContainTransform<GenericDataParser>, constraint?: GenericConstrainHandler): NewTypeHandler<GenericName, DeepReadonly<DDataParser.Output<GenericDataParser>>, DArray.ArrayCoalescing<NeverCoalescing<GenericConstrainHandler, readonly []>>>;
153
+ ]) = never>(name: GenericName, dataParser: GenericDataParser & DataParserContainTransform<GenericDataParser>, constraint?: GenericConstraintsHandler): NewTypeHandler<GenericName, DeepReadonly<DDataParser.Output<GenericDataParser>>, DArray.ArrayCoalescing<NeverCoalescing<GenericConstraintsHandler, readonly []>>>;
144
154
  export type GetNewType<GenericHandler extends NewTypeHandler<string, unknown, readonly any[]>> = Extract<GenericHandler extends any ? NewType<GenericHandler["name"], DDataParser.Output<GenericHandler["dataParser"]>, GenericHandler["constrains"][number]["name"]> : never, any>;
145
155
  export {};
@@ -1,5 +1,4 @@
1
1
  import { createCleanKind } from './kind.mjs';
2
- import { constrainedTypeKind } from './constraint/base.mjs';
3
2
  import { kindHeritage } from '../common/kind.mjs';
4
3
  import { flatMap } from '../array/flatMap.mjs';
5
4
  import { coalescing } from '../array/coalescing.mjs';
@@ -10,6 +9,7 @@ import { createErrorKind } from '../common/errorKindNamespace.mjs';
10
9
  import { isLeft } from '../either/left/is.mjs';
11
10
  import { unwrap } from '../common/unwrap.mjs';
12
11
  import { left } from '../either/left/create.mjs';
12
+ import { constrainedTypeKind } from './constraint/base.mjs';
13
13
  import { right } from '../either/right/create.mjs';
14
14
  import { wrapValue } from '../common/wrapValue.mjs';
15
15
  import { fromEntries } from '../object/fromEntries.mjs';
@@ -31,12 +31,16 @@ class CreateNewTypeError extends kindHeritage("create-new-type-error", createErr
31
31
  * {@include clean/createNewType/index.md}
32
32
  */
33
33
  function createNewType(name, dataParser, constraint) {
34
- const constrains = coalescing(constraint ?? []);
35
- const checkers = flatMap(constrains, ({ checkers }) => checkers);
34
+ const constraints = coalescing(constraint ?? []);
35
+ const checkers = flatMap(constraints, ({ checkers }) => checkers);
36
36
  const dataParserWithCheckers = constraint
37
37
  ? dataParser.addChecker(...checkers)
38
38
  : dataParser;
39
- const constraintKindValue = pipe(constrains, map(({ name }) => entry(name, null)), fromEntries);
39
+ const constraintKindValue = pipe(constraints, map(({ name }) => entry(name, null)), fromEntries);
40
+ const wrappedConstraints = pipe(constraints, map((constrain) => entry(constrain.name, constrain)), fromEntries);
41
+ function getConstraint(name) {
42
+ return wrappedConstraints[name];
43
+ }
40
44
  function create(data) {
41
45
  const result = dataParserWithCheckers.parse(unwrap(data));
42
46
  if (isLeft(result)) {
@@ -67,8 +71,8 @@ function createNewType(name, dataParser, constraint) {
67
71
  return false;
68
72
  }
69
73
  // eslint-disable-next-line @typescript-eslint/prefer-for-of
70
- for (let index = 0; index < constrains.length; index++) {
71
- if (!constrains[index].is(input)) {
74
+ for (let index = 0; index < constraints.length; index++) {
75
+ if (!constraints[index].is(input)) {
72
76
  return false;
73
77
  }
74
78
  }
@@ -77,7 +81,8 @@ function createNewType(name, dataParser, constraint) {
77
81
  return newTypeHandlerKind.setTo({
78
82
  name,
79
83
  dataParser: dataParserWithCheckers,
80
- constrains,
84
+ constrains: constraints,
85
+ getConstraint,
81
86
  create,
82
87
  createOrThrow,
83
88
  createWithUnknown: create,
@@ -42,6 +42,7 @@ export * from "./toJSON";
42
42
  export * from "./toTransform";
43
43
  export * from "./toWrappedValue";
44
44
  export * from "./unwrap";
45
+ export * from "./unwrapGroup";
45
46
  export * from "./asyncLoop";
46
47
  export * from "./asyncRetry";
47
48
  export * from "./wrapValue";
@@ -59,6 +60,7 @@ export * from "./or";
59
60
  export * from "./whenElse";
60
61
  export * from "./justReturn";
61
62
  export * from "./memo";
63
+ export * from "./memoPromise";
62
64
  export * from "./instanceOf";
63
65
  export * from "./globalStore";
64
66
  export * from "./builder";
@@ -1,13 +1,12 @@
1
- import { type AnyValue } from "./types";
2
1
  export interface Memoized<GenericValue extends unknown> {
3
2
  readonly value: GenericValue;
4
3
  }
5
4
  /**
6
- * The memo() function evaluates a function only once then memorizes the result. Subsequent calls return the same value without recalculation.
5
+ * The memo() function evaluates a function only once then memorizes the result. The first access to `value` triggers the evaluation.
7
6
  *
8
- * Signature: `memo(theFunction)` → returns a value
7
+ * Signature: `memo(theFunction)` → returns a memoized object
9
8
  *
10
- * The input value is not mutated.
9
+ * The input function is called only once.
11
10
  *
12
11
  * ```ts
13
12
  * let calls = 0;
@@ -25,4 +24,4 @@ export interface Memoized<GenericValue extends unknown> {
25
24
  * @see https://utils.duplojs.dev/en/v1/api/common/memo
26
25
  *
27
26
  */
28
- export declare function memo<GenericOutput extends AnyValue>(theFunction: () => GenericOutput): Memoized<GenericOutput>;
27
+ export declare function memo<GenericOutput extends unknown>(theFunction: () => GenericOutput): Memoized<GenericOutput>;
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ var externalPromise = require('./externalPromise.cjs');
4
+ var forward = require('./forward.cjs');
5
+
6
+ /**
7
+ * {@include common/memoPromise/index.md}
8
+ */
9
+ function memoPromise(theFunction) {
10
+ let externalPromise$1 = forward.forward(undefined);
11
+ const payload = {
12
+ get value() {
13
+ if (externalPromise$1) {
14
+ return externalPromise$1.promise;
15
+ }
16
+ externalPromise$1 = externalPromise.createExternalPromise();
17
+ const { resolve, reject } = externalPromise$1;
18
+ const promise = theFunction();
19
+ void (promise instanceof Promise
20
+ ? promise
21
+ : Promise.resolve(promise))
22
+ .then((result) => {
23
+ Object.defineProperty(payload, "value", {
24
+ value: result,
25
+ });
26
+ resolve(result);
27
+ })
28
+ .catch(reject);
29
+ return externalPromise$1.promise;
30
+ },
31
+ };
32
+ return payload;
33
+ }
34
+
35
+ exports.memoPromise = memoPromise;
@@ -0,0 +1,25 @@
1
+ import { type MaybePromise } from "./types";
2
+ export interface MemoizedPromise<GenericValue extends unknown> {
3
+ readonly value: MaybePromise<GenericValue>;
4
+ }
5
+ /**
6
+ * The memoPromise() function lazily evaluates a function that returns a value or a promise, then memoizes the resolved result.
7
+ *
8
+ * Signature: `memoPromise(theFunction)` → returns a memoized object
9
+ *
10
+ * The input function is called only once, and concurrent reads share the same promise.
11
+ *
12
+ * ```ts
13
+ * const memoizedValue = memoPromise(() => "ready");
14
+ * const first = await memoizedValue.value;
15
+ * // "ready"
16
+ *
17
+ * const memoizedPromise = memoPromise(() => Promise.resolve("ok"));
18
+ * const okValue = await memoizedPromise.value;
19
+ * // "ok"
20
+ * ```
21
+ *
22
+ * @see https://utils.duplojs.dev/en/v1/api/common/memoPromise
23
+ *
24
+ */
25
+ export declare function memoPromise<GenericOutput extends unknown>(theFunction: () => MaybePromise<GenericOutput>): MemoizedPromise<GenericOutput>;
@@ -0,0 +1,33 @@
1
+ import { createExternalPromise } from './externalPromise.mjs';
2
+ import { forward } from './forward.mjs';
3
+
4
+ /**
5
+ * {@include common/memoPromise/index.md}
6
+ */
7
+ function memoPromise(theFunction) {
8
+ let externalPromise = forward(undefined);
9
+ const payload = {
10
+ get value() {
11
+ if (externalPromise) {
12
+ return externalPromise.promise;
13
+ }
14
+ externalPromise = createExternalPromise();
15
+ const { resolve, reject } = externalPromise;
16
+ const promise = theFunction();
17
+ void (promise instanceof Promise
18
+ ? promise
19
+ : Promise.resolve(promise))
20
+ .then((result) => {
21
+ Object.defineProperty(payload, "value", {
22
+ value: result,
23
+ });
24
+ resolve(result);
25
+ })
26
+ .catch(reject);
27
+ return externalPromise.promise;
28
+ },
29
+ };
30
+ return payload;
31
+ }
32
+
33
+ export { memoPromise };
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ var unwrap = require('./unwrap.cjs');
4
+
5
+ /**
6
+ * {@include common/unwrapGroup/index.md}
7
+ */
8
+ function unwrapGroup(group) {
9
+ const result = {};
10
+ for (const key in group) {
11
+ result[key] = unwrap.unwrap(group[key]);
12
+ }
13
+ return result;
14
+ }
15
+
16
+ exports.unwrapGroup = unwrapGroup;
@@ -0,0 +1,36 @@
1
+ import { type SimplifyTopLevel } from "./types";
2
+ import { type Unwrap } from "./unwrap";
3
+ type ComputeResult<GenericGroup extends Record<string, unknown>> = SimplifyTopLevel<{
4
+ [Prop in keyof GenericGroup]: Unwrap<GenericGroup[Prop]>;
5
+ }>;
6
+ /**
7
+ * The unwrapGroup() function unwraps every value of an object using unwrap(), returning a new object with the same keys.
8
+ *
9
+ * Signature: `unwrapGroup(group)` → returns an object
10
+ *
11
+ * The input object is not mutated.
12
+ *
13
+ * ```ts
14
+ * const first = unwrapGroup({
15
+ * value: wrapValue(1),
16
+ * });
17
+ * // { value: 1 }
18
+ *
19
+ * const mixed = unwrapGroup({
20
+ * count: wrapValue(2),
21
+ * label: "ok",
22
+ * });
23
+ * // { count: 2, label: "ok" }
24
+ *
25
+ * const user = unwrapGroup({
26
+ * firstName: wrapValue("Ada"),
27
+ * lastName: "Lovelace",
28
+ * });
29
+ * // { firstName: "Ada", lastName: "Lovelace" }
30
+ * ```
31
+ *
32
+ * @see https://utils.duplojs.dev/en/v1/api/common/unwrapGroup
33
+ *
34
+ */
35
+ export declare function unwrapGroup<const GenericGroup extends Record<string, unknown>>(group: GenericGroup): ComputeResult<GenericGroup>;
36
+ export {};
@@ -0,0 +1,14 @@
1
+ import { unwrap } from './unwrap.mjs';
2
+
3
+ /**
4
+ * {@include common/unwrapGroup/index.md}
5
+ */
6
+ function unwrapGroup(group) {
7
+ const result = {};
8
+ for (const key in group) {
9
+ result[key] = unwrap(group[key]);
10
+ }
11
+ return result;
12
+ }
13
+
14
+ export { unwrapGroup };
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ var toJSON = require('./common/toJSON.cjs');
31
31
  var toTransform = require('./common/toTransform.cjs');
32
32
  var toWrappedValue = require('./common/toWrappedValue.cjs');
33
33
  var unwrap = require('./common/unwrap.cjs');
34
+ var unwrapGroup = require('./common/unwrapGroup.cjs');
34
35
  var asyncLoop = require('./common/asyncLoop.cjs');
35
36
  var asyncRetry = require('./common/asyncRetry.cjs');
36
37
  var wrapValue = require('./common/wrapValue.cjs');
@@ -48,6 +49,7 @@ var or = require('./common/or.cjs');
48
49
  var whenElse = require('./common/whenElse.cjs');
49
50
  var justReturn = require('./common/justReturn.cjs');
50
51
  var memo = require('./common/memo.cjs');
52
+ var memoPromise = require('./common/memoPromise.cjs');
51
53
  var instanceOf = require('./common/instanceOf.cjs');
52
54
  var globalStore = require('./common/globalStore.cjs');
53
55
  var builder = require('./common/builder.cjs');
@@ -115,6 +117,7 @@ exports.toJSON = toJSON.toJSON;
115
117
  exports.toTransform = toTransform.toTransform;
116
118
  exports.toWrappedValue = toWrappedValue.toWrappedValue;
117
119
  exports.unwrap = unwrap.unwrap;
120
+ exports.unwrapGroup = unwrapGroup.unwrapGroup;
118
121
  exports.asyncLoop = asyncLoop.asyncLoop;
119
122
  exports.createAsyncRetry = asyncRetry.createAsyncRetry;
120
123
  exports.useAsyncRetry = asyncRetry.useAsyncRetry;
@@ -136,6 +139,7 @@ exports.or = or.or;
136
139
  exports.whenElse = whenElse.whenElse;
137
140
  exports.justReturn = justReturn.justReturn;
138
141
  exports.memo = memo.memo;
142
+ exports.memoPromise = memoPromise.memoPromise;
139
143
  exports.instanceOf = instanceOf.instanceOf;
140
144
  exports.createGlobalStore = globalStore.createGlobalStore;
141
145
  exports.MissingBuilderMethodsError = builder.MissingBuilderMethodsError;
package/dist/index.mjs CHANGED
@@ -53,6 +53,7 @@ export { toJSON } from './common/toJSON.mjs';
53
53
  export { toTransform } from './common/toTransform.mjs';
54
54
  export { toWrappedValue } from './common/toWrappedValue.mjs';
55
55
  export { unwrap } from './common/unwrap.mjs';
56
+ export { unwrapGroup } from './common/unwrapGroup.mjs';
56
57
  export { asyncLoop } from './common/asyncLoop.mjs';
57
58
  export { createAsyncRetry, useAsyncRetry } from './common/asyncRetry.mjs';
58
59
  export { isRuntimeWrappedValueKey, isWrappedValue, keyWrappedValue, wrapValue } from './common/wrapValue.mjs';
@@ -70,6 +71,7 @@ export { or } from './common/or.mjs';
70
71
  export { whenElse } from './common/whenElse.mjs';
71
72
  export { justReturn } from './common/justReturn.mjs';
72
73
  export { memo } from './common/memo.mjs';
74
+ export { memoPromise } from './common/memoPromise.mjs';
73
75
  export { instanceOf } from './common/instanceOf.mjs';
74
76
  export { createGlobalStore } from './common/globalStore.mjs';
75
77
  export { MissingBuilderMethodsError, builderKind, createBuilder } from './common/builder.mjs';
@@ -626,6 +626,15 @@
626
626
  },
627
627
  {
628
628
  "name": "index.d.ts"
629
+ },
630
+ {
631
+ "name": "set.cjs"
632
+ },
633
+ {
634
+ "name": "set.d.ts"
635
+ },
636
+ {
637
+ "name": "set.mjs"
629
638
  }
630
639
  ]
631
640
  },
@@ -1415,6 +1424,15 @@
1415
1424
  {
1416
1425
  "name": "memo.mjs"
1417
1426
  },
1427
+ {
1428
+ "name": "memoPromise.cjs"
1429
+ },
1430
+ {
1431
+ "name": "memoPromise.d.ts"
1432
+ },
1433
+ {
1434
+ "name": "memoPromise.mjs"
1435
+ },
1418
1436
  {
1419
1437
  "name": "mimeType.cjs"
1420
1438
  },
@@ -1577,6 +1595,15 @@
1577
1595
  {
1578
1596
  "name": "unwrap.mjs"
1579
1597
  },
1598
+ {
1599
+ "name": "unwrapGroup.cjs"
1600
+ },
1601
+ {
1602
+ "name": "unwrapGroup.d.ts"
1603
+ },
1604
+ {
1605
+ "name": "unwrapGroup.mjs"
1606
+ },
1580
1607
  {
1581
1608
  "name": "when.cjs"
1582
1609
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duplojs/utils",
3
- "version": "1.4.50",
3
+ "version": "1.4.52",
4
4
  "author": {
5
5
  "name": "mathcovax",
6
6
  "url": "https://github.com/mathcovax"
@@ -27,8 +27,8 @@
27
27
  "test:tu:watch": "vitest --coverage --watch",
28
28
  "test:tu:update": "vitest --coverage --update",
29
29
  "test:types": "tsc -p tsconfig.test.json && npm -w docs run test:types",
30
- "test:lint": "eslint",
31
- "test:lint:fix": "eslint --fix",
30
+ "test:lint": "eslint --quiet",
31
+ "test:lint:fix": "eslint --fix --quiet",
32
32
  "prepare": "husky"
33
33
  },
34
34
  "sideEffects": false,