Compare commits

...

43 Commits

Author SHA1 Message Date
e5a1399857 v4.2.1 2026-02-15 22:57:28 +00:00
40d72de979 fix(cronmanager): improve cron scheduling and lifecycle handling; add wake/wakeCycle to promptly recalculate scheduling when jobs are added/removed/started/stopped, fix timeout handling, and update tests and deps 2026-02-15 22:57:28 +00:00
51943fad1c 4.2.0 2024-12-14 02:22:43 +01:00
ce3af11ca8 feat(ondemand): Add on-demand timestamp feature 2024-12-14 02:22:43 +01:00
a941f10af3 4.1.1 2024-12-13 22:09:31 +01:00
6e7f8f3dda fix(smarttime.units): Fix issue in getMilliSecondsAsHumanReadableAgoTime 2024-12-13 22:09:30 +01:00
bfa00feadd 4.1.0 2024-12-13 22:04:26 +01:00
55c2d95b7d feat(smarttime.units): Add function to get human-readable time ago string from milliseconds. 2024-12-13 22:04:26 +01:00
71ce4de8ff 4.0.9 2024-12-13 21:55:02 +01:00
491176bb35 fix(dependencies): Updated dependencies in package.json and resolved cron function issues. 2024-12-13 21:55:02 +01:00
35e387da7c 4.0.8 2024-06-23 23:30:15 +02:00
c96248ea72 fix(documentation): Corrected formatting issues in changelog.md 2024-06-23 23:30:14 +02:00
7eb8e9c4f7 4.0.7 2024-06-23 23:27:11 +02:00
c0e9a7f19a fix(build): Remove GitLab CI configuration and update dependencies in package.json 2024-06-23 23:27:10 +02:00
6e18d6e13c update description 2024-05-29 14:16:49 +02:00
580b33448e update tsconfig 2024-04-14 18:28:37 +02:00
691c4f0aba update tsconfig 2024-04-01 21:41:37 +02:00
f06abc49b6 update npmextra.json: githost 2024-04-01 19:59:55 +02:00
1adfed02df update npmextra.json: githost 2024-03-30 21:48:56 +01:00
22e6798a3c 4.0.6 2023-10-20 12:50:48 +02:00
4dd4980374 fix(core): update 2023-10-20 12:50:47 +02:00
edadbe6cf5 4.0.5 2023-08-13 21:55:07 +02:00
58f213a099 fix(core): update 2023-08-13 21:55:06 +02:00
1e5fd80a69 4.0.4 2023-07-21 03:39:59 +02:00
1de9412a31 fix(core): update 2023-07-21 03:39:59 +02:00
fa3ac0ff77 4.0.3 2023-07-21 03:39:33 +02:00
25eee6cf73 fix(core): update 2023-07-21 03:39:32 +02:00
c290a75f01 4.0.2 2023-07-12 11:28:52 +02:00
9a20f8f6a1 fix(core): update 2023-07-12 11:28:52 +02:00
f91fa33568 4.0.1 2023-01-06 20:05:03 +01:00
c234cb4caa fix(core): update 2023-01-06 20:05:02 +01:00
5f5957b0c0 4.0.0 2022-11-21 12:33:26 +01:00
31275536ec BREAKING CHANGE(core): switch to esm 2022-11-21 12:33:25 +01:00
c759d436dd 3.0.48 2022-11-21 11:31:30 +01:00
010c9e7bed fix(core): update 2022-11-21 11:31:29 +01:00
264c08d848 3.0.47 2022-11-21 09:14:32 +01:00
b2a5cda468 fix(core): update 2022-11-21 09:14:32 +01:00
d3dd03534a 3.0.46 2022-11-21 01:19:39 +01:00
9b96779d19 fix(core): update 2022-11-21 01:19:38 +01:00
20b181b2f3 3.0.45 2022-02-02 17:03:59 +01:00
d278722da2 fix(core): update 2022-02-02 17:03:58 +01:00
e3daf08d67 3.0.44 2022-02-02 16:55:13 +01:00
0483b55a9e fix(core): update 2022-02-02 16:55:12 +01:00
29 changed files with 10785 additions and 26978 deletions

View File

@@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

View File

@@ -1,137 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

24
.vscode/launch.json vendored
View File

@@ -2,28 +2,10 @@
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
"type": "node-terminal"
}
]
}

131
changelog.md Normal file
View File

