@evolu/common 6.0.1-preview.2 → 6.0.1-preview.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/Assert.d.ts +6 -3
- package/dist/src/Assert.d.ts.map +1 -1
- package/dist/src/Assert.js +7 -4
- package/dist/src/Brand.d.ts +75 -0
- package/dist/src/Brand.d.ts.map +1 -0
- package/dist/src/Brand.js +1 -0
- package/dist/src/Buffer.d.ts +1 -1
- package/dist/src/Buffer.d.ts.map +1 -1
- package/dist/src/Buffer.js +1 -1
- package/dist/src/CallbackRegistry.d.ts +53 -0
- package/dist/src/CallbackRegistry.d.ts.map +1 -0
- package/dist/src/CallbackRegistry.js +25 -0
- package/dist/src/Console.d.ts +31 -6
- package/dist/src/Console.d.ts.map +1 -1
- package/dist/src/Console.js +72 -9
- package/dist/src/Crypto.d.ts +61 -34
- package/dist/src/Crypto.d.ts.map +1 -1
- package/dist/src/Crypto.js +29 -42
- package/dist/src/Evolu/Db.d.ts +159 -66
- package/dist/src/Evolu/Db.d.ts.map +1 -1
- package/dist/src/Evolu/Db.js +300 -705
- package/dist/src/Evolu/Diff.d.ts +3 -3
- package/dist/src/Evolu/Diff.d.ts.map +1 -1
- package/dist/src/Evolu/Diff.js +7 -5
- package/dist/src/Evolu/Evolu.d.ts +200 -115
- package/dist/src/Evolu/Evolu.d.ts.map +1 -1
- package/dist/src/Evolu/Evolu.js +287 -157
- package/dist/src/Evolu/Internal.d.ts +0 -2
- package/dist/src/Evolu/Internal.d.ts.map +1 -1
- package/dist/src/Evolu/Internal.js +0 -2
- package/dist/src/Evolu/LocalAuth.d.ts +144 -0
- package/dist/src/Evolu/LocalAuth.d.ts.map +1 -0
- package/dist/src/Evolu/LocalAuth.js +171 -0
- package/dist/src/Evolu/Owner.d.ts +209 -124
- package/dist/src/Evolu/Owner.d.ts.map +1 -1
- package/dist/src/Evolu/Owner.js +118 -104
- package/dist/src/Evolu/Platform.d.ts +9 -7
- package/dist/src/Evolu/Platform.d.ts.map +1 -1
- package/dist/src/Evolu/Protocol.d.ts +256 -211
- package/dist/src/Evolu/Protocol.d.ts.map +1 -1
- package/dist/src/Evolu/Protocol.js +558 -359
- package/dist/src/Evolu/Public.d.ts +6 -8
- package/dist/src/Evolu/Public.d.ts.map +1 -1
- package/dist/src/Evolu/Public.js +2 -3
- package/dist/src/Evolu/PublicKysely.js +3 -3
- package/dist/src/Evolu/Query.d.ts +2 -1
- package/dist/src/Evolu/Query.d.ts.map +1 -1
- package/dist/src/Evolu/Relay.d.ts +72 -4
- package/dist/src/Evolu/Relay.d.ts.map +1 -1
- package/dist/src/Evolu/Relay.js +124 -13
- package/dist/src/Evolu/Schema.d.ts +129 -73
- package/dist/src/Evolu/Schema.d.ts.map +1 -1
- package/dist/src/Evolu/Schema.js +169 -89
- package/dist/src/Evolu/Storage.d.ts +159 -14
- package/dist/src/Evolu/Storage.d.ts.map +1 -1
- package/dist/src/Evolu/Storage.js +42 -32
- package/dist/src/Evolu/Sync.d.ts +68 -13
- package/dist/src/Evolu/Sync.d.ts.map +1 -1
- package/dist/src/Evolu/Sync.js +414 -20
- package/dist/src/Evolu/Timestamp.d.ts +35 -27
- package/dist/src/Evolu/Timestamp.d.ts.map +1 -1
- package/dist/src/Evolu/Timestamp.js +27 -18
- package/dist/src/ManyToManyMap.d.ts +74 -10
- package/dist/src/ManyToManyMap.d.ts.map +1 -1
- package/dist/src/ManyToManyMap.js +41 -6
- package/dist/src/Number.d.ts +2 -1
- package/dist/src/Number.d.ts.map +1 -1
- package/dist/src/Random.d.ts +3 -2
- package/dist/src/Random.d.ts.map +1 -1
- package/dist/src/RefCountedResourceManager.d.ts +119 -0
- package/dist/src/RefCountedResourceManager.d.ts.map +1 -0
- package/dist/src/RefCountedResourceManager.js +197 -0
- package/dist/src/Result.d.ts +176 -51
- package/dist/src/Result.d.ts.map +1 -1
- package/dist/src/Result.js +30 -241
- package/dist/src/Sqlite.d.ts +21 -4
- package/dist/src/Sqlite.d.ts.map +1 -1
- package/dist/src/Sqlite.js +50 -8
- package/dist/src/Task.d.ts +511 -0
- package/dist/src/Task.d.ts.map +1 -0
- package/dist/src/Task.js +410 -0
- package/dist/src/Time.d.ts +59 -0
- package/dist/src/Time.d.ts.map +1 -1
- package/dist/src/Time.js +87 -4
- package/dist/src/Type.d.ts +474 -327
- package/dist/src/Type.d.ts.map +1 -1
- package/dist/src/Type.js +502 -436
- package/dist/src/Types.d.ts +0 -74
- package/dist/src/Types.d.ts.map +1 -1
- package/dist/src/WebSocket.d.ts +5 -2
- package/dist/src/WebSocket.d.ts.map +1 -1
- package/dist/src/WebSocket.js +12 -13
- package/dist/src/Worker.d.ts +39 -11
- package/dist/src/Worker.d.ts.map +1 -1
- package/dist/src/Worker.js +22 -4
- package/dist/src/index.d.ts +3 -3
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +3 -3
- package/package.json +14 -13
- package/src/Assert.ts +8 -7
- package/src/Brand.ts +75 -0
- package/src/Buffer.ts +1 -1
- package/src/CallbackRegistry.ts +84 -0
- package/src/Console.ts +91 -11
- package/src/Crypto.ts +94 -79
- package/src/Evolu/Db.ts +528 -1027
- package/src/Evolu/Diff.ts +7 -5
- package/src/Evolu/Evolu.ts +682 -329
- package/src/Evolu/Internal.ts +0 -2
- package/src/Evolu/LocalAuth.ts +422 -0
- package/src/Evolu/Owner.ts +282 -227
- package/src/Evolu/Platform.ts +9 -9
- package/src/Evolu/Protocol.ts +788 -640
- package/src/Evolu/Public.ts +7 -14
- package/src/Evolu/PublicKysely.ts +3 -3
- package/src/Evolu/Query.ts +2 -1
- package/src/Evolu/Relay.ts +238 -18
- package/src/Evolu/Schema.ts +391 -191
- package/src/Evolu/Storage.ts +275 -55
- package/src/Evolu/Sync.ts +708 -37
- package/src/Evolu/Timestamp.ts +38 -35
- package/src/ManyToManyMap.ts +127 -24
- package/src/Number.ts +2 -6
- package/src/Random.ts +3 -2
- package/src/RefCountedResourceManager.ts +368 -0
- package/src/Result.ts +183 -53
- package/src/Sqlite.ts +59 -23
- package/src/Task.ts +779 -0
- package/src/Time.ts +168 -4
- package/src/Type.ts +708 -660
- package/src/Types.ts +0 -76
- package/src/WebSocket.ts +23 -17
- package/src/Worker.ts +72 -23
- package/src/index.ts +3 -3
- package/dist/src/Callbacks.d.ts +0 -20
- package/dist/src/Callbacks.d.ts.map +0 -1
- package/dist/src/Callbacks.js +0 -18
- package/dist/src/Evolu/Config.d.ts +0 -69
- package/dist/src/Evolu/Config.d.ts.map +0 -1
- package/dist/src/Evolu/Config.js +0 -9
- package/dist/src/Evolu/Kysely.d.ts +0 -6
- package/dist/src/Evolu/Kysely.d.ts.map +0 -1
- package/dist/src/Evolu/Kysely.js +0 -21
- package/dist/src/NanoId.d.ts +0 -27
- package/dist/src/NanoId.d.ts.map +0 -1
- package/dist/src/NanoId.js +0 -6
- package/dist/src/Promise.d.ts +0 -180
- package/dist/src/Promise.d.ts.map +0 -1
- package/dist/src/Promise.js +0 -176
- package/src/Callbacks.ts +0 -43
- package/src/Evolu/Config.ts +0 -83
- package/src/Evolu/Kysely.ts +0 -38
- package/src/NanoId.ts +0 -39
- package/src/Promise.ts +0 -295
package/dist/src/Type.d.ts
CHANGED
|
@@ -1,77 +1,179 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 🧩
|
|
2
|
+
* 🧩 Type-safe runtime types
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Evolu {@link Type} is like a type guard that returns typed errors (via
|
|
5
|
+
* {@link Result}) instead of throwing. We either get a safely typed value or a
|
|
6
|
+
* precise, composable error value telling us exactly why validation failed.
|
|
5
7
|
*
|
|
6
|
-
*
|
|
8
|
+
* Why another validation library?
|
|
7
9
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
+
* - **Result-based error handling** – no exceptions for normal control flow.
|
|
11
|
+
* - **Typed errors with decoupled formatters** – validation logic ≠ user
|
|
12
|
+
* messages.
|
|
13
|
+
* - **Consistent constraints via {@link Brand}** – every constraint becomes part
|
|
14
|
+
* of the type.
|
|
15
|
+
* - **No user-land chaining DSL** – designed with the upcoming ES pipe operator
|
|
16
|
+
* in mind.
|
|
17
|
+
* - **Selective validation** – parent validations are skipped when already proved
|
|
18
|
+
* by typing.
|
|
19
|
+
* - **Simple, top-down implementation** – readable source code from top to bottom
|
|
20
|
+
* with no hidden magic; just plain functions and composition.
|
|
10
21
|
*
|
|
11
|
-
*
|
|
12
|
-
* exceptions.
|
|
13
|
-
* - **Consistent constraints**: Enforcing {@link Brand} for all constraints.
|
|
14
|
-
* - **Typed errors with decoupled formatters**: Avoiding coupling error messages
|
|
15
|
-
* with validators.
|
|
16
|
-
* - **No user-land chaining**: Designed with ES pipe operator in mind.
|
|
17
|
-
* - **Selective validation/transformation**: Skipping parent Type validations and
|
|
18
|
-
* transformations when TypeScript's type system can be relied upon.
|
|
19
|
-
* - **Bidirectional transformations**: Supporting transformations in both
|
|
20
|
-
* directions.
|
|
21
|
-
* - **Minimal and transparent code**: No runtime dependencies or hidden magic.
|
|
22
|
+
* ### Base Types Quick Start
|
|
22
23
|
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* // Validate unknown values
|
|
26
|
+
* const value: unknown = "hello";
|
|
27
|
+
* const stringResult = String.fromUnknown(value);
|
|
28
|
+
* if (!stringResult.ok) {
|
|
29
|
+
* // console.error(formatStringError(stringResult.error));
|
|
30
|
+
* return stringResult; // inside a function returning Result<string, _>
|
|
31
|
+
* }
|
|
32
|
+
* // Safe branch: value is now string
|
|
33
|
+
* const upper = stringResult.value.toUpperCase();
|
|
34
|
+
*
|
|
35
|
+
* // Type guard style
|
|
36
|
+
* if (String.is(value)) {
|
|
37
|
+
* // narrowed to string
|
|
38
|
+
* }
|
|
39
|
+
*
|
|
40
|
+
* // Composing: arrays & objects
|
|
41
|
+
* const Numbers = array(Number); // ReadonlyArray<number>
|
|
42
|
+
* const Point = object({ x: Number, y: Number });
|
|
43
|
+
*
|
|
44
|
+
* Numbers.from([1, 2, 3]); // ok
|
|
45
|
+
* Point.from({ x: 1, y: 2 }); // ok
|
|
46
|
+
* Point.from({ x: 1, y: "2" }); // err -> nested Number error
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* ### Branding Basics
|
|
50
|
+
*
|
|
51
|
+
* Branding adds semantic meaning & constraints while preserving the runtime
|
|
52
|
+
* shape:
|
|
53
|
+
*
|
|
54
|
+
* ```ts
|
|
55
|
+
* const CurrencyCode = brand("CurrencyCode", String, (value) =>
|
|
56
|
+
* /^[A-Z]{3}$/.test(value)
|
|
57
|
+
* ? ok(value)
|
|
58
|
+
* : err<CurrencyCodeError>({ type: "CurrencyCode", value }),
|
|
59
|
+
* );
|
|
60
|
+
* type CurrencyCode = typeof CurrencyCode.Type; // string & Brand<"CurrencyCode">
|
|
61
|
+
*
|
|
62
|
+
* interface CurrencyCodeError extends TypeError<"CurrencyCode"> {}
|
|
63
|
+
*
|
|
64
|
+
* const formatCurrencyCodeError =
|
|
65
|
+
* createTypeErrorFormatter<CurrencyCodeError>(
|
|
66
|
+
* (error) => `Invalid currency code: ${error.value}`,
|
|
67
|
+
* );
|
|
68
|
+
*
|
|
69
|
+
* const r = CurrencyCode.from("USD"); // ok("USD")
|
|
70
|
+
* const e = CurrencyCode.from("usd"); // err(...)
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* See also reusable brand factories like `minLength`, `maxLength`, `trimmed`,
|
|
74
|
+
* `positive`, `between`, etc.
|
|
75
|
+
*
|
|
76
|
+
* ### Objects & Optional Fields
|
|
77
|
+
*
|
|
78
|
+
* ```ts
|
|
79
|
+
* const User = object({
|
|
80
|
+
* name: NonEmptyTrimmedString100,
|
|
81
|
+
* age: optional(PositiveInt),
|
|
82
|
+
* });
|
|
83
|
+
* type User = typeof User.Type;
|
|
84
|
+
*
|
|
85
|
+
* User.from({ name: "Alice" }); // ok
|
|
86
|
+
* User.from({ name: "Alice", age: -1 }); // err(PositiveInt)
|
|
87
|
+
* ```
|
|
27
88
|
*
|
|
28
|
-
*
|
|
89
|
+
* ### Deriving JSON String Types
|
|
29
90
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
91
|
+
* ```ts
|
|
92
|
+
* const Person = object({
|
|
93
|
+
* name: NonEmptyString50,
|
|
94
|
+
* // Did you know that JSON.stringify converts NaN (a number) into null?
|
|
95
|
+
* // To prevent this, use FiniteNumber.
|
|
96
|
+
* age: FiniteNumber,
|
|
97
|
+
* });
|
|
98
|
+
* type Person = typeof Person.Type;
|
|
99
|
+
*
|
|
100
|
+
* const [PersonJson, personToPersonJson, personJsonToPerson] = json(
|
|
101
|
+
* Person,
|
|
102
|
+
* "PersonJson",
|
|
103
|
+
* );
|
|
104
|
+
* // string & Brand<"PersonJson">
|
|
105
|
+
* type PersonJson = typeof PersonJson.Type;
|
|
106
|
+
*
|
|
107
|
+
* const person = Person.orThrow({
|
|
108
|
+
* name: "Alice",
|
|
109
|
+
* age: 30,
|
|
110
|
+
* });
|
|
111
|
+
*
|
|
112
|
+
* const personJson = personToPersonJson(person);
|
|
113
|
+
* expect(personJsonToPerson(personJson)).toEqual(person);
|
|
114
|
+
* ```
|
|
115
|
+
*
|
|
116
|
+
* ### Error Formatting
|
|
117
|
+
*
|
|
118
|
+
* Evolu separates validation logic from human-readable messages. There are two
|
|
119
|
+
* layers:
|
|
120
|
+
*
|
|
121
|
+
* 1. Per-type formatters (e.g. `formatStringError`) – simple, focused, already
|
|
122
|
+
* used earlier in the quick start example.
|
|
123
|
+
* 2. A unified formatter via `createFormatTypeError` – composes all built-in and
|
|
124
|
+
* custom errors (including nested composite types) and lets us override
|
|
125
|
+
* selected messages.
|
|
34
126
|
*
|
|
35
|
-
*
|
|
36
|
-
* unknown value into something and can continue with further refinements or
|
|
37
|
-
* transformations. For example, `NonEmptyTrimmedString100` chain looks like
|
|
38
|
-
* this:
|
|
127
|
+
* #### 1. Per-Type Formatter (recap)
|
|
39
128
|
*
|
|
40
|
-
*
|
|
129
|
+
* ```ts
|
|
130
|
+
* const r = String.fromUnknown(42);
|
|
131
|
+
* if (!r.ok) console.error(formatStringError(r.error));
|
|
132
|
+
* ```
|
|
41
133
|
*
|
|
42
|
-
*
|
|
43
|
-
* `TrimmedString`, the parent Type is `String`.
|
|
134
|
+
* #### 2. Unified Formatter with Overrides
|
|
44
135
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
136
|
+
* ```ts
|
|
137
|
+
* // Override only what we care about; fall back to built-ins for the rest.
|
|
138
|
+
* const formatTypeError = createFormatTypeError((error) => {
|
|
139
|
+
* if (error.type === "MinLength") return `Min length is ${error.min}`;
|
|
140
|
+
* });
|
|
48
141
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
142
|
+
* const User = object({ name: NonEmptyTrimmedString100 });
|
|
143
|
+
* const resultUser = User.from({ name: "" });
|
|
144
|
+
* if (!resultUser.ok) console.error(formatTypeError(resultUser.error));
|
|
51
145
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
146
|
+
* const badPoint = object({ x: Number, y: Number }).from({
|
|
147
|
+
* x: 1,
|
|
148
|
+
* y: "foo",
|
|
149
|
+
* });
|
|
150
|
+
* if (!badPoint.ok) console.error(formatTypeError(badPoint.error));
|
|
151
|
+
* ```
|
|
152
|
+
*
|
|
153
|
+
* The unified formatter walks nested structures (object / array / record /
|
|
154
|
+
* tuple / union) and applies overrides only where specified, greatly reducing
|
|
155
|
+
* boilerplate when formatting complex validation errors.
|
|
57
156
|
*
|
|
58
157
|
* ### Tip
|
|
59
158
|
*
|
|
60
159
|
* If necessary, write `globalThis.String` instead of `String` to avoid naming
|
|
61
|
-
* clashes with
|
|
160
|
+
* clashes with native types.
|
|
62
161
|
*
|
|
63
|
-
* ### Design Decision:
|
|
162
|
+
* ### Design Decision: No Bidirectional Transformations
|
|
64
163
|
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
164
|
+
* Evolu Type intentionally does not support bidirectional transformations. It
|
|
165
|
+
* previously did, but supporting that while keeping typed error fidelity added
|
|
166
|
+
* complexity that hurt readability & reliability. Most persistence pipelines
|
|
167
|
+
* (e.g. SQLite) already require explicit mapping of query results, so implicit
|
|
168
|
+
* reverse transforms would not buy much. We may revisit this if we can design a
|
|
169
|
+
* minimal, 100% safe API that preserves simplicity.
|
|
69
170
|
*
|
|
70
171
|
* @module
|
|
71
172
|
*/
|
|
72
|
-
import {
|
|
73
|
-
import {
|
|
74
|
-
import
|
|
173
|
+
import type { Brand } from "./Brand.js";
|
|
174
|
+
import { type RandomBytesDep } from "./Crypto.js";
|
|
175
|
+
import { Result } from "./Result.js";
|
|
176
|
+
import type { Literal, Simplify, WidenLiteral } from "./Types.js";
|
|
75
177
|
export interface Type<Name extends TypeName,
|
|
76
178
|
/** The type this Type resolves to. */
|
|
77
179
|
T,
|
|
@@ -93,38 +195,58 @@ ParentError extends TypeError = Error> {
|
|
|
93
195
|
*/
|
|
94
196
|
readonly from: (value: Input) => Result<T, ParentError | Error>;
|
|
95
197
|
/**
|
|
96
|
-
* Creates `T` from an
|
|
198
|
+
* Creates `T` from an `Input` value, throwing an error if validation fails.
|
|
97
199
|
*
|
|
98
|
-
* This is
|
|
99
|
-
*/
|
|
100
|
-
readonly fromUnknown: (value: unknown) => Result<T, ParentError | Error>;
|
|
101
|
-
/**
|
|
102
|
-
* The opposite of `from` and `fromUnknown`.
|
|
200
|
+
* This is a convenience method that combines `from` with `getOrThrow`.
|
|
103
201
|
*
|
|
104
|
-
*
|
|
202
|
+
* **When to use:**
|
|
105
203
|
*
|
|
106
|
-
*
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
*
|
|
204
|
+
* - Configuration values that are guaranteed to be valid (e.g., hardcoded
|
|
205
|
+
* constants)
|
|
206
|
+
* - Application startup where failure should crash the program
|
|
207
|
+
* - Test code with known valid inputs
|
|
208
|
+
* - Converting from trusted sources where validation failure indicates a
|
|
209
|
+
* programming error
|
|
111
210
|
*
|
|
112
|
-
*
|
|
113
|
-
* already partially validated/transformed value.
|
|
211
|
+
* **When NOT to use:**
|
|
114
212
|
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
213
|
+
* - User input validation - use `from` and handle errors gracefully
|
|
214
|
+
* - Data from external APIs or files - use `from` for proper error handling
|
|
215
|
+
* - Library code that should return Results rather than throw
|
|
117
216
|
*
|
|
118
217
|
* ### Example
|
|
119
218
|
*
|
|
120
219
|
* ```ts
|
|
121
|
-
* //
|
|
122
|
-
* const
|
|
220
|
+
* // ✅ Good: Known valid constant
|
|
221
|
+
* const maxRetries = PositiveInt.orThrow(3);
|
|
222
|
+
*
|
|
223
|
+
* // ✅ Good: App configuration that should crash on invalid values
|
|
224
|
+
* const appName = SimpleName.orThrow("MyApp");
|
|
225
|
+
*
|
|
226
|
+
* // ❌ Avoid: User input (use `from` instead)
|
|
227
|
+
* const userAge = PositiveInt.orThrow(userInput); // Could crash!
|
|
228
|
+
*
|
|
229
|
+
* // ✅ Better: Handle user input gracefully
|
|
230
|
+
* const ageResult = PositiveInt.from(userInput);
|
|
231
|
+
* if (!ageResult.ok) {
|
|
232
|
+
* // Handle validation error
|
|
233
|
+
* }
|
|
123
234
|
* ```
|
|
124
235
|
*/
|
|
236
|
+
readonly orThrow: (value: Input) => T;
|
|
237
|
+
/**
|
|
238
|
+
* Creates `T` from an unknown value.
|
|
239
|
+
*
|
|
240
|
+
* This is useful when a value is unknown.
|
|
241
|
+
*/
|
|
242
|
+
readonly fromUnknown: (value: unknown) => Result<T, ParentError | Error>;
|
|
243
|
+
/**
|
|
244
|
+
* Creates `T` from `Parent` type.
|
|
245
|
+
*
|
|
246
|
+
* This function skips parent Types validations when we have already partially
|
|
247
|
+
* validated value.
|
|
248
|
+
*/
|
|
125
249
|
readonly fromParent: (value: Parent) => Result<T, Error>;
|
|
126
|
-
/** The opposite of `fromParent`. */
|
|
127
|
-
readonly toParent: (value: T) => Parent;
|
|
128
250
|
/**
|
|
129
251
|
* A **type guard** that checks whether an unknown value satisfies the
|
|
130
252
|
* {@link Type}.
|
|
@@ -230,12 +352,47 @@ export interface TypeErrorWithReason<Name extends TypeName = TypeName, Reason ex
|
|
|
230
352
|
readonly reason: Reason;
|
|
231
353
|
}
|
|
232
354
|
export type AnyType = Type<any, any, any, any, any, any>;
|
|
355
|
+
/**
|
|
356
|
+
* Extracts the name from a {@link Type}.
|
|
357
|
+
*
|
|
358
|
+
* @category Utilities
|
|
359
|
+
*/
|
|
233
360
|
export type InferName<A extends AnyType> = A extends Type<infer Name, any, any, any, any, any> ? Name : never;
|
|
361
|
+
/**
|
|
362
|
+
* Extracts the type from a {@link Type}.
|
|
363
|
+
*
|
|
364
|
+
* @category Utilities
|
|
365
|
+
*/
|
|
234
366
|
export type InferType<A extends AnyType> = A extends Type<any, infer T, any, any, any, any> ? T : never;
|
|
367
|
+
/**
|
|
368
|
+
* Extracts the input type from a {@link Type}.
|
|
369
|
+
*
|
|
370
|
+
* @category Utilities
|
|
371
|
+
*/
|
|
235
372
|
export type InferInput<A extends AnyType> = A extends Type<any, any, infer Input, any, any, any> ? Input : never;
|
|
373
|
+
/**
|
|
374
|
+
* Extracts the specific error type from a {@link Type}.
|
|
375
|
+
*
|
|
376
|
+
* @category Utilities
|
|
377
|
+
*/
|
|
236
378
|
export type InferError<A extends AnyType> = A extends Type<any, any, any, infer Error, any, any> ? Error : never;
|
|
379
|
+
/**
|
|
380
|
+
* Extracts the parent type from a {@link Type}.
|
|
381
|
+
*
|
|
382
|
+
* @category Utilities
|
|
383
|
+
*/
|
|
237
384
|
export type InferParent<A extends AnyType> = A extends Type<any, any, any, any, infer Parent, any> ? Parent : never;
|
|
385
|
+
/**
|
|
386
|
+
* Extracts the parent error type from a {@link Type}.
|
|
387
|
+
*
|
|
388
|
+
* @category Utilities
|
|
389
|
+
*/
|
|
238
390
|
export type InferParentError<A extends AnyType> = A extends Type<any, any, any, any, any, infer ParentError> ? ParentError : never;
|
|
391
|
+
/**
|
|
392
|
+
* Extracts all error types (Error | ParentError) from a {@link Type}.
|
|
393
|
+
*
|
|
394
|
+
* @category Utilities
|
|
395
|
+
*/
|
|
239
396
|
export type InferErrors<T extends AnyType> = T extends Type<any, any, any, infer Error, any, infer ParentError> ? Error | ParentError : never;
|
|
240
397
|
declare const EvoluTypeSymbol: unique symbol;
|
|
241
398
|
/**
|
|
@@ -268,12 +425,6 @@ export type TypeErrorFormatter<Error extends TypeError> = (error: Error) => stri
|
|
|
268
425
|
* Base {@link Type}.
|
|
269
426
|
*
|
|
270
427
|
* A Base Type validates that a value conforms to a specific TypeScript type.
|
|
271
|
-
* Unlike refinements or transformations, Base Types establish the fundamental
|
|
272
|
-
* shape of a value before any branding or transformation occurs.
|
|
273
|
-
*
|
|
274
|
-
* - To **refine** a Base Type further, use the {@link brand} Type Factory.
|
|
275
|
-
* - To **transform** a Base Type into a different representation, use the
|
|
276
|
-
* {@link transform} Type Factory.
|
|
277
428
|
*
|
|
278
429
|
* ### Example
|
|
279
430
|
*
|
|
@@ -410,7 +561,7 @@ export declare const formatIsTypeError: TypeErrorFormatter<EvoluTypeError>;
|
|
|
410
561
|
* The `brand` Type Factory takes the name of a new {@link Brand}, a parent Type
|
|
411
562
|
* to be branded, and the optional `refine` function for additional constraint.
|
|
412
563
|
*
|
|
413
|
-
*
|
|
564
|
+
* The `refine` function can be omitted if we only want to add a brand.
|
|
414
565
|
*
|
|
415
566
|
* ### Examples
|
|
416
567
|
*
|
|
@@ -489,7 +640,7 @@ export declare const formatIsTypeError: TypeErrorFormatter<EvoluTypeError>;
|
|
|
489
640
|
* confirmPassword: SimplePassword,
|
|
490
641
|
* });
|
|
491
642
|
*
|
|
492
|
-
* const ValidForm = brand("
|
|
643
|
+
* const ValidForm = brand("ValidForm", Form, (value) => {
|
|
493
644
|
* if (value.password !== value.confirmPassword)
|
|
494
645
|
* return err<ValidFormError>({
|
|
495
646
|
* type: "ValidForm",
|
|
@@ -567,17 +718,19 @@ export declare const formatCurrencyCodeError: TypeErrorFormatter<CurrencyCodeErr
|
|
|
567
718
|
* ### Example
|
|
568
719
|
*
|
|
569
720
|
* ```ts
|
|
570
|
-
* const result =
|
|
571
|
-
* const error =
|
|
721
|
+
* const result = DateIso.from("2023-01-01T12:00:00.000Z"); // ok
|
|
722
|
+
* const error = DateIso.from("10000-01-01T00:00:00.000Z"); // err
|
|
572
723
|
* ```
|
|
573
724
|
*
|
|
574
725
|
* @category String
|
|
575
726
|
*/
|
|
576
|
-
export declare const
|
|
577
|
-
export type
|
|
578
|
-
export interface
|
|
727
|
+
export declare const DateIso: BrandType<Type<"String", string, string, StringError, string, StringError>, "DateIso", DateIsoError, StringError>;
|
|
728
|
+
export type DateIso = typeof DateIso.Type;
|
|
729
|
+
export interface DateIsoError extends TypeError<"DateIso"> {
|
|
579
730
|
}
|
|
580
|
-
export declare const
|
|
731
|
+
export declare const formatDateIsoError: TypeErrorFormatter<DateIsoError>;
|
|
732
|
+
export declare const dateToDateIso: (value: Date) => Result<DateIso, DateIsoError>;
|
|
733
|
+
export declare const dateIsoToDate: (value: DateIso) => Date;
|
|
581
734
|
/**
|
|
582
735
|
* Helper type for Type Factory that creates a branded Type.
|
|
583
736
|
*
|
|
@@ -600,18 +753,12 @@ export type BrandFactory<Name extends TypeName, Input, RefineError extends TypeE
|
|
|
600
753
|
/**
|
|
601
754
|
* Trimmed string.
|
|
602
755
|
*
|
|
603
|
-
* This Type Factory
|
|
604
|
-
*
|
|
605
|
-
* Factory.
|
|
756
|
+
* This Type Factory validates whether a string has no leading or trailing
|
|
757
|
+
* whitespaces.
|
|
606
758
|
*
|
|
607
|
-
* ###
|
|
759
|
+
* ### Example
|
|
608
760
|
*
|
|
609
761
|
* ```ts
|
|
610
|
-
* // this Type already exists
|
|
611
|
-
* const TrimmedString = trimmed(String);
|
|
612
|
-
* type TrimmedString = typeof TrimmedString.Type;
|
|
613
|
-
*
|
|
614
|
-
* // we can make any branded Type trimmed:
|
|
615
762
|
* const TrimmedNonEmptyString = trimmed(minLength(1)(String));
|
|
616
763
|
* // string & Brand<"MinLength1"> & Brand<"Trimmed">
|
|
617
764
|
* type TrimmedNonEmptyString = typeof TrimmedNonEmptyString.Type;
|
|
@@ -623,33 +770,6 @@ export declare const trimmed: BrandFactory<"Trimmed", string, TrimmedError>;
|
|
|
623
770
|
export interface TrimmedError extends TypeError<"Trimmed"> {
|
|
624
771
|
}
|
|
625
772
|
export declare const formatTrimmedError: TypeErrorFormatter<TrimmedError>;
|
|
626
|
-
export type TransformBrandFactory<Name extends TypeName, Input, TransformError extends TypeError = never> = <PName extends TypeName, P extends Input, PInput, PParent, PError extends TypeError = never, PParentError extends TypeError = never>(parent: Type<PName, P, PInput, PError, PParent, PParentError>) => TransformType<Type<PName, P, PInput, PError, PParent, PParentError>, BrandType<Type<PName, P, PInput, PError, PParent, PParentError>, Name, never, PError | PParentError>, TransformError>;
|
|
627
|
-
/**
|
|
628
|
-
* Trims leading and trailing whitespace from a string.
|
|
629
|
-
*
|
|
630
|
-
* This Type Factory **transforms** the input string by removing whitespace from
|
|
631
|
-
* both ends. For validation only, use {@link trimmed} Type Factory.
|
|
632
|
-
*
|
|
633
|
-
* ### Example
|
|
634
|
-
*
|
|
635
|
-
* ```ts
|
|
636
|
-
* const TrimString = trim(String);
|
|
637
|
-
* expect(TrimString.from("a ")).toEqual(ok("a"));
|
|
638
|
-
* expect(TrimString.fromParent("a ").value).toEqual("a");
|
|
639
|
-
*
|
|
640
|
-
* const TrimNonEmptyString = trim(NonEmptyString);
|
|
641
|
-
* expect(TrimNonEmptyString.from("a " as NonEmptyString)).toEqual(ok("a"));
|
|
642
|
-
* expect(
|
|
643
|
-
* TrimNonEmptyString.fromParent("a " as NonEmptyString).value,
|
|
644
|
-
* ).toEqual("a");
|
|
645
|
-
* ```
|
|
646
|
-
*
|
|
647
|
-
* **Note:** This transformation is irreversible. Calling `toParent` will not
|
|
648
|
-
* restore the original representation.
|
|
649
|
-
*
|
|
650
|
-
* @category String
|
|
651
|
-
*/
|
|
652
|
-
export declare const trim: TransformBrandFactory<"Trimmed", string>;
|
|
653
773
|
/**
|
|
654
774
|
* Trimmed string
|
|
655
775
|
*
|
|
@@ -660,6 +780,7 @@ export declare const trim: TransformBrandFactory<"Trimmed", string>;
|
|
|
660
780
|
*/
|
|
661
781
|
export declare const TrimmedString: BrandType<Type<"String", string, string, StringError, string, StringError>, "Trimmed", TrimmedError, StringError>;
|
|
662
782
|
export type TrimmedString = typeof TrimmedString.Type;
|
|
783
|
+
export declare const trim: (value: string) => TrimmedString;
|
|
663
784
|
/**
|
|
664
785
|
* Minimum length.
|
|
665
786
|
*
|
|
@@ -782,9 +903,9 @@ export interface RegexError<Name extends TypeName = TypeName> extends TypeError<
|
|
|
782
903
|
}
|
|
783
904
|
export declare const formatRegexError: TypeErrorFormatter<RegexError<Capitalize<string>>>;
|
|
784
905
|
/**
|
|
785
|
-
* URL-safe
|
|
906
|
+
* URL-safe string.
|
|
786
907
|
*
|
|
787
|
-
* A `
|
|
908
|
+
* A `UrlSafeString` uses a limited alphabet that is safe for URLs:
|
|
788
909
|
*
|
|
789
910
|
* - Uppercase letters (`A-Z`)
|
|
790
911
|
* - Lowercase letters (`a-z`)
|
|
@@ -792,31 +913,47 @@ export declare const formatRegexError: TypeErrorFormatter<RegexError<Capitalize<
|
|
|
792
913
|
* - Dash (`-`)
|
|
793
914
|
* - Underscore (`_`)
|
|
794
915
|
*
|
|
916
|
+
* This is the same character set used by Base64Url encoding, but this type does
|
|
917
|
+
* not validate that the string is actually Base64Url-encoded data.
|
|
918
|
+
*
|
|
795
919
|
* ### Example
|
|
796
920
|
*
|
|
797
921
|
* ```ts
|
|
798
|
-
* const result =
|
|
922
|
+
* const result = UrlSafeString.from("abc123_-");
|
|
799
923
|
* if (result.ok) {
|
|
800
|
-
* console.log("Valid
|
|
924
|
+
* console.log("Valid URL-safe string:", result.value);
|
|
801
925
|
* } else {
|
|
802
|
-
* console.error("Invalid
|
|
926
|
+
* console.error("Invalid URL-safe string:", result.error);
|
|
803
927
|
* }
|
|
804
928
|
* ```
|
|
805
929
|
*
|
|
806
930
|
* @category String
|
|
807
931
|
*/
|
|
808
|
-
export declare const
|
|
809
|
-
export type
|
|
810
|
-
export type
|
|
932
|
+
export declare const UrlSafeString: BrandType<Type<"String", string, string, StringError, string, StringError>, "UrlSafeString", RegexError<"UrlSafeString">, StringError>;
|
|
933
|
+
export type UrlSafeString = typeof UrlSafeString.Type;
|
|
934
|
+
export type UrlSafeStringError = typeof UrlSafeString.Error;
|
|
811
935
|
/**
|
|
812
|
-
*
|
|
936
|
+
* Base64Url without padding.
|
|
813
937
|
*
|
|
814
|
-
*
|
|
938
|
+
* Encode with {@link uint8ArrayToBase64Url}, decode with
|
|
939
|
+
* {@link base64UrlToUint8Array}.
|
|
815
940
|
*
|
|
816
|
-
*
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
941
|
+
* @category String
|
|
942
|
+
*/
|
|
943
|
+
export declare const Base64Url: BrandType<Type<"String", string, string, StringError, string, StringError>, "Base64Url", Base64UrlError, StringError>;
|
|
944
|
+
export type Base64Url = typeof Base64Url.Type;
|
|
945
|
+
export interface Base64UrlError extends TypeError<"Base64Url"> {
|
|
946
|
+
}
|
|
947
|
+
export declare const formatBase64UrlError: TypeErrorFormatter<Base64UrlError>;
|
|
948
|
+
/** Encodes a Uint8Array to a {@link Base64Url} string. */
|
|
949
|
+
export declare const uint8ArrayToBase64Url: (bytes: Uint8Array) => Base64Url;
|
|
950
|
+
/** Decodes a {@link Base64Url} string to a Uint8Array. */
|
|
951
|
+
export declare const base64UrlToUint8Array: (str: Base64Url) => Uint8Array;
|
|
952
|
+
/**
|
|
953
|
+
* Simple alphanumeric string for naming in file systems, URLs, and identifiers.
|
|
954
|
+
*
|
|
955
|
+
* Uses the same safe alphabet as {@link UrlSafeString} (letters, digits, `-`,
|
|
956
|
+
* `_`). See `UrlSafeString` for details.
|
|
820
957
|
*
|
|
821
958
|
* The string must be between 1 and 42 characters.
|
|
822
959
|
*
|
|
@@ -833,17 +970,10 @@ export type Base64UrlError = typeof Base64Url.Error;
|
|
|
833
970
|
*
|
|
834
971
|
* @category String
|
|
835
972
|
*/
|
|
836
|
-
export declare const SimpleName: BrandType<Type<"String", string, string, StringError, string, StringError>, "
|
|
973
|
+
export declare const SimpleName: BrandType<BrandType<Type<"String", string, string, StringError, string, StringError>, "UrlSafeString", RegexError<"UrlSafeString">, StringError>, "SimpleName", SimpleNameError, StringError | RegexError<"UrlSafeString">>;
|
|
837
974
|
export type SimpleName = typeof SimpleName.Type;
|
|
838
|
-
export
|
|
839
|
-
|
|
840
|
-
* Default NanoId.
|
|
841
|
-
*
|
|
842
|
-
* @category String
|
|
843
|
-
*/
|
|
844
|
-
export declare const NanoId: BrandType<Type<"String", string, string, StringError, string, StringError>, "NanoId", RegexError<"NanoId">, StringError>;
|
|
845
|
-
export type NanoId = typeof NanoId.Type;
|
|
846
|
-
export type NanoIdError = typeof NanoId.Error;
|
|
975
|
+
export interface SimpleNameError extends TypeError<"SimpleName"> {
|
|
976
|
+
}
|
|
847
977
|
/**
|
|
848
978
|
* Trimmed string between 8 and 64 characters, branded as `SimplePassword`.
|
|
849
979
|
*
|
|
@@ -854,16 +984,49 @@ export type SimplePassword = typeof SimplePassword.Type;
|
|
|
854
984
|
export type SimplePasswordError = typeof SimplePassword.Error;
|
|
855
985
|
export declare const formatSimplePasswordError: (formatTypeError: TypeErrorFormatter<StringError | MinLengthError<8> | MaxLengthError<64> | TrimmedError>) => TypeErrorFormatter<SimplePasswordError>;
|
|
856
986
|
/**
|
|
857
|
-
*
|
|
987
|
+
* Globally unique identifier.
|
|
858
988
|
*
|
|
859
|
-
*
|
|
860
|
-
*
|
|
989
|
+
* **Evolu Id** is 16 random bytes from a cryptographically secure random
|
|
990
|
+
* generator, encoded as 22-character Base64Url string. This provides strong
|
|
991
|
+
* collision resistance for distributed ID generation.
|
|
992
|
+
*
|
|
993
|
+
* ### Design Rationale
|
|
994
|
+
*
|
|
995
|
+
* Why Evolu Id over alternatives:
|
|
996
|
+
*
|
|
997
|
+
* - **NanoID**: No standard binary serialization format, and uses only ~126 bits
|
|
998
|
+
* of entropy (21 characters from 64-symbol alphabet) compared to Evolu Id's
|
|
999
|
+
* 128 bits.
|
|
1000
|
+
* - **UUID (v4)**: String format is 36 characters (with hyphens) compared to
|
|
1001
|
+
* Evolu Id's 22 characters. While UUIDs can be stored as 16 bytes, their
|
|
1002
|
+
* standard string representation is verbose.
|
|
1003
|
+
* - **UUID v7**: Includes timestamp in the ID, which leaks information about when
|
|
1004
|
+
* data was created. This is a privacy concern for local-first applications
|
|
1005
|
+
* where creation time must remain private.
|
|
1006
|
+
*
|
|
1007
|
+
* Evolu Id provides 128 bits of entropy, compact string representation (22
|
|
1008
|
+
* characters), standard and native string serialization (Base64Url), and no
|
|
1009
|
+
* privacy leaks.
|
|
1010
|
+
*
|
|
1011
|
+
* ### Future Consideration
|
|
1012
|
+
*
|
|
1013
|
+
* For database-heavy workloads where insert performance is critical, a hybrid
|
|
1014
|
+
* approach could be considered: `timestamp ^ H(cluster_id, timestamp >> N)`
|
|
1015
|
+
* where H is a keyed hash function and N is a configurable parameter. This
|
|
1016
|
+
* would maintain spatial locality for database caches (improving insert
|
|
1017
|
+
* performance by an order of magnitude) while adding entropy to prevent
|
|
1018
|
+
* timestamp leakage and correlation across systems. The parameter N would allow
|
|
1019
|
+
* trading off cache locality (larger N = better locality) versus entropy
|
|
1020
|
+
* distribution. See https://brooker.co.za/blog/2025/10/22/uuidv7.html for
|
|
1021
|
+
* details on this approach.
|
|
861
1022
|
*
|
|
862
1023
|
* @category String
|
|
863
1024
|
*/
|
|
864
|
-
export declare const Id: BrandType<Type<"String", string, string, StringError, string, StringError>, "Id",
|
|
1025
|
+
export declare const Id: BrandType<Type<"String", string, string, StringError, string, StringError>, "Id", IdError, StringError>;
|
|
865
1026
|
export type Id = typeof Id.Type;
|
|
866
|
-
export
|
|
1027
|
+
export interface IdError extends TypeError<"Id"> {
|
|
1028
|
+
}
|
|
1029
|
+
export declare const formatIdError: TypeErrorFormatter<IdError>;
|
|
867
1030
|
/**
|
|
868
1031
|
* Creates an {@link Id}.
|
|
869
1032
|
*
|
|
@@ -872,11 +1035,48 @@ export declare const idTypeValueLength = 21;
|
|
|
872
1035
|
* ```ts
|
|
873
1036
|
* // string & Brand<"Id">
|
|
874
1037
|
* const id = createId(deps);
|
|
1038
|
+
*
|
|
1039
|
+
* // string & Brand<"Id"> & Brand<"Todo">
|
|
1040
|
+
* const todoId = createId<"Todo">(deps);
|
|
875
1041
|
* ```
|
|
876
1042
|
*/
|
|
877
|
-
export declare const createId: (deps:
|
|
1043
|
+
export declare const createId: <B extends string = never>(deps: RandomBytesDep) => [B] extends [never] ? Id : Id & Brand<B>;
|
|
878
1044
|
/**
|
|
879
|
-
*
|
|
1045
|
+
* Creates an {@link Id} from a string using SHA-256.
|
|
1046
|
+
*
|
|
1047
|
+
* When integrating with external systems that use different ID formats, use
|
|
1048
|
+
* this function to convert external IDs into valid Evolu IDs.
|
|
1049
|
+
*
|
|
1050
|
+
* In Evolu's CRDT, the ID serves as the unique identifier for conflict
|
|
1051
|
+
* resolution across distributed clients. When multiple clients create records
|
|
1052
|
+
* with the same external identifier, they must resolve to the same Evolu ID to
|
|
1053
|
+
* ensure data consistency.
|
|
1054
|
+
*
|
|
1055
|
+
* ### Example
|
|
1056
|
+
*
|
|
1057
|
+
* ```ts
|
|
1058
|
+
* // Both clients will generate the same ID
|
|
1059
|
+
* const id1 = createIdFromString("user-api-123");
|
|
1060
|
+
* const id2 = createIdFromString("user-api-123");
|
|
1061
|
+
* console.log(id1 === id2); // true
|
|
1062
|
+
*
|
|
1063
|
+
* upsert("todo", {
|
|
1064
|
+
* id: createIdFromString("external-todo-456"),
|
|
1065
|
+
* title: "Synced from external system",
|
|
1066
|
+
* });
|
|
1067
|
+
* ```
|
|
1068
|
+
*
|
|
1069
|
+
* **Important**: This transformation is one-way. We cannot recover the original
|
|
1070
|
+
* external string from the generated {@link Id}. If we need to preserve the
|
|
1071
|
+
* original external ID, store it in a separate column.
|
|
1072
|
+
*
|
|
1073
|
+
* @category String
|
|
1074
|
+
*/
|
|
1075
|
+
export declare const createIdFromString: <B extends string = never>(value: string) => [B] extends [never] ? Id : Id & Brand<B>;
|
|
1076
|
+
/**
|
|
1077
|
+
* Creates a branded {@link Id} Type for a table's primary key.
|
|
1078
|
+
*
|
|
1079
|
+
* The table name becomes an additional brand for type safety.
|
|
880
1080
|
*
|
|
881
1081
|
* ### Example
|
|
882
1082
|
*
|
|
@@ -888,14 +1088,20 @@ export declare const createId: (deps: NanoIdLibDep) => Id;
|
|
|
888
1088
|
*
|
|
889
1089
|
* @category String
|
|
890
1090
|
*/
|
|
891
|
-
export declare const id: <Table extends TypeName>(table: Table) =>
|
|
892
|
-
export interface
|
|
1091
|
+
export declare const id: <Table extends TypeName>(table: Table) => TableId<Table>;
|
|
1092
|
+
export interface TableId<Table extends TypeName> extends Type<"Id", string & Brand<"Id"> & Brand<Table>, string, TableIdError<Table>, string, StringError> {
|
|
893
1093
|
table: Table;
|
|
894
1094
|
}
|
|
895
|
-
export interface
|
|
1095
|
+
export interface TableIdError<Table extends TypeName = TypeName> extends TypeError<"TableId"> {
|
|
896
1096
|
readonly table: Table;
|
|
897
1097
|
}
|
|
898
|
-
export declare const
|
|
1098
|
+
export declare const formatTableIdError: TypeErrorFormatter<TableIdError<Capitalize<string>>>;
|
|
1099
|
+
/** Binary representation of an {@link Id}. */
|
|
1100
|
+
export declare const IdBytes: BrandType<BrandType<Type<"Uint8Array", Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>, Uint8ArrayError, Uint8Array<ArrayBufferLike>, Uint8ArrayError>, "Length16", LengthError<16>, Uint8ArrayError>, "IdBytes", BrandWithoutRefineError<"IdBytes", LengthError<16> | Uint8ArrayError>, never>;
|
|
1101
|
+
export type IdBytes = typeof IdBytes.Type;
|
|
1102
|
+
export declare const idBytesTypeValueLength: NonNegativeInt;
|
|
1103
|
+
export declare const idToIdBytes: (id: Id) => IdBytes;
|
|
1104
|
+
export declare const idBytesToId: (idBytes: IdBytes) => Id;
|
|
899
1105
|
/**
|
|
900
1106
|
* Positive number.
|
|
901
1107
|
*
|
|
@@ -963,7 +1169,7 @@ export declare const formatNonNegativeError: TypeErrorFormatter<NonNegativeError
|
|
|
963
1169
|
export declare const NonNegativeNumber: BrandType<Type<"Number", number, number, NumberError, number, NumberError>, "NonNegative", NonNegativeError, NumberError>;
|
|
964
1170
|
export type NonNegativeNumber = typeof NonNegativeNumber.Type;
|
|
965
1171
|
/** @category Number */
|
|
966
|
-
export declare const PositiveNumber: BrandType<Type<"Brand", number & Brand<"NonNegative">, number, NonNegativeError, number, NumberError>, "Positive", PositiveError,
|
|
1172
|
+
export declare const PositiveNumber: BrandType<Type<"Brand", number & Brand<"NonNegative">, number, NonNegativeError, number, NumberError>, "Positive", PositiveError, NonNegativeError | NumberError>;
|
|
967
1173
|
export type PositiveNumber = typeof PositiveNumber.Type;
|
|
968
1174
|
/** @category Number */
|
|
969
1175
|
export declare const NonPositiveNumber: BrandType<Type<"Number", number, number, NumberError, number, NumberError>, "NonPositive", NonPositiveError, NumberError>;
|
|
@@ -994,16 +1200,18 @@ export declare const formatIntError: TypeErrorFormatter<IntError>;
|
|
|
994
1200
|
export declare const Int: BrandType<Type<"Number", number, number, NumberError, number, NumberError>, "Int", IntError, NumberError>;
|
|
995
1201
|
export type Int = typeof Int.Type;
|
|
996
1202
|
/** @category Number */
|
|
997
|
-
export declare const NonNegativeInt: BrandType<Type<"Brand", number & Brand<"Int">, number, IntError, number, NumberError>, "NonNegative", NonNegativeError,
|
|
1203
|
+
export declare const NonNegativeInt: BrandType<Type<"Brand", number & Brand<"Int">, number, IntError, number, NumberError>, "NonNegative", NonNegativeError, IntError | NumberError>;
|
|
998
1204
|
export type NonNegativeInt = typeof NonNegativeInt.Type;
|
|
999
1205
|
/** @category Number */
|
|
1000
|
-
export declare const PositiveInt: BrandType<Type<"Brand", number & Brand<"Int"> & Brand<"NonNegative">, number, NonNegativeError, number & Brand<"Int">,
|
|
1206
|
+
export declare const PositiveInt: BrandType<Type<"Brand", number & Brand<"Int"> & Brand<"NonNegative">, number, NonNegativeError, number & Brand<"Int">, IntError | NumberError>, "Positive", PositiveError, NonNegativeError | IntError | NumberError>;
|
|
1001
1207
|
export type PositiveInt = typeof PositiveInt.Type;
|
|
1208
|
+
/** Maximum safe positive integer value for practically infinite operations. */
|
|
1209
|
+
export declare const maxPositiveInt: number & Brand<"Int"> & Brand<"NonNegative"> & Brand<"Positive">;
|
|
1002
1210
|
/** @category Number */
|
|
1003
|
-
export declare const NonPositiveInt: BrandType<Type<"Brand", number & Brand<"Int">, number, IntError, number, NumberError>, "NonPositive", NonPositiveError,
|
|
1211
|
+
export declare const NonPositiveInt: BrandType<Type<"Brand", number & Brand<"Int">, number, IntError, number, NumberError>, "NonPositive", NonPositiveError, IntError | NumberError>;
|
|
1004
1212
|
export type NonPositiveInt = typeof NonPositiveInt.Type;
|
|
1005
1213
|
/** @category Number */
|
|
1006
|
-
export declare const NegativeInt: BrandType<Type<"Brand", number & Brand<"Int"> & Brand<"NonPositive">, number, NonPositiveError, number & Brand<"Int">,
|
|
1214
|
+
export declare const NegativeInt: BrandType<Type<"Brand", number & Brand<"Int"> & Brand<"NonPositive">, number, NonPositiveError, number & Brand<"Int">, IntError | NumberError>, "Negative", NegativeError, IntError | NumberError | NonPositiveError>;
|
|
1007
1215
|
export type NegativeInt = typeof NegativeInt.Type;
|
|
1008
1216
|
/**
|
|
1009
1217
|
* Number greater than a specified value.
|
|
@@ -1110,9 +1318,6 @@ export interface BetweenError<Min extends number = number, Max extends number =
|
|
|
1110
1318
|
readonly max: Max;
|
|
1111
1319
|
}
|
|
1112
1320
|
export declare const formatBetweenError: TypeErrorFormatter<BetweenError<number, number>>;
|
|
1113
|
-
/** @category Number */
|
|
1114
|
-
export declare const Between1And10: BrandType<Type<"Number", number, number, NumberError, number, NumberError>, "Between1-10", BetweenError<1, 10>, NumberError>;
|
|
1115
|
-
export type Between1And10 = typeof Between1And10.Type;
|
|
1116
1321
|
/**
|
|
1117
1322
|
* Literal {@link Type}.
|
|
1118
1323
|
*
|
|
@@ -1138,67 +1343,6 @@ export interface LiteralError<T extends Literal = Literal> extends TypeError<"Li
|
|
|
1138
1343
|
readonly expected: T;
|
|
1139
1344
|
}
|
|
1140
1345
|
export declare const formatLiteralError: TypeErrorFormatter<LiteralError<Literal>>;
|
|
1141
|
-
/**
|
|
1142
|
-
* {@link Type} that transforms values between `FromType` and `ToType`.
|
|
1143
|
-
*
|
|
1144
|
-
* - `fromParent`: Converts `FromType` to `ToType`, may fail.
|
|
1145
|
-
* - `toParent`: Converts `ToType` back to `FromType`, must not fail.
|
|
1146
|
-
*
|
|
1147
|
-
* ### Example
|
|
1148
|
-
*
|
|
1149
|
-
* // TODO: Examples
|
|
1150
|
-
*
|
|
1151
|
-
* @category Base Factories
|
|
1152
|
-
*/
|
|
1153
|
-
export declare const transform: <FromType extends AnyType, ToType extends AnyType, TransformError extends TypeError = never>(fromType: FromType, toType: ToType, fromParent: (parentValue: InferType<FromType>) => Result<InferType<ToType>, TransformError>, toParent: (value: InferType<ToType>) => InferType<FromType>) => TransformType<FromType, ToType, TransformError>;
|
|
1154
|
-
/**
|
|
1155
|
-
* TransformType extends {@link Type} with additional `fromType` and `toType`
|
|
1156
|
-
* properties for reflection.
|
|
1157
|
-
*/
|
|
1158
|
-
export interface TransformType<FromType extends AnyType, ToType extends AnyType, TransformError extends TypeError = never> extends Type<"Transform", InferType<ToType>, InferInput<FromType>, TransformError, InferType<FromType>, InferErrors<FromType>> {
|
|
1159
|
-
readonly fromType: FromType;
|
|
1160
|
-
readonly toType: ToType;
|
|
1161
|
-
readonly fromParent: (value: InferType<FromType>) => [TransformError] extends [never] ? Ok<InferType<ToType>> : Result<InferType<ToType>, TransformError>;
|
|
1162
|
-
}
|
|
1163
|
-
/**
|
|
1164
|
-
* Trims leading and trailing whitespace from a string.
|
|
1165
|
-
*
|
|
1166
|
-
* ### Example
|
|
1167
|
-
*
|
|
1168
|
-
* ```ts
|
|
1169
|
-
* expect(TrimString.from("a ")).toEqual(ok("a"));
|
|
1170
|
-
* expect(TrimString.fromParent("a ").value).toEqual("a");
|
|
1171
|
-
* ```
|
|
1172
|
-
*
|
|
1173
|
-
* @category String
|
|
1174
|
-
*/
|
|
1175
|
-
export declare const TrimString: TransformType<Type<"String", string, string, StringError, string, StringError>, BrandType<Type<"String", string, string, StringError, string, StringError>, "Trimmed", never, StringError>, never>;
|
|
1176
|
-
/**
|
|
1177
|
-
* Transforms a {@link Date} into a {@link DateIsoString} string and vice versa.
|
|
1178
|
-
*
|
|
1179
|
-
* ### Example
|
|
1180
|
-
*
|
|
1181
|
-
* TODO:
|
|
1182
|
-
*
|
|
1183
|
-
* @category String
|
|
1184
|
-
*/
|
|
1185
|
-
export declare const DateIso: TransformType<InstanceOfType<DateConstructor>, BrandType<Type<"String", string, string, StringError, string, StringError>, "DateIso", DateIsoStringError, StringError>, DateIsoStringError>;
|
|
1186
|
-
/**
|
|
1187
|
-
* Transforms a {@link NonEmptyTrimmedString} into a {@link FiniteNumber}.
|
|
1188
|
-
*
|
|
1189
|
-
* ### Example
|
|
1190
|
-
*
|
|
1191
|
-
* ```ts
|
|
1192
|
-
* NumberFromString.from("42"); // ok(42)
|
|
1193
|
-
* NumberFromString.from("abc"); // err({ type: "NumberFromString", value: "abc" })
|
|
1194
|
-
* ```
|
|
1195
|
-
*
|
|
1196
|
-
* @category Number
|
|
1197
|
-
*/
|
|
1198
|
-
export declare const NumberFromString: TransformType<BrandType<Type<"Brand", string & Brand<"Trimmed">, string, TrimmedError, string, StringError>, "MinLength1", MinLengthError<1>, StringError | TrimmedError>, BrandType<Type<"Number", number, number, NumberError, number, NumberError>, "Finite", FiniteError, NumberError>, NumberFromStringError>;
|
|
1199
|
-
export interface NumberFromStringError extends TypeError<"NumberFromString"> {
|
|
1200
|
-
}
|
|
1201
|
-
export declare const formatNumberFromStringError: TypeErrorFormatter<NumberFromStringError>;
|
|
1202
1346
|
/**
|
|
1203
1347
|
* Array of a specific {@link Type}.
|
|
1204
1348
|
*
|
|
@@ -1656,16 +1800,12 @@ export type Int64 = typeof Int64.Type;
|
|
|
1656
1800
|
export interface Int64Error extends TypeError<"Int64"> {
|
|
1657
1801
|
}
|
|
1658
1802
|
export declare const formatInt64Error: TypeErrorFormatter<Int64Error>;
|
|
1659
|
-
export declare const BigIntFromString: TransformType<Type<"String", string, string, StringError, string, StringError>, Type<"BigInt", bigint, bigint, BigIntError, bigint, BigIntError>, BigIntFromStringError>;
|
|
1660
|
-
export interface BigIntFromStringError extends TypeError<"BigIntFromString"> {
|
|
1661
|
-
}
|
|
1662
|
-
export declare const formatBigIntFromStringError: TypeErrorFormatter<BigIntFromStringError>;
|
|
1663
1803
|
/**
|
|
1664
1804
|
* Stringified {@link Int64}.
|
|
1665
1805
|
*
|
|
1666
|
-
* @category
|
|
1806
|
+
* @category String
|
|
1667
1807
|
*/
|
|
1668
|
-
export declare const Int64String: BrandType<Type<"
|
|
1808
|
+
export declare const Int64String: BrandType<BrandType<Type<"Brand", string & Brand<"Trimmed">, string, TrimmedError, string, StringError>, "MinLength1", MinLengthError<1>, StringError | TrimmedError>, "Int64", Int64StringError, StringError | TrimmedError | MinLengthError<1>>;
|
|
1669
1809
|
export type Int64String = typeof Int64String.Type;
|
|
1670
1810
|
export interface Int64StringError extends TypeError<"Int64String"> {
|
|
1671
1811
|
}
|
|
@@ -1700,42 +1840,63 @@ export declare const JsonArray: ArrayType<RecursiveType<UnionType<[Type<"String"
|
|
|
1700
1840
|
* @category Object
|
|
1701
1841
|
*/
|
|
1702
1842
|
export declare const JsonObject: RecordType<"String", string, string, StringError, string, StringError, RecursiveType<UnionType<[Type<"String", string, string, StringError, string, StringError>, BrandType<Type<"Number", number, number, NumberError, number, NumberError>, "Finite", FiniteError, NumberError>, Type<"Boolean", boolean, boolean, BooleanError, boolean, BooleanError>, Type<"Null", null, null, NullError, null, NullError>, ArrayType<Type<"Recursive", JsonValue, JsonValueInput, JsonValueError, JsonValueInput, JsonValueError>>, RecordType<"String", string, string, StringError, string, StringError, Type<"Recursive", JsonValue, JsonValueInput, JsonValueError, JsonValueInput, JsonValueError>>]>>>;
|
|
1843
|
+
export declare const parseJson: (value: string) => Result<JsonValue, JsonError>;
|
|
1703
1844
|
/**
|
|
1704
|
-
*
|
|
1705
|
-
* JsonValue back into a JSON string.
|
|
1845
|
+
* JSON-string {@link Type}.
|
|
1706
1846
|
*
|
|
1707
1847
|
* ### Example
|
|
1708
1848
|
*
|
|
1709
1849
|
* ```ts
|
|
1710
|
-
*
|
|
1711
|
-
*
|
|
1850
|
+
* const result = Json.from('{"key":"value"}'); // ok
|
|
1851
|
+
* const error = Json.from("invalid json"); // err
|
|
1712
1852
|
* ```
|
|
1713
1853
|
*
|
|
1714
1854
|
* @category String
|
|
1715
1855
|
*/
|
|
1716
|
-
export declare const
|
|
1717
|
-
export
|
|
1856
|
+
export declare const Json: BrandType<Type<"String", string, string, StringError, string, StringError>, "Json", JsonError, StringError>;
|
|
1857
|
+
export type Json = typeof Json.Type;
|
|
1858
|
+
export interface JsonError extends TypeError<"Json"> {
|
|
1718
1859
|
readonly message: string;
|
|
1719
1860
|
}
|
|
1720
|
-
export declare const
|
|
1861
|
+
export declare const formatJsonError: TypeErrorFormatter<JsonError>;
|
|
1862
|
+
export declare const jsonValueToJson: (value: JsonValue) => Json;
|
|
1863
|
+
export declare const jsonToJsonValue: (value: Json) => JsonValue;
|
|
1721
1864
|
/**
|
|
1722
|
-
* JSON
|
|
1865
|
+
* Creates a branded JSON string {@link Type} and type-safe conversion functions
|
|
1866
|
+
* for a given Type.
|
|
1867
|
+
*
|
|
1868
|
+
* This factory creates:
|
|
1869
|
+
*
|
|
1870
|
+
* 1. A branded string Type that validates JSON parsing and structural conformity
|
|
1871
|
+
* 2. A serialization function (Type → branded JSON string)
|
|
1872
|
+
* 3. A parsing function (branded JSON string → Type, skipping validation)
|
|
1873
|
+
*
|
|
1874
|
+
* Optimized for Evolu's SQLite workflow where we store typed JSON strings and
|
|
1875
|
+
* need type-safe conversions without double parsing.
|
|
1723
1876
|
*
|
|
1724
1877
|
* ### Example
|
|
1725
1878
|
*
|
|
1726
1879
|
* ```ts
|
|
1727
|
-
* const
|
|
1728
|
-
*
|
|
1729
|
-
*
|
|
1880
|
+
* const Person = object({
|
|
1881
|
+
* name: NonEmptyString100,
|
|
1882
|
+
* age: FiniteNumber,
|
|
1883
|
+
* });
|
|
1884
|
+
* type Person = typeof Person.Type;
|
|
1730
1885
|
*
|
|
1731
|
-
*
|
|
1886
|
+
* const [PersonJson, personToPersonJson, personJsonToPerson] = json(
|
|
1887
|
+
* Person,
|
|
1888
|
+
* "PersonJson",
|
|
1889
|
+
* );
|
|
1890
|
+
* // string & Brand<"PersonJson">
|
|
1891
|
+
* type PersonJson = typeof PersonJson.Type;
|
|
1892
|
+
*
|
|
1893
|
+
* // Usage:
|
|
1894
|
+
* const person: Person = { name: "Alice", age: 30 };
|
|
1895
|
+
* const jsonString = personToPersonJson(person); // PersonJson
|
|
1896
|
+
* const backToPerson = personJsonToPerson(jsonString); // Person
|
|
1897
|
+
* ```
|
|
1732
1898
|
*/
|
|
1733
|
-
export declare const
|
|
1734
|
-
export type Json = typeof Json.Type;
|
|
1735
|
-
export interface JsonError extends TypeError<"Json"> {
|
|
1736
|
-
readonly message: string;
|
|
1737
|
-
}
|
|
1738
|
-
export declare const formatJsonError: TypeErrorFormatter<JsonError>;
|
|
1899
|
+
export declare const json: <T extends AnyType, Name extends TypeName>(type: T, name: Name) => [BrandType<typeof String, Name, JsonError | InferErrors<T>, StringError>, (value: InferType<T>) => InferType<BrandType<typeof String, Name, JsonError | InferErrors<T>, StringError>>, (value: InferType<BrandType<typeof String, Name, JsonError | InferErrors<T>, StringError>>) => InferType<T>];
|
|
1739
1900
|
/**
|
|
1740
1901
|
* Optional {@link Type}.
|
|
1741
1902
|
*
|
|
@@ -1766,7 +1927,7 @@ export declare const isOptionalType: (x: unknown) => x is OptionalType<any>;
|
|
|
1766
1927
|
/**
|
|
1767
1928
|
* Creates a partial object type where all properties are optional.
|
|
1768
1929
|
*
|
|
1769
|
-
* This is useful when
|
|
1930
|
+
* This is useful when we want to validate an object in which none of the keys
|
|
1770
1931
|
* are required, but if they are present they must conform to their
|
|
1771
1932
|
* corresponding Types.
|
|
1772
1933
|
*
|
|
@@ -1812,36 +1973,18 @@ export type NullTypeInMembers<Members extends [AnyType, ...Array<AnyType>]> = Me
|
|
|
1812
1973
|
* @category Object
|
|
1813
1974
|
*/
|
|
1814
1975
|
export declare function omit<T extends ObjectType<any>, Keys extends keyof T["props"]>(objectType: T, ...keys: ReadonlyArray<Keys>): ObjectType<Omit<T["props"], Keys>>;
|
|
1976
|
+
export declare const maxMutationSize = 655360;
|
|
1815
1977
|
/**
|
|
1816
|
-
*
|
|
1817
|
-
*
|
|
1818
|
-
*
|
|
1819
|
-
*
|
|
1820
|
-
* ### Example
|
|
1821
|
-
*
|
|
1822
|
-
* ```ts
|
|
1823
|
-
* const Person = object({
|
|
1824
|
-
* name: NonEmptyString50,
|
|
1825
|
-
* age: FiniteNumber,
|
|
1826
|
-
* });
|
|
1827
|
-
* type Person = typeof Person.Type;
|
|
1828
|
-
*
|
|
1829
|
-
* const PersonJson = json(Person, "PersonJson");
|
|
1830
|
-
* // string & Brand<"PersonJson">
|
|
1831
|
-
* type PersonJson = typeof PersonJson.Type;
|
|
1832
|
-
*
|
|
1833
|
-
* // Person -> string & Brand<"PersonJson">
|
|
1834
|
-
* const personJson = PersonJson.from({ name: "Alice", age: 30 });
|
|
1835
|
-
* expect(personJson).toEqual(ok('{"name":"Alice","age":30}'));
|
|
1836
|
-
*
|
|
1837
|
-
* // string & Brand<"PersonJson"> -> Person
|
|
1838
|
-
* const person = PersonJson.to(personJson);
|
|
1839
|
-
*
|
|
1840
|
-
* // serialize/parse any JSON value
|
|
1841
|
-
* const AnyJson = json(JsonValue, "AnyJson");
|
|
1842
|
-
* ```
|
|
1978
|
+
* Evolu has to limit the maximum mutation size. Otherwise, sync couldn't use
|
|
1979
|
+
* the `maxProtocolMessageRangesSize`. The max size is 640KB in bytes, measured
|
|
1980
|
+
* via MessagePack. Evolu Protocol DbChange will be smaller thanks to various
|
|
1981
|
+
* optimizations.
|
|
1843
1982
|
*/
|
|
1844
|
-
export declare const
|
|
1983
|
+
export declare const validMutationSize: <T extends AnyType>(type: T) => BrandType<T, "ValidMutationSize", ValidMutationSizeError, InferErrors<T>>;
|
|
1984
|
+
export interface ValidMutationSizeError extends TypeError<"ValidMutationSize"> {
|
|
1985
|
+
}
|
|
1986
|
+
export declare const formatValidMutationSizeError: TypeErrorFormatter<ValidMutationSizeError>;
|
|
1987
|
+
export type ValidMutationSize<Props extends Record<string, AnyType>> = BrandType<ObjectType<Props>, "ValidMutationSize", ValidMutationSizeError, InferErrors<ObjectType<Props>>>;
|
|
1845
1988
|
/**
|
|
1846
1989
|
* Union of all `TypeError`s defined in the `Type.ts` file, including base type
|
|
1847
1990
|
* errors (e.g., `StringError`, `NumberError`), composite type errors
|
|
@@ -1855,72 +1998,76 @@ export declare const json: <T extends AnyType, Name extends TypeName>(type: T, n
|
|
|
1855
1998
|
*
|
|
1856
1999
|
* @category Utilities
|
|
1857
2000
|
*/
|
|
1858
|
-
export type TypeErrors<ExtraErrors extends TypeError = never> = StringError | NumberError | BigIntError | BooleanError | UndefinedError | NullError | FunctionError | Uint8ArrayError | InstanceOfError | EvoluTypeError | CurrencyCodeError |
|
|
2001
|
+
export type TypeErrors<ExtraErrors extends TypeError = never> = StringError | NumberError | BigIntError | BooleanError | UndefinedError | NullError | FunctionError | Uint8ArrayError | InstanceOfError | EvoluTypeError | CurrencyCodeError | DateIsoError | TrimmedError | MinLengthError | MaxLengthError | LengthError | MnemonicError | RegexError | SimplePasswordError | IdError | TableIdError | PositiveError | NegativeError | NonPositiveError | NonNegativeError | IntError | GreaterThanError | LessThanError | GreaterThanOrEqualToError | LessThanOrEqualToError | NonNaNError | FiniteError | MultipleOfError | BetweenError | LiteralError | Int64Error | Int64StringError | JsonError | ValidMutationSizeError | ExtraErrors | ArrayError<TypeErrors<ExtraErrors>> | RecordError<TypeErrors<ExtraErrors>, TypeErrors<ExtraErrors>> | ObjectError<Record<string, TypeErrors<ExtraErrors>>> | ObjectWithRecordError<Record<string, TypeErrors<ExtraErrors>>, TypeErrors<ExtraErrors>, TypeErrors<ExtraErrors>> | UnionError<TypeErrors<ExtraErrors>> | TupleError<TypeErrors<ExtraErrors>>;
|
|
1859
2002
|
/**
|
|
1860
|
-
*
|
|
1861
|
-
* {@link TypeErrors} and custom errors. It also lets us override the default
|
|
1862
|
-
* formatting for specific errors.
|
|
2003
|
+
* Formats Evolu Type errors into user-friendly messages.
|
|
1863
2004
|
*
|
|
1864
|
-
*
|
|
1865
|
-
*
|
|
2005
|
+
* Evolu Type typed errors ensure every error type must have a formatter.
|
|
2006
|
+
* TypeScript enforces this at compile-time, preventing unhandled validation
|
|
2007
|
+
* errors from reaching users.
|
|
1866
2008
|
*
|
|
1867
|
-
*
|
|
2009
|
+
* The `createFormatTypeError` function handles both built-in {@link TypeErrors}
|
|
2010
|
+
* and custom errors, and lets us override default formatting for specific
|
|
2011
|
+
* errors.
|
|
2012
|
+
*
|
|
2013
|
+
* ### Example
|
|
1868
2014
|
*
|
|
1869
2015
|
* ```ts
|
|
1870
|
-
* const
|
|
1871
|
-
*
|
|
1872
|
-
*
|
|
2016
|
+
* const formatTypeError = createFormatTypeError<
|
|
2017
|
+
* MinLengthError | MaxLengthError
|
|
2018
|
+
* >((error): string => {
|
|
2019
|
+
* switch (error.type) {
|
|
2020
|
+
* case "MinLength":
|
|
2021
|
+
* return `Text must be at least ${error.min} character${error.min === 1 ? "" : "s"} long`;
|
|
2022
|
+
* case "MaxLength":
|
|
2023
|
+
* return `Text is too long (maximum ${error.max} characters)`;
|
|
2024
|
+
* }
|
|
2025
|
+
* });
|
|
1873
2026
|
* ```
|
|
1874
2027
|
*
|
|
1875
|
-
*
|
|
2028
|
+
* Alternatively, write a custom formatter from scratch without using
|
|
2029
|
+
* `createFormatTypeError`. This gives us full control over error formatting:
|
|
1876
2030
|
*
|
|
1877
2031
|
* ```ts
|
|
1878
|
-
*
|
|
1879
|
-
*
|
|
2032
|
+
* const Person = object({
|
|
2033
|
+
* name: NonEmptyTrimmedString100,
|
|
2034
|
+
* age: optional(PositiveInt),
|
|
2035
|
+
* });
|
|
2036
|
+
*
|
|
2037
|
+
* // Define only the errors actually used by Person Type
|
|
2038
|
+
* type PersonErrors =
|
|
1880
2039
|
* | StringError
|
|
1881
|
-
* | MinLengthError
|
|
1882
2040
|
* | MaxLengthError
|
|
1883
|
-
* |
|
|
1884
|
-
* | IdError
|
|
2041
|
+
* | MinLengthError
|
|
1885
2042
|
* | TrimmedError
|
|
1886
|
-
* |
|
|
1887
|
-
* |
|
|
1888
|
-
*
|
|
1889
|
-
* |
|
|
1890
|
-
* |
|
|
1891
|
-
*
|
|
1892
|
-
* const formatTypeError: TypeErrorFormatter<
|
|
1893
|
-
* // In the real code, we would use the createTypeErrorFormatter helper
|
|
1894
|
-
* // that safely stringifies error value.
|
|
2043
|
+
* | PositiveError
|
|
2044
|
+
* | NonNegativeError
|
|
2045
|
+
* | IntError
|
|
2046
|
+
* | NumberError
|
|
2047
|
+
* | ObjectError<Record<string, PersonErrors>>;
|
|
2048
|
+
*
|
|
2049
|
+
* const formatTypeError: TypeErrorFormatter<PersonErrors> = (error) => {
|
|
1895
2050
|
* switch (error.type) {
|
|
1896
|
-
* case "Id":
|
|
1897
|
-
* return `Invalid Id on table: ${error.table}.`;
|
|
1898
|
-
* case "MaxLength":
|
|
1899
|
-
* return `Max length is ${error.max}.`;
|
|
1900
|
-
* case "MinLength":
|
|
1901
|
-
* return `Min length is ${error.min}.`;
|
|
1902
|
-
* case "Mnemonic":
|
|
1903
|
-
* return `Invalid mnemonic: ${String(error.value)}`;
|
|
1904
|
-
* case "Null":
|
|
1905
|
-
* return `Not null`;
|
|
1906
2051
|
* case "String":
|
|
1907
|
-
* // We can reuse existing formatter.
|
|
1908
2052
|
* return formatStringError(error);
|
|
2053
|
+
* case "Number":
|
|
2054
|
+
* return "Must be a number";
|
|
2055
|
+
* case "MinLength":
|
|
2056
|
+
* return `Must be at least ${error.min} characters`;
|
|
2057
|
+
* case "MaxLength":
|
|
2058
|
+
* return `Cannot exceed ${error.max} characters`;
|
|
1909
2059
|
* case "Trimmed":
|
|
1910
|
-
* return "
|
|
1911
|
-
* case "
|
|
1912
|
-
* return "
|
|
1913
|
-
* case "
|
|
1914
|
-
* return
|
|
1915
|
-
*
|
|
1916
|
-
*
|
|
1917
|
-
* return `Union errors: ${error.errors.map(formatTypeError).join(", ")}`;
|
|
2060
|
+
* return "Cannot have leading or trailing spaces";
|
|
2061
|
+
* case "Positive":
|
|
2062
|
+
* return "Must be a positive number";
|
|
2063
|
+
* case "NonNegative":
|
|
2064
|
+
* return "Must be zero or positive";
|
|
2065
|
+
* case "Int":
|
|
2066
|
+
* return "Must be an integer";
|
|
1918
2067
|
* case "Object": {
|
|
1919
|
-
* if (
|
|
1920
|
-
*
|
|
1921
|
-
*
|
|
1922
|
-
* )
|
|
1923
|
-
* return "A developer made an error, this should not happen.";
|
|
2068
|
+
* if (error.reason.kind === "NotObject") return "Must be an object";
|
|
2069
|
+
* if (error.reason.kind === "ExtraKeys")
|
|
2070
|
+
* return "Contains unexpected fields";
|
|
1924
2071
|
* const firstError = Object.values(error.reason.errors).find(
|
|
1925
2072
|
* (e) => e !== undefined,
|
|
1926
2073
|
* )!;
|