wellcrafted 0.19.1 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/error/index.d.ts +4 -4
- package/dist/error/index.js +4 -4
- package/dist/error/index.js.map +1 -1
- package/dist/{index-DRbikk8-.d.ts → index-BoczdhDh.d.ts} +2 -2
- package/dist/{index-DRbikk8-.d.ts.map → index-BoczdhDh.d.ts.map} +1 -1
- package/dist/query/index.d.ts +5 -5
- package/dist/query/index.d.ts.map +1 -1
- package/dist/query/index.js +7 -8
- package/dist/query/index.js.map +1 -1
- package/dist/result/index.d.ts +2 -2
- package/dist/result/index.js +2 -2
- package/dist/{result-DxmXBFi5.js → result-BJtW-Wuc.js} +25 -27
- package/dist/{result-DxmXBFi5.js.map → result-BJtW-Wuc.js.map} +1 -1
- package/dist/{result-BCv06xhR.js → result-DJgTC46e.js} +2 -2
- package/dist/{result-BCv06xhR.js.map → result-DJgTC46e.js.map} +1 -1
- package/dist/{result-t0dngyiE.d.ts → result-fCtNge01.d.ts} +25 -27
- package/dist/result-fCtNge01.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/result-t0dngyiE.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -81,7 +81,7 @@ type ApiError = ReturnType<typeof ApiError>;
|
|
|
81
81
|
// Wrap any throwing operation
|
|
82
82
|
const { data, error } = await tryAsync({
|
|
83
83
|
try: () => fetch('/api/user').then(r => r.json()),
|
|
84
|
-
|
|
84
|
+
mapErr: (error) => ApiErr({
|
|
85
85
|
message: "Failed to fetch user",
|
|
86
86
|
context: { endpoint: '/api/user' },
|
|
87
87
|
cause: error
|
|
@@ -182,7 +182,7 @@ if (error) {
|
|
|
182
182
|
// Synchronous
|
|
183
183
|
const result = trySync({
|
|
184
184
|
try: () => JSON.parse(jsonString),
|
|
185
|
-
|
|
185
|
+
mapErr: (error) => Err({
|
|
186
186
|
name: "ParseError",
|
|
187
187
|
message: "Invalid JSON",
|
|
188
188
|
context: { input: jsonString },
|
|
@@ -193,7 +193,7 @@ const result = trySync({
|
|
|
193
193
|
// Asynchronous
|
|
194
194
|
const result = await tryAsync({
|
|
195
195
|
try: () => fetch(url),
|
|
196
|
-
|
|
196
|
+
mapErr: (error) => Err({
|
|
197
197
|
name: "NetworkError",
|
|
198
198
|
message: "Request failed",
|
|
199
199
|
context: { url },
|
|
@@ -230,7 +230,7 @@ export function createUserService(db: Database) {
|
|
|
230
230
|
|
|
231
231
|
return tryAsync({
|
|
232
232
|
try: () => db.save(input),
|
|
233
|
-
|
|
233
|
+
mapErr: (error) => DatabaseErr({
|
|
234
234
|
message: "Failed to save user",
|
|
235
235
|
context: { operation: 'createUser', input },
|
|
236
236
|
cause: error
|
|
@@ -241,7 +241,7 @@ export function createUserService(db: Database) {
|
|
|
241
241
|
async getUser(id: string): Promise<Result<User | null, DatabaseError>> {
|
|
242
242
|
return tryAsync({
|
|
243
243
|
try: () => db.findById(id),
|
|
244
|
-
|
|
244
|
+
mapErr: (error) => DatabaseErr({
|
|
245
245
|
message: "Failed to fetch user",
|
|
246
246
|
context: { userId: id },
|
|
247
247
|
cause: error
|
package/dist/error/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Err } from "../result-
|
|
1
|
+
import { Err } from "../result-fCtNge01.js";
|
|
2
2
|
|
|
3
3
|
//#region src/error/types.d.ts
|
|
4
4
|
|
|
@@ -80,7 +80,7 @@ type TaggedError<T extends string> = BaseError & {
|
|
|
80
80
|
/**
|
|
81
81
|
* Extracts a readable error message from an unknown error value
|
|
82
82
|
*
|
|
83
|
-
* This utility is commonly used in
|
|
83
|
+
* This utility is commonly used in mapErr functions when converting
|
|
84
84
|
* unknown errors to typed error objects in the Result system.
|
|
85
85
|
*
|
|
86
86
|
* @param error - The unknown error to extract a message from
|
|
@@ -100,10 +100,10 @@ type TaggedError<T extends string> = BaseError & {
|
|
|
100
100
|
* const unknownError = { code: 500, details: "Server error" };
|
|
101
101
|
* const message3 = extractErrorMessage(unknownError); // '{"code":500,"details":"Server error"}'
|
|
102
102
|
*
|
|
103
|
-
* // Used in
|
|
103
|
+
* // Used in mapErr function
|
|
104
104
|
* const result = await tryAsync({
|
|
105
105
|
* try: () => riskyOperation(),
|
|
106
|
-
*
|
|
106
|
+
* mapErr: (error) => Err({
|
|
107
107
|
* name: "NetworkError",
|
|
108
108
|
* message: extractErrorMessage(error),
|
|
109
109
|
* context: { operation: "riskyOperation" },
|
package/dist/error/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Err } from "../result-
|
|
1
|
+
import { Err } from "../result-BJtW-Wuc.js";
|
|
2
2
|
|
|
3
3
|
//#region src/error/utils.ts
|
|
4
4
|
/**
|
|
5
5
|
* Extracts a readable error message from an unknown error value
|
|
6
6
|
*
|
|
7
|
-
* This utility is commonly used in
|
|
7
|
+
* This utility is commonly used in mapErr functions when converting
|
|
8
8
|
* unknown errors to typed error objects in the Result system.
|
|
9
9
|
*
|
|
10
10
|
* @param error - The unknown error to extract a message from
|
|
@@ -24,10 +24,10 @@ import { Err } from "../result-DxmXBFi5.js";
|
|
|
24
24
|
* const unknownError = { code: 500, details: "Server error" };
|
|
25
25
|
* const message3 = extractErrorMessage(unknownError); // '{"code":500,"details":"Server error"}'
|
|
26
26
|
*
|
|
27
|
-
* // Used in
|
|
27
|
+
* // Used in mapErr function
|
|
28
28
|
* const result = await tryAsync({
|
|
29
29
|
* try: () => riskyOperation(),
|
|
30
|
-
*
|
|
30
|
+
* mapErr: (error) => Err({
|
|
31
31
|
* name: "NetworkError",
|
|
32
32
|
* message: extractErrorMessage(error),
|
|
33
33
|
* context: { operation: "riskyOperation" },
|
package/dist/error/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["error: unknown","name: TErrorName","error: TaggedErrorWithoutName<TErrorName>"],"sources":["../../src/error/utils.ts"],"sourcesContent":["import type { TaggedError } from \"./types.js\";\nimport { Err } from \"../result/result.js\";\n\n/**\n * Extracts a readable error message from an unknown error value\n *\n * This utility is commonly used in
|
|
1
|
+
{"version":3,"file":"index.js","names":["error: unknown","name: TErrorName","error: TaggedErrorWithoutName<TErrorName>"],"sources":["../../src/error/utils.ts"],"sourcesContent":["import type { TaggedError } from \"./types.js\";\nimport { Err } from \"../result/result.js\";\n\n/**\n * Extracts a readable error message from an unknown error value\n *\n * This utility is commonly used in mapErr functions when converting\n * unknown errors to typed error objects in the Result system.\n *\n * @param error - The unknown error to extract a message from\n * @returns A string representation of the error\n *\n * @example\n * ```ts\n * // With native Error\n * const error = new Error(\"Something went wrong\");\n * const message = extractErrorMessage(error); // \"Something went wrong\"\n *\n * // With string error\n * const stringError = \"String error\";\n * const message2 = extractErrorMessage(stringError); // \"String error\"\n *\n * // With object error\n * const unknownError = { code: 500, details: \"Server error\" };\n * const message3 = extractErrorMessage(unknownError); // '{\"code\":500,\"details\":\"Server error\"}'\n *\n * // Used in mapErr function\n * const result = await tryAsync({\n * try: () => riskyOperation(),\n * mapErr: (error) => Err({\n * name: \"NetworkError\",\n * message: extractErrorMessage(error),\n * context: { operation: \"riskyOperation\" },\n * cause: error,\n * }),\n * });\n * ```\n */\nexport function extractErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\n\tif (typeof error === \"object\" && error !== null) {\n\t\t// Check for common error properties\n\t\tconst errorObj = error as Record<string, unknown>;\n\t\tif (typeof errorObj.message === \"string\") {\n\t\t\treturn errorObj.message;\n\t\t}\n\t\tif (typeof errorObj.error === \"string\") {\n\t\t\treturn errorObj.error;\n\t\t}\n\t\tif (typeof errorObj.description === \"string\") {\n\t\t\treturn errorObj.description;\n\t\t}\n\n\t\t// Fallback to JSON stringification\n\t\ttry {\n\t\t\treturn JSON.stringify(error);\n\t\t} catch {\n\t\t\treturn String(error);\n\t\t}\n\t}\n\n\treturn String(error);\n}\n\n/**\n * Input type for creating a tagged error (everything except the name)\n */\ntype TaggedErrorWithoutName<T extends string> = Omit<TaggedError<T>, \"name\">;\n\n/**\n * Replaces the \"Error\" suffix with \"Err\" suffix in error type names.\n *\n * This utility type is used to create companion function names for error constructors\n * that return Err-wrapped results, maintaining consistent naming conventions.\n *\n * @template T - An error type name that must end with \"Error\"\n * @returns The type name with \"Error\" replaced by \"Err\"\n *\n * @example\n * ```ts\n * type NetworkErr = ReplaceErrorWithErr<\"NetworkError\">; // \"NetworkErr\"\n * type ValidationErr = ReplaceErrorWithErr<\"ValidationError\">; // \"ValidationErr\"\n * type AuthErr = ReplaceErrorWithErr<\"AuthError\">; // \"AuthErr\"\n * ```\n */\ntype ReplaceErrorWithErr<T extends `${string}Error`> =\n\tT extends `${infer TBase}Error` ? `${TBase}Err` : never;\n\n/**\n * Return type for createTaggedError - contains both factory functions.\n *\n * Provides two factory functions:\n * - One that creates plain TaggedError objects (named with \"Error\" suffix)\n * - One that creates Err-wrapped TaggedError objects (named with \"Err\" suffix)\n */\ntype TaggedErrorFactories<TErrorName extends `${string}Error`> = {\n\t[K in TErrorName]: (input: TaggedErrorWithoutName<K>) => TaggedError<K>;\n} & {\n\t[K in ReplaceErrorWithErr<TErrorName>]: (\n\t\tinput: TaggedErrorWithoutName<TErrorName>,\n\t) => Err<TaggedError<TErrorName>>;\n};\n\n/**\n * Returns two different factory functions for tagged errors.\n *\n * Given an error name like \"NetworkError\", this returns:\n * - `NetworkError`: Creates a plain TaggedError object\n * - `NetworkErr`: Creates a TaggedError object wrapped in an Err result\n *\n * The naming pattern automatically replaces the \"Error\" suffix with \"Err\" suffix\n * for the Result-wrapped version.\n *\n * @param name - The name of the error type (must end with \"Error\")\n * @returns An object with two factory functions:\n * - [name]: Function that creates plain TaggedError objects\n * - [name with \"Error\" replaced by \"Err\"]: Function that creates Err-wrapped TaggedError objects\n *\n * @example\n * ```ts\n * const { NetworkError, NetworkErr } = createTaggedError('NetworkError');\n *\n * // NetworkError: Creates just the error object\n * const error = NetworkError({\n * message: 'Connection failed',\n * context: { url: 'https://api.example.com' },\n * cause: undefined\n * });\n * // Returns: { name: 'NetworkError', message: 'Connection failed', ... }\n *\n * // NetworkErr: Creates error and wraps in Err result\n * return NetworkErr({\n * message: 'Connection failed',\n * context: { url: 'https://api.example.com' },\n * cause: undefined\n * });\n * // Returns: Err({ name: 'NetworkError', message: 'Connection failed', ... })\n * ```\n */\nexport function createTaggedError<TErrorName extends `${string}Error`>(\n\tname: TErrorName,\n): TaggedErrorFactories<TErrorName> {\n\tconst errorConstructor = (\n\t\terror: TaggedErrorWithoutName<TErrorName>,\n\t): TaggedError<TErrorName> => ({ ...error, name }) as TaggedError<TErrorName>;\n\n\tconst errName = name.replace(\n\t\t/Error$/,\n\t\t\"Err\",\n\t) as ReplaceErrorWithErr<TErrorName>;\n\tconst errConstructor = (error: TaggedErrorWithoutName<TErrorName>) =>\n\t\tErr(errorConstructor(error));\n\n\treturn {\n\t\t[name]: errorConstructor,\n\t\t[errName]: errConstructor,\n\t} as TaggedErrorFactories<TErrorName>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,oBAAoBA,OAAwB;AAC3D,KAAI,iBAAiB,MACpB,QAAO,MAAM;AAGd,YAAW,UAAU,SACpB,QAAO;AAGR,YAAW,UAAU,YAAY,UAAU,MAAM;EAEhD,MAAM,WAAW;AACjB,aAAW,SAAS,YAAY,SAC/B,QAAO,SAAS;AAEjB,aAAW,SAAS,UAAU,SAC7B,QAAO,SAAS;AAEjB,aAAW,SAAS,gBAAgB,SACnC,QAAO,SAAS;AAIjB,MAAI;AACH,UAAO,KAAK,UAAU,MAAM;EAC5B,QAAO;AACP,UAAO,OAAO,MAAM;EACpB;CACD;AAED,QAAO,OAAO,MAAM;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ED,SAAgB,kBACfC,MACmC;CACnC,MAAM,mBAAmB,CACxBC,WAC8B;EAAE,GAAG;EAAO;CAAM;CAEjD,MAAM,UAAU,KAAK,QACpB,UACA,MACA;CACD,MAAM,iBAAiB,CAACA,UACvB,IAAI,iBAAiB,MAAM,CAAC;AAE7B,QAAO;GACL,OAAO;GACP,UAAU;CACX;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Err, Ok, Result } from "./result-
|
|
1
|
+
import { Err, Ok, Result } from "./result-fCtNge01.js";
|
|
2
2
|
|
|
3
3
|
//#region src/result/utils.d.ts
|
|
4
4
|
|
|
@@ -25,4 +25,4 @@ declare function partitionResults<T, E>(results: Result<T, E>[]): {
|
|
|
25
25
|
//# sourceMappingURL=utils.d.ts.map
|
|
26
26
|
//#endregion
|
|
27
27
|
export { partitionResults };
|
|
28
|
-
//# sourceMappingURL=index-
|
|
28
|
+
//# sourceMappingURL=index-BoczdhDh.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-BoczdhDh.d.ts","names":[],"sources":["../src/result/utils.ts"],"sourcesContent":[],"mappings":";;;;;;AAmBA;;;;;;;;;AAK+B;;;;;iBALf,gCAAgC,OAAO,GAAG;OAK7C,GAAG;QAAY,IAAI"}
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Result } from "../result-
|
|
2
|
-
import "../index-
|
|
1
|
+
import { Result } from "../result-fCtNge01.js";
|
|
2
|
+
import "../index-BoczdhDh.js";
|
|
3
3
|
import { MutationFunction, MutationKey, MutationOptions, QueryClient, QueryFunction, QueryKey, QueryObserverOptions } from "@tanstack/query-core";
|
|
4
4
|
|
|
5
5
|
//#region src/query/utils.d.ts
|
|
@@ -25,7 +25,7 @@ type DefineQueryInput<TQueryFnData, TError, TData = TQueryFnData, TQueryKey exte
|
|
|
25
25
|
*
|
|
26
26
|
* Provides both reactive and imperative interfaces for data fetching:
|
|
27
27
|
* - `options()`: Returns config for use with createQuery() in components
|
|
28
|
-
* - `
|
|
28
|
+
* - `fetch()`: Imperatively fetches data (useful for actions/event handlers)
|
|
29
29
|
*
|
|
30
30
|
* @template TQueryFnData - The type of data returned by the query function
|
|
31
31
|
* @template TError - The type of error that can be thrown
|
|
@@ -34,7 +34,7 @@ type DefineQueryInput<TQueryFnData, TError, TData = TQueryFnData, TQueryKey exte
|
|
|
34
34
|
*/
|
|
35
35
|
type DefineQueryOutput<TQueryFnData, TError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = {
|
|
36
36
|
options: () => QueryObserverOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>;
|
|
37
|
-
|
|
37
|
+
fetch: () => Promise<Result<TData, TError>>;
|
|
38
38
|
};
|
|
39
39
|
/**
|
|
40
40
|
* Input options for defining a mutation.
|
|
@@ -106,7 +106,7 @@ type DefineMutationOutput<TData, TError, TVariables, TContext = unknown> = {
|
|
|
106
106
|
* const query = createQuery(userQuery.options());
|
|
107
107
|
*
|
|
108
108
|
* // Or imperatively
|
|
109
|
-
* const { data, error } = await userQuery.
|
|
109
|
+
* const { data, error } = await userQuery.fetch();
|
|
110
110
|
* ```
|
|
111
111
|
*/
|
|
112
112
|
declare function createQueryFactories(queryClient: QueryClient): {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/query/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAwBA;;;;;;;;;;AAMC,KANW,gBAMX,CAAA,YAAA,EAAA,MAAA,EAAA,QAHQ,YAGR,EAAA,kBAFkB,QAElB,GAF6B,QAE7B,CAAA,GADG,IACH,CAAA,oBAAA,CAAqB,YAArB,EAAmC,MAAnC,EAA2C,KAA3C,EAAkD,YAAlD,EAAgE,SAAhE,CAAA,EAAA,SAAA,CAAA,GAAA;EAAoB,QADjB,EAIO,SAJP;EAAI,aAIG,EACK,aADL,CACmB,MADnB,CAC0B,YAD1B,EACwC,MADxC,CAAA,EACiD,SADjD,CAAA;CAAS;;;;;AACS;AAe7B;;;;;;;AASE,KATU,iBASV,CAAA,YAAA,EAAA,MAAA,EAAA,QANO,YAMP,EAAA,kBALiB,QAKjB,GAL4B,QAK5B,CAAA,GAAA;EAAK,OACL,EAAA,GAAA,GAJc,oBAId,CAHA,YAGA,EAFA,MAEA,EADA,KACA,EAAA,YAAA,EACA,SADA,CAAA;EAAY,
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/query/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAwBA;;;;;;;;;;AAMC,KANW,gBAMX,CAAA,YAAA,EAAA,MAAA,EAAA,QAHQ,YAGR,EAAA,kBAFkB,QAElB,GAF6B,QAE7B,CAAA,GADG,IACH,CAAA,oBAAA,CAAqB,YAArB,EAAmC,MAAnC,EAA2C,KAA3C,EAAkD,YAAlD,EAAgE,SAAhE,CAAA,EAAA,SAAA,CAAA,GAAA;EAAoB,QADjB,EAIO,SAJP;EAAI,aAIG,EACK,aADL,CACmB,MADnB,CAC0B,YAD1B,EACwC,MADxC,CAAA,EACiD,SADjD,CAAA;CAAS;;;;;AACS;AAe7B;;;;;;;AASE,KATU,iBASV,CAAA,YAAA,EAAA,MAAA,EAAA,QANO,YAMP,EAAA,kBALiB,QAKjB,GAL4B,QAK5B,CAAA,GAAA;EAAK,OACL,EAAA,GAAA,GAJc,oBAId,CAHA,YAGA,EAFA,MAEA,EADA,KACA,EAAA,YAAA,EACA,SADA,CAAA;EAAY,KACZ,EAAA,GAAA,GAEY,OAFZ,CAEoB,MAFpB,CAE2B,KAF3B,EAEkC,MAFlC,CAAA,CAAA;CAAS;;;;;AAEU;AAerB;;;;;;;AAKI,KALQ,mBAKR,CAAA,KAAA,EAAA,MAAA,EAAA,UAAA,EAAA,WAAA,OAAA,CAAA,GAAA,IAAA,CAAK,eAAL,CAAqB,KAArB,EAA4B,MAA5B,EAAoC,UAApC,EAAgD,QAAhD,CAAA,EAAA,YAAA,CAAA,GAAA;EAAI,WACM,EAAA,WAAA;EAAW,gBACkB,EAAxB,gBAAwB,CAAP,MAAO,CAAA,KAAA,EAAO,MAAP,CAAA,EAAgB,UAAhB,CAAA;CAAK;;;;AAAb;AAenC;;;;;;;;AAOoD,KAPxC,oBAOwC,CAAA,KAAA,EAAA,MAAA,EAAA,UAAA,EAAA,WAAA,OAAA,CAAA,GAAA;EAAK,OAAE,EAAA,GAAA,GAD3C,eAC2C,CAD3B,KAC2B,EADpB,MACoB,EADZ,UACY,EADA,QACA,CAAA;EAAM,OAApB,EAAA,CAAA,SAAA,EAAvB,UAAuB,EAAA,GAAR,OAAQ,CAAA,MAAA,CAAO,KAAP,EAAc,MAAd,CAAA,CAAA;CAAM;AAAP;AA4C5C;;;;;;;;;;;;;;;;;;;;;;;;;AA0LwB;;;;;;;;;;;;;;;iBA1LR,oBAAA,cAAkC;8CAsD3C,gCACa,wCAET,iBAAiB,cAAc,QAAQ,OAAO,eACrD,kBAAkB,cAAc,QAAQ,OAAO;2EA+HxC,oBAAoB,OAAO,QAAQ,YAAY,cACtD,qBAAqB,OAAO,QAAQ,YAAY"}
|
package/dist/query/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Err, Ok, resolve } from "../result-
|
|
2
|
-
import "../result-
|
|
1
|
+
import { Err, Ok, resolve } from "../result-BJtW-Wuc.js";
|
|
2
|
+
import "../result-DJgTC46e.js";
|
|
3
3
|
|
|
4
4
|
//#region src/query/utils.ts
|
|
5
5
|
/**
|
|
@@ -40,7 +40,7 @@ import "../result-BCv06xhR.js";
|
|
|
40
40
|
* const query = createQuery(userQuery.options());
|
|
41
41
|
*
|
|
42
42
|
* // Or imperatively
|
|
43
|
-
* const { data, error } = await userQuery.
|
|
43
|
+
* const { data, error } = await userQuery.fetch();
|
|
44
44
|
* ```
|
|
45
45
|
*/
|
|
46
46
|
function createQueryFactories(queryClient) {
|
|
@@ -52,7 +52,7 @@ function createQueryFactories(queryClient) {
|
|
|
52
52
|
*
|
|
53
53
|
* ## Why use defineQuery?
|
|
54
54
|
*
|
|
55
|
-
* 1. **Dual Interface**: Provides both reactive (`.options()`) and imperative (`.
|
|
55
|
+
* 1. **Dual Interface**: Provides both reactive (`.options()`) and imperative (`.fetch()`) APIs
|
|
56
56
|
* 2. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically
|
|
57
57
|
* unwrapped by TanStack Query, giving you proper error states in your components
|
|
58
58
|
* 3. **Type Safety**: Full TypeScript support with proper inference for data and error types
|
|
@@ -70,7 +70,7 @@ function createQueryFactories(queryClient) {
|
|
|
70
70
|
*
|
|
71
71
|
* @returns Query definition object with two methods:
|
|
72
72
|
* - `options()`: Returns config for use with createQuery() in Svelte components
|
|
73
|
-
*
|
|
73
|
+
* - `fetch()`: Imperatively fetches data (useful for actions/event handlers)
|
|
74
74
|
*
|
|
75
75
|
* @example
|
|
76
76
|
* ```typescript
|
|
@@ -88,8 +88,7 @@ function createQueryFactories(queryClient) {
|
|
|
88
88
|
*
|
|
89
89
|
* // Step 2b: Use imperatively in an action
|
|
90
90
|
* async function prefetchUser() {
|
|
91
|
-
* const { data, error } = await userQuery.
|
|
92
|
-
* if (error) {
|
|
91
|
+
* const { data, error } = await userQuery.fetch(); * if (error) {
|
|
93
92
|
* console.error('Failed to fetch user:', error);
|
|
94
93
|
* }
|
|
95
94
|
* }
|
|
@@ -106,7 +105,7 @@ function createQueryFactories(queryClient) {
|
|
|
106
105
|
};
|
|
107
106
|
return {
|
|
108
107
|
options: () => newOptions,
|
|
109
|
-
async
|
|
108
|
+
async fetch() {
|
|
110
109
|
try {
|
|
111
110
|
return Ok(await queryClient.fetchQuery({
|
|
112
111
|
queryKey: newOptions.queryKey,
|
package/dist/query/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["queryClient: QueryClient","options: DefineQueryInput<TQueryFnData, TError, TData, TQueryKey>","context: QueryFunctionContext<TQueryKey>","options: DefineMutationInput<TData, TError, TVariables, TContext>","variables: TVariables","options: MutationOptions<TData, TError, TVariables, TContext>"],"sources":["../../src/query/utils.ts"],"sourcesContent":["import type {\n\tMutationFunction,\n\tMutationKey,\n\tMutationOptions,\n\tQueryClient,\n\tQueryFunction,\n\tQueryFunctionContext,\n\tQueryKey,\n} from \"@tanstack/query-core\";\nimport { Err, Ok, type Result, resolve } from \"../result/index.js\";\nimport type { QueryObserverOptions } from \"@tanstack/query-core\";\n\n/**\n * Input options for defining a query.\n *\n * Extends TanStack Query's QueryObserverOptions but replaces queryFn with resultQueryFn.\n * This type represents the configuration for creating a query definition with both\n * reactive and imperative interfaces for data fetching.\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\nexport type DefineQueryInput<\n\tTQueryFnData,\n\tTError,\n\tTData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = Omit<\n\tQueryObserverOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>,\n\t\"queryFn\"\n> & {\n\tqueryKey: TQueryKey;\n\tresultQueryFn: QueryFunction<Result<TQueryFnData, TError>, TQueryKey>;\n};\n\n/**\n * Output of defineQuery function.\n *\n * Provides both reactive and imperative interfaces for data fetching:\n * - `options()`: Returns config for use with createQuery() in components\n * - `fetchCached()`: Imperatively fetches data (useful for actions/event handlers)\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\nexport type DefineQueryOutput<\n\tTQueryFnData,\n\tTError,\n\tTData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = {\n\toptions: () => QueryObserverOptions<\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData,\n\t\tTQueryFnData,\n\t\tTQueryKey\n\t>;\n\tfetchCached: () => Promise<Result<TData, TError>>;\n};\n\n/**\n * Input options for defining a mutation.\n *\n * Extends TanStack Query's MutationOptions but replaces mutationFn with resultMutationFn.\n * This type represents the configuration for creating a mutation definition with both\n * reactive and imperative interfaces for data mutations.\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\nexport type DefineMutationInput<\n\tTData,\n\tTError,\n\tTVariables,\n\tTContext = unknown,\n> = Omit<MutationOptions<TData, TError, TVariables, TContext>, \"mutationFn\"> & {\n\tmutationKey: MutationKey;\n\tresultMutationFn: MutationFunction<Result<TData, TError>, TVariables>;\n};\n\n/**\n * Output of defineMutation function.\n *\n * Provides both reactive and imperative interfaces for data mutations:\n * - `options()`: Returns config for use with createMutation() in Svelte components\n * - `execute()`: Directly executes the mutation and returns a Result\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\nexport type DefineMutationOutput<\n\tTData,\n\tTError,\n\tTVariables,\n\tTContext = unknown,\n> = {\n\toptions: () => MutationOptions<TData, TError, TVariables, TContext>;\n\texecute: (variables: TVariables) => Promise<Result<TData, TError>>;\n};\n\n/**\n * Creates factory functions for defining queries and mutations bound to a specific QueryClient.\n *\n * This factory pattern allows you to create isolated query/mutation definitions that are\n * bound to a specific QueryClient instance, enabling:\n * - Multiple query clients in the same application\n * - Testing with isolated query clients\n * - Framework-agnostic query definitions\n * - Proper separation of concerns between query logic and client instances\n *\n * The returned functions handle Result types automatically, unwrapping them for TanStack Query\n * while maintaining type safety throughout your application.\n *\n * @param queryClient - The QueryClient instance to bind the factories to\n * @returns An object containing defineQuery and defineMutation functions bound to the provided client\n *\n * @example\n * ```typescript\n * // Create your query client\n * const queryClient = new QueryClient({\n * defaultOptions: {\n * queries: { staleTime: 5 * 60 * 1000 }\n * }\n * });\n *\n * // Create the factory functions\n * const { defineQuery, defineMutation } = createQueryFactories(queryClient);\n *\n * // Now use defineQuery and defineMutation as before\n * const userQuery = defineQuery({\n * queryKey: ['user', userId],\n * resultQueryFn: () => services.getUser(userId)\n * });\n *\n * // Use in components\n * const query = createQuery(userQuery.options());\n *\n * // Or imperatively\n * const { data, error } = await userQuery.fetchCached();\n * ```\n */\nexport function createQueryFactories(queryClient: QueryClient) {\n\t/**\n\t * Creates a query definition that bridges the gap between pure service functions and reactive UI components.\n\t *\n\t * This factory function is the cornerstone of our data fetching architecture. It wraps service calls\n\t * with TanStack Query superpowers while maintaining type safety through Result types.\n\t *\n\t * ## Why use defineQuery?\n\t *\n\t * 1. **Dual Interface**: Provides both reactive (`.options()`) and imperative (`.fetchCached()`) APIs\n\t * 2. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically\n\t * unwrapped by TanStack Query, giving you proper error states in your components\n\t * 3. **Type Safety**: Full TypeScript support with proper inference for data and error types\n\t * 4. **Consistency**: Every query in the app follows the same pattern, making it easy to understand\n\t *\n\t * @template TQueryFnData - The type of data returned by the query function\n\t * @template TError - The type of error that can be thrown\n\t * @template TData - The type of data returned by the query (after select transform)\n\t * @template TQueryKey - The type of the query key\n\t *\n\t * @param options - Query configuration object\n\t * @param options.queryKey - Unique key for this query (used for caching and refetching)\n\t * @param options.resultQueryFn - Function that fetches data and returns a Result type\n\t * @param options.* - Any other TanStack Query options (staleTime, refetchInterval, etc.)\n\t *\n\t * @returns Query definition object with two methods:\n\t * - `options()`: Returns config for use with createQuery() in Svelte components\n\t * - `fetchCached()`: Imperatively fetches data (useful for actions/event handlers)\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your query in the query layer\n\t * const userQuery = defineQuery({\n\t * queryKey: ['users', userId],\n\t * resultQueryFn: () => services.getUser(userId), // Returns Result<User, ApiError>\n\t * staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte component\n\t * const query = createQuery(userQuery.options());\n\t * // $query.data is User | undefined\n\t * // $query.error is ApiError | null\n\t *\n\t * // Step 2b: Use imperatively in an action\n\t * async function prefetchUser() {\n\t * const { data, error } = await userQuery.fetchCached();\n\t * if (error) {\n\t * console.error('Failed to fetch user:', error);\n\t * }\n\t * }\n\t * ```\n\t */\n\tconst defineQuery = <\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData = TQueryFnData,\n\t\tTQueryKey extends QueryKey = QueryKey,\n\t>(\n\t\toptions: DefineQueryInput<TQueryFnData, TError, TData, TQueryKey>,\n\t): DefineQueryOutput<TQueryFnData, TError, TData, TQueryKey> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tqueryFn: async (context: QueryFunctionContext<TQueryKey>) => {\n\t\t\t\tlet result = options.resultQueryFn(context);\n\t\t\t\tif (result instanceof Promise) result = await result;\n\t\t\t\treturn resolve(result);\n\t\t\t},\n\t\t} satisfies QueryObserverOptions<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryFnData,\n\t\t\tTQueryKey\n\t\t>;\n\n\t\treturn {\n\t\t\t/**\n\t\t\t * Returns the query options for reactive usage with TanStack Query hooks.\n\t\t\t * Use this with `createQuery()` in Svelte components for automatic subscriptions.\n\t\t\t * @returns The query options object configured for TanStack Query\n\t\t\t */\n\t\t\toptions: () => newOptions,\n\n\t\t\t/**\n\t\t\t * Fetches data for this query, returning cached data if fresh or refetching if stale/missing.\n\t\t\t *\n\t\t\t * This method is perfect for:\n\t\t\t * - Prefetching data before navigation\n\t\t\t * - Loading data in response to user actions\n\t\t\t * - Accessing query data outside of components\n\t\t\t *\n\t\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t\t *\n\t\t\t * @example\n\t\t\t * const { data, error } = await userQuery.fetchCached();\n\t\t\t * if (error) {\n\t\t\t * console.error('Failed to load user:', error);\n\t\t\t * }\n\t\t\t */\n\t\t\tasync fetchCached(): Promise<Result<TData, TError>> {\n\t\t\t\ttry {\n\t\t\t\t\treturn Ok(\n\t\t\t\t\t\tawait queryClient.fetchQuery<TQueryFnData, Error, TData, TQueryKey>(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn Err(error as TError);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t};\n\n\t/**\n\t * Creates a mutation definition for operations that modify data (create, update, delete).\n\t *\n\t * This factory function is the mutation counterpart to defineQuery. It provides a clean way to\n\t * wrap service functions that perform side effects, while maintaining the same dual interface\n\t * pattern for maximum flexibility.\n\t *\n\t * ## Why use defineMutation?\n\t *\n\t * 1. **Dual Interface**: Just like queries, mutations can be used reactively or imperatively\n\t * 2. **Direct Execution**: The `.execute()` method lets you run mutations without creating hooks,\n\t * perfect for event handlers and non-component code\n\t * 3. **Consistent Error Handling**: Service functions return `Result<T, E>` types, ensuring\n\t * errors are handled consistently throughout the app\n\t * 4. **Cache Management**: Mutations often update the cache after success (see examples)\n\t *\n\t * @template TData - The type of data returned by the mutation\n\t * @template TError - The type of error that can be thrown\n\t * @template TVariables - The type of variables passed to the mutation\n\t * @template TContext - The type of context data for optimistic updates\n\t *\n\t * @param options - Mutation configuration object\n\t * @param options.mutationKey - Unique key for this mutation (used for tracking in-flight state)\n\t * @param options.resultMutationFn - Function that performs the mutation and returns a Result type\n\t * @param options.* - Any other TanStack Mutation options (onSuccess, onError, etc.)\n\t *\n\t * @returns Mutation definition object with two methods:\n\t * - `options()`: Returns config for use with createMutation() in Svelte components\n\t * - `execute()`: Directly executes the mutation and returns a Result\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your mutation with cache updates\n\t * const createRecording = defineMutation({\n\t * mutationKey: ['recordings', 'create'],\n\t * resultMutationFn: async (recording: Recording) => {\n\t * // Call the service\n\t * const result = await services.db.createRecording(recording);\n\t * if (result.error) return Err(result.error);\n\t *\n\t * // Update cache on success\n\t * queryClient.setQueryData(['recordings'], (old) =>\n\t * [...(old || []), recording]\n\t * );\n\t *\n\t * return Ok(result.data);\n\t * }\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a component\n\t * const mutation = createMutation(createRecording.options());\n\t * // Call with: $mutation.mutate(recordingData)\n\t *\n\t * // Step 2b: Use imperatively in an action\n\t * async function saveRecording(data: Recording) {\n\t * const { error } = await createRecording.execute(data);\n\t * if (error) {\n\t * notify.error.execute({ title: 'Failed to save', description: error.message });\n\t * } else {\n\t * notify.success.execute({ title: 'Recording saved!' });\n\t * }\n\t * }\n\t * ```\n\t *\n\t * @tip The imperative `.execute()` method is especially useful for:\n\t * - Event handlers that need to await the result\n\t * - Sequential operations that depend on each other\n\t * - Non-component code that needs to trigger mutations\n\t */\n\tconst defineMutation = <TData, TError, TVariables, TContext = unknown>(\n\t\toptions: DefineMutationInput<TData, TError, TVariables, TContext>,\n\t): DefineMutationOutput<TData, TError, TVariables, TContext> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tmutationFn: async (variables: TVariables) => {\n\t\t\t\treturn resolve(await options.resultMutationFn(variables));\n\t\t\t},\n\t\t} satisfies MutationOptions<TData, TError, TVariables, TContext>;\n\n\t\treturn {\n\t\t\t/**\n\t\t\t * Returns the mutation options for reactive usage with TanStack Query hooks.\n\t\t\t * Use this with `createMutation()` in Svelte components for reactive mutation state.\n\t\t\t * @returns The mutation options object configured for TanStack Query\n\t\t\t */\n\t\t\toptions: () => newOptions,\n\t\t\t/**\n\t\t\t * Bypasses the reactive mutation hooks and executes the mutation imperatively.\n\t\t\t *\n\t\t\t * This is the recommended way to trigger mutations from:\n\t\t\t * - Button click handlers\n\t\t\t * - Form submissions\n\t\t\t * - Keyboard shortcuts\n\t\t\t * - Any non-component code\n\t\t\t *\n\t\t\t * The method automatically wraps the result in a Result type, so you always\n\t\t\t * get back `{ data, error }` for consistent error handling.\n\t\t\t *\n\t\t\t * @param variables - The variables to pass to the mutation function\n\t\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t\t *\n\t\t\t * @example\n\t\t\t * // In an event handler\n\t\t\t * async function handleSubmit(formData: FormData) {\n\t\t\t * const { data, error } = await createUser.execute(formData);\n\t\t\t * if (error) {\n\t\t\t * notify.error.execute({ title: 'Failed to create user', description: error.message });\n\t\t\t * return;\n\t\t\t * }\n\t\t\t * goto(`/users/${data.id}`);\n\t\t\t * }\n\t\t\t */\n\t\t\tasync execute(variables: TVariables) {\n\t\t\t\ttry {\n\t\t\t\t\treturn Ok(await executeMutation(queryClient, newOptions, variables));\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn Err(error as TError);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t};\n\n\treturn {\n\t\tdefineQuery,\n\t\tdefineMutation,\n\t};\n}\n\n/**\n * Internal helper that executes a mutation directly using the query client's mutation cache.\n *\n * This is what powers the `.execute()` method on mutations. It bypasses the reactive\n * mutation hooks and runs the mutation imperatively, which is perfect for event handlers\n * and other imperative code.\n *\n * @internal\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data\n * @param queryClient - The query client instance to use\n * @param options - The mutation options including mutationFn and mutationKey\n * @param variables - The variables to pass to the mutation function\n * @returns Promise that resolves with the mutation result\n */\nfunction executeMutation<TData, TError, TVariables, TContext>(\n\tqueryClient: QueryClient,\n\toptions: MutationOptions<TData, TError, TVariables, TContext>,\n\tvariables: TVariables,\n) {\n\tconst mutation = queryClient.getMutationCache().build(queryClient, options);\n\treturn mutation.execute(variables);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsJA,SAAgB,qBAAqBA,aAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoD9D,MAAM,cAAc,CAMnBC,YAC+D;EAC/D,MAAM,aAAa;GAClB,GAAG;GACH,SAAS,OAAOC,YAA6C;IAC5D,IAAI,SAAS,QAAQ,cAAc,QAAQ;AAC3C,QAAI,kBAAkB,QAAS,UAAS,MAAM;AAC9C,WAAO,QAAQ,OAAO;GACtB;EACD;AAQD,SAAO;GAMN,SAAS,MAAM;GAkBf,MAAM,cAA8C;AACnD,QAAI;AACH,YAAO,GACN,MAAM,YAAY,WACjB;MACC,UAAU,WAAW;MACrB,SAAS,WAAW;KACpB,EACD,CACD;IACD,SAAQ,OAAO;AACf,YAAO,IAAI,MAAgB;IAC3B;GACD;EACD;CACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuED,MAAM,iBAAiB,CACtBC,YAC+D;EAC/D,MAAM,aAAa;GAClB,GAAG;GACH,YAAY,OAAOC,cAA0B;AAC5C,WAAO,QAAQ,MAAM,QAAQ,iBAAiB,UAAU,CAAC;GACzD;EACD;AAED,SAAO;GAMN,SAAS,MAAM;GA2Bf,MAAM,QAAQA,WAAuB;AACpC,QAAI;AACH,YAAO,GAAG,MAAM,gBAAgB,aAAa,YAAY,UAAU,CAAC;IACpE,SAAQ,OAAO;AACf,YAAO,IAAI,MAAgB;IAC3B;GACD;EACD;CACD;AAED,QAAO;EACN;EACA;CACA;AACD;;;;;;;;;;;;;;;;;;AAmBD,SAAS,gBACRJ,aACAK,SACAD,WACC;CACD,MAAM,WAAW,YAAY,kBAAkB,CAAC,MAAM,aAAa,QAAQ;AAC3E,QAAO,SAAS,QAAQ,UAAU;AAClC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["queryClient: QueryClient","options: DefineQueryInput<TQueryFnData, TError, TData, TQueryKey>","context: QueryFunctionContext<TQueryKey>","options: DefineMutationInput<TData, TError, TVariables, TContext>","variables: TVariables","options: MutationOptions<TData, TError, TVariables, TContext>"],"sources":["../../src/query/utils.ts"],"sourcesContent":["import type {\n\tMutationFunction,\n\tMutationKey,\n\tMutationOptions,\n\tQueryClient,\n\tQueryFunction,\n\tQueryFunctionContext,\n\tQueryKey,\n} from \"@tanstack/query-core\";\nimport { Err, Ok, type Result, resolve } from \"../result/index.js\";\nimport type { QueryObserverOptions } from \"@tanstack/query-core\";\n\n/**\n * Input options for defining a query.\n *\n * Extends TanStack Query's QueryObserverOptions but replaces queryFn with resultQueryFn.\n * This type represents the configuration for creating a query definition with both\n * reactive and imperative interfaces for data fetching.\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\nexport type DefineQueryInput<\n\tTQueryFnData,\n\tTError,\n\tTData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = Omit<\n\tQueryObserverOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>,\n\t\"queryFn\"\n> & {\n\tqueryKey: TQueryKey;\n\tresultQueryFn: QueryFunction<Result<TQueryFnData, TError>, TQueryKey>;\n};\n\n/**\n * Output of defineQuery function.\n *\n * Provides both reactive and imperative interfaces for data fetching:\n * - `options()`: Returns config for use with createQuery() in components\n * - `fetch()`: Imperatively fetches data (useful for actions/event handlers)\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\nexport type DefineQueryOutput<\n\tTQueryFnData,\n\tTError,\n\tTData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = {\n\toptions: () => QueryObserverOptions<\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData,\n\t\tTQueryFnData,\n\t\tTQueryKey\n\t>;\n\tfetch: () => Promise<Result<TData, TError>>;\n};\n\n/**\n * Input options for defining a mutation.\n *\n * Extends TanStack Query's MutationOptions but replaces mutationFn with resultMutationFn.\n * This type represents the configuration for creating a mutation definition with both\n * reactive and imperative interfaces for data mutations.\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\nexport type DefineMutationInput<\n\tTData,\n\tTError,\n\tTVariables,\n\tTContext = unknown,\n> = Omit<MutationOptions<TData, TError, TVariables, TContext>, \"mutationFn\"> & {\n\tmutationKey: MutationKey;\n\tresultMutationFn: MutationFunction<Result<TData, TError>, TVariables>;\n};\n\n/**\n * Output of defineMutation function.\n *\n * Provides both reactive and imperative interfaces for data mutations:\n * - `options()`: Returns config for use with createMutation() in Svelte components\n * - `execute()`: Directly executes the mutation and returns a Result\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\nexport type DefineMutationOutput<\n\tTData,\n\tTError,\n\tTVariables,\n\tTContext = unknown,\n> = {\n\toptions: () => MutationOptions<TData, TError, TVariables, TContext>;\n\texecute: (variables: TVariables) => Promise<Result<TData, TError>>;\n};\n\n/**\n * Creates factory functions for defining queries and mutations bound to a specific QueryClient.\n *\n * This factory pattern allows you to create isolated query/mutation definitions that are\n * bound to a specific QueryClient instance, enabling:\n * - Multiple query clients in the same application\n * - Testing with isolated query clients\n * - Framework-agnostic query definitions\n * - Proper separation of concerns between query logic and client instances\n *\n * The returned functions handle Result types automatically, unwrapping them for TanStack Query\n * while maintaining type safety throughout your application.\n *\n * @param queryClient - The QueryClient instance to bind the factories to\n * @returns An object containing defineQuery and defineMutation functions bound to the provided client\n *\n * @example\n * ```typescript\n * // Create your query client\n * const queryClient = new QueryClient({\n * defaultOptions: {\n * queries: { staleTime: 5 * 60 * 1000 }\n * }\n * });\n *\n * // Create the factory functions\n * const { defineQuery, defineMutation } = createQueryFactories(queryClient);\n *\n * // Now use defineQuery and defineMutation as before\n * const userQuery = defineQuery({\n * queryKey: ['user', userId],\n * resultQueryFn: () => services.getUser(userId)\n * });\n *\n * // Use in components\n * const query = createQuery(userQuery.options());\n *\n * // Or imperatively\n * const { data, error } = await userQuery.fetch();\n * ```\n */\nexport function createQueryFactories(queryClient: QueryClient) {\n\t/**\n\t * Creates a query definition that bridges the gap between pure service functions and reactive UI components.\n\t *\n\t * This factory function is the cornerstone of our data fetching architecture. It wraps service calls\n\t * with TanStack Query superpowers while maintaining type safety through Result types.\n\t *\n\t * ## Why use defineQuery?\n\t *\n\t * 1. **Dual Interface**: Provides both reactive (`.options()`) and imperative (`.fetch()`) APIs\n\t * 2. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically\n\t * unwrapped by TanStack Query, giving you proper error states in your components\n\t * 3. **Type Safety**: Full TypeScript support with proper inference for data and error types\n\t * 4. **Consistency**: Every query in the app follows the same pattern, making it easy to understand\n\t *\n\t * @template TQueryFnData - The type of data returned by the query function\n\t * @template TError - The type of error that can be thrown\n\t * @template TData - The type of data returned by the query (after select transform)\n\t * @template TQueryKey - The type of the query key\n\t *\n\t * @param options - Query configuration object\n\t * @param options.queryKey - Unique key for this query (used for caching and refetching)\n\t * @param options.resultQueryFn - Function that fetches data and returns a Result type\n\t * @param options.* - Any other TanStack Query options (staleTime, refetchInterval, etc.)\n\t *\n\t * @returns Query definition object with two methods:\n\t * - `options()`: Returns config for use with createQuery() in Svelte components\n\t * - `fetch()`: Imperatively fetches data (useful for actions/event handlers)\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your query in the query layer\n\t * const userQuery = defineQuery({\n\t * queryKey: ['users', userId],\n\t * resultQueryFn: () => services.getUser(userId), // Returns Result<User, ApiError>\n\t * staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte component\n\t * const query = createQuery(userQuery.options());\n\t * // $query.data is User | undefined\n\t * // $query.error is ApiError | null\n\t *\n\t * // Step 2b: Use imperatively in an action\n\t * async function prefetchUser() {\n\t * const { data, error } = await userQuery.fetch();\t * if (error) {\n\t * console.error('Failed to fetch user:', error);\n\t * }\n\t * }\n\t * ```\n\t */\n\tconst defineQuery = <\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData = TQueryFnData,\n\t\tTQueryKey extends QueryKey = QueryKey,\n\t>(\n\t\toptions: DefineQueryInput<TQueryFnData, TError, TData, TQueryKey>,\n\t): DefineQueryOutput<TQueryFnData, TError, TData, TQueryKey> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tqueryFn: async (context: QueryFunctionContext<TQueryKey>) => {\n\t\t\t\tlet result = options.resultQueryFn(context);\n\t\t\t\tif (result instanceof Promise) result = await result;\n\t\t\t\treturn resolve(result);\n\t\t\t},\n\t\t} satisfies QueryObserverOptions<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryFnData,\n\t\t\tTQueryKey\n\t\t>;\n\n\t\treturn {\n\t\t\t/**\n\t\t\t * Returns the query options for reactive usage with TanStack Query hooks.\n\t\t\t * Use this with `createQuery()` in Svelte components for automatic subscriptions.\n\t\t\t * @returns The query options object configured for TanStack Query\n\t\t\t */\n\t\t\toptions: () => newOptions,\n\n\t\t\t/**\n\t\t\t * Fetches data for this query, returning cached data if fresh or refetching if stale/missing.\n\t\t\t *\n\t\t\t * This method is perfect for:\n\t\t\t * - Prefetching data before navigation\n\t\t\t * - Loading data in response to user actions\n\t\t\t * - Accessing query data outside of components\n\t\t\t *\n\t\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t\t *\n\t\t\t * @example\n\t\t\t * const { data, error } = await userQuery.fetch();\n\t\t\t * if (error) {\n\t\t\t * console.error('Failed to load user:', error);\n\t\t\t * }\n\t\t\t */\n\t\t\tasync fetch(): Promise<Result<TData, TError>> {\n\t\t\t\ttry {\n\t\t\t\t\treturn Ok(\n\t\t\t\t\t\tawait queryClient.fetchQuery<TQueryFnData, Error, TData, TQueryKey>(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn Err(error as TError);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t};\n\n\t/**\n\t * Creates a mutation definition for operations that modify data (create, update, delete).\n\t *\n\t * This factory function is the mutation counterpart to defineQuery. It provides a clean way to\n\t * wrap service functions that perform side effects, while maintaining the same dual interface\n\t * pattern for maximum flexibility.\n\t *\n\t * ## Why use defineMutation?\n\t *\n\t * 1. **Dual Interface**: Just like queries, mutations can be used reactively or imperatively\n\t * 2. **Direct Execution**: The `.execute()` method lets you run mutations without creating hooks,\n\t * perfect for event handlers and non-component code\n\t * 3. **Consistent Error Handling**: Service functions return `Result<T, E>` types, ensuring\n\t * errors are handled consistently throughout the app\n\t * 4. **Cache Management**: Mutations often update the cache after success (see examples)\n\t *\n\t * @template TData - The type of data returned by the mutation\n\t * @template TError - The type of error that can be thrown\n\t * @template TVariables - The type of variables passed to the mutation\n\t * @template TContext - The type of context data for optimistic updates\n\t *\n\t * @param options - Mutation configuration object\n\t * @param options.mutationKey - Unique key for this mutation (used for tracking in-flight state)\n\t * @param options.resultMutationFn - Function that performs the mutation and returns a Result type\n\t * @param options.* - Any other TanStack Mutation options (onSuccess, onError, etc.)\n\t *\n\t * @returns Mutation definition object with two methods:\n\t * - `options()`: Returns config for use with createMutation() in Svelte components\n\t * - `execute()`: Directly executes the mutation and returns a Result\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your mutation with cache updates\n\t * const createRecording = defineMutation({\n\t * mutationKey: ['recordings', 'create'],\n\t * resultMutationFn: async (recording: Recording) => {\n\t * // Call the service\n\t * const result = await services.db.createRecording(recording);\n\t * if (result.error) return Err(result.error);\n\t *\n\t * // Update cache on success\n\t * queryClient.setQueryData(['recordings'], (old) =>\n\t * [...(old || []), recording]\n\t * );\n\t *\n\t * return Ok(result.data);\n\t * }\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a component\n\t * const mutation = createMutation(createRecording.options());\n\t * // Call with: $mutation.mutate(recordingData)\n\t *\n\t * // Step 2b: Use imperatively in an action\n\t * async function saveRecording(data: Recording) {\n\t * const { error } = await createRecording.execute(data);\n\t * if (error) {\n\t * notify.error.execute({ title: 'Failed to save', description: error.message });\n\t * } else {\n\t * notify.success.execute({ title: 'Recording saved!' });\n\t * }\n\t * }\n\t * ```\n\t *\n\t * @tip The imperative `.execute()` method is especially useful for:\n\t * - Event handlers that need to await the result\n\t * - Sequential operations that depend on each other\n\t * - Non-component code that needs to trigger mutations\n\t */\n\tconst defineMutation = <TData, TError, TVariables, TContext = unknown>(\n\t\toptions: DefineMutationInput<TData, TError, TVariables, TContext>,\n\t): DefineMutationOutput<TData, TError, TVariables, TContext> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tmutationFn: async (variables: TVariables) => {\n\t\t\t\treturn resolve(await options.resultMutationFn(variables));\n\t\t\t},\n\t\t} satisfies MutationOptions<TData, TError, TVariables, TContext>;\n\n\t\treturn {\n\t\t\t/**\n\t\t\t * Returns the mutation options for reactive usage with TanStack Query hooks.\n\t\t\t * Use this with `createMutation()` in Svelte components for reactive mutation state.\n\t\t\t * @returns The mutation options object configured for TanStack Query\n\t\t\t */\n\t\t\toptions: () => newOptions,\n\t\t\t/**\n\t\t\t * Bypasses the reactive mutation hooks and executes the mutation imperatively.\n\t\t\t *\n\t\t\t * This is the recommended way to trigger mutations from:\n\t\t\t * - Button click handlers\n\t\t\t * - Form submissions\n\t\t\t * - Keyboard shortcuts\n\t\t\t * - Any non-component code\n\t\t\t *\n\t\t\t * The method automatically wraps the result in a Result type, so you always\n\t\t\t * get back `{ data, error }` for consistent error handling.\n\t\t\t *\n\t\t\t * @param variables - The variables to pass to the mutation function\n\t\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t\t *\n\t\t\t * @example\n\t\t\t * // In an event handler\n\t\t\t * async function handleSubmit(formData: FormData) {\n\t\t\t * const { data, error } = await createUser.execute(formData);\n\t\t\t * if (error) {\n\t\t\t * notify.error.execute({ title: 'Failed to create user', description: error.message });\n\t\t\t * return;\n\t\t\t * }\n\t\t\t * goto(`/users/${data.id}`);\n\t\t\t * }\n\t\t\t */\n\t\t\tasync execute(variables: TVariables) {\n\t\t\t\ttry {\n\t\t\t\t\treturn Ok(await executeMutation(queryClient, newOptions, variables));\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn Err(error as TError);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t};\n\n\treturn {\n\t\tdefineQuery,\n\t\tdefineMutation,\n\t};\n}\n\n/**\n * Internal helper that executes a mutation directly using the query client's mutation cache.\n *\n * This is what powers the `.execute()` method on mutations. It bypasses the reactive\n * mutation hooks and runs the mutation imperatively, which is perfect for event handlers\n * and other imperative code.\n *\n * @internal\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data\n * @param queryClient - The query client instance to use\n * @param options - The mutation options including mutationFn and mutationKey\n * @param variables - The variables to pass to the mutation function\n * @returns Promise that resolves with the mutation result\n */\nfunction executeMutation<TData, TError, TVariables, TContext>(\n\tqueryClient: QueryClient,\n\toptions: MutationOptions<TData, TError, TVariables, TContext>,\n\tvariables: TVariables,\n) {\n\tconst mutation = queryClient.getMutationCache().build(queryClient, options);\n\treturn mutation.execute(variables);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsJA,SAAgB,qBAAqBA,aAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmD9D,MAAM,cAAc,CAMnBC,YAC+D;EAC/D,MAAM,aAAa;GAClB,GAAG;GACH,SAAS,OAAOC,YAA6C;IAC5D,IAAI,SAAS,QAAQ,cAAc,QAAQ;AAC3C,QAAI,kBAAkB,QAAS,UAAS,MAAM;AAC9C,WAAO,QAAQ,OAAO;GACtB;EACD;AAQD,SAAO;GAMN,SAAS,MAAM;GAkBf,MAAM,QAAwC;AAC7C,QAAI;AACH,YAAO,GACN,MAAM,YAAY,WACjB;MACC,UAAU,WAAW;MACrB,SAAS,WAAW;KACpB,EACD,CACD;IACD,SAAQ,OAAO;AACf,YAAO,IAAI,MAAgB;IAC3B;GACD;EACD;CACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuED,MAAM,iBAAiB,CACtBC,YAC+D;EAC/D,MAAM,aAAa;GAClB,GAAG;GACH,YAAY,OAAOC,cAA0B;AAC5C,WAAO,QAAQ,MAAM,QAAQ,iBAAiB,UAAU,CAAC;GACzD;EACD;AAED,SAAO;GAMN,SAAS,MAAM;GA2Bf,MAAM,QAAQA,WAAuB;AACpC,QAAI;AACH,YAAO,GAAG,MAAM,gBAAgB,aAAa,YAAY,UAAU,CAAC;IACpE,SAAQ,OAAO;AACf,YAAO,IAAI,MAAgB;IAC3B;GACD;EACD;CACD;AAED,QAAO;EACN;EACA;CACA;AACD;;;;;;;;;;;;;;;;;;AAmBD,SAAS,gBACRJ,aACAK,SACAD,WACC;CACD,MAAM,WAAW,YAAY,kBAAkB,CAAC,MAAM,aAAa,QAAQ;AAC3E,QAAO,SAAS,QAAQ,UAAU;AAClC"}
|
package/dist/result/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-
|
|
2
|
-
import { partitionResults } from "../index-
|
|
1
|
+
import { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-fCtNge01.js";
|
|
2
|
+
import { partitionResults } from "../index-BoczdhDh.js";
|
|
3
3
|
export { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
|
package/dist/result/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-
|
|
2
|
-
import { partitionResults } from "../result-
|
|
1
|
+
import { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-BJtW-Wuc.js";
|
|
2
|
+
import { partitionResults } from "../result-DJgTC46e.js";
|
|
3
3
|
|
|
4
4
|
export { Err, Ok, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
|
|
@@ -132,26 +132,24 @@ function isErr(result) {
|
|
|
132
132
|
* This function attempts to execute the `operation`.
|
|
133
133
|
* - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.
|
|
134
134
|
* - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to
|
|
135
|
-
* the `
|
|
136
|
-
* exception into a well-typed error value of type `E`.
|
|
137
|
-
* in an `Err<E>` variant.
|
|
135
|
+
* the `mapErr` function. `mapErr` is responsible for transforming this `unknown`
|
|
136
|
+
* exception into an `Err<E>` variant containing a well-typed error value of type `E`.
|
|
138
137
|
*
|
|
139
138
|
* @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 `
|
|
139
|
+
* @template E - The type of the error value produced by `mapErr` if the `operation` fails.
|
|
141
140
|
* @param options - An object containing the operation and error mapping function.
|
|
142
141
|
* @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.
|
|
143
|
-
* @param options.
|
|
144
|
-
*
|
|
145
|
-
*
|
|
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.
|
|
142
|
+
* @param options.mapErr - A function that takes the `unknown` exception caught from `options.try`
|
|
143
|
+
* and transforms it into an `Err<E>` variant containing a specific error value of type `E`.
|
|
144
|
+
* @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapErr` provides an error variant.
|
|
147
145
|
* @example
|
|
148
146
|
* ```ts
|
|
149
147
|
* function parseJson(jsonString: string): Result<object, SyntaxError> {
|
|
150
148
|
* return trySync({
|
|
151
149
|
* try: () => JSON.parse(jsonString),
|
|
152
|
-
*
|
|
153
|
-
* if (err instanceof SyntaxError) return err;
|
|
154
|
-
* return new SyntaxError("Unknown parsing error");
|
|
150
|
+
* mapErr: (err: unknown) => {
|
|
151
|
+
* if (err instanceof SyntaxError) return Err(err);
|
|
152
|
+
* return Err(new SyntaxError("Unknown parsing error"));
|
|
155
153
|
* }
|
|
156
154
|
* });
|
|
157
155
|
* }
|
|
@@ -163,12 +161,12 @@ function isErr(result) {
|
|
|
163
161
|
* if (isErr(invalidResult)) console.error(invalidResult.error.message);
|
|
164
162
|
* ```
|
|
165
163
|
*/
|
|
166
|
-
function trySync({ try: operation,
|
|
164
|
+
function trySync({ try: operation, mapErr }) {
|
|
167
165
|
try {
|
|
168
166
|
const data = operation();
|
|
169
167
|
return Ok(data);
|
|
170
168
|
} catch (error) {
|
|
171
|
-
return
|
|
169
|
+
return mapErr(error);
|
|
172
170
|
}
|
|
173
171
|
}
|
|
174
172
|
/**
|
|
@@ -177,29 +175,29 @@ function trySync({ try: operation, mapError }) {
|
|
|
177
175
|
* This function attempts to execute the asynchronous `operation`.
|
|
178
176
|
* - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.
|
|
179
177
|
* - 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 `
|
|
181
|
-
* `
|
|
182
|
-
*
|
|
178
|
+
* the caught exception/rejection reason (of type `unknown`) is passed to the `mapErr` function.
|
|
179
|
+
* `mapErr` is responsible for transforming this `unknown` error into an `Err<E>` variant containing
|
|
180
|
+
* a well-typed error value of type `E`.
|
|
183
181
|
*
|
|
184
182
|
* The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.
|
|
185
183
|
*
|
|
186
184
|
* @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 `
|
|
185
|
+
* @template E - The type of the error value produced by `mapErr` if the `operation` fails or rejects.
|
|
188
186
|
* @param options - An object containing the asynchronous operation and error mapping function.
|
|
189
187
|
* @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.
|
|
190
|
-
* @param options.
|
|
191
|
-
*
|
|
192
|
-
*
|
|
188
|
+
* @param options.mapErr - A function that takes the `unknown` exception/rejection reason caught from `options.try`
|
|
189
|
+
* and transforms it into an `Err<E>` variant containing a specific error value of type `E`.
|
|
190
|
+
* This function must return `Err<E>` directly.
|
|
193
191
|
* @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.
|
|
192
|
+
* or `Err<E>` if it rejects/throws and `options.mapErr` provides an error variant.
|
|
195
193
|
* @example
|
|
196
194
|
* ```ts
|
|
197
195
|
* async function fetchData(url: string): Promise<Result<Response, Error>> {
|
|
198
196
|
* return tryAsync({
|
|
199
197
|
* try: async () => fetch(url),
|
|
200
|
-
*
|
|
201
|
-
* if (err instanceof Error) return err;
|
|
202
|
-
* return new Error("Network request failed");
|
|
198
|
+
* mapErr: (err: unknown) => {
|
|
199
|
+
* if (err instanceof Error) return Err(err);
|
|
200
|
+
* return Err(new Error("Network request failed"));
|
|
203
201
|
* }
|
|
204
202
|
* });
|
|
205
203
|
* }
|
|
@@ -216,12 +214,12 @@ function trySync({ try: operation, mapError }) {
|
|
|
216
214
|
* processData();
|
|
217
215
|
* ```
|
|
218
216
|
*/
|
|
219
|
-
async function tryAsync({ try: operation,
|
|
217
|
+
async function tryAsync({ try: operation, mapErr }) {
|
|
220
218
|
try {
|
|
221
219
|
const data = await operation();
|
|
222
220
|
return Ok(data);
|
|
223
221
|
} catch (error) {
|
|
224
|
-
return
|
|
222
|
+
return mapErr(error);
|
|
225
223
|
}
|
|
226
224
|
}
|
|
227
225
|
/**
|
|
@@ -332,4 +330,4 @@ function resolve(value) {
|
|
|
332
330
|
|
|
333
331
|
//#endregion
|
|
334
332
|
export { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap };
|
|
335
|
-
//# sourceMappingURL=result-
|
|
333
|
+
//# sourceMappingURL=result-BJtW-Wuc.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"result-DxmXBFi5.js","names":["data: T","error: E","value: unknown","result: Result<T, E>","value: T | Result<T, E>"],"sources":["../src/result/result.ts"],"sourcesContent":["/**\n * Represents the successful outcome of an operation, encapsulating the success value.\n *\n * This is the 'Ok' variant of the `Result` type. It holds a `data` property\n * of type `T` (the success value) and an `error` property explicitly set to `null`,\n * signifying no error occurred.\n *\n * Use this type in conjunction with `Err<E>` and `Result<T, E>`.\n *\n * @template T - The type of the success value contained within.\n */\nexport type Ok<T> = { data: T; error: null };\n\n/**\n * Represents the failure outcome of an operation, encapsulating the error value.\n *\n * This is the 'Err' variant of the `Result` type. It holds an `error` property\n * of type `E` (the error value) and a `data` property explicitly set to `null`,\n * signifying that no success value is present due to the failure.\n *\n * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.\n *\n * @template E - The type of the error value contained within.\n */\nexport type Err<E> = { error: E; data: null };\n\n/**\n * A type that represents the outcome of an operation that can either succeed or fail.\n *\n * `Result<T, E>` is a discriminated union type with two possible variants:\n * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.\n * In this case, the `error` field is `null`.\n * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.\n * In this case, the `data` field is `null`.\n *\n * This type promotes explicit error handling by requiring developers to check\n * the variant of the `Result` before accessing its potential value or error.\n * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).\n *\n * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).\n * @template E - The type of the error value if the operation fails (held in `Err<E>`).\n * @example\n * ```ts\n * function divide(numerator: number, denominator: number): Result<number, string> {\n * if (denominator === 0) {\n * return Err(\"Cannot divide by zero\");\n * }\n * return Ok(numerator / denominator);\n * }\n *\n * const result1 = divide(10, 2);\n * if (isOk(result1)) {\n * console.log(\"Success:\", result1.data); // Output: Success: 5\n * }\n *\n * const result2 = divide(10, 0);\n * if (isErr(result2)) {\n * console.error(\"Failure:\", result2.error); // Output: Failure: Cannot divide by zero\n * }\n * ```\n */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Constructs an `Ok<T>` variant, representing a successful outcome.\n *\n * This factory function creates the success variant of a `Result`.\n * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.\n *\n * @template T - The type of the success value.\n * @param data - The success value to be wrapped in the `Ok` variant.\n * @returns An `Ok<T>` object with the provided data and `error` set to `null`.\n * @example\n * ```ts\n * const successfulResult = Ok(\"Operation completed successfully\");\n * // successfulResult is { data: \"Operation completed successfully\", error: null }\n * ```\n */\nexport const Ok = <T>(data: T): Ok<T> => ({ data, error: null });\n\n/**\n * Constructs an `Err<E>` variant, representing a failure outcome.\n *\n * This factory function creates the error variant of a `Result`.\n * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.\n *\n * @template E - The type of the error value.\n * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.\n * @returns An `Err<E>` object with the provided error and `data` set to `null`.\n * @example\n * ```ts\n * const failedResult = Err(new TypeError(\"Invalid input\"));\n * // failedResult is { error: TypeError(\"Invalid input\"), data: null }\n * ```\n */\nexport const Err = <E>(error: E): Err<E> => ({ error, data: null });\n\n/**\n * Utility type to extract the `Ok<T>` variant from a `Result<T, E>` union type.\n *\n * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve\n * to `Ok<string>`. This can be useful in generic contexts or for type narrowing.\n *\n * @template R - The `Result<T, E>` union type from which to extract the `Ok<T>` variant.\n * Must extend `Result<unknown, unknown>`.\n */\nexport type ExtractOkFromResult<R extends Result<unknown, unknown>> = Extract<\n\tR,\n\t{ error: null }\n>;\n\n/**\n * Utility type to extract the `Err<E>` variant from a `Result<T, E>` union type.\n *\n * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve\n * to `Err<Error>`. This can be useful in generic contexts or for type narrowing.\n *\n * @template R - The `Result<T, E>` union type from which to extract the `Err<E>` variant.\n * Must extend `Result<unknown, unknown>`.\n */\nexport type ExtractErrFromResult<R extends Result<unknown, unknown>> = Extract<\n\tR,\n\t{ data: null }\n>;\n\n/**\n * Utility type to extract the success value's type `T` from a `Result<T, E>` type.\n *\n * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),\n * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `data` field when you know you have a success.\n *\n * @template R - The `Result<T, E>` type from which to extract the success value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number\n *\n * type MyErrorResult = Err<string>;\n * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never\n * ```\n */\nexport type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>\n\t? U\n\t: never;\n\n/**\n * Utility type to extract the error value's type `E` from a `Result<T, E>` type.\n *\n * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),\n * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `error` field when you know you have a failure.\n *\n * @template R - The `Result<T, E>` type from which to extract the error value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string\n *\n * type MySuccessResult = Ok<number>;\n * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never\n * ```\n */\nexport type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<\n\tinfer E\n>\n\t? E\n\t: never;\n\n/**\n * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.\n *\n * A value is considered a valid `Result` if:\n * 1. It is a non-null object.\n * 2. It has both `data` and `error` properties.\n * 3. Exactly one of `data` or `error` is `null`. The other must be non-`null`.\n *\n * This function does not validate the types of `data` or `error` beyond `null` checks.\n *\n * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).\n * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).\n * @param value - The value to check.\n * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.\n * @example\n * ```ts\n * declare const someValue: unknown;\n *\n * if (isResult<string, Error>(someValue)) {\n * // someValue is now typed as Result<string, Error>\n * if (isOk(someValue)) {\n * console.log(someValue.data); // string\n * } else {\n * console.error(someValue.error); // Error\n * }\n * }\n * ```\n */\nexport function isResult<T = unknown, E = unknown>(\n\tvalue: unknown,\n): value is Result<T, E> {\n\tconst isNonNullObject = typeof value === \"object\" && value !== null;\n\tif (!isNonNullObject) return false;\n\n\tconst hasDataProperty = \"data\" in value;\n\tconst hasErrorProperty = \"error\" in value;\n\tif (!hasDataProperty || !hasErrorProperty) return false;\n\n\tconst isBothNull = value.data === null && value.error === null;\n\tif (isBothNull) return false;\n\n\tconst isNeitherNull = value.data !== null && value.error !== null;\n\tif (isNeitherNull) return false;\n\n\t// Exactly one property is null\n\treturn true;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.\n *\n * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.\n * An `Ok<T>` variant is identified by its `error` property being `null`.\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isOk(myResult)) {\n * // myResult is now typed as Ok<number>\n * console.log(\"Success value:\", myResult.data); // myResult.data is number\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.error === null;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.\n *\n * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.\n * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isErr(myResult)) {\n * // myResult is now typed as Err<string>\n * console.error(\"Error value:\", myResult.error); // myResult.error is string\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.error !== null; // Equivalent to result.data === null\n}\n\n/**\n * Executes a synchronous operation and wraps its outcome (success or failure) in a `Result<T, E>`.\n *\n * This function attempts to execute the `operation`.\n * - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.\n * - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to\n * the `mapError` function. `mapError` is responsible for transforming this `unknown`\n * exception into a well-typed error value of type `E`. This error value is then wrapped\n * in an `Err<E>` variant.\n *\n * @template T - The type of the success value returned by the `operation` if it succeeds.\n * @template E - The type of the error value produced by `mapError` if the `operation` fails.\n * @param options - An object containing the operation and error mapping function.\n * @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.\n * @param options.mapError - A function that takes the `unknown` exception caught from `options.try`\n * and transforms it into a specific error value of type `E`. This function\n * is crucial for creating a well-typed error for the `Err<E>` variant.\n * @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapError` provides an error value.\n * @example\n * ```ts\n * function parseJson(jsonString: string): Result<object, SyntaxError> {\n * return trySync({\n * try: () => JSON.parse(jsonString),\n * mapError: (err: unknown) => {\n * if (err instanceof SyntaxError) return err;\n * return new SyntaxError(\"Unknown parsing error\");\n * }\n * });\n * }\n *\n * const validResult = parseJson('{\"name\":\"Result\"}'); // Ok<{name: string}>\n * const invalidResult = parseJson('invalid json'); // Err<SyntaxError>\n *\n * if (isOk(validResult)) console.log(validResult.data);\n * if (isErr(invalidResult)) console.error(invalidResult.error.message);\n * ```\n */\nexport function trySync<T, E>({\n\ttry: operation,\n\tmapError,\n}: {\n\ttry: () => T;\n\tmapError: (error: unknown) => E;\n}): Result<T, E> {\n\ttry {\n\t\tconst data = operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn Err(mapError(error));\n\t}\n}\n\n/**\n * Executes an asynchronous operation (returning a `Promise`) and wraps its outcome in a `Promise<Result<T, E>>`.\n *\n * This function attempts to execute the asynchronous `operation`.\n * - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.\n * - If the `Promise` returned by `operation` rejects, or if `operation` itself throws an exception synchronously,\n * the caught exception/rejection reason (of type `unknown`) is passed to the `mapError` function.\n * `mapError` is responsible for transforming this `unknown` error into a well-typed error value of type `E`.\n * This error value is then wrapped in an `Err<E>` variant.\n *\n * The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.\n *\n * @template T - The type of the success value the `Promise` from `operation` resolves to.\n * @template E - The type of the error value produced by `mapError` if the `operation` fails or rejects.\n * @param options - An object containing the asynchronous operation and error mapping function.\n * @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.\n * @param options.mapError - A function that takes the `unknown` exception/rejection reason caught from `options.try`\n * and transforms it into a specific error value of type `E`. This function\n * is crucial for creating a well-typed error for the `Err<E>` variant.\n * @returns A `Promise` that resolves to a `Result<T, E>`: `Ok<T>` if `options.try`'s `Promise` resolves,\n * or `Err<E>` if it rejects/throws and `options.mapError` provides an error value.\n * @example\n * ```ts\n * async function fetchData(url: string): Promise<Result<Response, Error>> {\n * return tryAsync({\n * try: async () => fetch(url),\n * mapError: (err: unknown) => {\n * if (err instanceof Error) return err;\n * return new Error(\"Network request failed\");\n * }\n * });\n * }\n *\n * async function processData() {\n * const result = await fetchData(\"/api/data\");\n * if (isOk(result)) {\n * const response = result.data;\n * console.log(\"Data fetched:\", await response.json());\n * } else {\n * console.error(\"Fetch error:\", result.error.message);\n * }\n * }\n * processData();\n * ```\n */\nexport async function tryAsync<T, E>({\n\ttry: operation,\n\tmapError,\n}: {\n\ttry: () => Promise<T>;\n\tmapError: (error: unknown) => E;\n}): Promise<Result<T, E>> {\n\ttry {\n\t\tconst data = await operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn Err(mapError(error));\n\t}\n}\n\n/**\n * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.\n *\n * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:\n * - If `value` is an `Ok<T>` variant, returns the contained success value.\n * - If `value` is an `Err<E>` variant, throws the contained error value.\n * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),\n * returns it as-is.\n *\n * This is useful when working with APIs that might return either direct values or Results,\n * allowing you to normalize them to the actual value or propagate errors via throwing.\n * \n * Use `resolve` when the input might or might not be a Result.\n * Use `unwrap` when you know the input is definitely a Result.\n *\n * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.\n * @template E - The type of the error value (if `value` is `Err<E>`).\n * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.\n * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.\n * @throws The error value `E` if `value` is an `Err<E>` variant.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const resolved = resolve(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"failure\"));\n * try {\n * resolve(errResult);\n * } catch (e) {\n * console.error(e.message); // \"failure\"\n * }\n *\n * // Example with a plain value\n * const plainValue = \"plain data\";\n * const resolved = resolve(plainValue); // \"plain data\"\n *\n * // Example with a function that might return Result or plain value\n * declare function mightReturnResult(): string | Result<string, Error>;\n * const outcome = mightReturnResult();\n * try {\n * const finalValue = resolve(outcome); // handles both cases\n * console.log(\"Final value:\", finalValue);\n * } catch (e) {\n * console.error(\"Operation failed:\", e);\n * }\n * ```\n */\n/**\n * Unwraps a `Result<T, E>`, returning the success value or throwing the error.\n *\n * This function extracts the data from a `Result`:\n * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.\n * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.\n *\n * Unlike `resolve`, this function expects the input to always be a `Result` type,\n * making it more direct for cases where you know you're working with a `Result`.\n *\n * @template T - The type of the success value contained in the `Ok<T>` variant.\n * @template E - The type of the error value contained in the `Err<E>` variant.\n * @param result - The `Result<T, E>` to unwrap.\n * @returns The success value of type `T` if the `Result` is `Ok<T>`.\n * @throws The error value of type `E` if the `Result` is `Err<E>`.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const value = unwrap(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"something went wrong\"));\n * try {\n * unwrap(errResult);\n * } catch (error) {\n * console.error(error.message); // \"something went wrong\"\n * }\n *\n * // Usage in a function that returns Result\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return Err(\"Division by zero\");\n * return Ok(a / b);\n * }\n *\n * try {\n * const result = unwrap(divide(10, 2)); // 5\n * console.log(\"Result:\", result);\n * } catch (error) {\n * console.error(\"Division failed:\", error);\n * }\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n\tif (isOk(result)) {\n\t\treturn result.data;\n\t}\n\tthrow result.error;\n}\n\nexport function resolve<T, E>(value: T | Result<T, E>): T {\n\tif (isResult<T, E>(value)) {\n\t\tif (isOk(value)) {\n\t\t\treturn value.data;\n\t\t}\n\t\t// If it's a Result and not Ok, it must be Err.\n\t\t// The type guard isResult<T,E>(value) and isOk(value) already refine the type.\n\t\t// So, 'value' here is known to be Err<E>.\n\t\tthrow value.error;\n\t}\n\n\t// If it's not a Result type, return the value as-is.\n\t// 'value' here is known to be of type T.\n\treturn value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,KAAK,CAAIA,UAAoB;CAAE;CAAM,OAAO;AAAM;;;;;;;;;;;;;;;;AAiB/D,MAAa,MAAM,CAAIC,WAAsB;CAAE;CAAO,MAAM;AAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGlE,SAAgB,SACfC,OACwB;CACxB,MAAM,yBAAyB,UAAU,YAAY,UAAU;AAC/D,MAAK,gBAAiB,QAAO;CAE7B,MAAM,kBAAkB,UAAU;CAClC,MAAM,mBAAmB,WAAW;AACpC,MAAK,oBAAoB,iBAAkB,QAAO;CAElD,MAAM,aAAa,MAAM,SAAS,QAAQ,MAAM,UAAU;AAC1D,KAAI,WAAY,QAAO;CAEvB,MAAM,gBAAgB,MAAM,SAAS,QAAQ,MAAM,UAAU;AAC7D,KAAI,cAAe,QAAO;AAG1B,QAAO;AACP;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,KAAWC,QAAuC;AACjE,QAAO,OAAO,UAAU;AACxB;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,MAAYA,QAAwC;AACnE,QAAO,OAAO,UAAU;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCD,SAAgB,QAAc,EAC7B,KAAK,WACL,UAIA,EAAgB;AAChB,KAAI;EACH,MAAM,OAAO,WAAW;AACxB,SAAO,GAAG,KAAK;CACf,SAAQ,OAAO;AACf,SAAO,IAAI,SAAS,MAAM,CAAC;CAC3B;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,eAAsB,SAAe,EACpC,KAAK,WACL,UAIA,EAAyB;AACzB,KAAI;EACH,MAAM,OAAO,MAAM,WAAW;AAC9B,SAAO,GAAG,KAAK;CACf,SAAQ,OAAO;AACf,SAAO,IAAI,SAAS,MAAM,CAAC;CAC3B;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGD,SAAgB,OAAaA,QAAyB;AACrD,KAAI,KAAK,OAAO,CACf,QAAO,OAAO;AAEf,OAAM,OAAO;AACb;AAED,SAAgB,QAAcC,OAA4B;AACzD,KAAI,SAAe,MAAM,EAAE;AAC1B,MAAI,KAAK,MAAM,CACd,QAAO,MAAM;AAKd,QAAM,MAAM;CACZ;AAID,QAAO;AACP"}
|
|
1
|
+
{"version":3,"file":"result-BJtW-Wuc.js","names":["data: T","error: E","value: unknown","result: Result<T, E>","value: T | Result<T, E>"],"sources":["../src/result/result.ts"],"sourcesContent":["/**\n * Represents the successful outcome of an operation, encapsulating the success value.\n *\n * This is the 'Ok' variant of the `Result` type. It holds a `data` property\n * of type `T` (the success value) and an `error` property explicitly set to `null`,\n * signifying no error occurred.\n *\n * Use this type in conjunction with `Err<E>` and `Result<T, E>`.\n *\n * @template T - The type of the success value contained within.\n */\nexport type Ok<T> = { data: T; error: null };\n\n/**\n * Represents the failure outcome of an operation, encapsulating the error value.\n *\n * This is the 'Err' variant of the `Result` type. It holds an `error` property\n * of type `E` (the error value) and a `data` property explicitly set to `null`,\n * signifying that no success value is present due to the failure.\n *\n * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.\n *\n * @template E - The type of the error value contained within.\n */\nexport type Err<E> = { error: E; data: null };\n\n/**\n * A type that represents the outcome of an operation that can either succeed or fail.\n *\n * `Result<T, E>` is a discriminated union type with two possible variants:\n * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.\n * In this case, the `error` field is `null`.\n * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.\n * In this case, the `data` field is `null`.\n *\n * This type promotes explicit error handling by requiring developers to check\n * the variant of the `Result` before accessing its potential value or error.\n * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).\n *\n * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).\n * @template E - The type of the error value if the operation fails (held in `Err<E>`).\n * @example\n * ```ts\n * function divide(numerator: number, denominator: number): Result<number, string> {\n * if (denominator === 0) {\n * return Err(\"Cannot divide by zero\");\n * }\n * return Ok(numerator / denominator);\n * }\n *\n * const result1 = divide(10, 2);\n * if (isOk(result1)) {\n * console.log(\"Success:\", result1.data); // Output: Success: 5\n * }\n *\n * const result2 = divide(10, 0);\n * if (isErr(result2)) {\n * console.error(\"Failure:\", result2.error); // Output: Failure: Cannot divide by zero\n * }\n * ```\n */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Constructs an `Ok<T>` variant, representing a successful outcome.\n *\n * This factory function creates the success variant of a `Result`.\n * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.\n *\n * @template T - The type of the success value.\n * @param data - The success value to be wrapped in the `Ok` variant.\n * @returns An `Ok<T>` object with the provided data and `error` set to `null`.\n * @example\n * ```ts\n * const successfulResult = Ok(\"Operation completed successfully\");\n * // successfulResult is { data: \"Operation completed successfully\", error: null }\n * ```\n */\nexport const Ok = <T>(data: T): Ok<T> => ({ data, error: null });\n\n/**\n * Constructs an `Err<E>` variant, representing a failure outcome.\n *\n * This factory function creates the error variant of a `Result`.\n * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.\n *\n * @template E - The type of the error value.\n * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.\n * @returns An `Err<E>` object with the provided error and `data` set to `null`.\n * @example\n * ```ts\n * const failedResult = Err(new TypeError(\"Invalid input\"));\n * // failedResult is { error: TypeError(\"Invalid input\"), data: null }\n * ```\n */\nexport const Err = <E>(error: E): Err<E> => ({ error, data: null });\n\n/**\n * Utility type to extract the `Ok<T>` variant from a `Result<T, E>` union type.\n *\n * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve\n * to `Ok<string>`. This can be useful in generic contexts or for type narrowing.\n *\n * @template R - The `Result<T, E>` union type from which to extract the `Ok<T>` variant.\n * Must extend `Result<unknown, unknown>`.\n */\nexport type ExtractOkFromResult<R extends Result<unknown, unknown>> = Extract<\n\tR,\n\t{ error: null }\n>;\n\n/**\n * Utility type to extract the `Err<E>` variant from a `Result<T, E>` union type.\n *\n * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve\n * to `Err<Error>`. This can be useful in generic contexts or for type narrowing.\n *\n * @template R - The `Result<T, E>` union type from which to extract the `Err<E>` variant.\n * Must extend `Result<unknown, unknown>`.\n */\nexport type ExtractErrFromResult<R extends Result<unknown, unknown>> = Extract<\n\tR,\n\t{ data: null }\n>;\n\n/**\n * Utility type to extract the success value's type `T` from a `Result<T, E>` type.\n *\n * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),\n * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `data` field when you know you have a success.\n *\n * @template R - The `Result<T, E>` type from which to extract the success value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number\n *\n * type MyErrorResult = Err<string>;\n * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never\n * ```\n */\nexport type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>\n\t? U\n\t: never;\n\n/**\n * Utility type to extract the error value's type `E` from a `Result<T, E>` type.\n *\n * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),\n * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `error` field when you know you have a failure.\n *\n * @template R - The `Result<T, E>` type from which to extract the error value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string\n *\n * type MySuccessResult = Ok<number>;\n * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never\n * ```\n */\nexport type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<\n\tinfer E\n>\n\t? E\n\t: never;\n\n/**\n * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.\n *\n * A value is considered a valid `Result` if:\n * 1. It is a non-null object.\n * 2. It has both `data` and `error` properties.\n * 3. Exactly one of `data` or `error` is `null`. The other must be non-`null`.\n *\n * This function does not validate the types of `data` or `error` beyond `null` checks.\n *\n * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).\n * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).\n * @param value - The value to check.\n * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.\n * @example\n * ```ts\n * declare const someValue: unknown;\n *\n * if (isResult<string, Error>(someValue)) {\n * // someValue is now typed as Result<string, Error>\n * if (isOk(someValue)) {\n * console.log(someValue.data); // string\n * } else {\n * console.error(someValue.error); // Error\n * }\n * }\n * ```\n */\nexport function isResult<T = unknown, E = unknown>(\n\tvalue: unknown,\n): value is Result<T, E> {\n\tconst isNonNullObject = typeof value === \"object\" && value !== null;\n\tif (!isNonNullObject) return false;\n\n\tconst hasDataProperty = \"data\" in value;\n\tconst hasErrorProperty = \"error\" in value;\n\tif (!hasDataProperty || !hasErrorProperty) return false;\n\n\tconst isBothNull = value.data === null && value.error === null;\n\tif (isBothNull) return false;\n\n\tconst isNeitherNull = value.data !== null && value.error !== null;\n\tif (isNeitherNull) return false;\n\n\t// Exactly one property is null\n\treturn true;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.\n *\n * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.\n * An `Ok<T>` variant is identified by its `error` property being `null`.\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isOk(myResult)) {\n * // myResult is now typed as Ok<number>\n * console.log(\"Success value:\", myResult.data); // myResult.data is number\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.error === null;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.\n *\n * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.\n * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isErr(myResult)) {\n * // myResult is now typed as Err<string>\n * console.error(\"Error value:\", myResult.error); // myResult.error is string\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.error !== null; // Equivalent to result.data === null\n}\n\n/**\n * Executes a synchronous operation and wraps its outcome (success or failure) in a `Result<T, E>`.\n *\n * This function attempts to execute the `operation`.\n * - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.\n * - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to\n * the `mapErr` function. `mapErr` is responsible for transforming this `unknown`\n * exception into an `Err<E>` variant containing a well-typed error value of type `E`.\n *\n * @template T - The type of the success value returned by the `operation` if it succeeds.\n * @template E - The type of the error value produced by `mapErr` if the `operation` fails.\n * @param options - An object containing the operation and error mapping function.\n * @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.\n * @param options.mapErr - A function that takes the `unknown` exception caught from `options.try`\n * and transforms it into an `Err<E>` variant containing a specific error value of type `E`.\n * @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapErr` provides an error variant.\n * @example\n * ```ts\n * function parseJson(jsonString: string): Result<object, SyntaxError> {\n * return trySync({\n * try: () => JSON.parse(jsonString),\n * mapErr: (err: unknown) => {\n * if (err instanceof SyntaxError) return Err(err);\n * return Err(new SyntaxError(\"Unknown parsing error\"));\n * }\n * });\n * }\n *\n * const validResult = parseJson('{\"name\":\"Result\"}'); // Ok<{name: string}>\n * const invalidResult = parseJson('invalid json'); // Err<SyntaxError>\n *\n * if (isOk(validResult)) console.log(validResult.data);\n * if (isErr(invalidResult)) console.error(invalidResult.error.message);\n * ```\n */\nexport function trySync<T, E>({\n\ttry: operation,\n\tmapErr,\n}: {\n\ttry: () => T;\n\tmapErr: (error: unknown) => Err<E>;\n}): Result<T, E> {\n\ttry {\n\t\tconst data = operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn mapErr(error);\n\t}\n}\n\n/**\n * Executes an asynchronous operation (returning a `Promise`) and wraps its outcome in a `Promise<Result<T, E>>`.\n *\n * This function attempts to execute the asynchronous `operation`.\n * - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.\n * - If the `Promise` returned by `operation` rejects, or if `operation` itself throws an exception synchronously,\n * the caught exception/rejection reason (of type `unknown`) is passed to the `mapErr` function.\n * `mapErr` is responsible for transforming this `unknown` error into an `Err<E>` variant containing\n * a well-typed error value of type `E`.\n *\n * The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.\n *\n * @template T - The type of the success value the `Promise` from `operation` resolves to.\n * @template E - The type of the error value produced by `mapErr` if the `operation` fails or rejects.\n * @param options - An object containing the asynchronous operation and error mapping function.\n * @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.\n * @param options.mapErr - A function that takes the `unknown` exception/rejection reason caught from `options.try`\n * and transforms it into an `Err<E>` variant containing a specific error value of type `E`.\n * This function must return `Err<E>` directly.\n * @returns A `Promise` that resolves to a `Result<T, E>`: `Ok<T>` if `options.try`'s `Promise` resolves,\n * or `Err<E>` if it rejects/throws and `options.mapErr` provides an error variant.\n * @example\n * ```ts\n * async function fetchData(url: string): Promise<Result<Response, Error>> {\n * return tryAsync({\n * try: async () => fetch(url),\n * mapErr: (err: unknown) => {\n * if (err instanceof Error) return Err(err);\n * return Err(new Error(\"Network request failed\"));\n * }\n * });\n * }\n *\n * async function processData() {\n * const result = await fetchData(\"/api/data\");\n * if (isOk(result)) {\n * const response = result.data;\n * console.log(\"Data fetched:\", await response.json());\n * } else {\n * console.error(\"Fetch error:\", result.error.message);\n * }\n * }\n * processData();\n * ```\n */\nexport async function tryAsync<T, E>({\n\ttry: operation,\n\tmapErr,\n}: {\n\ttry: () => Promise<T>;\n\tmapErr: (error: unknown) => Err<E>;\n}): Promise<Result<T, E>> {\n\ttry {\n\t\tconst data = await operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn mapErr(error);\n\t}\n}\n\n/**\n * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.\n *\n * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:\n * - If `value` is an `Ok<T>` variant, returns the contained success value.\n * - If `value` is an `Err<E>` variant, throws the contained error value.\n * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),\n * returns it as-is.\n *\n * This is useful when working with APIs that might return either direct values or Results,\n * allowing you to normalize them to the actual value or propagate errors via throwing.\n * \n * Use `resolve` when the input might or might not be a Result.\n * Use `unwrap` when you know the input is definitely a Result.\n *\n * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.\n * @template E - The type of the error value (if `value` is `Err<E>`).\n * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.\n * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.\n * @throws The error value `E` if `value` is an `Err<E>` variant.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const resolved = resolve(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"failure\"));\n * try {\n * resolve(errResult);\n * } catch (e) {\n * console.error(e.message); // \"failure\"\n * }\n *\n * // Example with a plain value\n * const plainValue = \"plain data\";\n * const resolved = resolve(plainValue); // \"plain data\"\n *\n * // Example with a function that might return Result or plain value\n * declare function mightReturnResult(): string | Result<string, Error>;\n * const outcome = mightReturnResult();\n * try {\n * const finalValue = resolve(outcome); // handles both cases\n * console.log(\"Final value:\", finalValue);\n * } catch (e) {\n * console.error(\"Operation failed:\", e);\n * }\n * ```\n */\n/**\n * Unwraps a `Result<T, E>`, returning the success value or throwing the error.\n *\n * This function extracts the data from a `Result`:\n * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.\n * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.\n *\n * Unlike `resolve`, this function expects the input to always be a `Result` type,\n * making it more direct for cases where you know you're working with a `Result`.\n *\n * @template T - The type of the success value contained in the `Ok<T>` variant.\n * @template E - The type of the error value contained in the `Err<E>` variant.\n * @param result - The `Result<T, E>` to unwrap.\n * @returns The success value of type `T` if the `Result` is `Ok<T>`.\n * @throws The error value of type `E` if the `Result` is `Err<E>`.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const value = unwrap(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"something went wrong\"));\n * try {\n * unwrap(errResult);\n * } catch (error) {\n * console.error(error.message); // \"something went wrong\"\n * }\n *\n * // Usage in a function that returns Result\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return Err(\"Division by zero\");\n * return Ok(a / b);\n * }\n *\n * try {\n * const result = unwrap(divide(10, 2)); // 5\n * console.log(\"Result:\", result);\n * } catch (error) {\n * console.error(\"Division failed:\", error);\n * }\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n\tif (isOk(result)) {\n\t\treturn result.data;\n\t}\n\tthrow result.error;\n}\n\nexport function resolve<T, E>(value: T | Result<T, E>): T {\n\tif (isResult<T, E>(value)) {\n\t\tif (isOk(value)) {\n\t\t\treturn value.data;\n\t\t}\n\t\t// If it's a Result and not Ok, it must be Err.\n\t\t// The type guard isResult<T,E>(value) and isOk(value) already refine the type.\n\t\t// So, 'value' here is known to be Err<E>.\n\t\tthrow value.error;\n\t}\n\n\t// If it's not a Result type, return the value as-is.\n\t// 'value' here is known to be of type T.\n\treturn value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,KAAK,CAAIA,UAAoB;CAAE;CAAM,OAAO;AAAM;;;;;;;;;;;;;;;;AAiB/D,MAAa,MAAM,CAAIC,WAAsB;CAAE;CAAO,MAAM;AAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGlE,SAAgB,SACfC,OACwB;CACxB,MAAM,yBAAyB,UAAU,YAAY,UAAU;AAC/D,MAAK,gBAAiB,QAAO;CAE7B,MAAM,kBAAkB,UAAU;CAClC,MAAM,mBAAmB,WAAW;AACpC,MAAK,oBAAoB,iBAAkB,QAAO;CAElD,MAAM,aAAa,MAAM,SAAS,QAAQ,MAAM,UAAU;AAC1D,KAAI,WAAY,QAAO;CAEvB,MAAM,gBAAgB,MAAM,SAAS,QAAQ,MAAM,UAAU;AAC7D,KAAI,cAAe,QAAO;AAG1B,QAAO;AACP;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,KAAWC,QAAuC;AACjE,QAAO,OAAO,UAAU;AACxB;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,MAAYA,QAAwC;AACnE,QAAO,OAAO,UAAU;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCD,SAAgB,QAAc,EAC7B,KAAK,WACL,QAIA,EAAgB;AAChB,KAAI;EACH,MAAM,OAAO,WAAW;AACxB,SAAO,GAAG,KAAK;CACf,SAAQ,OAAO;AACf,SAAO,OAAO,MAAM;CACpB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,eAAsB,SAAe,EACpC,KAAK,WACL,QAIA,EAAyB;AACzB,KAAI;EACH,MAAM,OAAO,MAAM,WAAW;AAC9B,SAAO,GAAG,KAAK;CACf,SAAQ,OAAO;AACf,SAAO,OAAO,MAAM;CACpB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGD,SAAgB,OAAaA,QAAyB;AACrD,KAAI,KAAK,OAAO,CACf,QAAO,OAAO;AAEf,OAAM,OAAO;AACb;AAED,SAAgB,QAAcC,OAA4B;AACzD,KAAI,SAAe,MAAM,EAAE;AAC1B,MAAI,KAAK,MAAM,CACd,QAAO,MAAM;AAKd,QAAM,MAAM;CACZ;AAID,QAAO;AACP"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isOk } from "./result-
|
|
1
|
+
import { isOk } from "./result-BJtW-Wuc.js";
|
|
2
2
|
|
|
3
3
|
//#region src/result/utils.ts
|
|
4
4
|
/**
|
|
@@ -27,4 +27,4 @@ function partitionResults(results) {
|
|
|
27
27
|
|
|
28
28
|
//#endregion
|
|
29
29
|
export { partitionResults };
|
|
30
|
-
//# sourceMappingURL=result-
|
|
30
|
+
//# sourceMappingURL=result-DJgTC46e.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"result-
|
|
1
|
+
{"version":3,"file":"result-DJgTC46e.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"}
|
|
@@ -239,26 +239,24 @@ declare function isErr<T, E>(result: Result<T, E>): result is Err<E>;
|
|
|
239
239
|
* This function attempts to execute the `operation`.
|
|
240
240
|
* - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.
|
|
241
241
|
* - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to
|
|
242
|
-
* the `
|
|
243
|
-
* exception into a well-typed error value of type `E`.
|
|
244
|
-
* in an `Err<E>` variant.
|
|
242
|
+
* the `mapErr` function. `mapErr` is responsible for transforming this `unknown`
|
|
243
|
+
* exception into an `Err<E>` variant containing a well-typed error value of type `E`.
|
|
245
244
|
*
|
|
246
245
|
* @template T - The type of the success value returned by the `operation` if it succeeds.
|
|
247
|
-
* @template E - The type of the error value produced by `
|
|
246
|
+
* @template E - The type of the error value produced by `mapErr` if the `operation` fails.
|
|
248
247
|
* @param options - An object containing the operation and error mapping function.
|
|
249
248
|
* @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.
|
|
250
|
-
* @param options.
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
* @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapError` provides an error value.
|
|
249
|
+
* @param options.mapErr - A function that takes the `unknown` exception caught from `options.try`
|
|
250
|
+
* and transforms it into an `Err<E>` variant containing a specific error value of type `E`.
|
|
251
|
+
* @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapErr` provides an error variant.
|
|
254
252
|
* @example
|
|
255
253
|
* ```ts
|
|
256
254
|
* function parseJson(jsonString: string): Result<object, SyntaxError> {
|
|
257
255
|
* return trySync({
|
|
258
256
|
* try: () => JSON.parse(jsonString),
|
|
259
|
-
*
|
|
260
|
-
* if (err instanceof SyntaxError) return err;
|
|
261
|
-
* return new SyntaxError("Unknown parsing error");
|
|
257
|
+
* mapErr: (err: unknown) => {
|
|
258
|
+
* if (err instanceof SyntaxError) return Err(err);
|
|
259
|
+
* return Err(new SyntaxError("Unknown parsing error"));
|
|
262
260
|
* }
|
|
263
261
|
* });
|
|
264
262
|
* }
|
|
@@ -272,10 +270,10 @@ declare function isErr<T, E>(result: Result<T, E>): result is Err<E>;
|
|
|
272
270
|
*/
|
|
273
271
|
declare function trySync<T, E>({
|
|
274
272
|
try: operation,
|
|
275
|
-
|
|
273
|
+
mapErr
|
|
276
274
|
}: {
|
|
277
275
|
try: () => T;
|
|
278
|
-
|
|
276
|
+
mapErr: (error: unknown) => Err<E>;
|
|
279
277
|
}): Result<T, E>;
|
|
280
278
|
/**
|
|
281
279
|
* Executes an asynchronous operation (returning a `Promise`) and wraps its outcome in a `Promise<Result<T, E>>`.
|
|
@@ -283,29 +281,29 @@ declare function trySync<T, E>({
|
|
|
283
281
|
* This function attempts to execute the asynchronous `operation`.
|
|
284
282
|
* - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.
|
|
285
283
|
* - If the `Promise` returned by `operation` rejects, or if `operation` itself throws an exception synchronously,
|
|
286
|
-
* the caught exception/rejection reason (of type `unknown`) is passed to the `
|
|
287
|
-
* `
|
|
288
|
-
*
|
|
284
|
+
* the caught exception/rejection reason (of type `unknown`) is passed to the `mapErr` function.
|
|
285
|
+
* `mapErr` is responsible for transforming this `unknown` error into an `Err<E>` variant containing
|
|
286
|
+
* a well-typed error value of type `E`.
|
|
289
287
|
*
|
|
290
288
|
* The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.
|
|
291
289
|
*
|
|
292
290
|
* @template T - The type of the success value the `Promise` from `operation` resolves to.
|
|
293
|
-
* @template E - The type of the error value produced by `
|
|
291
|
+
* @template E - The type of the error value produced by `mapErr` if the `operation` fails or rejects.
|
|
294
292
|
* @param options - An object containing the asynchronous operation and error mapping function.
|
|
295
293
|
* @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.
|
|
296
|
-
* @param options.
|
|
297
|
-
*
|
|
298
|
-
*
|
|
294
|
+
* @param options.mapErr - A function that takes the `unknown` exception/rejection reason caught from `options.try`
|
|
295
|
+
* and transforms it into an `Err<E>` variant containing a specific error value of type `E`.
|
|
296
|
+
* This function must return `Err<E>` directly.
|
|
299
297
|
* @returns A `Promise` that resolves to a `Result<T, E>`: `Ok<T>` if `options.try`'s `Promise` resolves,
|
|
300
|
-
* or `Err<E>` if it rejects/throws and `options.
|
|
298
|
+
* or `Err<E>` if it rejects/throws and `options.mapErr` provides an error variant.
|
|
301
299
|
* @example
|
|
302
300
|
* ```ts
|
|
303
301
|
* async function fetchData(url: string): Promise<Result<Response, Error>> {
|
|
304
302
|
* return tryAsync({
|
|
305
303
|
* try: async () => fetch(url),
|
|
306
|
-
*
|
|
307
|
-
* if (err instanceof Error) return err;
|
|
308
|
-
* return new Error("Network request failed");
|
|
304
|
+
* mapErr: (err: unknown) => {
|
|
305
|
+
* if (err instanceof Error) return Err(err);
|
|
306
|
+
* return Err(new Error("Network request failed"));
|
|
309
307
|
* }
|
|
310
308
|
* });
|
|
311
309
|
* }
|
|
@@ -324,10 +322,10 @@ declare function trySync<T, E>({
|
|
|
324
322
|
*/
|
|
325
323
|
declare function tryAsync<T, E>({
|
|
326
324
|
try: operation,
|
|
327
|
-
|
|
325
|
+
mapErr
|
|
328
326
|
}: {
|
|
329
327
|
try: () => Promise<T>;
|
|
330
|
-
|
|
328
|
+
mapErr: (error: unknown) => Err<E>;
|
|
331
329
|
}): Promise<Result<T, E>>;
|
|
332
330
|
/**
|
|
333
331
|
* Resolves a value that may or may not be wrapped in a `Result`, returning the final value.
|
|
@@ -428,4 +426,4 @@ declare function resolve<T, E>(value: T | Result<T, E>): T;
|
|
|
428
426
|
//# sourceMappingURL=result.d.ts.map
|
|
429
427
|
//#endregion
|
|
430
428
|
export { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap };
|
|
431
|
-
//# sourceMappingURL=result-
|
|
429
|
+
//# sourceMappingURL=result-fCtNge01.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"result-fCtNge01.d.ts","names":[],"sources":["../src/result/result.ts"],"sourcesContent":[],"mappings":";;AAWA;AAaA;AAqCA;;;;;;AAAsC;AAiBtC;AAAgE,KAnEpD,EAmEoD,CAAA,CAAA,CAAA,GAAA;EAAA,IAApC,EAnEA,CAmEA;EAAC,KAAM,EAAA,IAAA;CAAC;AAAF;AAiBlC;;;;;AAAqC;AAWrC;;;;AAAsE,KAlF1D,GAkF0D,CAAA,CAAA,CAAA,GAAA;EAAO,KAAA,EAlF/C,CAkF+C;EAcjE,IAAA,EAAA,IAAA;CAAoB;;;;AAA8C;AAuB9E;;;;;;AACI;AAqBJ;;;;;;AAGI;AAgCJ;;;;;AAEkB;AAuClB;;;;;;;AAA8D;AAyB9D;;;AAA8C,KA7MlC,MA6MkC,CAAA,CAAA,EAAA,CAAA,CAAA,GA7MnB,EA6MmB,CA7MhB,CA6MgB,CAAA,GA7MX,GA6MW,CA7MP,CA6MO,CAAA;;;;AAAkB;AAuChE;;;;;;;;;;AAMU;AAsDY,cA/RT,EA+RiB,EAAA,CAAA,CAAA,CAAA,CAAA,IAAA,EA/RF,CA+RE,EAAA,GA/RE,EA+RF,CA/RK,CA+RL,CAAA;;;;;;;;;;;;AAMnB;AAuGX;;;AAA+C,cA3XlC,GA2XkC,EAAA,CAAA,CAAA,CAAA,CAAA,KAAA,EA3XjB,CA2XiB,EAAA,GA3Xb,GA2Xa,CA3XT,CA2XS,CAAA;;;AAAM;AAOrD;;;;;;AAAwD,KAvX5C,mBAuX4C,CAAA,UAvXd,MAuXc,CAAA,OAAA,EAAA,OAAA,CAAA,CAAA,GAvXc,OAuXd,CAtXvD,CAsXuD,EAAA;EAAC,KAAA,EAAA,IAAA;;;;;;;;;;;KAzW7C,+BAA+B,4BAA4B,QACtE;;;;;;;;;;;;;;;;;;;;;KAsBW,mBAAmB,4BAA4B,UAAU,cAClE;;;;;;;;;;;;;;;;;;;KAqBS,oBAAoB,4BAA4B,UAAU,eAGnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCa,6DAEJ,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;iBAuCN,mBAAmB,OAAO,GAAG,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;iBAyB/C,oBAAoB,OAAO,GAAG,eAAe,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuCjD;OACV;;;aAGM;8BACiB,IAAI;IAC7B,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsDQ;OAChB;;;aAGM,QAAQ;8BACS,IAAI;IAC7B,QAAQ,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuGN,qBAAqB,OAAO,GAAG,KAAK;iBAOpC,qBAAqB,IAAI,OAAO,GAAG,KAAK"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"result-t0dngyiE.d.ts","names":[],"sources":["../src/result/result.ts"],"sourcesContent":[],"mappings":";;AAWA;AAaA;AAqCA;;;;;;AAAsC;AAiBtC;AAAgE,KAnEpD,EAmEoD,CAAA,CAAA,CAAA,GAAA;EAAA,IAApC,EAnEA,CAmEA;EAAC,KAAM,EAAA,IAAA;CAAC;AAAF;AAiBlC;;;;;AAAqC;AAWrC;;;;AAAsE,KAlF1D,GAkF0D,CAAA,CAAA,CAAA,GAAA;EAAO,KAAA,EAlF/C,CAkF+C;EAcjE,IAAA,EAAA,IAAA;CAAoB;;;;AAA8C;AAuB9E;;;;;;AACI;AAqBJ;;;;;;AAGI;AAgCJ;;;;;AAEkB;AAuClB;;;;;;;AAA8D;AAyB9D;;;AAA8C,KA7MlC,MA6MkC,CAAA,CAAA,EAAA,CAAA,CAAA,GA7MnB,EA6MmB,CA7MhB,CA6MgB,CAAA,GA7MX,GA6MW,CA7MP,CA6MO,CAAA;;;;AAAkB;AAyChE;;;;;;;;;AAMU;AAsDV;AAA8B,cAjSjB,EAiSiB,EAAA,CAAA,CAAA,CAAA,CAAA,IAAA,EAjSF,CAiSE,EAAA,GAjSE,EAiSF,CAjSK,CAiSL,CAAA;;;;;;;;;;AAMnB;AAuGX;;;;;AAAoD,cA7XvC,GA6XuC,EAAA,CAAA,CAAA,CAAA,CAAA,KAAA,EA7XtB,CA6XsB,EAAA,GA7XlB,GA6XkB,CA7Xd,CA6Xc,CAAA;AAAC;AAOrD;;;;;;;AAAyD;KAzX7C,8BAA8B,4BAA4B,QACrE;;;;;;;;;;;;KAaW,+BAA+B,4BAA4B,QACtE;;;;;;;;;;;;;;;;;;;;;KAsBW,mBAAmB,4BAA4B,UAAU,cAClE;;;;;;;;;;;;;;;;;;;KAqBS,oBAAoB,4BAA4B,UAAU,eAGnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCa,6DAEJ,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;iBAuCN,mBAAmB,OAAO,GAAG,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;iBAyB/C,oBAAoB,OAAO,GAAG,eAAe,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCjD;OACV;;;aAGM;gCACmB;IAC3B,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsDQ;OAChB;;;aAGM,QAAQ;gCACW;IAC3B,QAAQ,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuGN,qBAAqB,OAAO,GAAG,KAAK;iBAOpC,qBAAqB,IAAI,OAAO,GAAG,KAAK"}
|