@@ -0,0 +1,131 @@
# Changelog
## 2026-02-15 - 4.2.1 - fix(cronmanager)
improve cron scheduling and lifecycle handling; add wake/wakeCycle to promptly recalculate scheduling when jobs are added/removed/started/stopped, fix timeout handling, and update tests and deps
- CronManager: add wakeCycle (Deferred) to wake the sleeping cycle immediately when jobs change
- CronManager: refactor runCronCycle to compute the soonest next execution (soonestMs), await timeout or wake signal, handle overdue jobs without waiting, and cancel timeouts to avoid lingering timers
- CronJob: guard checkExecution to return when job status is 'stopped' to prevent unnecessary scheduling work
- Stop logic: safely cancel executionTimeout only if present and ensure the cycle is woken when stopping
- Tests: switch test imports to @git.zone/tstest/tapbundle
- Dependencies: bump several devDependencies and dependencies (tsbuild, tsbundle, tstest, croner, smartpromise, dayjs, pretty-ms, etc.)
- Docs/config: expand README with examples and security/reporting info; add @git.zone/cli release config to npmextra.json
## 2024-12-14 - 4.2.0 - feat(ondemand)
Add on-demand timestamp feature
- Added an on-demand script to output human-readable time ago for current timestamp.
## 2024-12-13 - 4.1.1 - fix(smarttime.units)
Fix issue in getMilliSecondsAsHumanReadableAgoTime
- Corrected the parameter type passed to date-fns.formatDistanceToNow within getMilliSecondsAsHumanReadableAgoTime function.
## 2024-12-13 - 4.1.0 - feat(smarttime.units)
Add function to get human-readable time ago string from milliseconds.
- Introduced `getMilliSecondsAsHumanReadableAgoTime` to convert a timestamp to a human-readable text indicating time ago.
## 2024-12-13 - 4.0.9 - fix(dependencies)
Updated dependencies in package.json and resolved cron function issues.
- Updated multiple dependencies in package.json to their latest versions.
- Fixed issue in cron job instantiation by correcting the import and initialization of the croner.Cron class.
## 2024-06-23 - 4.0.8 - fix(documentation)
Corrected formatting issues in changelog.md
- Fixed markdown formatting by removing unnecessary newlines.
## 2024-06-23 - 4.0.7 - fix(build)
Remove GitLab CI configuration and update dependencies in package.json
- Removed .gitlab-ci.yml from the project
- Updated @git.zone/tsbuild from ^2.1.72 to ^2.1.80
- Updated @git.zone/tstest from ^1.0.86 to ^1.0.90
- Updated @push.rocks/tapbundle from ^5.0.15 to ^5.0.23
- Updated @types/node from ^20.11.19 to ^20.14.8
- Updated @push.rocks/lik from ^6.0.12 to ^6.0.15
- Updated dayjs from ^1.11.10 to ^1.11.11
- Fixed test files to export default tap.start()
## 2024-05-29 - 4.0.6 - Maintenance Updates
Updates to configuration files and metadata.
- Updated description in the project documentation.
- Revised tsconfig settings.
- Changes to npmextra.json regarding githost configuration.
## 2023-10-20 - 4.0.5 to 4.0.6 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2023-08-13 - 4.0.4 to 4.0.5 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2023-07-21 - 4.0.2 to 4.0.4 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2023-01-06 - 4.0.0 to 4.0.1 - Core Changes
Routine fixes and core updates.
- fix(core): update
## 2022-11-21 - 3.0.45 to 4.0.0 - Major Release
Significant changes and breaking updates.
- BREAKING CHANGE(core): switch to esm
## 2021-11-08 - 3.0.41 to 3.0.42 - Timestamp Update
Updates and bug fixes for the timestamp feature.
- fix(timestamp): add missing .isOlderThanOtherTimeStamp() to TimeStamp class
- fix(readme): fix readme
- fix(update croner): update croner package, closes #1. Thank you @Hexagon4
## 2020-09-04 - 3.0.28 to 3.0.31 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2020-07-11 - 3.0.19 to 3.0.20 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2020-05-25 - 3.0.12 to 3.0.16 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2019-06-18 - 3.0.8 to 3.0.12 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2018-10-21 - 3.0.0 to 3.0.1 - Date Handling
Updates to date and time support.
- fix(date): now supports date and time
- fix(ExtendedDate): now respects single digit dates
## 2018-10-17 - 2.0.2 to 3.0.0 - Major Release
Breaking changes and dependency updates.
- BREAKING CHANGE(deps): remove moment and use luxon
## 2018-06-10 - 2.0.0 to 2.0.1 - Core Changes
Updated and changed the scope of core functionalities.
- fix(core): update and change scope
## 2017-08-16 - 1.0.0 to 1.0.3 - Initial Implementation
Inception of project with core functionalities.
- first implementation

