Compare commits

..

No commits in common. "master" and "v2.0.4" have entirely different histories.

16 changed files with 1701 additions and 5108 deletions

20
.gitignore vendored
View File

@ -1,20 +1,4 @@
.nogit/
# artifacts
node_modules/
docs/
coverage/
public/
pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom

View File

@ -1,55 +1,65 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
# gitzone standard
image: hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
key: "$CI_BUILD_STAGE"
stages:
- security
- test
- release
- metadata
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
mirror:
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
- npmci git mirror
tags:
- lossless
- docker
allow_failure: true
- notpriv
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
snyk:
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --dev
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- lossless
- docker
allow_failure: true
- notpriv
# ====================
# test stage
# ====================
testLEGACY:
stage: test
script:
- npmci node install legacy
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
allow_failure: true
testStable:
testLTS:
stage: test
script:
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test
script:
- npmci node install stable
@ -58,16 +68,7 @@ testStable:
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci node install stable
- npmci npm install
- npmci npm build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
release:
stage: release
@ -77,7 +78,6 @@ release:
only:
- tags
tags:
- lossless
- docker
- notpriv
@ -86,15 +86,20 @@ release:
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
only:
- tags
services:
- docker:stable-dind
script:
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags:
- lossless
- docker
- priv
@ -105,18 +110,16 @@ trigger:
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci node install stable
- npmci npm install
- npmci command npm run buildDocs
- npmci command npm install -g npmpage
- npmci command npmpage
tags:
- lossless
- docker
- notpriv
only:
@ -126,3 +129,13 @@ pages:
paths:
- public
allow_failure: true
windowsCompatibility:
image: stefanscherer/node-windows:10-build-tools
stage: metadata
script:
- npm install & npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- windows
allow_failure: true

11
.vscode/launch.json vendored
View File

@ -1,11 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored
View File

@ -1,26 +0,0 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

37
README.md Normal file
View File

