@wentools/simmer 0.1.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.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +107 -0
  3. package/esm/debounce/debounce.d.ts +15 -0
  4. package/esm/debounce/debounce.d.ts.map +1 -0
  5. package/esm/debounce/debounce.js +61 -0
  6. package/esm/debounce/mod.d.ts +2 -0
  7. package/esm/debounce/mod.d.ts.map +1 -0
  8. package/esm/debounce/mod.js +1 -0
  9. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/err/err.d.ts +38 -0
  10. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/err/err.d.ts.map +1 -0
  11. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/err/err.js +38 -0
  12. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/err/mod.d.ts +2 -0
  13. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/err/mod.d.ts.map +1 -0
  14. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/err/mod.js +1 -0
  15. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/is_result/is_result.d.ts +11 -0
  16. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/is_result/is_result.d.ts.map +1 -0
  17. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/is_result/is_result.js +14 -0
  18. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/is_result/mod.d.ts +2 -0
  19. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/is_result/mod.d.ts.map +1 -0
  20. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/is_result/mod.js +1 -0
  21. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/mod.d.ts +156 -0
  22. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/mod.d.ts.map +1 -0
  23. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/mod.js +65 -0
  24. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/mod.d.ts +2 -0
  25. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/mod.d.ts.map +1 -0
  26. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/mod.js +1 -0
  27. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/propagate_err.d.ts +28 -0
  28. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/propagate_err.d.ts.map +1 -0
  29. package/esm/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/propagate_err.js +30 -0
  30. package/esm/eventual/eventual.d.ts +32 -0
  31. package/esm/eventual/eventual.d.ts.map +1 -0
  32. package/esm/eventual/eventual.js +47 -0
  33. package/esm/eventual/mod.d.ts +3 -0
  34. package/esm/eventual/mod.d.ts.map +1 -0
  35. package/esm/eventual/mod.js +1 -0
  36. package/esm/mod.d.ts +7 -0
  37. package/esm/mod.d.ts.map +1 -0
  38. package/esm/mod.js +4 -0
  39. package/esm/package.json +3 -0
  40. package/esm/retry/delay.d.ts +8 -0
  41. package/esm/retry/delay.d.ts.map +1 -0
  42. package/esm/retry/delay.js +28 -0
  43. package/esm/retry/mod.d.ts +5 -0
  44. package/esm/retry/mod.d.ts.map +1 -0
  45. package/esm/retry/mod.js +3 -0
  46. package/esm/retry/retry.d.ts +23 -0
  47. package/esm/retry/retry.d.ts.map +1 -0
  48. package/esm/retry/retry.js +128 -0
  49. package/esm/retry/types.d.ts +59 -0
  50. package/esm/retry/types.d.ts.map +1 -0
  51. package/esm/retry/types.js +8 -0
  52. package/esm/sleep/mod.d.ts +2 -0
  53. package/esm/sleep/mod.d.ts.map +1 -0
  54. package/esm/sleep/mod.js +1 -0
  55. package/esm/sleep/sleep.d.ts +6 -0
  56. package/esm/sleep/sleep.d.ts.map +1 -0
  57. package/esm/sleep/sleep.js +7 -0
  58. package/package.json +33 -0
  59. package/script/debounce/debounce.d.ts +15 -0
  60. package/script/debounce/debounce.d.ts.map +1 -0
  61. package/script/debounce/debounce.js +65 -0
  62. package/script/debounce/mod.d.ts +2 -0
  63. package/script/debounce/mod.d.ts.map +1 -0
  64. package/script/debounce/mod.js +6 -0
  65. package/script/deps/jsr.io/@wentools/result/0.1.3/src/err/err.d.ts +38 -0
  66. package/script/deps/jsr.io/@wentools/result/0.1.3/src/err/err.d.ts.map +1 -0
  67. package/script/deps/jsr.io/@wentools/result/0.1.3/src/err/err.js +41 -0
  68. package/script/deps/jsr.io/@wentools/result/0.1.3/src/err/mod.d.ts +2 -0
  69. package/script/deps/jsr.io/@wentools/result/0.1.3/src/err/mod.d.ts.map +1 -0
  70. package/script/deps/jsr.io/@wentools/result/0.1.3/src/err/mod.js +5 -0
  71. package/script/deps/jsr.io/@wentools/result/0.1.3/src/is_result/is_result.d.ts +11 -0
  72. package/script/deps/jsr.io/@wentools/result/0.1.3/src/is_result/is_result.d.ts.map +1 -0
  73. package/script/deps/jsr.io/@wentools/result/0.1.3/src/is_result/is_result.js +17 -0
  74. package/script/deps/jsr.io/@wentools/result/0.1.3/src/is_result/mod.d.ts +2 -0
  75. package/script/deps/jsr.io/@wentools/result/0.1.3/src/is_result/mod.d.ts.map +1 -0
  76. package/script/deps/jsr.io/@wentools/result/0.1.3/src/is_result/mod.js +5 -0
  77. package/script/deps/jsr.io/@wentools/result/0.1.3/src/mod.d.ts +156 -0
  78. package/script/deps/jsr.io/@wentools/result/0.1.3/src/mod.d.ts.map +1 -0
  79. package/script/deps/jsr.io/@wentools/result/0.1.3/src/mod.js +77 -0
  80. package/script/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/mod.d.ts +2 -0
  81. package/script/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/mod.d.ts.map +1 -0
  82. package/script/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/mod.js +5 -0
  83. package/script/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/propagate_err.d.ts +28 -0
  84. package/script/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/propagate_err.d.ts.map +1 -0
  85. package/script/deps/jsr.io/@wentools/result/0.1.3/src/propagate_err/propagate_err.js +33 -0
  86. package/script/eventual/eventual.d.ts +32 -0
  87. package/script/eventual/eventual.d.ts.map +1 -0
  88. package/script/eventual/eventual.js +53 -0
  89. package/script/eventual/mod.d.ts +3 -0
  90. package/script/eventual/mod.d.ts.map +1 -0
  91. package/script/eventual/mod.js +8 -0
  92. package/script/mod.d.ts +7 -0
  93. package/script/mod.d.ts.map +1 -0
  94. package/script/mod.js +20 -0
  95. package/script/package.json +3 -0
  96. package/script/retry/delay.d.ts +8 -0
  97. package/script/retry/delay.d.ts.map +1 -0
  98. package/script/retry/delay.js +32 -0
  99. package/script/retry/mod.d.ts +5 -0
  100. package/script/retry/mod.d.ts.map +1 -0
  101. package/script/retry/mod.js +12 -0
  102. package/script/retry/retry.d.ts +23 -0
  103. package/script/retry/retry.d.ts.map +1 -0
  104. package/script/retry/retry.js +134 -0
  105. package/script/retry/types.d.ts +59 -0
  106. package/script/retry/types.d.ts.map +1 -0
  107. package/script/retry/types.js +11 -0
  108. package/script/sleep/mod.d.ts +2 -0
  109. package/script/sleep/mod.d.ts.map +1 -0
  110. package/script/sleep/mod.js +5 -0
  111. package/script/sleep/sleep.d.ts +6 -0
  112. package/script/sleep/sleep.d.ts.map +1 -0
  113. package/script/sleep/sleep.js +10 -0
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Propagates an error Result to a different success type context.
3
+ *
4
+ * This is safe because error Results never contain the success value - only the error.
5
+ * TypeScript's structural typing prevents direct assignment of Result<T, E> to Result<U, E>
6
+ * even though the error type is identical and we're in the error branch.
7
+ *
8
+ * Common use case: Early return from a function that creates multiple items. If creating
9
+ * item 2 fails with Result<Item, DatabaseError>, we need to return Result<Item[], DatabaseError>.
10
+ *
11
+ * @example
12
+ * const result = await createUser(db, data) // Result<User, DatabaseError>
13
+ * if (result.isErr()) {
14
+ * // Need to return Result<Profile, DatabaseError> but have Result<User, DatabaseError>
15
+ * return propagateErr(result)
16
+ * }
17
+ *
18
+ * @example
19
+ * // In bulk creation, propagate single-item error to array context
20
+ * const itemResult = await createItem(data) // Result<Item, Error>
21
+ * if (itemResult.isErr()) {
22
+ * return propagateErr<Item[], Error>(itemResult) // Result<Item[], Error>
23
+ * }
24
+ */
25
+ const propagateErr = (errorResult) => {
26
+ // Type assertion is safe: we're only propagating errors, and error Results
27
+ // don't contain the success value. The error type E is preserved exactly.
28
+ return errorResult;
29
+ };
30
+ export { propagateErr };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * EventualResult - A utility for the "stale-while-revalidate" pattern
3
+ *
4
+ * Returns cached data immediately, optionally refreshes in background.
5
+ */
6
+ type EventualResult<TData> = {
7
+ readonly current: TData;
8
+ readonly fresh: Promise<TData> | null;
9
+ readonly isStale: boolean;
10
+ };
11
+ /**
12
+ * Create an EventualResult from current data and optional fresh promise
13
+ */
14
+ declare const eventual: <TData>(current: TData, fresh: Promise<TData> | null) => EventualResult<TData>;
15
+ /**
16
+ * Create an EventualResult, lazily creating the fresh promise only when stale
17
+ */
18
+ declare const eventualIf: <TData>(current: TData, isStale: boolean, getFresh: () => Promise<TData>) => EventualResult<TData>;
19
+ /**
20
+ * Transform both current and fresh values of an EventualResult
21
+ */
22
+ declare const mapEventual: <TInput, TOutput>(result: EventualResult<TInput>, fn: (value: TInput) => TOutput) => EventualResult<TOutput>;
23
+ /**
24
+ * Combine multiple EventualResults into a single EventualResult
25
+ *
26
+ * The combined result is stale if any input is stale.
27
+ * The fresh promise resolves when all stale inputs have refreshed.
28
+ */
29
+ declare const combineEventual: <TResults extends Record<string, EventualResult<unknown>>>(results: TResults) => EventualResult<{ [K in keyof TResults]: TResults[K]["current"]; }>;
30
+ export { eventual, eventualIf, mapEventual, combineEventual };
31
+ export type { EventualResult };
32
+ //# sourceMappingURL=eventual.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventual.d.ts","sourceRoot":"","sources":["../../src/eventual/eventual.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,KAAK,cAAc,CAAC,KAAK,IAAI;IAC5B,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAA;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;CACzB,CAAA;AAED;;GAEG;AACH,QAAA,MAAM,QAAQ,GAAI,KAAK,EAAE,SAAS,KAAK,EAAE,OAAO,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,KAAG,cAAc,CAAC,KAAK,CAI1F,CAAA;AAEF;;GAEG;AACH,QAAA,MAAM,UAAU,GAAI,KAAK,EACxB,SAAS,KAAK,EACd,SAAS,OAAO,EAChB,UAAU,MAAM,OAAO,CAAC,KAAK,CAAC,KAC5B,cAAc,CAAC,KAAK,CAIrB,CAAA;AAEF;;GAEG;AACH,QAAA,MAAM,WAAW,GAAI,MAAM,EAAE,OAAO,EACnC,QAAQ,cAAc,CAAC,MAAM,CAAC,EAC9B,IAAI,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,KAC5B,cAAc,CAAC,OAAO,CAIvB,CAAA;AAEF;;;;;GAKG;AACH,QAAA,MAAM,eAAe,GAAI,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,EAChF,SAAS,QAAQ,KACf,cAAc,CAAC,GAAG,CAAC,IAAI,MAAM,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAE,CAqBlE,CAAA;AAED,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,CAAA;AAC7D,YAAY,EAAE,cAAc,EAAE,CAAA"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * EventualResult - A utility for the "stale-while-revalidate" pattern
3
+ *
4
+ * Returns cached data immediately, optionally refreshes in background.
5
+ */
6
+ /**
7
+ * Create an EventualResult from current data and optional fresh promise
8
+ */
9
+ const eventual = (current, fresh) => ({
10
+ current,
11
+ fresh,
12
+ isStale: fresh !== null,
13
+ });
14
+ /**
15
+ * Create an EventualResult, lazily creating the fresh promise only when stale
16
+ */
17
+ const eventualIf = (current, isStale, getFresh) => ({
18
+ current,
19
+ fresh: isStale ? getFresh() : null,
20
+ isStale,
21
+ });
22
+ /**
23
+ * Transform both current and fresh values of an EventualResult
24
+ */
25
+ const mapEventual = (result, fn) => ({
26
+ current: fn(result.current),
27
+ fresh: result.fresh?.then(fn) ?? null,
28
+ isStale: result.isStale,
29
+ });
30
+ /**
31
+ * Combine multiple EventualResults into a single EventualResult
32
+ *
33
+ * The combined result is stale if any input is stale.
34
+ * The fresh promise resolves when all stale inputs have refreshed.
35
+ */
36
+ const combineEventual = (results) => {
37
+ const current = Object.fromEntries(Object.entries(results).map(([k, v]) => [k, v.current]));
38
+ const freshEntries = Object.entries(results).filter((entry) => entry[1].fresh !== null);
39
+ const fresh = freshEntries.length > 0
40
+ ? Promise.all(freshEntries.map(([k, v]) => v.fresh.then((val) => [k, val]))).then((entries) => ({
41
+ ...current,
42
+ ...Object.fromEntries(entries),
43
+ }))
44
+ : null;
45
+ return { current, fresh, isStale: fresh !== null };
46
+ };
47
+ export { eventual, eventualIf, mapEventual, combineEventual };
@@ -0,0 +1,3 @@
1
+ export { eventual, eventualIf, mapEventual, combineEventual } from './eventual.js';
2
+ export type { EventualResult } from './eventual.js';
3
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/eventual/mod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAClF,YAAY,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA"}
@@ -0,0 +1 @@
1
+ export { eventual, eventualIf, mapEventual, combineEventual } from './eventual.js';
package/esm/mod.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { sleep } from './sleep/mod.js';
2
+ export { debounce, debounceAsync } from './debounce/mod.js';
3
+ export { withRetry, retryPromise, makeRetryable, withRetryMetadata, calculateDelay, defaultRetryOptions, } from './retry/mod.js';
4
+ export type { RetryOptions, RetryError, ExecutionAttempt, ExecutionMetadata, } from './retry/mod.js';
5
+ export { eventual, eventualIf, mapEventual, combineEventual } from './eventual/mod.js';
6
+ export type { EventualResult } from './eventual/mod.js';
7
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../src/mod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAA;AACtC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAC3D,OAAO,EACN,SAAS,EACT,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,mBAAmB,GACnB,MAAM,gBAAgB,CAAA;AACvB,YAAY,EACX,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,iBAAiB,GACjB,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACtF,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA"}
package/esm/mod.js ADDED
@@ -0,0 +1,4 @@
1
+ export { sleep } from './sleep/mod.js';
2
+ export { debounce, debounceAsync } from './debounce/mod.js';
3
+ export { withRetry, retryPromise, makeRetryable, withRetryMetadata, calculateDelay, defaultRetryOptions, } from './retry/mod.js';
4
+ export { eventual, eventualIf, mapEventual, combineEventual } from './eventual/mod.js';
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,8 @@
1
+ import type { RetryOptions } from './types.js';
2
+ import { sleep } from '../sleep/mod.js';
3
+ /**
4
+ * Calculate delay for next retry attempt based on strategy
5
+ */
6
+ declare const calculateDelay: (attempt: number, options: Pick<RetryOptions, "backoffStrategy" | "initialDelayMs" | "maxDelayMs" | "jitter">) => number;
7
+ export { calculateDelay, sleep };
8
+ //# sourceMappingURL=delay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delay.d.ts","sourceRoot":"","sources":["../../src/retry/delay.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAA;AAEvC;;GAEG;AACH,QAAA,MAAM,cAAc,GACnB,SAAS,MAAM,EACf,SAAS,IAAI,CAAC,YAAY,EAAE,iBAAiB,GAAG,gBAAgB,GAAG,YAAY,GAAG,QAAQ,CAAC,KACzF,MA4BF,CAAA;AAED,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,CAAA"}
@@ -0,0 +1,28 @@
1
+ import { sleep } from '../sleep/mod.js';
2
+ /**
3
+ * Calculate delay for next retry attempt based on strategy
4
+ */
5
+ const calculateDelay = (attempt, options) => {
6
+ let delay;
7
+ switch (options.backoffStrategy) {
8
+ case 'exponential':
9
+ delay = options.initialDelayMs * Math.pow(2, attempt);
10
+ break;
11
+ case 'linear':
12
+ delay = options.initialDelayMs * (attempt + 1);
13
+ break;
14
+ case 'constant':
15
+ default:
16
+ delay = options.initialDelayMs;
17
+ break;
18
+ }
19
+ // Cap at maxDelay
20
+ delay = Math.min(delay, options.maxDelayMs);
21
+ // Add jitter to prevent thundering herd
22
+ if (options.jitter) {
23
+ const jitterFactor = 0.8 + Math.random() * 0.4;
24
+ delay = Math.floor(delay * jitterFactor);
25
+ }
26
+ return delay;
27
+ };
28
+ export { calculateDelay, sleep };
@@ -0,0 +1,5 @@
1
+ export { withRetry, retryPromise, makeRetryable, withRetryMetadata } from './retry.js';
2
+ export { calculateDelay } from './delay.js';
3
+ export { defaultRetryOptions } from './types.js';
4
+ export type { RetryOptions, RetryError, ExecutionAttempt, ExecutionMetadata } from './types.js';
5
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/retry/mod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AACtF,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAChD,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA"}
@@ -0,0 +1,3 @@
1
+ export { withRetry, retryPromise, makeRetryable, withRetryMetadata } from './retry.js';
2
+ export { calculateDelay } from './delay.js';
3
+ export { defaultRetryOptions } from './types.js';
@@ -0,0 +1,23 @@
1
+ import { type Result } from '../deps/jsr.io/@wentools/result/0.1.3/src/mod.js';
2
+ import type { RetryOptions, RetryError, ExecutionMetadata } from './types.js';
3
+ /**
4
+ * Retry a function that returns a Result until it succeeds or max attempts reached
5
+ */
6
+ declare const withRetry: <TSuccess, TError>(fn: () => Promise<Result<TSuccess, TError>>, options?: Partial<RetryOptions>) => Promise<Result<TSuccess, RetryError<TError>>>;
7
+ /**
8
+ * Retry a function that returns a Promise (not Result) until it succeeds
9
+ */
10
+ declare const retryPromise: <TSuccess>(fn: () => Promise<TSuccess>, options?: Partial<RetryOptions>) => Promise<Result<TSuccess, RetryError<unknown>>>;
11
+ /**
12
+ * Create a retryable version of a function
13
+ */
14
+ declare const makeRetryable: <TArgs extends unknown[], TSuccess, TError>(fn: (...args: TArgs) => Promise<Result<TSuccess, TError>>, defaultOptions?: Partial<RetryOptions>) => (...args: TArgs) => ((options?: Partial<RetryOptions>) => Promise<Result<TSuccess, RetryError<TError>>>);
15
+ /**
16
+ * Execute a Result-returning function with retry logic and full execution tracking
17
+ *
18
+ * Like withRetry, but returns detailed metadata about all attempts including
19
+ * timing, results, and delays. Useful for observability, monitoring, and audit trails.
20
+ */
21
+ declare const withRetryMetadata: <TSuccess, TError>(fn: () => Promise<Result<TSuccess, TError>>, options?: Partial<RetryOptions>) => Promise<ExecutionMetadata<TSuccess, TError>>;
22
+ export { withRetry, retryPromise, makeRetryable, withRetryMetadata };
23
+ //# sourceMappingURL=retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/retry/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAW,MAAM,kDAAkD,CAAA;AACvF,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAoB,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAI/F;;GAEG;AACH,QAAA,MAAM,SAAS,GAAU,QAAQ,EAAE,MAAM,EACxC,IAAI,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,EAC3C,UAAS,OAAO,CAAC,YAAY,CAAM,KACjC,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC,CA+C9C,CAAA;AAED;;GAEG;AACH,QAAA,MAAM,YAAY,GAAU,QAAQ,EACnC,IAAI,MAAM,OAAO,CAAC,QAAQ,CAAC,EAC3B,UAAS,OAAO,CAAC,YAAY,CAAM,KACjC,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,OAAO,CAAC,CAAC,CAW/C,CAAA;AAED;;GAEG;AACH,QAAA,MAAM,aAAa,GAAI,KAAK,SAAS,OAAO,EAAE,EAAE,QAAQ,EAAE,MAAM,EAC/D,IAAI,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,EACzD,iBAAgB,OAAO,CAAC,YAAY,CAAM,MAGzC,GAAG,MAAM,KAAK,KACZ,CAAC,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAItF,CAAA;AAED;;;;;GAKG;AACH,QAAA,MAAM,iBAAiB,GAAU,QAAQ,EAAE,MAAM,EAChD,IAAI,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,EAC3C,UAAS,OAAO,CAAC,YAAY,CAAM,KACjC,OAAO,CAAC,iBAAiB,CAAC,QAAQ,EAAE,MAAM,CAAC,CAoE7C,CAAA;AAED,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,iBAAiB,EAAE,CAAA"}
@@ -0,0 +1,128 @@
1
+ import { err, ok } from '../deps/jsr.io/@wentools/result/0.1.3/src/mod.js';
2
+ import { defaultRetryOptions } from './types.js';
3
+ import { calculateDelay, sleep } from './delay.js';
4
+ /**
5
+ * Retry a function that returns a Result until it succeeds or max attempts reached
6
+ */
7
+ const withRetry = async (fn, options = {}) => {
8
+ const opts = {
9
+ ...defaultRetryOptions,
10
+ ...options,
11
+ };
12
+ const errors = [];
13
+ let lastError;
14
+ for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {
15
+ const result = await fn();
16
+ if (result.isOk()) {
17
+ return ok(result.value);
18
+ }
19
+ lastError = result.error;
20
+ errors.push(result.error);
21
+ if (opts.shouldRetry && !opts.shouldRetry(result.error, attempt)) {
22
+ return err('RETRY_EXHAUSTED', `Retry aborted after ${attempt + 1} attempts - error not retryable`, {
23
+ attempts: attempt + 1,
24
+ lastError,
25
+ errors,
26
+ });
27
+ }
28
+ if (attempt < opts.maxAttempts - 1) {
29
+ const delayMs = calculateDelay(attempt, opts);
30
+ if (opts.onRetry) {
31
+ opts.onRetry(attempt + 1, result.error, delayMs);
32
+ }
33
+ await sleep(delayMs);
34
+ }
35
+ }
36
+ return err('RETRY_EXHAUSTED', `All ${opts.maxAttempts} retry attempts failed`, {
37
+ attempts: opts.maxAttempts,
38
+ lastError: lastError,
39
+ errors,
40
+ });
41
+ };
42
+ /**
43
+ * Retry a function that returns a Promise (not Result) until it succeeds
44
+ */
45
+ const retryPromise = async (fn, options = {}) => {
46
+ const resultFn = async () => {
47
+ try {
48
+ const value = await fn();
49
+ return ok(value);
50
+ }
51
+ catch (error) {
52
+ return err('PROMISE_ERROR', 'Promise rejected', { cause: error });
53
+ }
54
+ };
55
+ return withRetry(resultFn, options);
56
+ };
57
+ /**
58
+ * Create a retryable version of a function
59
+ */
60
+ const makeRetryable = (fn, defaultOptions = {}) => {
61
+ return (...args) => {
62
+ return (options) => withRetry(() => fn(...args), { ...defaultOptions, ...options });
63
+ };
64
+ };
65
+ /**
66
+ * Execute a Result-returning function with retry logic and full execution tracking
67
+ *
68
+ * Like withRetry, but returns detailed metadata about all attempts including
69
+ * timing, results, and delays. Useful for observability, monitoring, and audit trails.
70
+ */
71
+ const withRetryMetadata = async (fn, options = {}) => {
72
+ const opts = {
73
+ ...defaultRetryOptions,
74
+ ...options,
75
+ };
76
+ if (opts.maxAttempts < 1) {
77
+ opts.maxAttempts = 1;
78
+ }
79
+ const attempts = [];
80
+ const overallStartTime = Date.now();
81
+ let previousDelayMs = 0;
82
+ for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {
83
+ const attemptStartTime = Date.now();
84
+ const attemptTimestamp = new Date(attemptStartTime);
85
+ const result = await fn();
86
+ const attemptDuration = Date.now() - attemptStartTime;
87
+ attempts.push({
88
+ attemptNumber: attempt + 1,
89
+ duration: attemptDuration,
90
+ result,
91
+ timestamp: attemptTimestamp,
92
+ delayBeforeMs: previousDelayMs,
93
+ });
94
+ if (result.isOk()) {
95
+ const totalDuration = Date.now() - overallStartTime;
96
+ return {
97
+ result,
98
+ totalAttempts: attempt + 1,
99
+ totalDuration,
100
+ attempts,
101
+ succeeded: true,
102
+ retriesNeeded: attempt,
103
+ };
104
+ }
105
+ if (opts.shouldRetry && !opts.shouldRetry(result.error, attempt)) {
106
+ break;
107
+ }
108
+ if (attempt < opts.maxAttempts - 1) {
109
+ const delayMs = calculateDelay(attempt, opts);
110
+ previousDelayMs = delayMs;
111
+ if (opts.onRetry) {
112
+ opts.onRetry(attempt + 1, result.error, delayMs);
113
+ }
114
+ await sleep(delayMs);
115
+ }
116
+ }
117
+ const lastAttempt = attempts[attempts.length - 1];
118
+ const totalDuration = Date.now() - overallStartTime;
119
+ return {
120
+ result: lastAttempt.result,
121
+ totalAttempts: attempts.length,
122
+ totalDuration,
123
+ attempts,
124
+ succeeded: false,
125
+ retriesNeeded: attempts.length - 1,
126
+ };
127
+ };
128
+ export { withRetry, retryPromise, makeRetryable, withRetryMetadata };
@@ -0,0 +1,59 @@
1
+ import type { Result } from '../deps/jsr.io/@wentools/result/0.1.3/src/mod.js';
2
+ interface RetryOptions {
3
+ maxAttempts: number;
4
+ initialDelayMs: number;
5
+ maxDelayMs: number;
6
+ backoffStrategy: 'exponential' | 'linear' | 'constant';
7
+ jitter?: boolean;
8
+ shouldRetry?: <TError>(error: TError, attempt: number) => boolean;
9
+ onRetry?: <TError>(attempt: number, error: TError, nextDelayMs: number) => void;
10
+ }
11
+ interface RetryError<TOriginalError> {
12
+ type: 'RETRY_EXHAUSTED';
13
+ message: string;
14
+ attempts: number;
15
+ lastError: TOriginalError;
16
+ errors: TOriginalError[];
17
+ }
18
+ /**
19
+ * Single execution attempt of a retryable operation
20
+ *
21
+ * Represents one attempt to execute the operation, whether it's the
22
+ * first attempt or a retry. Includes timing and result information.
23
+ */
24
+ interface ExecutionAttempt<TSuccess, TError> {
25
+ /** Attempt number (1 = first attempt, 2 = first retry, etc.) */
26
+ attemptNumber: number;
27
+ /** Duration of this specific attempt in milliseconds */
28
+ duration: number;
29
+ /** Result of this attempt (Ok or Err) */
30
+ result: Result<TSuccess, TError>;
31
+ /** Timestamp when this attempt started */
32
+ timestamp: Date;
33
+ /** Delay before this attempt (0 for first attempt) */
34
+ delayBeforeMs: number;
35
+ }
36
+ /**
37
+ * Complete execution metadata for a retry operation
38
+ *
39
+ * Contains the final result plus full execution history of all attempts.
40
+ * Provides rich context for monitoring, debugging, and audit trails.
41
+ */
42
+ interface ExecutionMetadata<TSuccess, TError> {
43
+ /** The final result of the operation (after all attempts) */
44
+ result: Result<TSuccess, TError>;
45
+ /** Total number of attempts made (1 = no retries, 2 = 1 retry, etc.) */
46
+ totalAttempts: number;
47
+ /** Total wall-clock duration including all delays in milliseconds */
48
+ totalDuration: number;
49
+ /** Complete history of all execution attempts */
50
+ attempts: ExecutionAttempt<TSuccess, TError>[];
51
+ /** Convenience: whether the operation ultimately succeeded */
52
+ succeeded: boolean;
53
+ /** Convenience: number of retries needed (totalAttempts - 1) */
54
+ retriesNeeded: number;
55
+ }
56
+ declare const defaultRetryOptions: Partial<RetryOptions>;
57
+ export type { RetryOptions, RetryError, ExecutionAttempt, ExecutionMetadata };
58
+ export { defaultRetryOptions };
59
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/retry/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kDAAkD,CAAA;AAE9E,UAAU,YAAY;IACrB,WAAW,EAAE,MAAM,CAAA;IACnB,cAAc,EAAE,MAAM,CAAA;IACtB,UAAU,EAAE,MAAM,CAAA;IAClB,eAAe,EAAE,aAAa,GAAG,QAAQ,GAAG,UAAU,CAAA;IACtD,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAA;IACjE,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/E;AAED,UAAU,UAAU,CAAC,cAAc;IAClC,IAAI,EAAE,iBAAiB,CAAA;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,cAAc,CAAA;IACzB,MAAM,EAAE,cAAc,EAAE,CAAA;CACxB;AAED;;;;;GAKG;AACH,UAAU,gBAAgB,CAAC,QAAQ,EAAE,MAAM;IAC1C,gEAAgE;IAChE,aAAa,EAAE,MAAM,CAAA;IAErB,wDAAwD;IACxD,QAAQ,EAAE,MAAM,CAAA;IAEhB,yCAAyC;IACzC,MAAM,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;IAEhC,0CAA0C;IAC1C,SAAS,EAAE,IAAI,CAAA;IAEf,sDAAsD;IACtD,aAAa,EAAE,MAAM,CAAA;CACrB;AAED;;;;;GAKG;AACH,UAAU,iBAAiB,CAAC,QAAQ,EAAE,MAAM;IAC3C,6DAA6D;IAC7D,MAAM,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;IAEhC,wEAAwE;IACxE,aAAa,EAAE,MAAM,CAAA;IAErB,qEAAqE;IACrE,aAAa,EAAE,MAAM,CAAA;IAErB,iDAAiD;IACjD,QAAQ,EAAE,gBAAgB,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAA;IAE9C,8DAA8D;IAC9D,SAAS,EAAE,OAAO,CAAA;IAElB,gEAAgE;IAChE,aAAa,EAAE,MAAM,CAAA;CACrB;AAED,QAAA,MAAM,mBAAmB,EAAE,OAAO,CAAC,YAAY,CAM9C,CAAA;AAED,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,CAAA;AAC7E,OAAO,EAAE,mBAAmB,EAAE,CAAA"}
@@ -0,0 +1,8 @@
1
+ const defaultRetryOptions = {
2
+ maxAttempts: 3,
3
+ initialDelayMs: 1000,
4
+ maxDelayMs: 30000,
5
+ backoffStrategy: 'exponential',
6
+ jitter: true,
7
+ };
8
+ export { defaultRetryOptions };
@@ -0,0 +1,2 @@
1
+ export { sleep } from './sleep.js';
2
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/sleep/mod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA"}
@@ -0,0 +1 @@
1
+ export { sleep } from './sleep.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Sleep for specified milliseconds
3
+ */
4
+ declare const sleep: (ms: number) => Promise<void>;
5
+ export { sleep };
6
+ //# sourceMappingURL=sleep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sleep.d.ts","sourceRoot":"","sources":["../../src/sleep/sleep.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,QAAA,MAAM,KAAK,GAAI,IAAI,MAAM,KAAG,OAAO,CAAC,IAAI,CAEvC,CAAA;AAED,OAAO,EAAE,KAAK,EAAE,CAAA"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Sleep for specified milliseconds
3
+ */
4
+ const sleep = (ms) => {
5
+ return new Promise((resolve) => setTimeout(resolve, ms));
6
+ };
7
+ export { sleep };
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@wentools/simmer",
3
+ "version": "0.1.0",
4
+ "description": "Async control flow primitives: debounce, retry, eventual, sleep",
5
+ "keywords": [
6
+ "debounce",
7
+ "retry",
8
+ "sleep",
9
+ "eventual",
10
+ "async",
11
+ "control-flow",
12
+ "typescript"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://gitlab.com/wentools/simmer"
17
+ },
18
+ "license": "MIT",
19
+ "main": "./script/mod.js",
20
+ "module": "./esm/mod.js",
21
+ "exports": {
22
+ ".": {
23
+ "import": "./esm/mod.js",
24
+ "require": "./script/mod.js"
25
+ }
26
+ },
27
+ "scripts": {},
28
+ "dependencies": {
29
+ "neverthrow": "^8.2.0"
30
+ },
31
+ "peerDependencies": {},
32
+ "_generatedBy": "dnt@dev"
33
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Creates a debounced version of a synchronous function, which delays invoking
3
+ * the function until after `wait` milliseconds have elapsed since the last invocation.
4
+ */
5
+ declare const debounce: <TDebounceCallback extends (...args: any[]) => void>(func: TDebounceCallback, wait: number) => ((...args: Parameters<TDebounceCallback>) => void);
6
+ /**
7
+ * Creates a debounced version of an asynchronous function, which delays invoking
8
+ * the function until after `waitTime` milliseconds have elapsed since the last time
9
+ * the debounced function was invoked. The debounced function returns a promise
10
+ * that resolves with the return value of the original function, but only for the
11
+ * latest invocation.
12
+ */
13
+ declare const debounceAsync: <TAsyncFunction extends (...args: any[]) => Promise<any>>(asyncFunction: TAsyncFunction, waitTime: number) => ((...args: Parameters<TAsyncFunction>) => Promise<Awaited<ReturnType<TAsyncFunction>>>);
14
+ export { debounce, debounceAsync };
15
+ //# sourceMappingURL=debounce.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debounce.d.ts","sourceRoot":"","sources":["../../src/debounce/debounce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,QAAA,MAAM,QAAQ,GAAI,iBAAiB,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,EACnE,MAAM,iBAAiB,EACvB,MAAM,MAAM,KACV,CAAC,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAYnD,CAAA;AAED;;;;;;GAMG;AAEH,QAAA,MAAM,aAAa,GAAI,cAAc,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EAC7E,eAAe,cAAc,EAC7B,UAAU,MAAM,KACd,CAAC,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,cAAc,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC,CA2CxF,CAAA;AAED,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAA"}
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.debounceAsync = exports.debounce = void 0;
4
+ /**
5
+ * Creates a debounced version of a synchronous function, which delays invoking
6
+ * the function until after `wait` milliseconds have elapsed since the last invocation.
7
+ */
8
+ // deno-lint-ignore no-explicit-any
9
+ const debounce = (func, wait) => {
10
+ let timeoutId = null;
11
+ return (...args) => {
12
+ if (timeoutId !== null) {
13
+ clearTimeout(timeoutId);
14
+ }
15
+ timeoutId = setTimeout(() => {
16
+ func(...args);
17
+ }, wait);
18
+ };
19
+ };
20
+ exports.debounce = debounce;
21
+ /**
22
+ * Creates a debounced version of an asynchronous function, which delays invoking
23
+ * the function until after `waitTime` milliseconds have elapsed since the last time
24
+ * the debounced function was invoked. The debounced function returns a promise
25
+ * that resolves with the return value of the original function, but only for the
26
+ * latest invocation.
27
+ */
28
+ // deno-lint-ignore no-explicit-any
29
+ const debounceAsync = (asyncFunction, waitTime) => {
30
+ let timeoutId = null;
31
+ let latestCallId = 0;
32
+ let pendingPromises = [];
33
+ return (...args) => {
34
+ const callId = ++latestCallId;
35
+ if (timeoutId !== null) {
36
+ clearTimeout(timeoutId);
37
+ }
38
+ // Cancel all pending promises from previous calls
39
+ const promisesToCancel = [...pendingPromises];
40
+ pendingPromises = [];
41
+ promisesToCancel.forEach(({ reject }) => {
42
+ reject(new Error('Debounced call was cancelled'));
43
+ });
44
+ return new Promise((resolve, reject) => {
45
+ pendingPromises.push({ callId, resolve, reject });
46
+ timeoutId = setTimeout(async () => {
47
+ const promiseIndex = pendingPromises.findIndex((p) => p.callId === callId);
48
+ if (promiseIndex === -1) {
49
+ return;
50
+ }
51
+ const currentPromise = pendingPromises.splice(promiseIndex, 1)[0];
52
+ if (!currentPromise)
53
+ return;
54
+ try {
55
+ const result = await asyncFunction(...args);
56
+ currentPromise.resolve(result);
57
+ }
58
+ catch (error) {
59
+ currentPromise.reject(error);
60
+ }
61
+ }, waitTime);
62
+ });
63
+ };
64
+ };
65
+ exports.debounceAsync = debounceAsync;
@@ -0,0 +1,2 @@
1
+ export { debounce, debounceAsync } from './debounce.js';
2
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/debounce/mod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA"}
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.debounceAsync = exports.debounce = void 0;
4
+ var debounce_js_1 = require("./debounce.js");
5
+ Object.defineProperty(exports, "debounce", { enumerable: true, get: function () { return debounce_js_1.debounce; } });
6
+ Object.defineProperty(exports, "debounceAsync", { enumerable: true, get: function () { return debounce_js_1.debounceAsync; } });