@crbroughton/failsafe 0.2.0 → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CRBroughton
4
+
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,4 +1,4 @@
1
- # @crbroughton/failsafe
1
+ # FailSafe
2
2
 
3
3
  Type-safe error handling utilities for TypeScript. A `Result<T, E>` type
4
4
  (inspired by Rust) plus helpers for turning throwing browser/Node APIs into
@@ -43,6 +43,7 @@ const message = matchResult(result, {
43
43
  - `@crbroughton/failsafe`: the `Result` type, `Ok`/`Err`, guards, and matchers
44
44
  - `@crbroughton/failsafe/try`: `Result`-returning wrappers around throwing web/Node APIs
45
45
  - `@crbroughton/failsafe/pipe`: plain left-to-right function composition
46
+ - `@crbroughton/failsafe/gen`: generator-based early-return error propagation
46
47
 
47
48
  ## `@crbroughton/failsafe`
48
49
 
@@ -201,6 +202,56 @@ const slug = pipe(
201
202
  // 'hello-world'
202
203
  ```
203
204
 
205
+ ## `@crbroughton/failsafe/gen`
206
+
207
+ Early-return error propagation for `Result` — like Rust's `?` operator, via
208
+ generators and `yield*`. Instead of manually checking `isErr` after every
209
+ step, short-circuit with `yield* fail(...)` or `yield* unwrap(existingResult)`
210
+ and let `gen()` collect the outcome into a `Result`.
211
+
212
+ ### `gen(block)`
213
+
214
+ Runs a generator block and collects it into a `Result`. Overloaded on sync
215
+ vs async: pass a `function*` and get `Result<T, E>` back directly; pass an
216
+ `async function*` and get `Promise<Result<T, E>>`. There's no separate name
217
+ for the async case — which overload applies follows from which kind of
218
+ function you write.
219
+
220
+ ### `fail(error)`
221
+
222
+ Short-circuits a `gen()` block with an error, via `yield* fail(...)`.
223
+
224
+ ### `unwrap(result)`
225
+
226
+ Unwraps a `Result` inside a `gen()` block via `yield* unwrap(...)` — yields
227
+ the error (short-circuiting) if `Err`, or resolves to the value if `Ok`.
228
+ Always takes a plain, already-resolved `Result<T, E>`; for an async
229
+ Result-returning call, await it at the call site: `yield* unwrap(await fetchUser(id))`.
230
+
231
+ ```ts
232
+ import type { TaggedError } from "@crbroughton/failsafe"
233
+ import { fail, gen, unwrap } from "@crbroughton/failsafe/gen"
234
+
235
+ type EmptyFieldError = TaggedError<"EmptyFieldError", { field: string }>
236
+
237
+ // Sync
238
+ const slug = gen(function* () {
239
+ if (input.trim() === "") {
240
+ return yield * fail<EmptyFieldError>({ tag: "EmptyFieldError", field: "slug" })
241
+ }
242
+ return input.trim().toLowerCase()
243
+ })
244
+ // Result<string, EmptyFieldError>
245
+
246
+ // Async — chaining multiple Result-returning calls
247
+ const login = await gen(async function* () {
248
+ const { token, userId } = yield * unwrap(await postLogin(email, password))
249
+ const user = yield * unwrap(await fetchUserProfile(userId))
250
+ return { user, token }
251
+ })
252
+ // Result<{ user: UserProfile, token: string }, LoginError>
253
+ ```
254
+
204
255
  ## Development
205
256
 
206
257
  This repo uses [devenv](https://devenv.sh) to provide Node and pnpm.
@@ -0,0 +1,84 @@
1
+ import { Result } from '../safe/index.mjs';
2
+
3
+ /**
4
+ * Short-circuits a `gen()` block with an error. Must only be driven via
5
+ * `yield*` inside a `gen()` generator — calling `.next()` on it directly a
6
+ * second time throws, since resuming past the yield has no meaning outside
7
+ * that context.
8
+ *
9
+ * @template E The type of the error
10
+ * @param error The error to short-circuit with
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * gen(function* () {
15
+ * if (!email.includes('@')) {
16
+ * return yield* fail({ tag: 'InvalidEmail', email })
17
+ * }
18
+ * // ...
19
+ * })
20
+ * ```
21
+ */
22
+ declare function fail<E>(error: E): Generator<E, never, unknown>;
23
+ /**
24
+ * Unwraps a `Result` inside a `gen()` block via `yield*` — yields the error
25
+ * (short-circuiting the block) if `Err`, or resolves to the value if `Ok`.
26
+ *
27
+ * Always takes a plain, already-resolved `Result<T, E>`. For an async
28
+ * Result-returning call, await it at the call site first:
29
+ * `yield* unwrap(await fetchUser(id))`.
30
+ *
31
+ * @template T The success type
32
+ * @template E The error type
33
+ * @param result The Result to unwrap
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * gen(function* () {
38
+ * const user = yield* unwrap(await fetchUser(id))
39
+ * return user.name
40
+ * })
41
+ * ```
42
+ */
43
+ declare function unwrap<T, E>(result: Result<T, E>): Generator<E, T, unknown>;
44
+ /**
45
+ * Runs a generator block and collects it into a `Result` — early-return
46
+ * error propagation (like Rust's `?` operator) via `yield* fail(...)` and
47
+ * `yield* unwrap(...)`, instead of manually checking `isErr` after every
48
+ * step.
49
+ *
50
+ * Overloaded on sync vs async generators: pass a `function*` for a sync
51
+ * block and get `Result<T, E>` back directly; pass an `async function*` and
52
+ * get `Promise<Result<T, E>>`. Which overload TS picks follows from which
53
+ * kind of function you write — there's no separate name for the async case.
54
+ *
55
+ * @template T The success type
56
+ * @template E The error type
57
+ * @param block A generator function that yields errors via `fail`/`unwrap`
58
+ * and returns the success value
59
+ * @returns Ok(value) or Err(error) — wrapped in a Promise for async blocks
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * // Sync
64
+ * const slug = gen(function* () {
65
+ * if (input.trim() === '') {
66
+ * return yield* fail({ tag: 'EmptyFieldError', field: 'slug' })
67
+ * }
68
+ * return input.trim().toLowerCase()
69
+ * })
70
+ * // Result<string, EmptyFieldError>
71
+ *
72
+ * // Async
73
+ * const login = await gen(async function* () {
74
+ * const { token, userId } = yield* unwrap(await postLogin(email, password))
75
+ * const user = yield* unwrap(await fetchUserProfile(userId))
76
+ * return { user, token }
77
+ * })
78
+ * // Result<{ user: UserProfile, token: string }, LoginError>
79
+ * ```
80
+ */
81
+ declare function gen<T, E>(block: () => Generator<E, T, unknown>): Result<T, E>;
82
+ declare function gen<T, E>(block: () => AsyncGenerator<E, T, unknown>): Promise<Result<T, E>>;
83
+
84
+ export { fail, gen, unwrap };
@@ -0,0 +1,84 @@
1
+ import { Result } from '../safe/index.js';
2
+
3
+ /**
4
+ * Short-circuits a `gen()` block with an error. Must only be driven via
5
+ * `yield*` inside a `gen()` generator — calling `.next()` on it directly a
6
+ * second time throws, since resuming past the yield has no meaning outside
7
+ * that context.
8
+ *
9
+ * @template E The type of the error
10
+ * @param error The error to short-circuit with
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * gen(function* () {
15
+ * if (!email.includes('@')) {
16
+ * return yield* fail({ tag: 'InvalidEmail', email })
17
+ * }
18
+ * // ...
19
+ * })
20
+ * ```
21
+ */
22
+ declare function fail<E>(error: E): Generator<E, never, unknown>;
23
+ /**
24
+ * Unwraps a `Result` inside a `gen()` block via `yield*` — yields the error
25
+ * (short-circuiting the block) if `Err`, or resolves to the value if `Ok`.
26
+ *
27
+ * Always takes a plain, already-resolved `Result<T, E>`. For an async
28
+ * Result-returning call, await it at the call site first:
29
+ * `yield* unwrap(await fetchUser(id))`.
30
+ *
31
+ * @template T The success type
32
+ * @template E The error type
33
+ * @param result The Result to unwrap
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * gen(function* () {
38
+ * const user = yield* unwrap(await fetchUser(id))
39
+ * return user.name
40
+ * })
41
+ * ```
42
+ */
43
+ declare function unwrap<T, E>(result: Result<T, E>): Generator<E, T, unknown>;
44
+ /**
45
+ * Runs a generator block and collects it into a `Result` — early-return
46
+ * error propagation (like Rust's `?` operator) via `yield* fail(...)` and
47
+ * `yield* unwrap(...)`, instead of manually checking `isErr` after every
48
+ * step.
49
+ *
50
+ * Overloaded on sync vs async generators: pass a `function*` for a sync
51
+ * block and get `Result<T, E>` back directly; pass an `async function*` and
52
+ * get `Promise<Result<T, E>>`. Which overload TS picks follows from which
53
+ * kind of function you write — there's no separate name for the async case.
54
+ *
55
+ * @template T The success type
56
+ * @template E The error type
57
+ * @param block A generator function that yields errors via `fail`/`unwrap`
58
+ * and returns the success value
59
+ * @returns Ok(value) or Err(error) — wrapped in a Promise for async blocks
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * // Sync
64
+ * const slug = gen(function* () {
65
+ * if (input.trim() === '') {
66
+ * return yield* fail({ tag: 'EmptyFieldError', field: 'slug' })
67
+ * }
68
+ * return input.trim().toLowerCase()
69
+ * })
70
+ * // Result<string, EmptyFieldError>
71
+ *
72
+ * // Async
73
+ * const login = await gen(async function* () {
74
+ * const { token, userId } = yield* unwrap(await postLogin(email, password))
75
+ * const user = yield* unwrap(await fetchUserProfile(userId))
76
+ * return { user, token }
77
+ * })
78
+ * // Result<{ user: UserProfile, token: string }, LoginError>
79
+ * ```
80
+ */
81
+ declare function gen<T, E>(block: () => Generator<E, T, unknown>): Result<T, E>;
82
+ declare function gen<T, E>(block: () => AsyncGenerator<E, T, unknown>): Promise<Result<T, E>>;
83
+
84
+ export { fail, gen, unwrap };
@@ -0,0 +1,27 @@
1
+ import { Ok, Err, isErr } from '../safe/index.mjs';
2
+
3
+ function* fail(error) {
4
+ yield error;
5
+ throw new Error("unreachable");
6
+ }
7
+ function* unwrap(result) {
8
+ if (isErr(result)) {
9
+ yield result.error;
10
+ }
11
+ return result.value;
12
+ }
13
+ function gen(block) {
14
+ const iter = block();
15
+ if (Symbol.asyncIterator in iter) {
16
+ const asyncIter = iter;
17
+ return (async () => {
18
+ const first2 = await asyncIter.next();
19
+ return first2.done ? Ok(first2.value) : Err(first2.value);
20
+ })();
21
+ }
22
+ const syncIter = iter;
23
+ const first = syncIter.next();
24
+ return first.done ? Ok(first.value) : Err(first.value);
25
+ }
26
+
27
+ export { fail, gen, unwrap };
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@crbroughton/failsafe",
3
3
  "type": "module",
4
- "version": "0.2.0",
4
+ "version": "0.3.0",
5
5
  "packageManager": "pnpm@9.15.0",
6
6
  "description": "Type-safe error handling utilities for TypeScript",
7
7
  "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/CRBroughton/failsafe.git"
11
+ },
8
12
  "sideEffects": false,
9
13
  "exports": {
10
14
  ".": {
@@ -18,6 +22,10 @@
18
22
  "./pipe": {
19
23
  "types": "./dist/pipe/index.d.mts",
20
24
  "import": "./dist/pipe/index.mjs"
25
+ },
26
+ "./gen": {
27
+ "types": "./dist/gen/index.d.mts",
28
+ "import": "./dist/gen/index.mjs"
21
29
  }
22
30
  },
23
31
  "main": "./dist/safe/index.mjs",