feat(build): modernize package configuration, tooling, and tests for ESM-compatible releases

This commit is contained in:
2026-05-02 09:51:34 +00:00
parent f9873b008b
commit 2051335d91
12 changed files with 7768 additions and 4117 deletions
+40
View File
@@ -0,0 +1,40 @@
{
"@ship.zone/szci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org"
},
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartdelay",
"shortDescription": "Async delay utilities",
"description": "A TypeScript library providing enhanced timeout functions compatible with async/await patterns.",
"npmPackagename": "@push.rocks/smartdelay",
"license": "MIT",
"keywords": [
"TypeScript",
"async/await",
"timeouts",
"delay",
"scheduling",
"task delay",
"asynchronous",
"programming utility",
"promise",
"timeout management"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.\n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.\n\nUse of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District Court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}
+64
View File
@@ -0,0 +1,64 @@
# Changelog
## 2026-05-02 - 3.1.0 - feat(build)
modernize package configuration, tooling, and tests for ESM-compatible releases
- add package exports and include smart config and license files in published package
- migrate build and test tooling to the @git.zone stack and refresh dependency versions
- tighten TypeScript typing for timeout handling and make unref calls optional for broader runtime compatibility
- replace legacy tests with updated node+chromium coverage and expand README usage documentation
## 2026-03-01 - 3.0.5 - maintenance
Project metadata and repository maintenance updates across 3.0.5.
- Removed `.gitlab-ci.yml`
- Updated package description
- Updated `tsconfig`
- Updated `npmextra.json` git host configuration
## 2023-07-13 - 3.0.5 - core
Patch release continuing core update fixes across versions 3.0.2 through 3.0.5.
- Applied repeated `core` update fixes in 3.0.2, 3.0.3, 3.0.4, and 3.0.5
## 2023-07-10 - 3.0.1 - project
Project organization update alongside early 3.x core fixes.
- Switched to the new organization scheme
- Included core update fixes leading into versions 3.0.0 and 3.0.1
## 2023-04-05 - 3.0.0 - core
Major core update with a breaking change for the 3.0.0 release.
- Introduced a breaking `core` update from 2.0.13 to 3.0.0
## 2021-06-04 - 2.0.13 - core
Series of patch releases with repeated core fixes from 2.0.3 through 2.0.13.
- Applied recurring `core` update fixes across versions 2.0.3 to 2.0.13
## 2018-08-08 - 2.0.1 - CI
Build and packaging maintenance around the 2.x transition.
- Switched CI to a new build stack in 2.0.1
- Fixed npm access levels in 2.0.0
## 2018-07-06 - 2.0.0 - switch scope
Major release introducing a breaking scope change.
- Updated package scope with a breaking change from 1.0.4 to 2.0.0
## 2017-10-09 - 1.0.3 - features
Feature updates and maintenance in the 1.0.x line.
- Implemented random time
- Updated CI
- Added cancelable `Timeout` in 1.0.1
- Included CI maintenance for 1.0.2
## 2017-01-17 - 1.0.0 - initial release
Initial release of the project.
- Implemented smartdelay
- Added initial implementation
- Created the initial project structure
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Task Venture Capital GmbH <hello@task.vc>
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+14 -6
View File
@@ -1,14 +1,15 @@
{ {
"npmci": { "@ship.zone/szci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmRegistryUrl": "registry.npmjs.org"
}, },
"gitzone": { "@git.zone/cli": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "code.foss.global", "githost": "code.foss.global",
"gitscope": "push.rocks", "gitscope": "push.rocks",
"gitrepo": "smartdelay", "gitrepo": "smartdelay",
"shortDescription": "Async delay utilities",
"description": "A TypeScript library providing enhanced timeout functions compatible with async/await patterns.", "description": "A TypeScript library providing enhanced timeout functions compatible with async/await patterns.",
"npmPackagename": "@push.rocks/smartdelay", "npmPackagename": "@push.rocks/smartdelay",
"license": "MIT", "license": "MIT",
@@ -24,9 +25,16 @@
"promise", "promise",
"timeout management" "timeout management"
] ]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
} }
}, },
"tsdoc": { "@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n" "legal": "\n## License and Legal Information\n\nThis repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.\n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.\n\nUse of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District Court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }
+14 -11
View File
@@ -3,33 +3,34 @@
"private": false, "private": false,
"version": "3.0.5", "version": "3.0.5",
"description": "A TypeScript library providing enhanced timeout functions compatible with async/await patterns.", "description": "A TypeScript library providing enhanced timeout functions compatible with async/await patterns.",
"exports": {
".": "./dist_ts/index.js"
},
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "tstest test/",
"build": "(tsbuild --web --allowimplicitany && tsbundle npm)", "build": "tsbuild --web",
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://code.foss.global/push.rocks/smartdelay.git" "url": "https://code.foss.global/push.rocks/smartdelay.git"
}, },
"author": "Lossless GmbH", "author": "Task Venture Capital GmbH <hello@task.vc>",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/pushrocks/smartdelay/issues" "url": "https://gitlab.com/pushrocks/smartdelay/issues"
}, },
"homepage": "https://code.foss.global/push.rocks/smartdelay", "homepage": "https://code.foss.global/push.rocks/smartdelay",
"dependencies": { "dependencies": {
"@push.rocks/smartpromise": "^4.0.2" "@push.rocks/smartpromise": "^4.2.4"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.66", "@git.zone/tsbuild": "^4.4.0",
"@gitzone/tsbundle": "^2.0.8", "@git.zone/tsdoc": "^2.0.3",
"@gitzone/tsrun": "^1.2.42", "@git.zone/tstest": "^3.6.3",
"@gitzone/tstest": "^1.0.74", "@types/node": "^25.6.0"
"@push.rocks/tapbundle": "^5.0.8",
"@types/node": "^20.4.1"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
@@ -40,6 +41,8 @@
"dist_ts_web/**/*", "dist_ts_web/**/*",
"assets/**/*", "assets/**/*",
"cli.js", "cli.js",
".smartconfig.json",
"license",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
], ],
@@ -59,4 +62,4 @@
"promise", "promise",
"timeout management" "timeout management"
] ]
} }
+7437 -3978
View File
File diff suppressed because it is too large Load Diff
+121 -59
View File
@@ -1,117 +1,179 @@
# @push.rocks/smartdelay # @push.rocks/smartdelay
@push.rocks/smartdelay is a modern library designed to simplify working with timeouts in the async/await era, all while being fully written in TypeScript. This tool offers a range of functionalities that streamline the process of implementing delays and timeouts in your asynchronous JavaScript code, making it more readable and maintainable. `@push.rocks/smartdelay` is a tiny TypeScript utility for awaitable delays. It turns timer-based waiting into clean `async`/`await` code, supports passing values through delayed flows, can wait for a randomized duration, and exposes a cancellable `Timeout` class for cases where you need direct control over the underlying timer.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install ## Install
To integrate @push.rocks/smartdelay into your project, you can install it via npm. Run the following command in your project directory:
```bash ```bash
npm install @push.rocks/smartdelay --save pnpm add @push.rocks/smartdelay
``` ```
This command adds the package to your project's dependencies, ensuring that you can easily import and utilize smartdelay's functions in your TypeScript files. ## Why Smartdelay?
JavaScript already has `setTimeout`, but it is callback-based and returns a timer handle. `@push.rocks/smartdelay` gives you Promise-based primitives that fit naturally into modern TypeScript applications:
- `delayFor(ms, value?)` waits for a fixed number of milliseconds.
- `delayForRandom(minMs, maxMs, value?)` waits for a random duration inside a range.
- `Timeout` creates a Promise-backed timer that can be cancelled or unrefed.
- All public APIs work in ESM TypeScript projects and browser-capable builds.
## Usage ## Usage
@push.rocks/smartdelay simplifies the handling of timeouts within async functions, offering methods to introduce specified delays or randomized time intervals. Below are detailed examples to demonstrate its usage. These examples are crafted using ECMAScript Modules (ESM) syntax and TypeScript. ### Wait Inside Async Code
### Basic Delay
To introduce a basic delay in your asynchronous function, use the `delayFor` function. This method halts the execution for a specified number of milliseconds.
```typescript ```typescript
import { delayFor } from '@push.rocks/smartdelay'; import { delayFor } from '@push.rocks/smartdelay';
async function basicDelayExample() { async function runJob() {
console.log('Delay start'); console.log('starting');
await delayFor(3000); // Execution will pause here for 3 seconds await delayFor(1000);
console.log('Delay ended'); console.log('continued after 1 second');
} }
basicDelayExample(); await runJob();
``` ```
In the above example, the program prints "Delay start", waits for 3 seconds due to `delayFor`, and then prints "Delay ended". `delayFor` resolves after the requested number of milliseconds. It is useful for polling intervals, backoff windows, test timing, UI pacing, or any flow where a simple awaited pause is cleaner than callback scheduling.
### Delay with Randomization ### Pass A Value Through A Delay
For scenarios where you need a delay within a random time range, `delayForRandom` can be utilized. This introduces a non-deterministic delay duration, making it ideal for simulating real-world scenarios or for testing purposes. ```typescript
import { delayFor } from '@push.rocks/smartdelay';
const result = await delayFor(250, {
status: 'ready',
retries: 2,
});
console.log(result.status); // 'ready'
```
The second argument is returned after the delay. This keeps typed values moving through async chains without adding temporary variables or custom wrappers.
### Wait For A Random Duration
```typescript ```typescript
import { delayForRandom } from '@push.rocks/smartdelay'; import { delayForRandom } from '@push.rocks/smartdelay';
async function randomDelayExample() { await delayForRandom(500, 1500);
console.log('Random delay start');
await delayForRandom(2000, 5000); // Delay execution for a random duration between 2 and 5 seconds
console.log('Random delay ended');
}
randomDelayExample();
``` ```
This function takes two parameters: the minimum and maximum bounds (in milliseconds) for the random delay. `delayForRandom(minMs, maxMs)` waits for a random number of milliseconds between `minMs` and `maxMs`. This is handy for jitter in retry loops, test simulations, and avoiding synchronized bursts of repeated work.
### Passing Through Values It can also pass a value through:
Both `delayFor` and `delayForRandom` can be used to pass through values after the delay. This feature can be particularly useful when chaining asynchronous operations.
```typescript ```typescript
import { delayFor } from '@push.rocks/smartdelay'; import { delayForRandom } from '@push.rocks/smartdelay';
async function passThroughExample() { const nextStep = await delayForRandom(100, 300, 'continue');
const result = await delayFor(3000, 'Hello after delay'); console.log(nextStep); // 'continue'
console.log(result); // Outputs: Hello after delay
}
passThroughExample();
``` ```
### Advanced Usage: Timeout Class ### Control A Timer Manually
@push.rocks/smartdelay provides a `Timeout` class for more granular control over timeouts, including support for cancellation.
```typescript ```typescript
import { Timeout } from '@push.rocks/smartdelay'; import { Timeout } from '@push.rocks/smartdelay';
async function timeoutExample() { const timeout = new Timeout<string>(1000, 'done');
const timeout = new Timeout<string>(5000, 'Result after 5 seconds');
// Cancel the timeout if needed
// timeout.cancel();
try { console.log(`milliseconds left: ${timeout.getTimeLeft()}`);
const result = await timeout.promise;
console.log(result); // Result after 5 seconds (if not cancelled)
} catch (error) {
console.error('Timeout was cancelled', error);
}
}
timeoutExample(); const result = await timeout.promise;
console.log(result); // 'done'
``` ```
This class allows you to programmatically cancel the timeout before it completes, providing flexibility for dynamic timeout management situations. `Timeout<T>` exposes a `promise` that resolves with the optional pass-through value once the timer completes.
## Conclusion ### Cancel A Timeout
@push.rocks/smartdelay offers a TypeScript-friendly, easy-to-use solution for managing timeouts and delays in asynchronous JavaScript. By leveraging this module, developers can write cleaner, more readable async code with minimal boilerplate. Whether you're implementing a simple delay, a random delay, or need finer control over your timeout logic, smartdelay provides the tools you need to get the job done effectively. ```typescript
import { Timeout, delayFor } from '@push.rocks/smartdelay';
const timeout = new Timeout(60_000);
timeout.cancel();
await delayFor(10);
console.log(timeout.getTimeLeft());
```
`cancel()` clears the underlying timer. A cancelled timeout does not resolve its `promise`, so cancellation is best used when you intentionally stop waiting for that timer from another part of your code.
### Create An Unrefed Timer In Node.js
```typescript
import { delayFor, Timeout } from '@push.rocks/smartdelay';
await delayFor(1000, undefined, true);
const timeout = new Timeout(5000, 'background result', true);
```
The optional third argument calls `unref()` on Node.js timer handles when available. That means the timer will not keep a Node.js process alive by itself. In browser environments, this is safely ignored because browser timer handles do not expose `unref()`.
## API
### `delayFor<T>(timeInMillisecondArg, passOnArg?, unrefedArg?)`
Waits for `timeInMillisecondArg` milliseconds and resolves with `passOnArg`.
```typescript
const value = await delayFor<number>(100, 42);
```
Parameters:
- `timeInMillisecondArg: number` - delay duration in milliseconds.
- `passOnArg?: T` - optional value returned after the delay.
- `unrefedArg = false` - when `true`, calls `unref()` on the timer handle if supported.
### `delayForRandom<T>(timeMinInMillisecondArg, timeMaxInMillisecondArg, passOnArg?, unrefedArg?)`
Waits for a random duration between the given minimum and maximum values, then resolves with `passOnArg`.
```typescript
const token = await delayForRandom<string>(100, 500, 'next');
```
Parameters:
- `timeMinInMillisecondArg: number` - minimum delay duration in milliseconds.
- `timeMaxInMillisecondArg: number` - maximum delay duration in milliseconds.
- `passOnArg?: T` - optional value returned after the delay.
- `unrefedArg = false` - when `true`, calls `unref()` on the timer handle if supported.
### `new Timeout<T>(timeInMillisecondArg, passOn?, unrefedArg?)`
Creates a Promise-backed timeout instance.
Properties and methods:
- `promise: Promise<T>` - resolves with `passOn` when the timer completes.
- `cancel()` - clears the timer and prevents resolution.
- `getTimeLeft()` - returns the remaining milliseconds, never below `0`.
- `makeUnrefed()` - calls `unref()` on the timer handle if the runtime supports it.
## License and Legal Information ## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks ### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
+42
View File
@@ -0,0 +1,42 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartdelay from '../ts/index.js';
tap.test('.delayFor should delay async', async () => {
let timePassed = false;
setTimeout(() => {
timePassed = true;
}, 10);
await smartdelay.delayFor(20);
expect(timePassed).toBeTrue();
});
tap.test('.delayForRandom should pass through values', async () => {
const originalRandom = Math.random;
Math.random = () => 0;
try {
const result = await smartdelay.delayForRandom(1, 2, 'random-result');
expect(result).toEqual('random-result');
} finally {
Math.random = originalRandom;
}
});
tap.test('.delayFor should pass on a type', async () => {
const hey = 'heyThere';
const stringArg = await smartdelay.delayFor<string>(1, hey);
expect(stringArg).toEqual('heyThere');
});
tap.test('smartdelay.Timeout', async () => {
const timeout = new smartdelay.Timeout(1);
await timeout.promise;
});
tap.test('smartdelay.Timeout should cancel', async () => {
const timeout = new smartdelay.Timeout(60000);
timeout.cancel();
expect(timeout.getTimeLeft()).toBeGreaterThan(0);
});
export default tap.start();
-53
View File
@@ -1,53 +0,0 @@
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartdelay from '../ts/index.js';
tap.test('.delayFor should delay async', async (tools) => {
tools.timeout(5000);
let timePassed = false;
setTimeout(() => {
timePassed = true;
}, 2000);
await smartdelay.delayFor(3000).then(async () => {
// tslint:disable-next-line:no-unused-expression
expect(timePassed).toBeTrue();
});
});
tap.test('.delayForRandom should delay async for a random time period', async (tools) => {
let timePassedBefore = false;
let timePassedAfter = false;
setTimeout(() => {
timePassedBefore = true;
}, 3000);
setTimeout(() => {
timePassedAfter = true;
}, 5000);
await smartdelay.delayForRandom(3000, 4900);
expect(timePassedBefore).toBeTrue();
expect(timePassedAfter).toBeFalse();
});
tap.test('.delayFor should pass on a type', async (tools) => {
tools.timeout(5000);
let timePassed = false;
setTimeout(() => {
timePassed = true;
}, 2000);
let hey = 'heyThere';
await smartdelay.delayFor<string>(3000, hey).then(async (stringArg) => {
expect(stringArg).toEqual('heyThere');
});
});
tap.test('smartdelay.Timeout', async () => {
let timeout = new smartdelay.Timeout(2000);
await timeout.promise;
});
tap.test('smartdelay.Timeout should cancel', async (tools) => {
let timeout = new smartdelay.Timeout(60000);
timeout.cancel();
});
tap.start();
+3 -3
View File
@@ -1,8 +1,8 @@
/** /**
* autocreated commitinfo by @pushrocks/commitinfo * autocreated commitinfo by @push.rocks/commitinfo
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartdelay', name: '@push.rocks/smartdelay',
version: '3.0.5', version: '3.1.0',
description: 'timeouts for the async/await era, written in TypeScript' description: 'A TypeScript library providing enhanced timeout functions compatible with async/await patterns.'
} }
+9 -6
View File
@@ -5,12 +5,12 @@ import * as smartpromise from '@push.rocks/smartpromise';
* @param timeInMillisecondArg * @param timeInMillisecondArg
* @param passOnArg * @param passOnArg
*/ */
export let delayFor = async <T>( export const delayFor = async <T>(
timeInMillisecondArg: number, timeInMillisecondArg: number,
passOnArg?: T, passOnArg?: T,
unrefedArg = false unrefedArg = false
) => { ) => {
const timeout = new Timeout(timeInMillisecondArg, null, unrefedArg); const timeout = new Timeout<null>(timeInMillisecondArg, null, unrefedArg);
await timeout.promise; await timeout.promise;
return passOnArg; return passOnArg;
}; };
@@ -18,7 +18,7 @@ export let delayFor = async <T>(
/** /**
* delay for a random time * delay for a random time
*/ */
export let delayForRandom = async <T>( export const delayForRandom = async <T>(
timeMinInMillisecondArg: number, timeMinInMillisecondArg: number,
timeMaxInMillisecondArg: number, timeMaxInMillisecondArg: number,
passOnArg?: T, passOnArg?: T,
@@ -35,13 +35,13 @@ export let delayForRandom = async <T>(
export class Timeout<T> { export class Timeout<T> {
promise: Promise<T>; promise: Promise<T>;
private _deferred: smartpromise.Deferred<T>; private _deferred: smartpromise.Deferred<T>;
private _timeout; private _timeout: ReturnType<typeof setTimeout>;
private _cancelled: boolean = false; private _cancelled: boolean = false;
private timeoutInMillis: number; private timeoutInMillis: number;
private started: number; private started: number;
constructor(timeInMillisecondArg, passOn?: T, unrefedArg = false) { constructor(timeInMillisecondArg: number, passOn?: T, unrefedArg = false) {
this.timeoutInMillis = timeInMillisecondArg; this.timeoutInMillis = timeInMillisecondArg;
this._deferred = smartpromise.defer<T>(); this._deferred = smartpromise.defer<T>();
this.promise = this._deferred.promise; this.promise = this._deferred.promise;
@@ -60,7 +60,10 @@ export class Timeout<T> {
* unreffing a timeout causes the node process to not wait for completion before exit * unreffing a timeout causes the node process to not wait for completion before exit
*/ */
public makeUnrefed() { public makeUnrefed() {
this._timeout.unref(); const timeoutWithUnref = this._timeout as ReturnType<typeof setTimeout> & {
unref?: () => void;
};
timeoutWithUnref.unref?.();
} }
/** /**
+3 -1
View File
@@ -5,8 +5,10 @@
"target": "ES2022", "target": "ES2022",
"module": "NodeNext", "module": "NodeNext",
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"noImplicitAny": true,
"esModuleInterop": true, "esModuleInterop": true,
"verbatimModuleSyntax": true "verbatimModuleSyntax": true,
"types": ["node"]
}, },
"exclude": [ "exclude": [
"dist_*/**/*.d.ts" "dist_*/**/*.d.ts"