@rwaterman/utils 1.1.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.md +21 -0
- package/README.md +35 -0
- package/lib/helpers/abortable.d.ts +1 -0
- package/lib/helpers/abortable.js +13 -0
- package/lib/helpers/debounce.d.ts +6 -0
- package/lib/helpers/debounce.js +24 -0
- package/lib/helpers/delay.d.ts +1 -0
- package/lib/helpers/delay.js +5 -0
- package/lib/helpers/index.d.ts +11 -0
- package/lib/helpers/index.js +11 -0
- package/lib/helpers/memoize.d.ts +5 -0
- package/lib/helpers/memoize.js +23 -0
- package/lib/helpers/once.d.ts +1 -0
- package/lib/helpers/once.js +7 -0
- package/lib/helpers/poll.d.ts +7 -0
- package/lib/helpers/poll.js +13 -0
- package/lib/helpers/requireEnv.d.ts +1 -0
- package/lib/helpers/requireEnv.js +6 -0
- package/lib/helpers/retry.d.ts +12 -0
- package/lib/helpers/retry.js +17 -0
- package/lib/helpers/throttle.d.ts +6 -0
- package/lib/helpers/throttle.js +36 -0
- package/lib/helpers/timeout.d.ts +4 -0
- package/lib/helpers/timeout.js +18 -0
- package/lib/helpers/to.d.ts +10 -0
- package/lib/helpers/to.js +16 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/package.json +52 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Rick Waterman
|
|
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,35 @@
|
|
|
1
|
+
# @rwaterman/utils
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@rwaterman/utils) [](https://github.com/rwaterman/utils-ts/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
Typed, small, dependency-free, lightweight async helper/utility functions we use all the time.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @rwaterman/utils
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Functions
|
|
12
|
+
|
|
13
|
+
- `to(promise)` — resolves to `{ res, err }` instead of throwing
|
|
14
|
+
- `toSync(fn)` — sync sibling of `to`: `{ res, err }` from a throwing function (`JSON.parse`, `new URL()`, ...)
|
|
15
|
+
- `delay(ms)` — promise that resolves after `ms`
|
|
16
|
+
- `timeout(promise, ms)` — rejects with `TimeoutError` if the promise takes longer than `ms`
|
|
17
|
+
- `retry({ yourAsyncFn, numTimes, delayMs, factor, maxDelayMs, shouldRetry })` — retries with optional exponential backoff, returns `{ res, errors }`
|
|
18
|
+
- `poll({ fn, until, everyMs, timeoutMs })` — calls `fn` every `everyMs` until `until(res)` is true; rejects with `TimeoutError` after `timeoutMs`
|
|
19
|
+
- `abortable(promise, signal)` — rejects with `signal.reason` on abort; composes with `AbortSignal.timeout()` / `AbortSignal.any()`
|
|
20
|
+
- `debounce(fn, ms)` — trailing-edge debounce with `.cancel()` and `.flush()`
|
|
21
|
+
- `throttle(fn, ms)` — leading edge plus one trailing call per window, with `.cancel()` and `.flush()`
|
|
22
|
+
- `once(fn)` — calls `fn` at most once and returns the cached result (a throw is not cached)
|
|
23
|
+
- `memoize(fn, { ttlMs, key })` — caches by arguments; async-aware (shares in-flight promises, never caches rejections)
|
|
24
|
+
- `requireEnv(name)` — returns `process.env[name]` or throws naming the missing variable
|
|
25
|
+
|
|
26
|
+
## Development
|
|
27
|
+
|
|
28
|
+
Node 24+, TypeScript 7 (native compiler), Vitest, oxlint.
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm ci
|
|
32
|
+
npm test
|
|
33
|
+
npm run lint
|
|
34
|
+
npm run build
|
|
35
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export async function abortable(promise, signal) {
|
|
2
|
+
if (signal.aborted)
|
|
3
|
+
throw signal.reason;
|
|
4
|
+
const { promise: aborted, reject } = Promise.withResolvers();
|
|
5
|
+
const onAbort = () => reject(signal.reason);
|
|
6
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
7
|
+
try {
|
|
8
|
+
return await Promise.race([promise, aborted]);
|
|
9
|
+
}
|
|
10
|
+
finally {
|
|
11
|
+
signal.removeEventListener('abort', onAbort);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function debounce(fn, ms) {
|
|
2
|
+
let timer;
|
|
3
|
+
let pending;
|
|
4
|
+
function flush() {
|
|
5
|
+
clearTimeout(timer);
|
|
6
|
+
timer = undefined;
|
|
7
|
+
if (!pending)
|
|
8
|
+
return;
|
|
9
|
+
const args = pending;
|
|
10
|
+
pending = undefined;
|
|
11
|
+
fn(...args);
|
|
12
|
+
}
|
|
13
|
+
function cancel() {
|
|
14
|
+
clearTimeout(timer);
|
|
15
|
+
timer = undefined;
|
|
16
|
+
pending = undefined;
|
|
17
|
+
}
|
|
18
|
+
const debounced = (...args) => {
|
|
19
|
+
pending = args;
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
timer = setTimeout(flush, ms);
|
|
22
|
+
};
|
|
23
|
+
return Object.assign(debounced, { cancel, flush });
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function delay(ms: number): Promise<void>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from './abortable.ts';
|
|
2
|
+
export * from './debounce.ts';
|
|
3
|
+
export * from './delay.ts';
|
|
4
|
+
export * from './memoize.ts';
|
|
5
|
+
export * from './once.ts';
|
|
6
|
+
export * from './poll.ts';
|
|
7
|
+
export * from './requireEnv.ts';
|
|
8
|
+
export * from './retry.ts';
|
|
9
|
+
export * from './throttle.ts';
|
|
10
|
+
export * from './timeout.ts';
|
|
11
|
+
export * from './to.ts';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from './abortable.js';
|
|
2
|
+
export * from './debounce.js';
|
|
3
|
+
export * from './delay.js';
|
|
4
|
+
export * from './memoize.js';
|
|
5
|
+
export * from './once.js';
|
|
6
|
+
export * from './poll.js';
|
|
7
|
+
export * from './requireEnv.js';
|
|
8
|
+
export * from './retry.js';
|
|
9
|
+
export * from './throttle.js';
|
|
10
|
+
export * from './timeout.js';
|
|
11
|
+
export * from './to.js';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function memoize(fn, options = {}) {
|
|
2
|
+
const cache = new Map();
|
|
3
|
+
const keyOf = options.key ?? ((...args) => JSON.stringify(args));
|
|
4
|
+
return (...args) => {
|
|
5
|
+
const key = keyOf(...args);
|
|
6
|
+
const hit = cache.get(key);
|
|
7
|
+
if (hit && hit.expiresAt > Date.now())
|
|
8
|
+
return hit.value;
|
|
9
|
+
const value = fn(...args);
|
|
10
|
+
cache.set(key, { value, expiresAt: options.ttlMs === undefined ? Infinity : Date.now() + options.ttlMs });
|
|
11
|
+
if (value instanceof Promise) {
|
|
12
|
+
void (async () => {
|
|
13
|
+
try {
|
|
14
|
+
await value;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
cache.delete(key);
|
|
18
|
+
}
|
|
19
|
+
})();
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function once<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { delay } from './delay.js';
|
|
2
|
+
import { TimeoutError } from './timeout.js';
|
|
3
|
+
export async function poll(params) {
|
|
4
|
+
const deadline = Date.now() + params.timeoutMs;
|
|
5
|
+
for (;;) {
|
|
6
|
+
const res = await params.fn();
|
|
7
|
+
if (params.until(res))
|
|
8
|
+
return res;
|
|
9
|
+
if (Date.now() >= deadline)
|
|
10
|
+
throw new TimeoutError(params.timeoutMs);
|
|
11
|
+
await delay(params.everyMs);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function requireEnv(name: string): string;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface RetryParams<T = unknown> {
|
|
2
|
+
numTimes?: number;
|
|
3
|
+
delayMs?: number;
|
|
4
|
+
factor?: number;
|
|
5
|
+
maxDelayMs?: number;
|
|
6
|
+
shouldRetry?: (err: unknown) => boolean;
|
|
7
|
+
yourAsyncFn: () => Promise<T>;
|
|
8
|
+
}
|
|
9
|
+
export declare function retry<T>(params: RetryParams<T>): Promise<{
|
|
10
|
+
res: T | null;
|
|
11
|
+
errors: unknown[];
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { delay } from './delay.js';
|
|
2
|
+
import { to } from './to.js';
|
|
3
|
+
export async function retry(params) {
|
|
4
|
+
const { numTimes = 3, delayMs = 0, factor = 2, maxDelayMs = Infinity, shouldRetry = () => true } = params;
|
|
5
|
+
const errors = [];
|
|
6
|
+
for (let attempt = 0; attempt < numTimes; ++attempt) {
|
|
7
|
+
if (attempt > 0 && delayMs > 0)
|
|
8
|
+
await delay(Math.min(delayMs * factor ** (attempt - 1), maxDelayMs));
|
|
9
|
+
const { err, res } = await to(params.yourAsyncFn());
|
|
10
|
+
if (err === null)
|
|
11
|
+
return { res, errors };
|
|
12
|
+
errors.push(err);
|
|
13
|
+
if (!shouldRetry(err))
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
return { res: null, errors };
|
|
17
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export function throttle(fn, ms) {
|
|
2
|
+
let timer;
|
|
3
|
+
let pending;
|
|
4
|
+
function onWindowEnd() {
|
|
5
|
+
timer = undefined;
|
|
6
|
+
if (!pending)
|
|
7
|
+
return;
|
|
8
|
+
const args = pending;
|
|
9
|
+
pending = undefined;
|
|
10
|
+
fn(...args);
|
|
11
|
+
timer = setTimeout(onWindowEnd, ms);
|
|
12
|
+
}
|
|
13
|
+
function flush() {
|
|
14
|
+
clearTimeout(timer);
|
|
15
|
+
timer = undefined;
|
|
16
|
+
if (!pending)
|
|
17
|
+
return;
|
|
18
|
+
const args = pending;
|
|
19
|
+
pending = undefined;
|
|
20
|
+
fn(...args);
|
|
21
|
+
}
|
|
22
|
+
function cancel() {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
timer = undefined;
|
|
25
|
+
pending = undefined;
|
|
26
|
+
}
|
|
27
|
+
const throttled = (...args) => {
|
|
28
|
+
if (timer) {
|
|
29
|
+
pending = args;
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
fn(...args);
|
|
33
|
+
timer = setTimeout(onWindowEnd, ms);
|
|
34
|
+
};
|
|
35
|
+
return Object.assign(throttled, { cancel, flush });
|
|
36
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export class TimeoutError extends Error {
|
|
2
|
+
constructor(ms) {
|
|
3
|
+
super(`Timed out after ${ms}ms`);
|
|
4
|
+
this.name = 'TimeoutError';
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export async function timeout(promise, ms) {
|
|
8
|
+
let timer;
|
|
9
|
+
const expiry = new Promise((_, reject) => {
|
|
10
|
+
timer = setTimeout(() => reject(new TimeoutError(ms)), ms);
|
|
11
|
+
});
|
|
12
|
+
try {
|
|
13
|
+
return await Promise.race([promise, expiry]);
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
clearTimeout(timer);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type ToSuccess<T> = {
|
|
2
|
+
res: T;
|
|
3
|
+
err: null;
|
|
4
|
+
};
|
|
5
|
+
export type ToError<E> = {
|
|
6
|
+
res: null;
|
|
7
|
+
err: E;
|
|
8
|
+
};
|
|
9
|
+
export declare function to<R = never, E = Error>(promise: Promise<R>): Promise<ToSuccess<R> | ToError<E>>;
|
|
10
|
+
export declare function toSync<R, E = Error>(fn: () => R): ToSuccess<R> | ToError<E>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export async function to(promise) {
|
|
2
|
+
try {
|
|
3
|
+
return { err: null, res: await promise };
|
|
4
|
+
}
|
|
5
|
+
catch (err) {
|
|
6
|
+
return { err: err, res: null };
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export function toSync(fn) {
|
|
10
|
+
try {
|
|
11
|
+
return { err: null, res: fn() };
|
|
12
|
+
}
|
|
13
|
+
catch (err) {
|
|
14
|
+
return { err: err, res: null };
|
|
15
|
+
}
|
|
16
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './helpers/index.ts';
|
package/lib/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './helpers/index.js';
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rwaterman/utils",
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "Typed, small, dependency-free, lightweight async helper/utility functions we use all the time",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./lib/index.d.ts",
|
|
9
|
+
"default": "./lib/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"types": "lib/index.d.ts",
|
|
13
|
+
"files": [
|
|
14
|
+
"lib/**/*"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=24"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsc -p tsconfig.build.json",
|
|
24
|
+
"format": "prettier --write \"src/**/*.ts\" \"*.{json,md}\"",
|
|
25
|
+
"lint": "oxlint --type-aware --deny-warnings src",
|
|
26
|
+
"postversion": "git push && git push --tags",
|
|
27
|
+
"prepare": "npm run build",
|
|
28
|
+
"prepublishOnly": "npm test && npm run lint",
|
|
29
|
+
"preversion": "npm run lint",
|
|
30
|
+
"test": "vitest run",
|
|
31
|
+
"version": "npm run format && git add -A src"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/rwaterman/utils-ts.git"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"TypeScript",
|
|
39
|
+
"Library",
|
|
40
|
+
"Async"
|
|
41
|
+
],
|
|
42
|
+
"author": "Rick Waterman",
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "^26.2.0",
|
|
46
|
+
"oxlint": "^1.79.0",
|
|
47
|
+
"oxlint-tsgolint": "^7.0.2001",
|
|
48
|
+
"prettier": "^3.9.6",
|
|
49
|
+
"typescript": "^7.0.2",
|
|
50
|
+
"vitest": "^4.1.11"
|
|
51
|
+
}
|
|
52
|
+
}
|