View File

@@ -6,12 +6,32 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smarttime",
"shortDescription": "handle time in smart ways",
"npmPackagename": "@pushrocks/smarttime",
"license": "MIT"
"description": "Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.",
"npmPackagename": "@push.rocks/smarttime",
"license": "MIT",
"keywords": [
"time handling",
"cron jobs",
"timestamps",
"time intervals",
"date operations",
"time formatting",
"scheduling"
]
}
},
"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"
},
"@git.zone/cli": {
"release": {
"registries": [
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
}
}

26639
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +1,34 @@
{
"name": "@pushrocks/smarttime",
"name": "@push.rocks/smarttime",
"private": false,
"version": "3.0.43",
"description": "handle time in smart ways",
"version": "4.2.1",
"description": "Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest ./test)",
"build": "(tsbuild --web && tsbundle npm)"
"build": "(tsbuild --web && tsbundle npm)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.28",
"@gitzone/tsbundle": "^1.0.88",
"@gitzone/tsrun": "^1.2.18",
"@gitzone/tstest": "^1.0.60",
"@pushrocks/tapbundle": "^3.2.14",
"@types/node": "^16.11.6",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0"
"@git.zone/tsbuild": "^4.1.2",
"@git.zone/tsbundle": "^2.8.3",
"@git.zone/tsrun": "^2.0.1",
"@git.zone/tstest": "^3.1.8",
"@push.rocks/tapbundle": "^6.0.3",
"@types/node": "^25.2.3"
},
"dependencies": {
"@pushrocks/lik": "^5.0.0",
"@pushrocks/smartdelay": "^2.0.13",
"@pushrocks/smartpromise": "^3.1.6",
"croner": "^4.0.69",
"dayjs": "^1.10.7",
"@push.rocks/lik": "^6.2.2",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartpromise": "^4.2.3",
"croner": "^10.0.1",
"date-fns": "^4.1.0",
"dayjs": "^1.11.19",
"is-nan": "^1.3.2",
"pretty-ms": "^7.0.1"
"pretty-ms": "^9.3.0"
},
"files": [
"ts/**/*",
@@ -44,5 +44,20 @@
],
"browserslist": [
"last 1 chrome versions"
]
],
"type": "module",
"keywords": [
"time handling",
"cron jobs",
"timestamps",
"time intervals",
"date operations",
"time formatting",
"scheduling"
],
"homepage": "https://code.foss.global/push.rocks/smarttime",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smarttime.git"
}
}

9977
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@@ -0,0 +1 @@

302
readme.md
View File

