wellcrafted 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,361 +1,4 @@
1
- //#region src/result/result.ts
2
- /**
3
- * Constructs an `Ok<T>` variant, representing a successful outcome.
4
- *
5
- * This factory function creates the success variant of a `Result`.
6
- * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.
7
- *
8
- * @template T - The type of the success value.
9
- * @param data - The success value to be wrapped in the `Ok` variant.
10
- * @returns An `Ok<T>` object with the provided data and `error` set to `null`.
11
- * @example
12
- * ```ts
13
- * const successfulResult = Ok("Operation completed successfully");
14
- * // successfulResult is { data: "Operation completed successfully", error: null }
15
- * ```
16
- */
17
- const Ok = (data) => ({
18
- data,
19
- error: null
20
- });
21
- /**
22
- * Constructs an `Err<E>` variant, representing a failure outcome.
23
- *
24
- * This factory function creates the error variant of a `Result`.
25
- * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.
26
- *
27
- * @template E - The type of the error value.
28
- * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.
29
- * @returns An `Err<E>` object with the provided error and `data` set to `null`.
30
- * @example
31
- * ```ts
32
- * const failedResult = Err(new TypeError("Invalid input"));
33
- * // failedResult is { error: TypeError("Invalid input"), data: null }
34
- * ```
35
- */
36
- const Err = (error) => ({
37
- error,
38
- data: null
39
- });
40
- /**
41
- * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.
42
- *
43
- * A value is considered a valid `Result` if:
44
- * 1. It is a non-null object.
45
- * 2. It has both `data` and `error` properties.
46
- * 3. Exactly one of `data` or `error` is `null`. The other must be non-`null`.
47
- *
48
- * This function does not validate the types of `data` or `error` beyond `null` checks.
49
- *
50
- * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).
51
- * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).
52
- * @param value - The value to check.
53
- * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.
54
- * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.
55
- * @example
56
- * ```ts
57
- * declare const someValue: unknown;
58
- *
59
- * if (isResult<string, Error>(someValue)) {
60
- * // someValue is now typed as Result<string, Error>
61
- * if (isOk(someValue)) {
62
- * console.log(someValue.data); // string
63
- * } else {
64
- * console.error(someValue.error); // Error
65
- * }
66
- * }
67
- * ```
68
- */
69
- function isResult(value) {
70
- const isNonNullObject = typeof value === "object" && value !== null;
71
- if (!isNonNullObject) return false;
72
- const hasDataProperty = "data" in value;
73
- const hasErrorProperty = "error" in value;
74
- if (!hasDataProperty || !hasErrorProperty) return false;
75
- const isBothNull = value.data === null && value.error === null;
76
- if (isBothNull) return false;
77
- const isNeitherNull = value.data !== null && value.error !== null;
78
- if (isNeitherNull) return false;
79
- return true;
80
- }
81
- /**
82
- * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.
83
- *
84
- * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.
85
- * An `Ok<T>` variant is identified by its `error` property being `null`.
86
- *
87
- * @template T - The success value type.
88
- * @template E - The error value type.
89
- * @param result - The `Result<T, E>` to check.
90
- * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.
91
- * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.
92
- * @example
93
- * ```ts
94
- * declare const myResult: Result<number, string>;
95
- *
96
- * if (isOk(myResult)) {
97
- * // myResult is now typed as Ok<number>
98
- * console.log("Success value:", myResult.data); // myResult.data is number
99
- * }
100
- * ```
101
- */
102
- function isOk(result) {
103
- return result.error === null;
104
- }
105
- /**
106
- * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.
107
- *
108
- * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.
109
- * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).
110
- *
111
- * @template T - The success value type.
112
- * @template E - The error value type.
113
- * @param result - The `Result<T, E>` to check.
114
- * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.
115
- * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.
116
- * @example
117
- * ```ts
118
- * declare const myResult: Result<number, string>;
119
- *
120
- * if (isErr(myResult)) {
121
- * // myResult is now typed as Err<string>
122
- * console.error("Error value:", myResult.error); // myResult.error is string
123
- * }
124
- * ```
125
- */
126
- function isErr(result) {
127
- return result.error !== null;
128
- }
129
- /**
130
- * Executes a synchronous operation and wraps its outcome (success or failure) in a `Result<T, E>`.
131
- *
132
- * This function attempts to execute the `operation`.
133
- * - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.
134
- * - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to
135
- * the `mapError` function. `mapError` is responsible for transforming this `unknown`
136
- * exception into a well-typed error value of type `E`. This error value is then wrapped
137
- * in an `Err<E>` variant.
138
- *
139
- * @template T - The type of the success value returned by the `operation` if it succeeds.
140
- * @template E - The type of the error value produced by `mapError` if the `operation` fails.
141
- * @param options - An object containing the operation and error mapping function.
142
- * @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.
143
- * @param options.mapError - A function that takes the `unknown` exception caught from `options.try`
144
- * and transforms it into a specific error value of type `E`. This function
145
- * is crucial for creating a well-typed error for the `Err<E>` variant.
146
- * @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapError` provides an error value.
147
- * @example
148
- * ```ts
149
- * function parseJson(jsonString: string): Result<object, SyntaxError> {
150
- * return trySync({
151
- * try: () => JSON.parse(jsonString),
152
- * mapError: (err: unknown) => {
153
- * if (err instanceof SyntaxError) return err;
154
- * return new SyntaxError("Unknown parsing error");
155
- * }
156
- * });
157
- * }
158
- *
159
- * const validResult = parseJson('{"name":"Result"}'); // Ok<{name: string}>
160
- * const invalidResult = parseJson('invalid json'); // Err<SyntaxError>
161
- *
162
- * if (isOk(validResult)) console.log(validResult.data);
163
- * if (isErr(invalidResult)) console.error(invalidResult.error.message);
164
- * ```
165
- */
166
- function trySync({ try: operation, mapError }) {
167
- try {
168
- const data = operation();
169
- return Ok(data);
170
- } catch (error) {
171
- return Err(mapError(error));
172
- }
173
- }
174
- /**
175
- * Executes an asynchronous operation (returning a `Promise`) and wraps its outcome in a `Promise<Result<T, E>>`.
176
- *
177
- * This function attempts to execute the asynchronous `operation`.
178
- * - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.
179
- * - If the `Promise` returned by `operation` rejects, or if `operation` itself throws an exception synchronously,
180
- * the caught exception/rejection reason (of type `unknown`) is passed to the `mapError` function.
181
- * `mapError` is responsible for transforming this `unknown` error into a well-typed error value of type `E`.
182
- * This error value is then wrapped in an `Err<E>` variant.
183
- *
184
- * The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.
185
- *
186
- * @template T - The type of the success value the `Promise` from `operation` resolves to.
187
- * @template E - The type of the error value produced by `mapError` if the `operation` fails or rejects.
188
- * @param options - An object containing the asynchronous operation and error mapping function.
189
- * @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.
190
- * @param options.mapError - A function that takes the `unknown` exception/rejection reason caught from `options.try`
191
- * and transforms it into a specific error value of type `E`. This function
192
- * is crucial for creating a well-typed error for the `Err<E>` variant.
193
- * @returns A `Promise` that resolves to a `Result<T, E>`: `Ok<T>` if `options.try`'s `Promise` resolves,
194
- * or `Err<E>` if it rejects/throws and `options.mapError` provides an error value.
195
- * @example
196
- * ```ts
197
- * async function fetchData(url: string): Promise<Result<Response, Error>> {
198
- * return tryAsync({
199
- * try: async () => fetch(url),
200
- * mapError: (err: unknown) => {
201
- * if (err instanceof Error) return err;
202
- * return new Error("Network request failed");
203
- * }
204
- * });
205
- * }
206
- *
207
- * async function processData() {
208
- * const result = await fetchData("/api/data");
209
- * if (isOk(result)) {
210
- * const response = result.data;
211
- * console.log("Data fetched:", await response.json());
212
- * } else {
213
- * console.error("Fetch error:", result.error.message);
214
- * }
215
- * }
216
- * processData();
217
- * ```
218
- */
219
- async function tryAsync({ try: operation, mapError }) {
220
- try {
221
- const data = await operation();
222
- return Ok(data);
223
- } catch (error) {
224
- return Err(mapError(error));
225
- }
226
- }
227
- /**
228
- * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.
229
- *
230
- * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:
231
- * - If `value` is an `Ok<T>` variant, returns the contained success value.
232
- * - If `value` is an `Err<E>` variant, throws the contained error value.
233
- * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),
234
- * returns it as-is.
235
- *
236
- * This is useful when working with APIs that might return either direct values or Results,
237
- * allowing you to normalize them to the actual value or propagate errors via throwing.
238
- *
239
- * Use `resolve` when the input might or might not be a Result.
240
- * Use `unwrap` when you know the input is definitely a Result.
241
- *
242
- * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.
243
- * @template E - The type of the error value (if `value` is `Err<E>`).
244
- * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.
245
- * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.
246
- * @throws The error value `E` if `value` is an `Err<E>` variant.
247
- *
248
- * @example
249
- * ```ts
250
- * // Example with an Ok variant
251
- * const okResult = Ok("success data");
252
- * const resolved = resolve(okResult); // "success data"
253
- *
254
- * // Example with an Err variant
255
- * const errResult = Err(new Error("failure"));
256
- * try {
257
- * resolve(errResult);
258
- * } catch (e) {
259
- * console.error(e.message); // "failure"
260
- * }
261
- *
262
- * // Example with a plain value
263
- * const plainValue = "plain data";
264
- * const resolved = resolve(plainValue); // "plain data"
265
- *
266
- * // Example with a function that might return Result or plain value
267
- * declare function mightReturnResult(): string | Result<string, Error>;
268
- * const outcome = mightReturnResult();
269
- * try {
270
- * const finalValue = resolve(outcome); // handles both cases
271
- * console.log("Final value:", finalValue);
272
- * } catch (e) {
273
- * console.error("Operation failed:", e);
274
- * }
275
- * ```
276
- */
277
- /**
278
- * Unwraps a `Result<T, E>`, returning the success value or throwing the error.
279
- *
280
- * This function extracts the data from a `Result`:
281
- * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.
282
- * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.
283
- *
284
- * Unlike `resolve`, this function expects the input to always be a `Result` type,
285
- * making it more direct for cases where you know you're working with a `Result`.
286
- *
287
- * @template T - The type of the success value contained in the `Ok<T>` variant.
288
- * @template E - The type of the error value contained in the `Err<E>` variant.
289
- * @param result - The `Result<T, E>` to unwrap.
290
- * @returns The success value of type `T` if the `Result` is `Ok<T>`.
291
- * @throws The error value of type `E` if the `Result` is `Err<E>`.
292
- *
293
- * @example
294
- * ```ts
295
- * // Example with an Ok variant
296
- * const okResult = Ok("success data");
297
- * const value = unwrap(okResult); // "success data"
298
- *
299
- * // Example with an Err variant
300
- * const errResult = Err(new Error("something went wrong"));
301
- * try {
302
- * unwrap(errResult);
303
- * } catch (error) {
304
- * console.error(error.message); // "something went wrong"
305
- * }
306
- *
307
- * // Usage in a function that returns Result
308
- * function divide(a: number, b: number): Result<number, string> {
309
- * if (b === 0) return Err("Division by zero");
310
- * return Ok(a / b);
311
- * }
312
- *
313
- * try {
314
- * const result = unwrap(divide(10, 2)); // 5
315
- * console.log("Result:", result);
316
- * } catch (error) {
317
- * console.error("Division failed:", error);
318
- * }
319
- * ```
320
- */
321
- function unwrap(result) {
322
- if (isOk(result)) return result.data;
323
- throw result.error;
324
- }
325
- function resolve(value) {
326
- if (isResult(value)) {
327
- if (isOk(value)) return value.data;
328
- throw value.error;
329
- }
330
- return value;
331
- }
1
+ import { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-DxmXBFi5.js";
2
+ import { partitionResults } from "../result-BCv06xhR.js";
332
3
 
333
- //#endregion
334
- //#region src/result/utils.ts
335
- /**
336
- * Partitions an array of Result objects into two separate arrays based on their status.
337
- *
338
- * @template T - The success type
339
- * @template E - The error type
340
- * @param results - An array of Result objects to partition
341
- * @returns An object containing two arrays:
342
- * - `oks`: Array of successful Result objects (Ok<T>[])
343
- * - `errs`: Array of error Result objects (Err<E>[])
344
- *
345
- * @example
346
- * const results = [Ok(1), Err("error"), Ok(2)];
347
- * const { oks, errs } = partitionResults(results);
348
- * // oks = [Ok(1), Ok(2)]
349
- * // errs = [Err("error")]
350
- */
351
- function partitionResults(results) {
352
- return {
353
- oks: [],
354
- errs: [],
355
- ...Object.groupBy(results, (result) => isOk(result) ? "oks" : "errs")
356
- };
357
- }
358
-
359
- //#endregion
360
- export { Err, Ok, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
361
- //# sourceMappingURL=index.js.map
4
+ export { Err, Ok, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
@@ -0,0 +1,30 @@
1
+ import { isOk } from "./result-DxmXBFi5.js";
2
+
3
+ //#region src/result/utils.ts
4
+ /**
5
+ * Partitions an array of Result objects into two separate arrays based on their status.
6
+ *
7
+ * @template T - The success type
8
+ * @template E - The error type
9
+ * @param results - An array of Result objects to partition
10
+ * @returns An object containing two arrays:
11
+ * - `oks`: Array of successful Result objects (Ok<T>[])
12
+ * - `errs`: Array of error Result objects (Err<E>[])
13
+ *
14
+ * @example
15
+ * const results = [Ok(1), Err("error"), Ok(2)];
16
+ * const { oks, errs } = partitionResults(results);
17
+ * // oks = [Ok(1), Ok(2)]
18
+ * // errs = [Err("error")]
19
+ */
20
+ function partitionResults(results) {
21
+ return {
22
+ oks: [],
23
+ errs: [],
24
+ ...Object.groupBy(results, (result) => isOk(result) ? "oks" : "errs")
25
+ };
26
+ }
27
+
28
+ //#endregion
29
+ export { partitionResults };
30
+ //# sourceMappingURL=result-BCv06xhR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-BCv06xhR.js","names":["results: Result<T, E>[]"],"sources":["../src/result/utils.ts"],"sourcesContent":["import type { Err, Ok, Result } from \"./result.js\";\nimport { isOk } from \"./result.js\";\n\n/**\n * Partitions an array of Result objects into two separate arrays based on their status.\n *\n * @template T - The success type\n * @template E - The error type\n * @param results - An array of Result objects to partition\n * @returns An object containing two arrays:\n * - `oks`: Array of successful Result objects (Ok<T>[])\n * - `errs`: Array of error Result objects (Err<E>[])\n *\n * @example\n * const results = [Ok(1), Err(\"error\"), Ok(2)];\n * const { oks, errs } = partitionResults(results);\n * // oks = [Ok(1), Ok(2)]\n * // errs = [Err(\"error\")]\n */\nexport function partitionResults<T, E>(results: Result<T, E>[]) {\n\treturn {\n\t\toks: [],\n\t\terrs: [],\n\t\t...Object.groupBy(results, (result) => (isOk(result) ? \"oks\" : \"errs\")),\n\t} as { oks: Ok<T>[]; errs: Err<E>[] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,iBAAuBA,SAAyB;AAC/D,QAAO;EACN,KAAK,CAAE;EACP,MAAM,CAAE;EACR,GAAG,OAAO,QAAQ,SAAS,CAAC,WAAY,KAAK,OAAO,GAAG,QAAQ,OAAQ;CACvE;AACD"}