@u17g/deferrable 1.0.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) 2025 Unbounded Pioneering
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 ADDED
@@ -0,0 +1,147 @@
1
+ # @u17g/deferrable
2
+
3
+ A tiny `defer` utility for JavaScript/TypeScript: register cleanup/rollback callbacks that run in LIFO order. Works in any runtime (Node.js, Bun, Deno, browsers).
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install -S @u17g/deferrable
9
+ pnpm add @u17g/deferrable
10
+ bun add @u17g/deferrable
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { deferrable } from "@u17g/deferrable";
17
+
18
+ await deferrable(async (defer): Promise<string> => {
19
+ defer(async ([result, err]) => {
20
+ if (err) {
21
+ console.error(err);
22
+ } else {
23
+ console.log(result);
24
+ }
25
+ });
26
+ return "Hello, World!";
27
+ });
28
+ ```
29
+
30
+ ### CommonJS
31
+
32
+ ```js
33
+ const { deferrable } = require("@u17g/deferrable");
34
+ ```
35
+
36
+ ## TypeScript notes
37
+
38
+ ### Annotate the callback's return type (recommended)
39
+
40
+ When using TypeScript, prefer annotating the return type of the callback you pass to `deferrable`:
41
+
42
+ ```ts
43
+ await deferrable(async (defer): Promise<number> => {
44
+ defer(([value, err]) => {
45
+ // value: number | undefined
46
+ // err: Error | undefined
47
+ });
48
+ return 42;
49
+ });
50
+ ```
51
+
52
+ **Why**: `defer` is typed in terms of the generic `T` (the value that the callback returns). If you omit the return type annotation, TypeScript can fail to infer `T` correctly, which may surface as confusing type errors inside `defer(([value, err]) => ...)`.
53
+
54
+ ## Behavior
55
+
56
+ `deferrable(callback)` runs `callback(defer)` and guarantees that deferred callbacks registered via `defer(...)` are executed **after** the callback finishes (either resolved or rejected).
57
+
58
+ - **Execution order (LIFO)**: deferred callbacks run in reverse order of registration (stack behavior).
59
+ - **Result passed to deferred callbacks**: each deferred callback receives a tuple `[value, error]`:
60
+ - `[value, undefined]` when the callback resolved
61
+ - `[undefined, error]` when the callback threw / rejected
62
+ - **Error propagation**: if the callback fails, deferred callbacks still run, then the original error is re-thrown.
63
+ - **Awaited sequentially**: deferred callbacks are awaited one by one (no parallel execution).
64
+ - **Deferred callback errors are ignored**: if a deferred callback throws/rejects, it is swallowed and does not affect the final result.
65
+
66
+ ### Example: LIFO order
67
+
68
+ ```ts
69
+ await deferrable(async (defer): Promise<string> => {
70
+ defer(() => console.log("first"));
71
+ defer(() => console.log("second"));
72
+ // Output:
73
+ // second
74
+ // first
75
+ return "ok";
76
+ });
77
+ ```
78
+
79
+ ### Example: observing success/failure
80
+
81
+ ```ts
82
+ await deferrable(async (defer): Promise<number> => {
83
+ defer(([value, err]) => {
84
+ if (err) {
85
+ console.error("failed:", err);
86
+ } else {
87
+ console.log("ok:", value);
88
+ }
89
+ });
90
+
91
+ // throw new Error("boom");
92
+ return 42;
93
+ });
94
+ ```
95
+
96
+ ### Example: catching errors at the call site
97
+
98
+ ```ts
99
+ await deferrable(async (_defer): Promise<void> => {
100
+ // Simulate failure
101
+ throw new Error("boom");
102
+ }).catch((err) => {
103
+ console.error("caught:", err);
104
+ });
105
+ ```
106
+
107
+ ## Patterns
108
+
109
+ ### Saga / compensating actions (transaction-like cleanup)
110
+
111
+ Because deferred callbacks run **in reverse order (LIFO)** and still run even if the callback fails, you can use `deferrable` to implement a lightweight saga pattern: after each step succeeds, register its compensation. On failure, compensations run in reverse order automatically.
112
+
113
+ ```ts
114
+ await deferrable(async (defer): Promise<void> => {
115
+ const orderId = await createOrder();
116
+ defer(async ([_, err]) => {
117
+ if (err) await cancelOrder(orderId);
118
+ });
119
+
120
+ const paymentId = await chargeCard();
121
+ defer(async ([_, err]) => {
122
+ if (err) await refundPayment(paymentId);
123
+ });
124
+
125
+ await reserveInventory(orderId);
126
+ defer(async ([_, err]) => {
127
+ if (err) await releaseInventory(orderId);
128
+ });
129
+ }).catch((err) => {
130
+ // If anything throws above, the registered compensations will run:
131
+ // releaseInventory -> refundPayment -> cancelOrder
132
+ console.error("saga failed:", err);
133
+ });
134
+
135
+ async function createOrder(): Promise<string> {
136
+ return "order_123";
137
+ }
138
+ async function cancelOrder(_orderId: string): Promise<void> {}
139
+ async function chargeCard(): Promise<string> {
140
+ return "payment_123";
141
+ }
142
+ async function refundPayment(_paymentId: string): Promise<void> {}
143
+ async function reserveInventory(_orderId: string): Promise<void> {
144
+ throw new Error("out of stock");
145
+ }
146
+ async function releaseInventory(_orderId: string): Promise<void> {}
147
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deferrable = deferrable;
4
+ function ok(value) {
5
+ return [value, undefined];
6
+ }
7
+ ;
8
+ function failure(error) {
9
+ return [undefined, error];
10
+ }
11
+ ;
12
+ async function wrap(promise) {
13
+ try {
14
+ const value = await promise;
15
+ return ok(value);
16
+ }
17
+ catch (error) {
18
+ return failure(error);
19
+ }
20
+ }
21
+ /**
22
+ * Deferrable execution.
23
+ *
24
+ * This function is used to execute a function with a deferrable execution stack - LIFO.
25
+ *
26
+ * @param fn - The function to execute.
27
+ * @returns The result of the function.
28
+ *
29
+ * @example
30
+ *
31
+ * await deferrable(async (defer): Promise<string> => {
32
+ * defer(async ([result, err]) => {
33
+ * if (err) {
34
+ * console.error(err);
35
+ * } else {
36
+ * console.log(result);
37
+ * }
38
+ * });
39
+ *
40
+ * return "Hello, world!";
41
+ * });
42
+ */
43
+ async function deferrable(fn) {
44
+ const stack = [];
45
+ const defer = (exec) => {
46
+ stack.push(exec);
47
+ };
48
+ const result = await wrap(fn(defer));
49
+ while (stack.length) {
50
+ const exec = stack.pop();
51
+ try {
52
+ await exec(result);
53
+ }
54
+ catch { }
55
+ }
56
+ const [value, error] = result;
57
+ if (error !== undefined)
58
+ throw error;
59
+ return value;
60
+ }
61
+ ;
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAyCA,gCAiBC;AAxDD,SAAS,EAAE,CAAI,KAAQ;IACrB,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5B,CAAC;AAAA,CAAC;AAEF,SAAS,OAAO,CAAY,KAAQ;IAClC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC;AAAA,CAAC;AAEF,KAAK,UAAU,IAAI,CAAe,OAAmB;IACnD,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC;QAC5B,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,OAAO,CAAC,KAAU,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACI,KAAK,UAAU,UAAU,CAC9B,EAAwI;IAExI,MAAM,KAAK,GAA8C,EAAE,CAAC;IAC5D,MAAM,KAAK,GAA6B,CAAC,IAAI,EAAE,EAAE;QAC/C,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAO,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;QACpB,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,EAAG,CAAC;QAC1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC,CAAC,CAAC;IACb,CAAC;IACD,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,MAAM,CAAC;IAC9B,IAAI,KAAK,KAAK,SAAS;QAAE,MAAM,KAAK,CAAC;IACrC,OAAO,KAAU,CAAC;AACpB,CAAC;AAAA,CAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Deferrable execution.
3
+ *
4
+ * This function is used to execute a function with a deferrable execution stack - LIFO.
5
+ *
6
+ * @param fn - The function to execute.
7
+ * @returns The result of the function.
8
+ *
9
+ * @example
10
+ *
11
+ * await deferrable(async (defer): Promise<string> => {
12
+ * defer(async ([result, err]) => {
13
+ * if (err) {
14
+ * console.error(err);
15
+ * } else {
16
+ * console.log(result);
17
+ * }
18
+ * });
19
+ *
20
+ * return "Hello, world!";
21
+ * });
22
+ */
23
+ export declare function deferrable<T, E = Error>(fn: (defer: (exec: (result: [value: T, error: undefined] | [value: undefined, error: E]) => void | Promise<void>) => void) => Promise<T>): Promise<T>;
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,UAAU,CAAC,CAAC,EAAE,CAAC,GAAG,KAAK,EAC3C,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,GACvI,OAAO,CAAC,CAAC,CAAC,CAeZ"}
package/dist/index.js ADDED
@@ -0,0 +1,59 @@
1
+ function ok(value) {
2
+ return [value, undefined];
3
+ }
4
+ ;
5
+ function failure(error) {
6
+ return [undefined, error];
7
+ }
8
+ ;
9
+ async function wrap(promise) {
10
+ try {
11
+ const value = await promise;
12
+ return ok(value);
13
+ }
14
+ catch (error) {
15
+ return failure(error);
16
+ }
17
+ }
18
+ /**
19
+ * Deferrable execution.
20
+ *
21
+ * This function is used to execute a function with a deferrable execution stack - LIFO.
22
+ *
23
+ * @param fn - The function to execute.
24
+ * @returns The result of the function.
25
+ *
26
+ * @example
27
+ *
28
+ * await deferrable(async (defer): Promise<string> => {
29
+ * defer(async ([result, err]) => {
30
+ * if (err) {
31
+ * console.error(err);
32
+ * } else {
33
+ * console.log(result);
34
+ * }
35
+ * });
36
+ *
37
+ * return "Hello, world!";
38
+ * });
39
+ */
40
+ export async function deferrable(fn) {
41
+ const stack = [];
42
+ const defer = (exec) => {
43
+ stack.push(exec);
44
+ };
45
+ const result = await wrap(fn(defer));
46
+ while (stack.length) {
47
+ const exec = stack.pop();
48
+ try {
49
+ await exec(result);
50
+ }
51
+ catch { }
52
+ }
53
+ const [value, error] = result;
54
+ if (error !== undefined)
55
+ throw error;
56
+ return value;
57
+ }
58
+ ;
59
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+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 @@
1
+ {
2
+ "name": "@u17g/deferrable",
3
+ "description": "A tiny defer utility for JavaScript/TypeScript: register cleanup/rollback callbacks that run in LIFO order. Works in any runtime (Node.js, Bun, Deno, browsers).",
4
+ "version": "1.0.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/u17g/deferrable.git"
8
+ },
9
+ "bugs": {
10
+ "url": "https://github.com/u17g/deferrable/issues"
11
+ },
12
+ "homepage": "https://github.com/u17g/deferrable#readme",
13
+ "types": "./dist/index.d.ts",
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.js",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "files": [
27
+ "dist",
28
+ "src"
29
+ ],
30
+ "scripts": {
31
+ "test": "bun test",
32
+ "build": "bun run scripts/build.ts",
33
+ "prepack": "bun run build",
34
+ "prepublishOnly": "bun test && bun run build"
35
+ },
36
+ "devDependencies": {
37
+ "@types/bun": "latest",
38
+ "typescript": "^5.0.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,59 @@
1
+ type Result<T, E = Error> = [value: T, error: undefined] | [value: undefined, error: E];
2
+
3
+ function ok<T>(value: T): Result<T, never> {
4
+ return [value, undefined];
5
+ };
6
+
7
+ function failure<E = Error>(error: E): Result<never, E> {
8
+ return [undefined, error];
9
+ };
10
+
11
+ async function wrap<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
12
+ try {
13
+ const value = await promise;
14
+ return ok(value);
15
+ } catch (error) {
16
+ return failure(error as E);
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Deferrable execution.
22
+ *
23
+ * This function is used to execute a function with a deferrable execution stack - LIFO.
24
+ *
25
+ * @param fn - The function to execute.
26
+ * @returns The result of the function.
27
+ *
28
+ * @example
29
+ *
30
+ * await deferrable(async (defer): Promise<string> => {
31
+ * defer(async ([result, err]) => {
32
+ * if (err) {
33
+ * console.error(err);
34
+ * } else {
35
+ * console.log(result);
36
+ * }
37
+ * });
38
+ *
39
+ * return "Hello, world!";
40
+ * });
41
+ */
42
+ export async function deferrable<T, E = Error>(
43
+ fn: (defer: (exec: (result: [value: T, error: undefined] | [value: undefined, error: E]) => void | Promise<void>) => void) => Promise<T>,
44
+ ): Promise<T> {
45
+ const stack: Parameters<Parameters<typeof fn>[0]>[0][] = [];
46
+ const defer: Parameters<typeof fn>[0] = (exec) => {
47
+ stack.push(exec);
48
+ };
49
+ const result = await wrap<T, E>(fn(defer));
50
+ while (stack.length) {
51
+ const exec = stack.pop()!;
52
+ try {
53
+ await exec(result);
54
+ } catch { }
55
+ }
56
+ const [value, error] = result;
57
+ if (error !== undefined) throw error;
58
+ return value as T;
59
+ };