@@ -1,63 +1,283 @@
# @pushrocks/smarttime
handle time in smart ways
# @push.rocks/smarttime
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smarttime)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smarttime)
* [github.com (source mirror)](https://github.com/pushrocks/smarttime)
* [docs (typedoc)](https://pushrocks.gitlab.io/smarttime/)
Handle time in smart ways — cron scheduling, extended dates, precise measurements, timers, intervals, and human-readable formatting. 🕐
## Status for master
## Issue Reporting and Security
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smarttime/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smarttime/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smarttime)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smarttime)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smarttime)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smarttime)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smarttime)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
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
```bash
npm install @push.rocks/smarttime
```
or with pnpm:
```bash
pnpm install @push.rocks/smarttime
```
## Usage
Use TypeScript for best in class instellisense.
`@push.rocks/smarttime` is a comprehensive TypeScript-first toolkit for working with time. It covers everything from cron-based scheduling and extended date manipulation to high-resolution measurements, timers, intervals, and human-readable time formatting.
Smarttime offers smart ways to deal with time.
All examples below use ESM imports and TypeScript.
### class CronManager
### ⏱️ Time Units & Calculations
This class provides scheduling of functions with a cron syntax
Convert human-readable time durations into milliseconds using the `units` helpers and `getMilliSecondsFromUnits`:
```typescript
import { CronManager } from '@pushrocks/smarrtime';
const cronManagerInstance = new CronManager();
cronManagerInstance.addCronjob('* * * * * *', async () => {
console.log('hello'); // will log 'hello' to console once every second;
import { units, getMilliSecondsFromUnits } from '@push.rocks/smarttime';
// Individual unit conversions
const oneDay = units.days(1); // 86400000
const twoHours = units.hours(2); // 7200000
const thirtySeconds = units.seconds(30); // 30000
// Combined duration — great for timeouts, TTLs, cache expiration, etc.
const duration = getMilliSecondsFromUnits({
years: 1,
months: 2,
weeks: 3,
days: 4,
hours: 5,
minutes: 6,
seconds: 7,
});
cronManagerInstance.start();
console.log(`Duration: ${duration}ms`);
```
### class ExtendedDate
### 🗓️ Human-Readable Time Formatting
This class offers static functions to create zone specific JavaScript dates from European formated time strings.
Turn raw milliseconds into a friendly string, or get a relative "time ago" description:
```TypeScript
import { ExtendedDate } from '@pushrocks/smarttime'
const myDate: Date = ExtendedDate.fromEuropeanDate('8.6.2018')
```typescript
import {
getMilliSecondsAsHumanReadableString,
getMilliSecondsAsHumanReadableAgoTime,
} from '@push.rocks/smarttime';
// "2h 30m"
console.log(getMilliSecondsAsHumanReadableString(9_000_000));
// "5 minutes ago" style output
const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
console.log(getMilliSecondsAsHumanReadableAgoTime(fiveMinutesAgo));
```
## Contribution
### 🔄 CronManager — Scheduled Task Execution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
The `CronManager` lets you register and run multiple cron jobs using standard 6-field cron syntax (seconds included). Powered by [croner](https://github.com/Hexagon/croner).
For further information read the linked docs at the top of this readme.
```typescript
import { CronManager } from '@push.rocks/smarttime';
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
const cronManager = new CronManager();
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
// Run every 10 seconds
const job1 = cronManager.addCronjob('*/10 * * * * *', async (triggerTime) => {
console.log(`Job 1 triggered at ${new Date(triggerTime).toISOString()}`);
});
// Run every full minute
const job2 = cronManager.addCronjob('0 * * * * *', async () => {
console.log('Full minute tick!');
});
// Start all registered jobs
cronManager.start();
// Later: remove a specific job
cronManager.removeCronjob(job1);
// Stop all jobs
cronManager.stop();
```
The `CronManager` automatically calculates the shortest sleep interval between jobs and efficiently schedules wake-ups — no polling required.
### 📅 ExtendedDate — Enhanced Date Handling
`ExtendedDate` extends the native JavaScript `Date` with factory methods for common date formats and useful inspection methods:
```typescript
import { ExtendedDate } from '@push.rocks/smarttime';
// From European format: "DD.MM.YYYY"
const date1 = ExtendedDate.fromEuropeanDate('25.12.2024');
// From European date + time with timezone context
const date2 = ExtendedDate.fromEuropeanDateAndTime('25.12.2024', '14:30:00', 'Europe/Berlin');
// From hyphenated date: "YYYY-MM-DD"
const date3 = ExtendedDate.fromHyphedDate('2024-12-25');
// From milliseconds
const date4 = ExtendedDate.fromMillis(Date.now());
// From an existing Date object
const date5 = ExtendedDate.fromDate(new Date());
// Export back to various formats
console.log(date1.exportToEuropeanDate()); // "25.12.2024"
console.log(date1.exportToHyphedSortableDate()); // "2024-12-25"
// Get structured date units
const units = date1.exportToUnits();
console.log(units.monthName); // "December"
console.log(units.dayOfTheWeekName); // "Wednesday"
// Custom formatting (via dayjs)
console.log(date1.format('YYYY-MM-DD HH:mm'));
// Boolean checks
console.log(date4.isToday()); // true
// Time comparison: has less than 1 hour passed since this date?
console.log(date4.lessTimePassedToNow({ hours: 1 })); // true
console.log(date4.moreTimePassedToNow({ days: 1 })); // false
```
### ⏱️ HrtMeasurement — High-Resolution Timing
Measure the duration of operations with precision:
```typescript
import { HrtMeasurement } from '@push.rocks/smarttime';
const measurement = new HrtMeasurement();
measurement.start();
// ... perform some operation ...
measurement.stop();
console.log(`Took ${measurement.milliSeconds}ms`);
console.log(`Took ${measurement.nanoSeconds}ns`);
// Reset and reuse
measurement.reset();
measurement.start();
// ...
```
### ⏲️ Timer — Pausable Countdown
A promise-based timer with pause, resume, and reset capabilities:
```typescript
import { Timer } from '@push.rocks/smarttime';
const timer = new Timer(5000); // 5-second countdown
timer.start();
// Await completion
await timer.completed;
console.log('Timer finished!');
// Or use pause/resume
const timer2 = new Timer(10000);
timer2.start();
// Pause after 3 seconds
setTimeout(() => timer2.pause(), 3000);
// Resume later
setTimeout(() => timer2.resume(), 6000);
await timer2.completed;
// Reset completely and start over
timer2.reset();
timer2.start();
```
Check remaining time with `timer.timeLeft`.
### 🔁 Interval — Repeating Jobs
Run functions at a fixed interval with start/stop control:
```typescript
import { Interval } from '@push.rocks/smarttime';
const interval = new Interval(2000); // Every 2 seconds
interval.addIntervalJob(() => {
console.log('Tick!', new Date().toISOString());
});
interval.addIntervalJob(() => {
console.log('Another parallel job');
});
interval.start();
// Stop later
setTimeout(() => interval.stop(), 10000);
```
### 🕰️ TimeStamp — Comparison & Tracking
The `TimeStamp` class captures a moment in time and provides comparison utilities:
```typescript
import { TimeStamp } from '@push.rocks/smarttime';
const stamp1 = new TimeStamp();
// ... some time passes ...
const stamp2 = new TimeStamp();
console.log(stamp1.milliSeconds); // Unix ms
console.log(stamp1.epochtime); // Unix seconds
// Comparison
console.log(stamp1.isOlderThan(stamp2)); // true
console.log(stamp2.isYoungerThanOtherTimeStamp(stamp1)); // true
// Derived timestamps track change
const derived = TimeStamp.fromTimeStamp(stamp1);
console.log(`${derived.change}ms have passed since stamp1`);
// From known milliseconds
const known = TimeStamp.fromMilliSeconds(1700000000000);
```
## API Overview
| Export | Description |
|---|---|
| `CronManager` | Register and run multiple cron jobs with automatic scheduling |
| `CronJob` | Individual cron job (created via `CronManager.addCronjob()`) |
| `ExtendedDate` | Enhanced `Date` with factory methods and formatting |
| `HrtMeasurement` | High-resolution time measurement |
| `Timer` | Promise-based countdown with pause/resume/reset |
| `Interval` | Repeating job execution at fixed intervals |
| `TimeStamp` | Point-in-time capture with comparison utilities |
| `units` | Time unit conversion functions (`days()`, `hours()`, etc.) |
| `getMilliSecondsFromUnits()` | Convert combined time units to milliseconds |
| `getMilliSecondsAsHumanReadableString()` | Format ms as human-readable string |
| `getMilliSecondsAsHumanReadableAgoTime()` | Format timestamp as relative "ago" string |
## License and Legal Information
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.
### 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 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
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
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.

3
test/ondemand.ts Normal file
View File

@@ -0,0 +1,3 @@
import * as smarttime from '../ts/index.js';
console.log(smarttime.getMilliSecondsAsHumanReadableAgoTime(Date.now()));

View File

@@ -1,6 +1,5 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smarttime from '../ts/index.js';
// Test TimeStamp class
let testTimeStamp: smarttime.TimeStamp;
@@ -9,15 +8,15 @@ tap.test('should create valid testTimeStamp instance', async (tools) => {
testTimeStamp = new smarttime.TimeStamp();
await tools.delayFor(2);
testTimeStamp2 = new smarttime.TimeStamp();
expect(testTimeStamp).to.be.instanceof(smarttime.TimeStamp);
expect(testTimeStamp).to.be.instanceof(smarttime.TimeStamp);
expect(testTimeStamp).toBeInstanceOf(smarttime.TimeStamp);
expect(testTimeStamp).toBeInstanceOf(smarttime.TimeStamp);
});
tap.test('should have valid linuxtime', async () => {
// tslint:disable-next-line:no-unused-expression
expect(testTimeStamp.isOlderThan(testTimeStamp2)).to.be.true;
expect(testTimeStamp.isOlderThan(testTimeStamp2)).toBeTrue();
// tslint:disable-next-line:no-unused-expression
expect(testTimeStamp.isYoungerThanOtherTimeStamp(testTimeStamp2)).to.be.false;
expect(testTimeStamp.isYoungerThanOtherTimeStamp(testTimeStamp2)).toBeFalse();
});
let testHrtMeasurement: smarttime.HrtMeasurement;
@@ -28,8 +27,8 @@ tap.test('should create valid HrtMeasurements', async (tools) => {
testHrtMeasurement.start();
await tools.delayFor(20);
testHrtMeasurement.stop();
expect(testHrtMeasurement.milliSeconds).to.be.greaterThan(19);
expect(testHrtMeasurement.milliSeconds).to.be.lessThan(25);
expect(testHrtMeasurement.milliSeconds).toBeGreaterThan(19);
expect(testHrtMeasurement.milliSeconds).toBeLessThan(25);
});
// check units
@@ -47,4 +46,4 @@ tap.test('should combine units', async () => {
console.log(computedTime);
});
tap.start();
export default tap.start();

View File

@@ -1,12 +1,12 @@
import { tap, expect } from '@pushrocks/tapbundle';
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smarttime from '../ts/index';
import * as smarttime from '../ts/index.js';
let testCronManager: smarttime.CronManager;
tap.test('should create a valid instance of cronmanager', async () => {
testCronManager = new smarttime.CronManager();
expect(testCronManager).to.be.instanceOf(smarttime.CronManager);
expect(testCronManager).toBeInstanceOf(smarttime.CronManager);
});
tap.test('should create a valid cronJon', async (tools) => {
@@ -57,4 +57,4 @@ tap.test('runs every full minute', async (tools) => {
testCronManager.stop();
});
tap.start();
export default tap.start();

View File

@@ -1,6 +1,6 @@
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smarttime from '../ts/index';
import * as smarttime from '../ts/index.js';
tap.test('should create a valid JavaScript Date', async () => {
const extendedDate = new smarttime.ExtendedDate(Date.now());
@@ -23,12 +23,12 @@ tap.test('should create a date and time with European Format', async () => {
tap.test('should create a European date string', async () => {
const extendedDate = smarttime.ExtendedDate.fromHyphedDate('2018-02-13');
expect(extendedDate.exportToEuropeanDate()).to.equal('13.02.2018');
expect(extendedDate.exportToEuropeanDate()).toEqual('13.02.2018');
});
tap.test('should format a date', async () => {
const extendedDate = new smarttime.ExtendedDate(Date.now());
console.log(extendedDate.format('YYYY-MM-DD - hh:mm'));
})
});
tap.start();
export default tap.start();

View File

@@ -1,13 +1,12 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Timer } from '../ts/index';
import { Timer } from '../ts/index.js';
let testTimer: Timer;
tap.test('should create a valid timer', async () => {
testTimer = new Timer(1000);
expect(testTimer).to.be.instanceof(Timer);
expect(testTimer).toBeInstanceOf(Timer);
});
tap.test('should start timer', async () => {
@@ -23,4 +22,4 @@ tap.test('should reset a timer', async () => {
await testTimer.completed;
});
tap.start();
export default tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smarttime',
version: '4.2.1',
description: 'Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.'
}

View File

@@ -1,8 +1,8 @@
export * from './smarttime.classes.cronmanager';
export * from './smarttime.classes.cronjob';
export * from './smarttime.classes.extendeddate';
export * from './smarttime.classes.hrtmeasurement';
export * from './smarttime.classes.interval';
export * from './smarttime.classes.timer';
export * from './smarttime.classes.timestamp';
export * from './smarttime.units';
export * from './smarttime.classes.cronmanager.js';
export * from './smarttime.classes.cronjob.js';
export * from './smarttime.classes.extendeddate.js';
export * from './smarttime.classes.hrtmeasurement.js';
export * from './smarttime.classes.interval.js';
export * from './smarttime.classes.timer.js';
export * from './smarttime.classes.timestamp.js';
export * from './smarttime.units.js';

View File

@@ -1,12 +1,12 @@
import * as plugins from './smarttime.plugins';
import { CronManager } from './smarttime.classes.cronmanager';
import * as plugins from './smarttime.plugins.js';
import { CronManager } from './smarttime.classes.cronmanager.js';
import { CronParser } from './smarttime.classes.cronparser';
export type TJobFunction = (() => void) | (() => Promise<any>);
export type TJobFunction =
| ((triggerTimeArg?: number) => void)
| ((triggerTimeArg?: number) => Promise<any>);
export class CronJob {
public cronParser: CronParser | typeof plugins.croner;
public cronParser: plugins.croner.Cron;
public status: 'started' | 'stopped' | 'initial' = 'initial';
public cronExpression: string;
public jobFunction: TJobFunction;
@@ -15,20 +15,23 @@ export class CronJob {
constructor(cronManager: CronManager, cronExpressionArg: string, jobFunction: TJobFunction) {
this.cronExpression = cronExpressionArg;
this.jobFunction = jobFunction;
this.cronParser = plugins.croner(cronExpressionArg);
this.cronParser = new plugins.croner.Cron(cronExpressionArg);
}
/**
* checks wether the cronjob needs to be executed
*/
public checkExecution(): number {
if (this.status === 'stopped') {
return this.nextExecutionUnix;
}
if (this.nextExecutionUnix === 0) {
this.getNextExecutionTime();
}
if (Date.now() > this.nextExecutionUnix) {
const maybePromise = this.jobFunction();
const maybePromise = this.jobFunction(this.nextExecutionUnix);
if (maybePromise instanceof Promise) {
maybePromise.catch(e => console.log(e));
maybePromise.catch((e) => console.log(e));
}
this.nextExecutionUnix = this.getNextExecutionTime();
}
@@ -36,7 +39,7 @@ export class CronJob {
}
public getNextExecutionTime() {
return this.nextExecutionUnix = Date.now() + this.getTimeToNextExecution();
return (this.nextExecutionUnix = Date.now() + this.getTimeToNextExecution());
}
/**

View File

@@ -1,6 +1,5 @@
import * as plugins from './smarttime.plugins';
import { CronJob } from './smarttime.classes.cronjob';
import { getMilliSecondsAsHumanReadableString } from './smarttime.units';
import * as plugins from './smarttime.plugins.js';
import { CronJob, type TJobFunction } from './smarttime.classes.cronjob.js';
export class CronManager {
public executionTimeout: plugins.smartdelay.Timeout<void>;
@@ -8,13 +7,26 @@ export class CronManager {
public status: 'started' | 'stopped' = 'stopped';
public cronjobs = new plugins.lik.ObjectMap<CronJob>();
private cycleWakeDeferred: plugins.smartpromise.Deferred<void> | null = null;
constructor() {}
public addCronjob(cronIdentifierArg: string, cronFunctionArg: () => Promise<void>) {
/**
* Resolves the current wake deferred, causing the sleeping cycle
* to immediately recalculate instead of waiting for its timeout.
*/
private wakeCycle() {
if (this.cycleWakeDeferred && this.cycleWakeDeferred.status === 'pending') {
this.cycleWakeDeferred.resolve();
}
}
public addCronjob(cronIdentifierArg: string, cronFunctionArg: TJobFunction) {
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
this.cronjobs.add(newCronJob);
if (this.status === 'started') {
newCronJob.start();
this.wakeCycle();
}
return newCronJob;
@@ -23,6 +35,9 @@ export class CronManager {
public removeCronjob(cronjobArg: CronJob) {
cronjobArg.stop();
this.cronjobs.remove(cronjobArg);
if (this.status === 'started') {
this.wakeCycle();
}
}
/**
@@ -34,49 +49,55 @@ export class CronManager {
for (const cronJob of this.cronjobs.getArray()) {
cronJob.start();
}
const runCronCycle = async () => {
this.executionTimeout = new plugins.smartdelay.Timeout(0);
do {
let nextRunningCronjob: CronJob;
for (const cronJob of this.cronjobs.getArray()) {
cronJob.checkExecution();
if (
!nextRunningCronjob ||
cronJob.getTimeToNextExecution() < nextRunningCronjob.getTimeToNextExecution()
) {
nextRunningCronjob = cronJob;
}
}
if (nextRunningCronjob) {
this.executionTimeout = new plugins.smartdelay.Timeout(
nextRunningCronjob.getTimeToNextExecution()
);
console.log(
`Next CronJob scheduled in ${getMilliSecondsAsHumanReadableString(
this.executionTimeout.getTimeLeft()
)}`
);
} else {
this.executionTimeout = new plugins.smartdelay.Timeout(1000);
console.log('no cronjobs specified! Checking again in 1 second');
}
await this.executionTimeout.promise;
} while (this.status === 'started');
};
runCronCycle();
this.runCronCycle();
}
}
private async runCronCycle() {
while (this.status === 'started') {
// Create a fresh wake signal for this iteration
this.cycleWakeDeferred = new plugins.smartpromise.Deferred<void>();
// Check all cronjobs and find the soonest next execution
let soonestMs = Infinity;
for (const cronJob of this.cronjobs.getArray()) {
cronJob.checkExecution();
const msToNext = cronJob.getTimeToNextExecution();
if (msToNext < soonestMs) {
soonestMs = msToNext;
}
}
// Sleep until the next job is due or until woken by a lifecycle event
if (soonestMs < Infinity && soonestMs > 0) {
this.executionTimeout = new plugins.smartdelay.Timeout(soonestMs);
await Promise.race([
this.executionTimeout.promise,
this.cycleWakeDeferred.promise,
]);
// Cancel the timeout to avoid lingering timers
this.executionTimeout.cancel();
} else if (soonestMs <= 0) {
// Job is overdue, loop immediately to execute it
continue;
} else {
// No jobs — wait indefinitely until woken by addCronjob or stop
await this.cycleWakeDeferred.promise;
}
}
this.cycleWakeDeferred = null;
}
/**
* stops all cronjobs
*/
public stop() {
if (this.status === 'started') {
this.status = 'stopped';
this.executionTimeout.cancel();
} else {
console.log(`You tried to stop a CronManager that was not actually started.`);
if (this.executionTimeout) {
this.executionTimeout.cancel();
}
this.wakeCycle();
}
for (const cron of this.cronjobs.getArray()) {
cron.stop();

View File

@@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
export class CronParser {
public cronExpression: string;
@@ -62,7 +62,7 @@ export class CronParser {
if (targetHour < currentHour) {
currentDay = (currentDay + 1) % 30;
}
const targetDay = currentDay;
if (targetDay < currentDay) {
currentMonth = (currentMonth + 1) % 11;
@@ -70,7 +70,7 @@ export class CronParser {
const targetMonth = currentMonth;
if (targetMonth < currentMonth) {
currentYear = (currentYear + 1);
currentYear = currentYear + 1;
}
const targetYear = currentYear;

View File

@@ -1,5 +1,5 @@
import * as plugins from './smarttime.plugins';
import * as units from './smarttime.units';
import * as plugins from './smarttime.plugins.js';
import * as units from './smarttime.units.js';
export type TAvailableZone = 'Europe/Berlin';
@@ -83,6 +83,11 @@ export class ExtendedDate extends Date {
return `${units.dayString}.${units.monthString}.${units.yearString}`;
}
public exportToHyphedSortableDate() {
const units = this.exportToUnits();
return `${units.yearString}-${units.monthString}-${units.dayString}`;
}
/**
* exports units
*/
@@ -123,14 +128,14 @@ export class ExtendedDate extends Date {
};
}
public format (formatArg: string) {
public format(formatArg: string) {
return plugins.dayjs(this.getTime()).format(formatArg);
}
/**
* boolean checks
*/
public isToday () {
public isToday() {
return plugins.dayjs(this.getTime()).isToday();
}

View File

@@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
export class Interval {
public status: 'started' | 'stopped' | 'initial' = 'initial';

View File

@@ -1,6 +1,6 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
import { TimeStamp } from './smarttime.classes.timestamp';
import { TimeStamp } from './smarttime.classes.timestamp.js';
export type TimerState = 'initiated' | 'started' | 'paused' | 'completed';
@@ -36,7 +36,7 @@ export class Timer {
/**
* the current timeout the needs to be canceled when this Timer is stopped
*/
private currentTimeout: NodeJS.Timer;
private currentTimeout: NodeJS.Timeout;
// a deferred triggeted when Timer has completed
private completedDeferred = plugins.smartpromise.defer<void>();

View File

@@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
/**
* TimeStamp

View File

@@ -1,16 +1,17 @@
// @pushrocks scope
import * as lik from '@pushrocks/lik';
import * as smartdelay from '@pushrocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise';
import * as lik from '@push.rocks/lik';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartpromise from '@push.rocks/smartpromise';
export { lik, smartdelay, smartpromise };
// third parties;
const croner: any = require('croner');
import * as croner from 'croner';
import * as dateFns from 'date-fns';
import dayjs from 'dayjs';
import isToday from 'dayjs/plugin/isToday';
import isToday from 'dayjs/plugin/isToday.js';
import prettyMs from 'pretty-ms';
dayjs.extend(isToday);
export { croner, dayjs, prettyMs };
export { croner, dateFns, dayjs, prettyMs };

View File

@@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
export let units = {
years: (timesArg = 1): number => {
@@ -19,6 +19,9 @@ export let units = {
minutes: (timesArg = 1) => {
return timesArg * 60000;
},
seconds: (timesArg = 1) => {
return timesArg * 1000;
},
};
export interface IUnitCombinationArg {
@@ -28,6 +31,7 @@ export interface IUnitCombinationArg {
days?: number;
hours?: number;
minutes?: number;
seconds?: number;
}
export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
@@ -53,10 +57,17 @@ export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
if (combinationArg.minutes) {
addMilliSeconds(units.minutes(combinationArg.minutes));
}
if (combinationArg.seconds) {
addMilliSeconds(units.seconds(combinationArg.seconds));
}
return timeInMilliseconds;
};
export const getMilliSecondsAsHumanReadableString = (milliSecondsArg: number): string => {
return plugins.prettyMs(milliSecondsArg);
};
export const getMilliSecondsAsHumanReadableAgoTime = (timeStampArg: number): string => {
return plugins.dateFns.formatDistanceToNow(new Date(timeStampArg));
}

14
tsconfig.json Normal file
View File

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

View File

@@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}