@ -0,0 +1,37 @@
# @pushrocks/smartdelay
timeouts for the async/await era, written in TypeScript
## Availabililty
[![npm](https://push.rocks/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartdelay)
[![git](https://push.rocks/assets/repo-button-git.svg)](https://GitLab.com/pushrocks/smartdelay)
[![git](https://push.rocks/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartdelay)
[![docs](https://push.rocks/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartdelay/)
## Status for master
[![build status](https://GitLab.com/pushrocks/smartdelay/badges/master/build.svg)](https://GitLab.com/pushrocks/smartdelay/commits/master)
[![coverage report](https://GitLab.com/pushrocks/smartdelay/badges/master/coverage.svg)](https://GitLab.com/pushrocks/smartdelay/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/smartdelay.svg)](https://www.npmjs.com/package/smartdelay)
[![Dependency Status](https://david-dm.org/pushrocks/smartdelay.svg)](https://david-dm.org/pushrocks/smartdelay)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartdelay/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartdelay/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartdelay/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartdelay)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
Use TypeScript for best in class instellisense.
```javascript
import * as smartdelay from 'smartdelay';
(async () => {
await smartdelay.delayFor('3000'); // excution will halt here 3 seconds for this function scope BUT NOT BLOCK anything else
console.log();
})();
```
[![npm](https://push.rocks/assets/repo-header.svg)](https://push.rocks)

View File

@ -2,31 +2,5 @@
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartdelay",
"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"
]
}
},
"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"
}
}

1524
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,62 +1,32 @@
{
"name": "@push.rocks/smartdelay",
"name": "@pushrocks/smartdelay",
"private": false,
"version": "3.0.5",
"description": "A TypeScript library providing enhanced timeout functions compatible with async/await patterns.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"version": "2.0.4",
"description": "timeouts for the async/await era, written in TypeScript",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild --web --allowimplicitany && tsbundle npm)",
"buildDocs": "tsdoc"
"build": "(tsbuild)"
},
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartdelay.git"
"url": "git+ssh://git@gitlab.com/pushrocks/smartdelay.git"
},
"author": "Lossless GmbH",
"license": "MIT",
"bugs": {
"url": "https://gitlab.com/pushrocks/smartdelay/issues"
},
"homepage": "https://code.foss.global/push.rocks/smartdelay",
"homepage": "https://gitlab.com/pushrocks/smartdelay#README",
"dependencies": {
"@push.rocks/smartpromise": "^4.0.2"
"@pushrocks/smartpromise": "^3.0.6"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsbundle": "^2.0.8",
"@gitzone/tsrun": "^1.2.42",
"@gitzone/tstest": "^1.0.74",
"@push.rocks/tapbundle": "^5.0.8",
"@types/node": "^20.4.1"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"type": "module",
"keywords": [
"TypeScript",
"async/await",
"timeouts",
"delay",
"scheduling",
"task delay",
"asynchronous",
"programming utility",
"promise",
"timeout management"
]
"@gitzone/tsbuild": "^2.1.17",
"@gitzone/tsrun": "^1.2.8",
"@gitzone/tstest": "^1.0.28",
"@pushrocks/tapbundle": "^3.0.13",
"@types/node": "^12.12.5"
}
}

4711
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@

117
readme.md
View File

@ -1,117 +0,0 @@
# @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.
## Install
To integrate @push.rocks/smartdelay into your project, you can install it via npm. Run the following command in your project directory:
```bash
npm install @push.rocks/smartdelay --save
```
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.
## 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.
### 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
import { delayFor } from '@push.rocks/smartdelay';
async function basicDelayExample() {
console.log('Delay start');
await delayFor(3000); // Execution will pause here for 3 seconds
console.log('Delay ended');
}
basicDelayExample();
```
In the above example, the program prints "Delay start", waits for 3 seconds due to `delayFor`, and then prints "Delay ended".
### Delay with Randomization
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 { delayForRandom } from '@push.rocks/smartdelay';
async function randomDelayExample() {
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.
### Passing Through Values
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
import { delayFor } from '@push.rocks/smartdelay';
async function passThroughExample() {
const result = await delayFor(3000, 'Hello after delay');
console.log(result); // Outputs: Hello after delay
}
passThroughExample();
```
### Advanced Usage: Timeout Class
@push.rocks/smartdelay provides a `Timeout` class for more granular control over timeouts, including support for cancellation.
```typescript
import { Timeout } from '@push.rocks/smartdelay';
async function timeoutExample() {
const timeout = new Timeout<string>(5000, 'Result after 5 seconds');
// Cancel the timeout if needed
// timeout.cancel();
try {
const result = await timeout.promise;
console.log(result); // Result after 5 seconds (if not cancelled)
} catch (error) {
console.error('Timeout was cancelled', error);
}
}
timeoutExample();
```
This class allows you to programmatically cancel the timeout before it completes, providing flexibility for dynamic timeout management situations.
## Conclusion
@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.
## 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.
**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
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.
### Company Information
Task Venture Capital GmbH
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.
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.

View File

@ -1,8 +1,8 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartdelay from '../ts/index.js';
import * as smartdelay from '../ts/index';
tap.test('.delayFor should delay async', async (tools) => {
tap.test('.delayFor should delay async', async tools => {
tools.timeout(5000);
let timePassed = false;
setTimeout(() => {
@ -10,33 +10,31 @@ tap.test('.delayFor should delay async', async (tools) => {
}, 2000);
await smartdelay.delayFor(3000).then(async () => {
// tslint:disable-next-line:no-unused-expression
expect(timePassed).toBeTrue();
expect(timePassed).to.be.true;
});
});
tap.test('.delayForRandom should delay async for a random time period', async (tools) => {
let timePassedBefore = false;
let timePassedAfter = false;
tap.test('.delayForRandpm should delay async for a random time period', async tools => {
tools.timeout(5000);
let timePassed = false;
setTimeout(() => {
timePassedBefore = true;
timePassed = true;
}, 3000);
setTimeout(() => {
timePassedAfter = true;
}, 5000);
await smartdelay.delayForRandom(3000, 4900);
expect(timePassedBefore).toBeTrue();
expect(timePassedAfter).toBeFalse();
await smartdelay.delayForRandom(3000, 4900).then(async () => {
// tslint:disable-next-line:no-unused-expression
expect(timePassed).to.be.true;
});
});
tap.test('.delayFor should pass on a type', async (tools) => {
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');
await smartdelay.delayFor<string>(3000, hey).then(async stringArg => {
expect(stringArg).equal('heyThere');
});
});
@ -45,7 +43,7 @@ tap.test('smartdelay.Timeout', async () => {
await timeout.promise;
});
tap.test('smartdelay.Timeout should cancel', async (tools) => {
tap.test('smartdelay.Timeout should cancel', async tools => {
let timeout = new smartdelay.Timeout(60000);
timeout.cancel();
});

View File

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartdelay',
version: '3.0.5',
description: 'timeouts for the async/await era, written in TypeScript'
}

View File

@ -1,48 +1,41 @@
import * as smartpromise from '@push.rocks/smartpromise';
import * as smartpromise from '@pushrocks/smartpromise';
/**
* delay something, works like setTimeout
* @param timeInMillisecondArg
* @param passOnArg
* @param timeInMillisecond
* @param passOn
*/
export let delayFor = async <T>(
timeInMillisecondArg: number,
passOnArg?: T,
unrefedArg = false
) => {
const timeout = new Timeout(timeInMillisecondArg, null, unrefedArg);
await timeout.promise;
return passOnArg;
export let delayFor = async <T>(timeInMillisecond: number, passOn?: T) => {
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, timeInMillisecond);
});
return passOn;
};
/**
* delay for a random time
*/
export let delayForRandom = async <T>(
timeMinInMillisecondArg: number,
timeMaxInMillisecondArg: number,
passOnArg?: T,
unrefedArg = false
timeMinInMillisecond: number,
timeMaxInMillisecond: number,
passOn?: T
) => {
await delayFor(
Math.random() * (timeMaxInMillisecondArg - timeMinInMillisecondArg) + timeMinInMillisecondArg,
null,
unrefedArg
);
return passOnArg;
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, Math.random() * (timeMaxInMillisecond - timeMinInMillisecond) + timeMinInMillisecond);
});
return passOn;
};
export class Timeout<T> {
promise: Promise<T>;
private _deferred: smartpromise.Deferred<T>;
private _timeout;
private _timeout: any;
private _cancelled: boolean = false;
private timeoutInMillis: number;
private started: number;
constructor(timeInMillisecondArg, passOn?: T, unrefedArg = false) {
this.timeoutInMillis = timeInMillisecondArg;
constructor(timeInMillisecondArg, passOn?: T) {
this._deferred = smartpromise.defer<T>();
this.promise = this._deferred.promise;
this._timeout = setTimeout(() => {
@ -50,29 +43,14 @@ export class Timeout<T> {
this._deferred.resolve(passOn);
}
}, timeInMillisecondArg);
this.started = Date.now();
if (unrefedArg) {
this.makeUnrefed();
}
}
/**
* unreffing a timeout causes the node process to not wait for completion before exit
*/
public makeUnrefed() {
makeUnrefed() {
this._timeout.unref();
}
/**
* cancels the timer
*/
public cancel() {
cancel() {
this._cancelled = true;
clearTimeout(this._timeout);
}
public getTimeLeft() {
const result = this.started + this.timeoutInMillis - Date.now();
return result > 0 ? result : 0;
this.makeUnrefed();
}
}

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

3
tslint.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "tslint-config-standard"
}