runtry 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,21 @@
1
- Copyright 2026 sebastiansala
2
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
1
+ MIT License
3
2
 
4
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
3
+ Copyright (c) 2026 Sebastian Sala
5
4
 
6
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,15 +1,173 @@
1
- # trycatchfinally
1
+ # runtry
2
2
 
3
- To install dependencies:
3
+ Run async functions and return a typed `Result` **instead of throwing**.
4
+
5
+ - ✅ No repetitive `try/catch` in UI code
6
+ - ✅ Typed success/error handling
7
+ - ✅ Pluggable error normalization (matchers / adapters)
8
+
9
+ ---
10
+
11
+ ## Install
4
12
 
5
13
  ```bash
6
- bun install
14
+ npm i runtry
15
+ # or
16
+ bun add runtry
17
+ # or
18
+ pnpm add runtry
7
19
  ```
8
20
 
9
- To run:
21
+ ---
10
22
 
11
- ```bash
12
- bun run index.ts
23
+ ## Quick start
24
+
25
+ ```ts
26
+ import { run } from "runtry";
27
+
28
+ const result = await run(async () => {
29
+ // any async work
30
+ return 42;
31
+ });
32
+
33
+ if (result.ok) {
34
+ console.log("data:", result.data);
35
+ } else {
36
+ console.error("error:", result.error.code, result.error.message);
37
+ }
13
38
  ```
14
39
 
15
- This project was created using `bun init` in bun v1.2.9. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
40
+ ---
41
+
42
+ ## API
43
+
44
+ ### `run(fn, options?)`
45
+
46
+ ```ts
47
+ import type { AppError, RunOptions, RunResult } from "runtry";
48
+
49
+ declare function run<T, E extends AppError = AppError>(
50
+ fn: () => Promise<T>,
51
+ options?: RunOptions<T, E>
52
+ ): Promise<RunResult<T, E>>;
53
+ ```
54
+
55
+ - Returns `{ ok: true, data, error: null }` on success
56
+ - Returns `{ ok: false, data: null, error }` on failure
57
+ - Never throws (unless your callbacks throw)
58
+
59
+ ---
60
+
61
+ ## Normalizing errors (matchers)
62
+
63
+ `runtry` can normalize unknown thrown values (`unknown`) into a consistent `AppError` shape.
64
+
65
+ ### 1) Create matchers (adapters)
66
+
67
+ ```ts
68
+ import {
69
+ createNormalizer,
70
+ abortMatcher,
71
+ instanceOfMatcher,
72
+ defaultFallback,
73
+ } from "runtry";
74
+ import type { AppError } from "runtry";
75
+ import { HttpError } from "./http-error"; // your app error class
76
+
77
+ type MyMeta = { url?: string; body?: unknown };
78
+
79
+ const httpMatcher = instanceOfMatcher(HttpError, (e) => ({
80
+ code: "HTTP",
81
+ message: e.message,
82
+ status: e.status,
83
+ meta: { url: e.url, body: e.body } as MyMeta,
84
+ cause: e,
85
+ }));
86
+
87
+ const toError = createNormalizer<AppError<MyMeta>>(
88
+ [abortMatcher, httpMatcher],
89
+ (e) => defaultFallback(e) as AppError<MyMeta>
90
+ );
91
+ ```
92
+
93
+ ### 2) Use the normalizer in `run`
94
+
95
+ ```ts
96
+ import { run } from "runtry";
97
+
98
+ const res = await run(getDocuments, {
99
+ toError,
100
+ onError: (e) => console.log(e.status, e.message),
101
+ });
102
+ ```
103
+
104
+ ---
105
+
106
+ ## `createClient()` (configure once, reuse everywhere)
107
+
108
+ If you don't want to pass `toError` every time, create a client:
109
+
110
+ ```ts
111
+ import {
112
+ createClient,
113
+ abortMatcher,
114
+ instanceOfMatcher,
115
+ defaultFallback,
116
+ } from "runtry";
117
+ import { HttpError } from "./http-error";
118
+
119
+ const client = createClient({
120
+ matchers: [
121
+ abortMatcher,
122
+ instanceOfMatcher(HttpError, (e) => ({
123
+ code: "HTTP",
124
+ message: e.message,
125
+ status: e.status,
126
+ meta: { url: e.url, body: e.body },
127
+ cause: e,
128
+ })),
129
+ ],
130
+ fallback: defaultFallback,
131
+ ignoreAbort: true, // default
132
+ });
133
+
134
+ const result = await client.run(getDocuments, {
135
+ onError: (e) => console.log(e.code, e.message),
136
+ });
137
+ ```
138
+
139
+ ---
140
+
141
+ ## React example (loading + toast, no try/catch)
142
+
143
+ ```ts
144
+ import { createClient, abortMatcher, defaultFallback } from "runtry";
145
+
146
+ const client = createClient({
147
+ matchers: [abortMatcher],
148
+ fallback: defaultFallback,
149
+ });
150
+
151
+ useEffect(() => {
152
+ let cancelled = false;
153
+ setIsLoading(true);
154
+
155
+ client.run(getDocuments, {
156
+ onSuccess: (docs) => {
157
+ if (cancelled) return;
158
+ setUploadedFiles(docs.map(mapper));
159
+ },
160
+ onError: (e) => {
161
+ if (e.code === "ABORTED") return;
162
+ toast.error(e.message);
163
+ },
164
+ onFinally: () => {
165
+ if (!cancelled) setIsLoading(false);
166
+ },
167
+ });
168
+
169
+ return () => {
170
+ cancelled = true;
171
+ };
172
+ }, []);
173
+ ```
@@ -0,0 +1,20 @@
1
+ import type { AppError } from "./error/types";
2
+ import type { Matcher } from "./error/normalize";
3
+ import type { RunOptions, RunResult } from "./types";
4
+ export type CreateClientOptions<E extends AppError = AppError> = {
5
+ matchers?: Matcher<E>[];
6
+ fallback?: (err: unknown) => E;
7
+ /**
8
+ * If you want a completely custom normalizer, you can provide it directly.
9
+ * If set, `matchers` and `fallback` are ignored.
10
+ */
11
+ toError?: (err: unknown) => E;
12
+ /** Default for run options */
13
+ ignoreAbort?: boolean;
14
+ /** Optional default mapper for all runs */
15
+ mapError?: (error: E) => E;
16
+ };
17
+ export declare function createClient<E extends AppError = AppError>(opts?: CreateClientOptions<E>): {
18
+ run<T>(fn: () => Promise<T>, options?: RunOptions<T, E>): Promise<RunResult<T, E>>;
19
+ };
20
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAOjD,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAErD,MAAM,MAAM,mBAAmB,CAAC,CAAC,SAAS,QAAQ,GAAG,QAAQ,IAAI;IAC/D,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;IACxB,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC;IAC/B;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC;IAE9B,8BAA8B;IAC9B,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB,2CAA2C;IAC3C,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC;AAEF,wBAAgB,YAAY,CAAC,CAAC,SAAS,QAAQ,GAAG,QAAQ,EACxD,IAAI,GAAE,mBAAmB,CAAC,CAAC,CAAM;QAiB3B,CAAC,MACC,MAAM,OAAO,CAAC,CAAC,CAAC,YACX,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,GACxB,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EAgB9B"}
package/dist/client.js ADDED
@@ -0,0 +1,26 @@
1
+ import { createNormalizer, defaultFallback, toAppError, } from "./error/normalize";
2
+ import { run as baseRun } from "./run";
3
+ export function createClient(opts = {}) {
4
+ const { matchers = [], fallback = (e) => defaultFallback(e), toError: customToError, ignoreAbort = true, mapError: defaultMapError, } = opts;
5
+ const toError = customToError ??
6
+ (matchers.length > 0
7
+ ? createNormalizer(matchers, fallback)
8
+ : toAppError);
9
+ return {
10
+ run(fn, options = {}) {
11
+ return baseRun(fn, {
12
+ toError,
13
+ ignoreAbort,
14
+ mapError: (err) => options.mapError
15
+ ? options.mapError(defaultMapError ? defaultMapError(err) : err)
16
+ : defaultMapError
17
+ ? defaultMapError(err)
18
+ : err,
19
+ onError: options.onError,
20
+ onSuccess: options.onSuccess,
21
+ onFinally: options.onFinally,
22
+ });
23
+ },
24
+ };
25
+ }
26
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,UAAU,GACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,GAAG,IAAI,OAAO,EAAE,MAAM,OAAO,CAAC;AAmBvC,MAAM,UAAU,YAAY,CAC1B,OAA+B,EAAE;IAEjC,MAAM,EACJ,QAAQ,GAAG,EAAE,EACb,QAAQ,GAAG,CAAC,CAAU,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAiB,EAC7D,OAAO,EAAE,aAAa,EACtB,WAAW,GAAG,IAAI,EAClB,QAAQ,EAAE,eAAe,GAC1B,GAAG,IAAI,CAAC;IAET,MAAM,OAAO,GACX,aAAa;QACb,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;YAClB,CAAC,CAAC,gBAAgB,CAAI,QAAQ,EAAE,QAAQ,CAAC;YACzC,CAAC,CAAE,UAA2C,CAAC,CAAC;IAEpD,OAAO;QACL,GAAG,CACD,EAAoB,EACpB,UAA4B,EAAE;YAE9B,OAAO,OAAO,CAAC,EAAE,EAAE;gBACjB,OAAO;gBACP,WAAW;gBACX,QAAQ,EAAE,CAAC,GAAG,EAAE,EAAE,CAChB,OAAO,CAAC,QAAQ;oBACd,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;oBAChE,CAAC,CAAC,eAAe;wBACjB,CAAC,CAAC,eAAe,CAAC,GAAG,CAAC;wBACtB,CAAC,CAAC,GAAG;gBACT,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;aAC7B,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { AppError } from "./types";
2
+ import type { Matcher } from "./normalize";
3
+ export declare const abortMatcher: Matcher;
4
+ export declare const timeoutMatcher: Matcher;
5
+ export declare function instanceOfMatcher<T extends Error, Meta = unknown>(ErrorCtor: new (...args: any[]) => T, map: (e: T) => AppError<Meta>): Matcher<AppError<Meta>>;
6
+ //# sourceMappingURL=matchers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matchers.d.ts","sourceRoot":"","sources":["../../src/error/matchers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAG3C,eAAO,MAAM,YAAY,EAAE,OAK1B,CAAC;AAGF,eAAO,MAAM,cAAc,EAAE,OAS5B,CAAC;AAGF,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,KAAK,EAAE,IAAI,GAAG,OAAO,EAC/D,SAAS,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,EACpC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,QAAQ,CAAC,IAAI,CAAC,GAC5B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAEzB"}
@@ -0,0 +1,23 @@
1
+ // Matcher genérico para AbortError (por si no quieres usar toAppError)
2
+ export const abortMatcher = (err) => {
3
+ if (err instanceof DOMException && err.name === "AbortError") {
4
+ return { code: "ABORTED", message: "Request cancelled", cause: err };
5
+ }
6
+ return null;
7
+ };
8
+ // Matcher para "timeout" (si el user usa AbortSignal.timeout o libs que tiran ese name)
9
+ export const timeoutMatcher = (err) => {
10
+ if (err instanceof DOMException && err.name === "TimeoutError") {
11
+ return { code: "TIMEOUT", message: "Request timed out", cause: err };
12
+ }
13
+ // algunas libs tiran Error con name = "TimeoutError"
14
+ if (err instanceof Error && err.name === "TimeoutError") {
15
+ return { code: "TIMEOUT", message: err.message || "Request timed out", cause: err };
16
+ }
17
+ return null;
18
+ };
19
+ // Helper para crear matcher basado en "instanceof" (plugin-friendly)
20
+ export function instanceOfMatcher(ErrorCtor, map) {
21
+ return (err) => (err instanceof ErrorCtor ? map(err) : null);
22
+ }
23
+ //# sourceMappingURL=matchers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matchers.js","sourceRoot":"","sources":["../../src/error/matchers.ts"],"names":[],"mappings":"AAGA,uEAAuE;AACvE,MAAM,CAAC,MAAM,YAAY,GAAY,CAAC,GAAG,EAAE,EAAE;IAC3C,IAAI,GAAG,YAAY,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QAC7D,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IACvE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF,wFAAwF;AACxF,MAAM,CAAC,MAAM,cAAc,GAAY,CAAC,GAAG,EAAE,EAAE;IAC7C,IAAI,GAAG,YAAY,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QAC/D,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IACvE,CAAC;IACD,qDAAqD;IACrD,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QACxD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,mBAAmB,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IACtF,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF,qEAAqE;AACrE,MAAM,UAAU,iBAAiB,CAC/B,SAAoC,EACpC,GAA6B;IAE7B,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,YAAY,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { AppError } from "./types";
2
+ export type Matcher<E extends AppError = AppError> = (err: unknown) => E | null;
3
+ export declare function createNormalizer<E extends AppError>(matchers: Matcher<E>[], fallback: (err: unknown) => E): (err: unknown) => E;
4
+ export declare function defaultFallback(err: unknown): AppError;
5
+ export declare function toAppError(err: unknown): AppError;
6
+ //# sourceMappingURL=normalize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/error/normalize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAExC,MAAM,MAAM,OAAO,CAAC,CAAC,SAAS,QAAQ,GAAG,QAAQ,IAAI,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,GAAG,IAAI,CAAC;AAEhF,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,QAAQ,EACjD,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,EACtB,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,IAErB,KAAK,OAAO,KAAG,CAAC,CAOzB;AAGD,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,GAAG,QAAQ,CAQtD;AAGD,wBAAgB,UAAU,CAAC,GAAG,EAAE,OAAO,GAAG,QAAQ,CAMjD"}
@@ -0,0 +1,29 @@
1
+ export function createNormalizer(matchers, fallback) {
2
+ return (err) => {
3
+ for (const m of matchers) {
4
+ const out = m(err);
5
+ if (out)
6
+ return out;
7
+ }
8
+ return fallback(err);
9
+ };
10
+ }
11
+ // Fallback general (sin depender de fetch / http)
12
+ export function defaultFallback(err) {
13
+ if (err instanceof Error) {
14
+ // En browsers, errores de red a veces caen como TypeError (fetch),
15
+ // pero esto no es 100% universal; lo tratamos como best-effort.
16
+ const code = err.name === "TypeError" ? "NETWORK" : "UNKNOWN";
17
+ return { code, message: err.message || "Something went wrong", cause: err };
18
+ }
19
+ return { code: "UNKNOWN", message: "Something went wrong", cause: err };
20
+ }
21
+ // Normalizador "default" que incluye matcher de abort (muy útil en UI)
22
+ export function toAppError(err) {
23
+ // AbortError (browser / fetch / AbortController)
24
+ if (err instanceof DOMException && err.name === "AbortError") {
25
+ return { code: "ABORTED", message: "Request cancelled", cause: err };
26
+ }
27
+ return defaultFallback(err);
28
+ }
29
+ //# sourceMappingURL=normalize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../src/error/normalize.ts"],"names":[],"mappings":"AAIA,MAAM,UAAU,gBAAgB,CAC9B,QAAsB,EACtB,QAA6B;IAE7B,OAAO,CAAC,GAAY,EAAK,EAAE;QACzB,KAAK,MAAM,CAAC,IAAI,QAAQ,EAAE,CAAC;YACzB,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;YACnB,IAAI,GAAG;gBAAE,OAAO,GAAG,CAAC;QACtB,CAAC;QACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC;AACJ,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,eAAe,CAAC,GAAY;IAC1C,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;QACzB,mEAAmE;QACnE,gEAAgE;QAChE,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;QAC9D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,sBAAsB,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,sBAAsB,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;AAC1E,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,UAAU,CAAC,GAAY;IACrC,iDAAiD;IACjD,IAAI,GAAG,YAAY,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QAC7D,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IACvE,CAAC;IACD,OAAO,eAAe,CAAC,GAAG,CAAC,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,18 @@
1
+ export type AppErrorCode = "ABORTED" | "NETWORK" | "TIMEOUT" | "VALIDATION" | "HTTP" | "UNKNOWN";
2
+ /**
3
+ * A normalized error shape returned by `run()`.
4
+ *
5
+ * - `code`: A stable identifier you can switch on (e.g. "HTTP", "VALIDATION").
6
+ * - `message`: User-facing or log-friendly message.
7
+ * - `status`: Optional numeric status (commonly HTTP status).
8
+ * - `meta`: Optional payload with extra context (response body, validation fields, etc.).
9
+ * - `cause`: The original thrown value for debugging.
10
+ */
11
+ export type AppError<Meta = unknown> = {
12
+ code: AppErrorCode | (string & {});
13
+ message: string;
14
+ status?: number;
15
+ meta?: Meta;
16
+ cause?: unknown;
17
+ };
18
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/error/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GACpB,SAAS,GACT,SAAS,GACT,SAAS,GACT,YAAY,GACZ,MAAM,GACN,SAAS,CAAC;AAEZ;;;;;;;;EAQC;AACH,MAAM,MAAM,QAAQ,CAAC,IAAI,GAAG,OAAO,IAAI;IACrC,IAAI,EAAE,YAAY,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/error/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ export { run } from "./run";
2
+ export type { RunOptions, RunResult } from "./types";
3
+ export type { AppError, AppErrorCode } from "./error/types";
4
+ export { toAppError, defaultFallback, createNormalizer, } from "./error/normalize";
5
+ export { abortMatcher, timeoutMatcher, instanceOfMatcher, } from "./error/matchers";
6
+ export { createClient } from "./client";
7
+ export type { CreateClientOptions } from "./client";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAErD,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,YAAY,EACZ,cAAc,EACd,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { run } from "./run";
2
+ export { toAppError, defaultFallback, createNormalizer, } from "./error/normalize";
3
+ export { abortMatcher, timeoutMatcher, instanceOfMatcher, } from "./error/matchers";
4
+ export { createClient } from "./client";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAI5B,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,YAAY,EACZ,cAAc,EACd,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC"}
package/dist/run.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { AppError } from "./error/types";
2
+ import type { RunOptions, RunResult } from "./types";
3
+ /**
4
+ * Executes an async operation and returns a Result instead of throwing.
5
+ *
6
+ * Errors are normalized into an `AppError` (or a custom error type `E`)
7
+ * using the provided `toError` function.
8
+ *
9
+ * This utility is framework-agnostic and works in browsers, Node.js,
10
+ * React effects, and any async context.
11
+ */
12
+ export declare function run<T, E extends AppError = AppError>(fn: () => Promise<T>, options?: RunOptions<T, E>): Promise<RunResult<T, E>>;
13
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAErD;;;;;;;;GAQG;AACH,wBAAsB,GAAG,CAAC,CAAC,EAAE,CAAC,SAAS,QAAQ,GAAG,QAAQ,EACxD,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,OAAO,GAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAM,GAC7B,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CA4B1B"}
package/dist/run.js ADDED
@@ -0,0 +1,33 @@
1
+ import { toAppError as defaultToAppError } from "./error/normalize";
2
+ /**
3
+ * Executes an async operation and returns a Result instead of throwing.
4
+ *
5
+ * Errors are normalized into an `AppError` (or a custom error type `E`)
6
+ * using the provided `toError` function.
7
+ *
8
+ * This utility is framework-agnostic and works in browsers, Node.js,
9
+ * React effects, and any async context.
10
+ */
11
+ export async function run(fn, options = {}) {
12
+ const { toError = defaultToAppError, mapError, onError, onSuccess, onFinally, ignoreAbort = true, } = options;
13
+ try {
14
+ const data = await fn();
15
+ onSuccess?.(data);
16
+ return { ok: true, data, error: null };
17
+ }
18
+ catch (e) {
19
+ let err = toError(e);
20
+ if (mapError)
21
+ err = mapError(err);
22
+ if (ignoreAbort && err.code === "ABORTED") {
23
+ // decisión de diseño: devolvemos ok:false pero sin llamar onError (para no toastear)
24
+ return { ok: false, data: null, error: err };
25
+ }
26
+ onError?.(err);
27
+ return { ok: false, data: null, error: err };
28
+ }
29
+ finally {
30
+ onFinally?.();
31
+ }
32
+ }
33
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,IAAI,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAGpE;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,GAAG,CACvB,EAAoB,EACpB,UAA4B,EAAE;IAE9B,MAAM,EACJ,OAAO,GAAG,iBAAmD,EAC7D,QAAQ,EACR,OAAO,EACP,SAAS,EACT,SAAS,EACT,WAAW,GAAG,IAAI,GACnB,GAAG,OAAO,CAAC;IAEZ,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,EAAE,EAAE,CAAC;QACxB,SAAS,EAAE,CAAC,IAAI,CAAC,CAAC;QAClB,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACzC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,GAAG,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACrB,IAAI,QAAQ;YAAE,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAElC,IAAI,WAAW,IAAI,GAAG,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC1C,qFAAqF;YACrF,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;QAC/C,CAAC;QAED,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;QACf,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IAC/C,CAAC;YAAS,CAAC;QACT,SAAS,EAAE,EAAE,CAAC;IAChB,CAAC;AACH,CAAC"}
@@ -0,0 +1,61 @@
1
+ import type { AppError } from "./error/types";
2
+ export type RunOptions<T, E extends AppError = AppError> = {
3
+ /**
4
+ * Converts an unknown thrown value into your normalized error type `E`.
5
+ *
6
+ * Use this to integrate custom errors (e.g. HttpError, AxiosError, ZodError),
7
+ * map status codes, or attach metadata for UI/debugging.
8
+ *
9
+ * If omitted, a default normalizer is used (best-effort).
10
+ */
11
+ toError?: (err: unknown) => E;
12
+ /**
13
+ * Optional error transformer applied AFTER `toError`.
14
+ *
15
+ * Useful for translating messages, mapping status to user-friendly text,
16
+ * or enforcing a consistent error format across the app.
17
+ */
18
+ mapError?: (error: E) => E;
19
+ /**
20
+ * Called when the operation fails (except when `ignoreAbort` is true and the error code is "ABORTED").
21
+ *
22
+ * Great place for toasts, logging, analytics, etc.
23
+ */
24
+ onError?: (error: E) => void;
25
+ /**
26
+ * Called when the operation succeeds.
27
+ */
28
+ onSuccess?: (data: T) => void;
29
+ /**
30
+ * Called after success or failure (similar to a `finally` block).
31
+ *
32
+ * Common use: stop loading spinners, cleanup state, etc.
33
+ */
34
+ finally?: () => void;
35
+ /**
36
+ * Called after success or failure, similar to `finally`, but with no return value.
37
+ *
38
+ * Common use: stop loading spinners, cleanup state, etc.
39
+ */
40
+ onFinally?: () => void;
41
+ /**
42
+ * When true, errors with `code === "ABORTED"` are treated as non-fatal:
43
+ * - `onError` is NOT called
44
+ * - the result is returned as `{ ok: false, error }`
45
+ *
46
+ * This is useful for cancellable side-effects (React effects, debounced searches, etc.).
47
+ *
48
+ * @default true
49
+ */
50
+ ignoreAbort?: boolean;
51
+ };
52
+ export type RunResult<T, E extends AppError = AppError> = {
53
+ ok: true;
54
+ data: T;
55
+ error: null;
56
+ } | {
57
+ ok: false;
58
+ data: null;
59
+ error: E;
60
+ };
61
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,MAAM,MAAM,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,QAAQ,GAAG,QAAQ,IAAI;IACzD;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC;IAE9B;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC;IAE3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,CAAC;IAE7B;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC;IAE9B;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IAErB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IAEvB;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,SAAS,CAAC,CAAC,EAAE,CAAC,SAAS,QAAQ,GAAG,QAAQ,IAClD;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,KAAK,EAAE,IAAI,CAAA;CAAE,GAClC;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runtry",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Run async functions and return a typed Result instead of throwing.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,12 +17,18 @@
17
17
  "LICENSE"
18
18
  ],
19
19
  "scripts": {
20
- "build": "tsc -p tsconfig.json",
20
+ "build": "tsc -p tsconfig.build.json",
21
21
  "prepublishOnly": "npm run build"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/bun": "latest",
25
25
  "typescript": "^5.0.0"
26
26
  },
27
- "license": "MIT"
27
+ "license": "MIT",
28
+ "homepage": "https://github.com/sebastiansala/runtry#readme",
29
+ "bugs": "https://github.com/sebastiansala/runtry/issues",
30
+ "author": {
31
+ "name": "sebasxsala",
32
+ "url": "https://github.com/sebasxsala"
33
+ }
28
34
  }