cron-schedule 3.0.5 → 4.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,2 @@
1
- export * from './schedulers/interval-based';
2
- export * from './schedulers/timer-based';
3
- export * from './cron-parser';
4
- export * from './cron';
5
- export * from './utils';
1
+ export * from './cron-parser.js';
2
+ export * from './cron.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './cron-parser.js';
2
+ export * from './cron.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAA;AAChC,cAAc,WAAW,CAAA"}
@@ -1,4 +1,4 @@
1
- import type { Cron } from '../cron';
1
+ import type { Cron } from '../cron.js';
2
2
  /**
3
3
  * A cron scheduler that is based on a single interval.
4
4
  * Every interval, it checks whether a registered cron task
@@ -0,0 +1,119 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _IntervalBasedCronScheduler_interval, _IntervalBasedCronScheduler_intervalId, _IntervalBasedCronScheduler_tasks, _IntervalBasedCronScheduler_nextTaskId;
13
+ import { wrapFunction } from '../utils.js';
14
+ /**
15
+ * A cron scheduler that is based on a single interval.
16
+ * Every interval, it checks whether a registered cron task
17
+ * was due during the last interval and executes it.
18
+ * This scheduler might be more performant depending on the use case,
19
+ * because it only creates a single interval for all scheduled crons,
20
+ * however depending on the interval and crons, tasks might be executed
21
+ * with a delay.
22
+ */
23
+ export class IntervalBasedCronScheduler {
24
+ /**
25
+ * Creates and starts a new scheduler with the given interval.
26
+ */
27
+ constructor(interval) {
28
+ _IntervalBasedCronScheduler_interval.set(this, void 0);
29
+ _IntervalBasedCronScheduler_intervalId.set(this, void 0);
30
+ _IntervalBasedCronScheduler_tasks.set(this, []);
31
+ _IntervalBasedCronScheduler_nextTaskId.set(this, 1
32
+ /**
33
+ * Creates and starts a new scheduler with the given interval.
34
+ */
35
+ );
36
+ __classPrivateFieldSet(this, _IntervalBasedCronScheduler_interval, interval, "f");
37
+ this.start();
38
+ }
39
+ /* Starts the scheduler. */
40
+ start() {
41
+ if (__classPrivateFieldGet(this, _IntervalBasedCronScheduler_intervalId, "f") !== undefined) {
42
+ throw new Error('Scheduler already started.');
43
+ }
44
+ __classPrivateFieldSet(this, _IntervalBasedCronScheduler_intervalId, setInterval(this.processTasks.bind(this), __classPrivateFieldGet(this, _IntervalBasedCronScheduler_interval, "f")), "f");
45
+ }
46
+ /* Ensures the scheduler is stopped. */
47
+ stop() {
48
+ if (__classPrivateFieldGet(this, _IntervalBasedCronScheduler_intervalId, "f")) {
49
+ clearInterval(__classPrivateFieldGet(this, _IntervalBasedCronScheduler_intervalId, "f"));
50
+ __classPrivateFieldSet(this, _IntervalBasedCronScheduler_intervalId, undefined, "f");
51
+ }
52
+ }
53
+ /* Inserts a task in the tasks array at the right position sorted by nextExecution time. */
54
+ insertTask(newTask) {
55
+ const index = __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").findIndex((task) => task.nextExecution.getTime() > newTask.nextExecution.getTime());
56
+ __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").splice(index, 0, newTask);
57
+ }
58
+ /* Registers a new task. */
59
+ registerTask(cron, task, opts) {
60
+ var _a;
61
+ const id = __classPrivateFieldGet(this, _IntervalBasedCronScheduler_nextTaskId, "f");
62
+ this.insertTask({
63
+ id,
64
+ cron,
65
+ nextExecution: cron.getNextDate(),
66
+ task,
67
+ isOneTimeTask: (_a = opts === null || opts === void 0 ? void 0 : opts.isOneTimeTask) !== null && _a !== void 0 ? _a : false,
68
+ errorHandler: opts === null || opts === void 0 ? void 0 : opts.errorHandler,
69
+ });
70
+ __classPrivateFieldSet(this, _IntervalBasedCronScheduler_nextTaskId, __classPrivateFieldGet(this, _IntervalBasedCronScheduler_nextTaskId, "f") + 1, "f");
71
+ return id;
72
+ }
73
+ /** Unregisters a task, causing it to no longer be executed. */
74
+ unregisterTask(id) {
75
+ const taskIndex = __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").findIndex((task) => task.id === id);
76
+ if (taskIndex === -1)
77
+ throw new Error('Task not found.');
78
+ __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").splice(taskIndex, 1);
79
+ }
80
+ /* Sorts the tasks array based on the next execution time so that the next task is first in the array. */
81
+ sortTasks() {
82
+ __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").sort((a, b) => {
83
+ return a.nextExecution.getTime() - b.nextExecution.getTime();
84
+ });
85
+ }
86
+ processTasks() {
87
+ const now = Date.now();
88
+ let taskExecuted = false;
89
+ let oneTimeTaskExecuted = false;
90
+ // Execute all due tasks and update nextExecution for non-one-time tasks.
91
+ for (let i = 0; i < __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").length; i += 1) {
92
+ const task = __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f")[i]; // eslint-disable-line security/detect-object-injection
93
+ if (task.nextExecution.getTime() <= now) {
94
+ wrapFunction(task.task, task.errorHandler)();
95
+ if (!task.isOneTimeTask) {
96
+ taskExecuted = true;
97
+ task.nextExecution = task.cron.getNextDate();
98
+ }
99
+ else {
100
+ oneTimeTaskExecuted = true;
101
+ }
102
+ }
103
+ else {
104
+ break;
105
+ }
106
+ }
107
+ if (oneTimeTaskExecuted) {
108
+ // Remove one time tasks.
109
+ __classPrivateFieldSet(this, _IntervalBasedCronScheduler_tasks, __classPrivateFieldGet(this, _IntervalBasedCronScheduler_tasks, "f").filter((task) => task.nextExecution.getTime() > now), "f");
110
+ }
111
+ // When at least one nextExecution time got updated (at least one non-one-time-task ran),
112
+ // we need to resort the tasks based on nextExecution.
113
+ if (taskExecuted) {
114
+ this.sortTasks();
115
+ }
116
+ }
117
+ }
118
+ _IntervalBasedCronScheduler_interval = new WeakMap(), _IntervalBasedCronScheduler_intervalId = new WeakMap(), _IntervalBasedCronScheduler_tasks = new WeakMap(), _IntervalBasedCronScheduler_nextTaskId = new WeakMap();
119
+ //# sourceMappingURL=interval-based.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interval-based.js","sourceRoot":"","sources":["../../src/schedulers/interval-based.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAW1C;;;;;;;;GAQG;AACH,MAAM,OAAO,0BAA0B;IAMrC;;OAEG;IACH,YAAmB,QAAgB;QARnC,uDAAiB;QACjB,yDAA4C;QAC5C,4CAAyB,EAAE,EAAA;QAC3B,iDAAc,CAAC;QAEf;;WAEG;UAJY;QAMb,uBAAA,IAAI,wCAAa,QAAQ,MAAA,CAAA;QACzB,IAAI,CAAC,KAAK,EAAE,CAAA;IACd,CAAC;IAED,2BAA2B;IACpB,KAAK;QACV,IAAI,uBAAA,IAAI,8CAAY,KAAK,SAAS,EAAE;YAClC,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC9C;QAED,uBAAA,IAAI,0CAAe,WAAW,CAAC,IAAI,CAAC,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AAM,CAC9B,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,GAAG,GAAG,CAC7C,MAAA,CAAA;SACF;QAED,yFAAyF;QACzF,sDAAsD;QACtD,IAAI,YAAY,EAAE;YAChB,IAAI,CAAC,SAAS,EAAE,CAAA;SACjB;IACH,CAAC;CACF"}
@@ -1,5 +1,5 @@
1
- import type { Cron } from '../cron';
2
- import { ITimerHandle } from '../utils';
1
+ import type { Cron } from '../cron.js';
2
+ import { ITimerHandle } from '../utils.js';
3
3
  /**
4
4
  * A cron scheduler that is based on timers.
5
5
  * It will create one timer for every scheduled cron.
@@ -0,0 +1,39 @@
1
+ import { longTimeout, wrapFunction } from '../utils.js';
2
+ /**
3
+ * A cron scheduler that is based on timers.
4
+ * It will create one timer for every scheduled cron.
5
+ * When the node timeout limit of ~24 days would be exceeded,
6
+ * it uses multiple consecutive timeouts.
7
+ */
8
+ export class TimerBasedCronScheduler {
9
+ /**
10
+ * Creates a timeout, which will fire the given task on the next cron date.
11
+ * Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.
12
+ */
13
+ static setTimeout(cron, task, opts) {
14
+ const nextSchedule = cron.getNextDate();
15
+ const timeout = nextSchedule.getTime() - Date.now();
16
+ return longTimeout(wrapFunction(task, opts === null || opts === void 0 ? void 0 : opts.errorHandler), timeout);
17
+ }
18
+ /**
19
+ * Creates an interval, which will fire the given task on every future cron date.
20
+ * Returns a handle which can be used to clear the interval using clearTimeoutOrInterval.
21
+ */
22
+ static setInterval(cron, task, opts) {
23
+ var _a;
24
+ const handle = (_a = opts === null || opts === void 0 ? void 0 : opts.handle) !== null && _a !== void 0 ? _a : { timeoutId: undefined };
25
+ const { timeoutId } = this.setTimeout(cron, () => {
26
+ wrapFunction(task, opts === null || opts === void 0 ? void 0 : opts.errorHandler)();
27
+ this.setInterval(cron, task, Object.assign(Object.assign({}, opts), { handle }));
28
+ });
29
+ handle.timeoutId = timeoutId;
30
+ return handle;
31
+ }
32
+ /** Clears a timeout or interval, making sure that the function will no longer execute. */
33
+ static clearTimeoutOrInterval(handle) {
34
+ if (handle.timeoutId) {
35
+ clearTimeout(handle.timeoutId);
36
+ }
37
+ }
38
+ }
39
+ //# sourceMappingURL=timer-based.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timer-based.js","sourceRoot":"","sources":["../../src/schedulers/timer-based.ts"],"names":[],"mappings":"AACA,OAAO,EAAgB,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAErE;;;;;GAKG;AACH,MAAM,OAAO,uBAAuB;IAClC;;;OAGG;IACI,MAAM,CAAC,UAAU,CACtB,IAAU,EACV,IAAmB,EACnB,IAAmD;QAEnD,MAAM,YAAY,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;QACvC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QAEnD,OAAO,WAAW,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,CAAC,EAAE,OAAO,CAAC,CAAA;IACrE,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,WAAW,CACvB,IAAU,EACV,IAAmB,EACnB,IAA0E;;QAE1E,MAAM,MAAM,GAAG,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,mCAAI,EAAE,SAAS,EAAE,SAAS,EAAE,CAAA;QAEvD,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,GAAG,EAAE;YAC/C,YAAY,CAAC,IAAI,EAAE,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,CAAC,EAAE,CAAA;YACxC,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,kCAAO,IAAI,KAAE,MAAM,IAAG,CAAA;QACnD,CAAC,CAAC,CAAA;QAEF,MAAM,CAAC,SAAS,GAAG,SAAS,CAAA;QAE5B,OAAO,MAAM,CAAA;IACf,CAAC;IAED,0FAA0F;IACnF,MAAM,CAAC,sBAAsB,CAAC,MAAoB;QACvD,IAAI,MAAM,CAAC,SAAS,EAAE;YACpB,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;SAC/B;IACH,CAAC;CACF"}
package/dist/utils.js ADDED
@@ -0,0 +1,70 @@
1
+ export const TIMEOUT_MAX = 2147483647; // 2^31-1
2
+ /**
3
+ * Creates a new timeout, which can exceed the max timeout limit of 2^31-1.
4
+ * Since multiple timeouts are used internally, the timeoutId used to clear the timeout
5
+ * is returned as a handle (object) and changes whenever the max timeout limit is exceeded.
6
+ * The handle parameter can be ignored, it is used internally for updating the timeoutId
7
+ * in the handle after creating the next timeout.
8
+ */
9
+ export function longTimeout(fn, timeout, handle) {
10
+ let after = 0;
11
+ if (timeout > TIMEOUT_MAX) {
12
+ after = timeout - TIMEOUT_MAX;
13
+ timeout = TIMEOUT_MAX;
14
+ }
15
+ handle !== null && handle !== void 0 ? handle : (handle = {
16
+ timeoutId: undefined,
17
+ });
18
+ handle.timeoutId = setTimeout(() => {
19
+ if (after > 0) {
20
+ longTimeout(fn, after, handle);
21
+ }
22
+ else {
23
+ fn();
24
+ }
25
+ }, timeout);
26
+ return handle;
27
+ }
28
+ /* Extracts second, minute, hour, date, month and the weekday from a date. */
29
+ export function extractDateElements(date) {
30
+ return {
31
+ second: date.getSeconds(),
32
+ minute: date.getMinutes(),
33
+ hour: date.getHours(),
34
+ day: date.getDate(),
35
+ month: date.getMonth(),
36
+ weekday: date.getDay(),
37
+ year: date.getFullYear(),
38
+ };
39
+ }
40
+ /* Gets the amount of days in the given month (indexed by 0) of the given year. */
41
+ export function getDaysInMonth(year, month) {
42
+ return new Date(year, month + 1, 0).getDate();
43
+ }
44
+ /* Gets the amount of days from weekday1 to weekday2. */
45
+ export function getDaysBetweenWeekdays(weekday1, weekday2) {
46
+ if (weekday1 <= weekday2) {
47
+ return weekday2 - weekday1;
48
+ }
49
+ return 6 - weekday1 + weekday2 + 1;
50
+ }
51
+ export function wrapFunction(fn, errorHandler) {
52
+ return () => {
53
+ try {
54
+ const res = fn();
55
+ if (res instanceof Promise) {
56
+ res.catch((err) => {
57
+ if (errorHandler) {
58
+ errorHandler(err);
59
+ }
60
+ });
61
+ }
62
+ }
63
+ catch (err) {
64
+ if (errorHandler) {
65
+ errorHandler(err);
66
+ }
67
+ }
68
+ };
69
+ }
70
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,WAAW,GAAG,UAAU,CAAA,CAAC,SAAS;AAM/C;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CACzB,EAAc,EACd,OAAe,EACf,MAAqB;IAErB,IAAI,KAAK,GAAG,CAAC,CAAA;IAEb,IAAI,OAAO,GAAG,WAAW,EAAE;QACzB,KAAK,GAAG,OAAO,GAAG,WAAW,CAAA;QAC7B,OAAO,GAAG,WAAW,CAAA;KACtB;IAED,MAAM,aAAN,MAAM,cAAN,MAAM,IAAN,MAAM,GAAK;QACT,SAAS,EAAE,SAAS;KACrB,EAAA;IAED,MAAM,CAAC,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE;QACjC,IAAI,KAAK,GAAG,CAAC,EAAE;YACb,WAAW,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;SAC/B;aAAM;YACL,EAAE,EAAE,CAAA;SACL;IACH,CAAC,EAAE,OAAO,CAAC,CAAA;IAEX,OAAO,MAAM,CAAA;AACf,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,mBAAmB,CAAC,IAAU;IAS5C,OAAO;QACL,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE;QACzB,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE;QACzB,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE;QACrB,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE;QACnB,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAE;QACtB,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE;QACtB,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE;KACzB,CAAA;AACH,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,cAAc,CAAC,IAAY,EAAE,KAAa;IACxD,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAA;AAC/C,CAAC;AAED,wDAAwD;AACxD,MAAM,UAAU,sBAAsB,CACpC,QAAgB,EAChB,QAAgB;IAEhB,IAAI,QAAQ,IAAI,QAAQ,EAAE;QACxB,OAAO,QAAQ,GAAG,QAAQ,CAAA;KAC3B;IAED,OAAO,CAAC,GAAG,QAAQ,GAAG,QAAQ,GAAG,CAAC,CAAA;AACpC,CAAC;AAED,MAAM,UAAU,YAAY,CAC1B,EAAiB,EACjB,YAAwC;IAExC,OAAO,GAAG,EAAE;QACV,IAAI;YACF,MAAM,GAAG,GAAG,EAAE,EAAE,CAAA;YAEhB,IAAI,GAAG,YAAY,OAAO,EAAE;gBAC1B,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;oBAChB,IAAI,YAAY,EAAE;wBAChB,YAAY,CAAC,GAAG,CAAC,CAAA;qBAClB;gBACH,CAAC,CAAC,CAAA;aACH;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,YAAY,EAAE;gBAChB,YAAY,CAAC,GAAG,CAAC,CAAA;aAClB;SACF;IACH,CAAC,CAAA;AACH,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cron-schedule",
3
3
  "description": "A zero-dependency cron parser and scheduler for Node.js, Deno and the browser.",
4
- "version": "3.0.5",
4
+ "version": "4.0.0-next.1",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -26,19 +26,37 @@
26
26
  "schedule-tasks",
27
27
  "nodejs"
28
28
  ],
29
- "main": "dist/cron-schedule.cjs.min.js",
30
- "module": "dist/cron-schedule.min.mjs",
31
- "unpkg": "dist/cron-schedule.iife.min.js",
29
+ "type": "module",
30
+ "packageManager": "yarn@3.2.0",
31
+ "engines": {
32
+ "node": ">=16"
33
+ },
34
+ "files": [
35
+ "dist/**/*.js",
36
+ "dist/**/*.js.map",
37
+ "dist/**/*.d.ts"
38
+ ],
32
39
  "exports": {
33
- "require": "./dist/cron-schedule.cjs.min.js",
34
- "import": "./dist/cron-schedule.min.mjs"
40
+ ".": {
41
+ "types": "./dist/index.d.ts",
42
+ "default": "./dist/index.js"
43
+ },
44
+ "./schedulers/interval-based.js": {
45
+ "type": "./dist/schedulerrs/interval-based.d.ts",
46
+ "default": "./dist/schedulers/interval-based.js"
47
+ },
48
+ "./schedulers/timer-based.js": {
49
+ "type": "./dist/schedulers/timer-based.d.ts",
50
+ "default": "./dist/schedulers/timer-based.js"
51
+ }
35
52
  },
53
+ "sideEffects": false,
36
54
  "release": {
37
55
  "branches": [
38
- "master",
56
+ "main",
39
57
  {
40
58
  "name": "next",
41
- "prelease": true
59
+ "prerelease": true
42
60
  }
43
61
  ],
44
62
  "preset": "angular",
@@ -58,60 +76,30 @@
58
76
  "@semantic-release/git"
59
77
  ]
60
78
  },
61
- "files": [
62
- "dist/**/*.js",
63
- "dist/**/*.js.map",
64
- "dist/**/*.mjs",
65
- "dist/**/*.mjs.map",
66
- "dist/**/*.d.ts"
67
- ],
68
- "types": "./dist/index.d.ts",
69
- "sideEffects": false,
70
79
  "scripts": {
71
- "build": "rimraf ./dist && tsc -p ./tsconfig.json --emitDeclarationOnly && node build.js",
80
+ "build": "rimraf ./dist && tsc -p ./tsconfig.json",
72
81
  "tsc:check": "tsc --project ./tsconfig.json --noEmit",
73
82
  "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
74
83
  "lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
75
- "test": "jest -c jest.config.js",
76
- "test:watch": "jest -c jest.config.js --watchAll",
77
- "prepack": "yarn build",
78
- "_postinstall": "husky install",
79
- "prepublishOnly": "pinst --disable",
80
- "postpublish": "pinst --enable"
84
+ "test": "vitest",
85
+ "test:run": "vitest run",
86
+ "prepack": "yarn build"
81
87
  },
82
88
  "devDependencies": {
83
- "@commitlint/cli": "16.2.1",
84
- "@commitlint/config-conventional": "16.2.1",
85
- "@commitlint/prompt-cli": "16.2.1",
86
- "@semantic-release/changelog": "6.0.1",
89
+ "@semantic-release/changelog": "6.0.3",
87
90
  "@semantic-release/git": "10.0.1",
88
- "@types/jest": "27.4.1",
89
- "@typescript-eslint/eslint-plugin": "5.12.1",
90
- "@typescript-eslint/parser": "5.12.1",
91
- "@typescript-eslint/typescript-estree": "5.12.1",
92
- "esbuild": "0.14.23",
93
- "eslint": "8.9.0",
94
- "eslint-config-prettier": "8.4.0",
95
- "eslint-plugin-import": "2.25.4",
96
- "eslint-plugin-prettier": "4.0.0",
97
- "eslint-plugin-security": "1.4.0",
98
- "husky": "7.0.4",
99
- "jest": "27.5.1",
100
- "pinst": "3.0.0",
101
- "prettier": "2.5.1",
102
- "rimraf": "3.0.2",
103
- "semantic-release": "19.0.2",
104
- "ts-jest": "27.1.3",
105
- "tslib": "2.3.1",
106
- "typescript": "4.5.5"
107
- },
108
- "resolutions": {
109
- "npm/chalk": "^4.1.2"
110
- },
111
- "commitlint": {
112
- "extends": [
113
- "@commitlint/config-conventional"
114
- ]
115
- },
116
- "packageManager": "yarn@3.2.0"
91
+ "@typescript-eslint/eslint-plugin": "5.57.0",
92
+ "@typescript-eslint/parser": "5.57.0",
93
+ "@typescript-eslint/typescript-estree": "5.57.0",
94
+ "eslint": "8.37.0",
95
+ "eslint-config-prettier": "8.8.0",
96
+ "eslint-plugin-import": "2.27.5",
97
+ "eslint-plugin-prettier": "4.2.1",
98
+ "eslint-plugin-security": "1.7.1",
99
+ "prettier": "2.8.7",
100
+ "rimraf": "4.4.1",
101
+ "semantic-release": "21.0.0",
102
+ "typescript": "5.0.2",
103
+ "vitest": "0.29.8"
104
+ }
117
105
  }
@@ -1,2 +0,0 @@
1
- var D=Object.defineProperty,z=Object.defineProperties,P=Object.getOwnPropertyDescriptor,B=Object.getOwnPropertyDescriptors,L=Object.getOwnPropertyNames,S=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable;var N=(r,e,n)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n,H=(r,e)=>{for(var n in e||(e={}))R.call(e,n)&&N(r,n,e[n]);if(S)for(var n of S(e))U.call(e,n)&&N(r,n,e[n]);return r},O=(r,e)=>z(r,B(e)),X=r=>D(r,"__esModule",{value:!0});var _=(r,e)=>{for(var n in e)D(r,n,{get:e[n],enumerable:!0})},j=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of L(e))!R.call(r,s)&&(n||s!=="default")&&D(r,s,{get:()=>e[s],enumerable:!(t=P(e,s))||t.enumerable});return r};var Y=(r=>(e,n)=>r&&r.get(e)||(n=j(X({}),e,1),r&&r.set(e,n),n))(typeof WeakMap!="undefined"?new WeakMap:0);var $=(r,e,n)=>{if(!e.has(r))throw TypeError("Cannot "+n)};var f=(r,e,n)=>($(r,e,"read from private field"),n?n.call(r):e.get(r)),v=(r,e,n)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,n)},p=(r,e,n,t)=>($(r,e,"write to private field"),t?t.call(r,n):e.set(r,n),n);var ne={};_(ne,{Cron:()=>M,IntervalBasedCronScheduler:()=>W,TIMEOUT_MAX:()=>re,TimerBasedCronScheduler:()=>F,extractDateElements:()=>I,getDaysBetweenWeekdays:()=>E,getDaysInMonth:()=>C,longTimeout:()=>A,parseCronExpression:()=>ee,wrapFunction:()=>g});var re=2147483647;function A(r,e,n){let t=0;return e>2147483647&&(t=e-2147483647,e=2147483647),n!=null||(n={timeoutId:void 0}),n.timeoutId=setTimeout(()=>{t>0?A(r,t,n):r()},e),n}function I(r){return{second:r.getSeconds(),minute:r.getMinutes(),hour:r.getHours(),day:r.getDate(),month:r.getMonth(),weekday:r.getDay(),year:r.getFullYear()}}function C(r,e){return new Date(r,e+1,0).getDate()}function E(r,e){return r<=e?e-r:6-r+e+1}function g(r,e){return()=>{try{let n=r();n instanceof Promise&&n.catch(t=>{e&&e(t)})}catch(n){e&&e(n)}}}var T,y,c,k,W=class{constructor(e){v(this,T,void 0);v(this,y,void 0);v(this,c,[]);v(this,k,1);p(this,T,e),this.start()}start(){if(f(this,y)!==void 0)throw new Error("Scheduler already started.");p(this,y,setInterval(this.processTasks.bind(this),f(this,T)))}stop(){f(this,y)&&(clearInterval(f(this,y)),p(this,y,void 0))}insertTask(e){let n=f(this,c).findIndex(t=>t.nextExecution.getTime()>e.nextExecution.getTime());f(this,c).splice(n,0,e)}registerTask(e,n,t){var o;let s=f(this,k);return this.insertTask({id:s,cron:e,nextExecution:e.getNextDate(),task:n,isOneTimeTask:(o=t==null?void 0:t.isOneTimeTask)!=null?o:!1,errorHandler:t==null?void 0:t.errorHandler}),p(this,k,f(this,k)+1),s}unregisterTask(e){let n=f(this,c).findIndex(t=>t.id===e);if(n===-1)throw new Error("Task not found.");f(this,c).splice(n,1)}sortTasks(){f(this,c).sort((e,n)=>e.nextExecution.getTime()-n.nextExecution.getTime())}processTasks(){let e=Date.now(),n=!1,t=!1;for(let s=0;s<f(this,c).length;s+=1){let o=f(this,c)[s];if(o.nextExecution.getTime()<=e)g(o.task,o.errorHandler)(),o.isOneTimeTask?t=!0:(n=!0,o.nextExecution=o.cron.getNextDate());else break}t&&p(this,c,f(this,c).filter(s=>s.nextExecution.getTime()>e)),n&&this.sortTasks()}};T=new WeakMap,y=new WeakMap,c=new WeakMap,k=new WeakMap;var F=class{static setTimeout(e,n,t){let o=e.getNextDate().getTime()-Date.now();return A(g(n,t==null?void 0:t.errorHandler),o)}static setInterval(e,n,t){var u;let s=(u=t==null?void 0:t.handle)!=null?u:{timeoutId:void 0},{timeoutId:o}=this.setTimeout(e,()=>{g(n,t==null?void 0:t.errorHandler)(),this.setInterval(e,n,O(H({},t),{handle:s}))});return s.timeoutId=o,s}static clearTimeoutOrInterval(e){e.timeoutId&&clearTimeout(e.timeoutId)}};var M=class{constructor({seconds:e,minutes:n,hours:t,days:s,months:o,weekdays:u}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!n||n.size===0)throw new Error("There must be at least one allowed minute.");if(!t||t.size===0)throw new Error("There must be at least one allowed hour.");if(!o||o.size===0)throw new Error("There must be at least one allowed month.");if((!u||u.size===0)&&(!s||s.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((i,d)=>i-d),this.minutes=Array.from(n).sort((i,d)=>i-d),this.hours=Array.from(t).sort((i,d)=>i-d),this.days=Array.from(s).sort((i,d)=>i-d),this.months=Array.from(o).sort((i,d)=>i-d),this.weekdays=Array.from(u).sort((i,d)=>i-d);let m=(i,d,a)=>{if(d.some(l=>typeof l!="number"||l%1!==0||l<a.min||l>a.max))throw new Error(`${i} must only consist of integers which are within the range of ${a.min} and ${a.max}`)};m("seconds",this.seconds,{min:0,max:59}),m("minutes",this.minutes,{min:0,max:59}),m("hours",this.hours,{min:0,max:23}),m("days",this.days,{min:1,max:31}),m("months",this.months,{min:0,max:11}),m("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(i=>i).reverse(),minutes:this.minutes.map(i=>i).reverse(),hours:this.hours.map(i=>i).reverse(),days:this.days.map(i=>i).reverse(),months:this.months.map(i=>i).reverse(),weekdays:this.weekdays.map(i=>i).reverse()}}findAllowedHour(e,n){return e==="next"?this.hours.find(t=>t>=n):this.reversed.hours.find(t=>t<=n)}findAllowedMinute(e,n){return e==="next"?this.minutes.find(t=>t>=n):this.reversed.minutes.find(t=>t<=n)}findAllowedSecond(e,n){return e==="next"?this.seconds.find(t=>t>n):this.reversed.seconds.find(t=>t<n)}findAllowedTime(e,n){let t=this.findAllowedHour(e,n.hour);if(t!==void 0)if(t===n.hour){let s=this.findAllowedMinute(e,n.minute);if(s!==void 0)if(s===n.minute){let o=this.findAllowedSecond(e,n.second);if(o!==void 0)return{hour:t,minute:s,second:o};if(s=this.findAllowedMinute(e,e==="next"?n.minute+1:n.minute-1),s!==void 0)return{hour:t,minute:s,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:t,minute:s,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(t=this.findAllowedHour(e,e==="next"?n.hour+1:n.hour-1),t!==void 0)return{hour:t,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:t,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,n,t,s){var a,l;if(s<1)throw new Error("startDay must not be smaller than 1.");let o=C(n,t),u=this.days.length!==31,m=this.weekdays.length!==7;if(!u&&!m)return s>o?e==="next"?void 0:o:s;let i;u&&(i=e==="next"?this.days.find(h=>h>=s):this.reversed.days.find(h=>h<=s),i!==void 0&&i>o&&(i=void 0));let d;if(m){let h=new Date(n,t,s).getDay(),x=e==="next"?(a=this.weekdays.find(b=>b>=h))!=null?a:this.weekdays[0]:(l=this.reversed.weekdays.find(b=>b<=h))!=null?l:this.reversed.weekdays[0];if(x!==void 0){let b=e==="next"?E(h,x):E(x,h);d=e==="next"?s+b:s-b,(d>o||d<1)&&(d=void 0)}}if(i!==void 0&&d!==void 0)return e==="next"?Math.min(i,d):Math.max(i,d);if(i!==void 0)return i;if(d!==void 0)return d}getNextDate(e=new Date){let n=I(e),t=n.year,s=this.months.findIndex(u=>u>=n.month);s===-1&&(s=0,t++);let o=this.months.length*5;for(let u=0;u<o;u++){let m=t+Math.floor((s+u)/this.months.length),i=this.months[(s+u)%this.months.length],d=m===n.year&&i===n.month,a=this.findAllowedDayInMonth("next",m,i,d?n.day:1),l=d&&a===n.day;if(a!==void 0&&l){let h=this.findAllowedTime("next",n);if(h!==void 0)return new Date(m,i,a,h.hour,h.minute,h.second);a=this.findAllowedDayInMonth("next",m,i,a+1),l=!1}if(a!==void 0&&!l)return new Date(m,i,a,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,n){let t=[],s;for(let o=0;o<e;o++)s=this.getNextDate(s!=null?s:n),t.push(s);return t}*getNextDatesIterator(e,n){let t;for(;;){if(t=this.getNextDate(e),e=t,n&&n.getTime()<t.getTime())return;yield t}}getPrevDate(e=new Date){let n=I(e),t=n.year,s=this.reversed.months.findIndex(u=>u<=n.month);s===-1&&(s=0,t--);let o=this.reversed.months.length*5;for(let u=0;u<o;u++){let m=t-Math.floor((s+u)/this.reversed.months.length),i=this.reversed.months[(s+u)%this.reversed.months.length],d=m===n.year&&i===n.month,a=this.findAllowedDayInMonth("prev",m,i,d?n.day:31),l=d&&a===n.day;if(a!==void 0&&l){let h=this.findAllowedTime("prev",n);if(h!==void 0)return new Date(m,i,a,h.hour,h.minute,h.second);a>1&&(a=this.findAllowedDayInMonth("prev",m,i,a-1),l=!1)}if(a!==void 0&&!l)return new Date(m,i,a,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,n){let t=[],s;for(let o=0;o<e;o++)s=this.getPrevDate(s!=null?s:n),t.push(s);return t}*getPrevDatesIterator(e,n){let t;for(;;){if(t=this.getPrevDate(e),e=t,n&&n.getTime()>t.getTime())return;yield t}}matchDate(e){let{second:n,minute:t,hour:s,day:o,month:u,weekday:m}=I(e);return this.seconds.indexOf(n)!==-1&&this.minutes.indexOf(t)!==-1&&this.hours.indexOf(s)!==-1&&this.months.indexOf(u)!==-1&&(this.days.indexOf(o)!==-1||this.weekdays.indexOf(m)!==-1)}};var G={min:0,max:59},Z={min:0,max:59},q={min:0,max:23},J={min:1,max:31},K={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Q={min:0,max:6,aliases:{"7":"0",sun:"0",mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6"}},V={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function w(r,e){let n=new Set;if(r==="*"){for(let a=e.min;a<=e.max;a=a+1)n.add(a);return n}let t=r.split(",");if(t.length>1)return t.forEach(a=>{w(a,e).forEach(h=>n.add(h))}),n;let s=a=>{var h,x;a=(x=(h=e.aliases)==null?void 0:h[a.toLowerCase()])!=null?x:a;let l=parseInt(a,10);if(Number.isNaN(l))throw new Error(`Failed to parse ${r}: ${a} is NaN.`);if(l<e.min||l>e.max)throw new Error(`Failed to parse ${r}: ${a} is outside of constraint range of ${e.min} - ${e.max}.`);return l},o=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(r);if(o===null)return n.add(s(r)),n;let u=o[1]==="*"?e.min:s(o[3]),m=o[1]==="*"?e.max:s(o[4]);if(u>m)throw new Error(`Failed to parse ${r}: Invalid range (start: ${u}, end: ${m}).`);let i=o[6],d=1;if(i!==void 0){if(d=parseInt(i,10),Number.isNaN(d))throw new Error(`Failed to parse step: ${i} is NaN.`);if(d<1)throw new Error(`Failed to parse step: Expected ${i} to be greater than 0.`)}for(let a=u;a<=m;a=a+d)n.add(a);return n}function ee(r){var i;if(typeof r!="string")throw new TypeError("Invalid cron expression: must be of type string.");r=(i=V[r.toLowerCase()])!=null?i:r;let e=r.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let n=e.length===6?e[0]:"0",t=e.length===6?e[1]:e[0],s=e.length===6?e[2]:e[1],o=e.length===6?e[3]:e[2],u=e.length===6?e[4]:e[3],m=e.length===6?e[5]:e[4];return new M({seconds:w(n,G),minutes:w(t,Z),hours:w(s,q),days:w(o,J),months:new Set(Array.from(w(u,K)).map(d=>d-1)),weekdays:w(m,Q)})}module.exports=Y(ne);0&&(module.exports={Cron,IntervalBasedCronScheduler,TIMEOUT_MAX,TimerBasedCronScheduler,extractDateElements,getDaysBetweenWeekdays,getDaysInMonth,longTimeout,parseCronExpression,wrapFunction});
2
- //# sourceMappingURL=cron-schedule.cjs.min.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.ts", "../src/utils.ts", "../src/schedulers/interval-based.ts", "../src/schedulers/timer-based.ts", "../src/cron.ts", "../src/cron-parser.ts"],
4
- "sourcesContent": ["export * from './schedulers/interval-based'\nexport * from './schedulers/timer-based'\nexport * from './cron-parser'\nexport * from './cron'\nexport * from './utils'\n", "export const TIMEOUT_MAX = 2147483647 // 2^31-1\n\nexport interface ITimerHandle {\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\n/**\n * Creates a new timeout, which can exceed the max timeout limit of 2^31-1.\n * Since multiple timeouts are used internally, the timeoutId used to clear the timeout\n * is returned as a handle (object) and changes whenever the max timeout limit is exceeded.\n * The handle parameter can be ignored, it is used internally for updating the timeoutId\n * in the handle after creating the next timeout.\n */\nexport function longTimeout(\n fn: () => void,\n timeout: number,\n handle?: ITimerHandle\n): ITimerHandle {\n let after = 0\n\n if (timeout > TIMEOUT_MAX) {\n after = timeout - TIMEOUT_MAX\n timeout = TIMEOUT_MAX\n }\n\n handle ??= {\n timeoutId: undefined,\n }\n\n handle.timeoutId = setTimeout(() => {\n if (after > 0) {\n longTimeout(fn, after, handle)\n } else {\n fn()\n }\n }, timeout)\n\n return handle\n}\n\n/* Extracts second, minute, hour, date, month and the weekday from a date. */\nexport function extractDateElements(date: Date): {\n second: number\n minute: number\n hour: number\n day: number\n month: number\n weekday: number\n year: number\n} {\n return {\n second: date.getSeconds(),\n minute: date.getMinutes(),\n hour: date.getHours(),\n day: date.getDate(),\n month: date.getMonth(),\n weekday: date.getDay(),\n year: date.getFullYear(),\n }\n}\n\n/* Gets the amount of days in the given month (indexed by 0) of the given year. */\nexport function getDaysInMonth(year: number, month: number): number {\n return new Date(year, month + 1, 0).getDate()\n}\n\n/* Gets the amount of days from weekday1 to weekday2. */\nexport function getDaysBetweenWeekdays(\n weekday1: number,\n weekday2: number\n): number {\n if (weekday1 <= weekday2) {\n return weekday2 - weekday1\n }\n\n return 6 - weekday1 + weekday2 + 1\n}\n\nexport function wrapFunction(\n fn: () => unknown,\n errorHandler?: (err: unknown) => unknown\n) {\n return () => {\n try {\n const res = fn()\n\n if (res instanceof Promise) {\n res.catch((err) => {\n if (errorHandler) {\n errorHandler(err)\n }\n })\n }\n } catch (err) {\n if (errorHandler) {\n errorHandler(err)\n }\n }\n }\n}\n", "import type { Cron } from '../cron'\nimport { wrapFunction } from '../utils'\n\ninterface ITaskWrapper {\n id: number\n cron: Cron\n nextExecution: Date\n task: () => unknown\n isOneTimeTask: boolean\n errorHandler?: (err: unknown) => unknown\n}\n\n/**\n * A cron scheduler that is based on a single interval.\n * Every interval, it checks whether a registered cron task\n * was due during the last interval and executes it.\n * This scheduler might be more performant depending on the use case,\n * because it only creates a single interval for all scheduled crons,\n * however depending on the interval and crons, tasks might be executed\n * with a delay.\n */\nexport class IntervalBasedCronScheduler {\n #interval: number\n #intervalId?: ReturnType<typeof setInterval>\n #tasks: ITaskWrapper[] = []\n #nextTaskId = 1\n\n /**\n * Creates and starts a new scheduler with the given interval.\n */\n public constructor(interval: number) {\n this.#interval = interval\n this.start()\n }\n\n /* Starts the scheduler. */\n public start(): void {\n if (this.#intervalId !== undefined) {\n throw new Error('Scheduler already started.')\n }\n\n this.#intervalId = setInterval(this.processTasks.bind(this), this.#interval)\n }\n\n /* Ensures the scheduler is stopped. */\n public stop(): void {\n if (this.#intervalId) {\n clearInterval(this.#intervalId)\n this.#intervalId = undefined\n }\n }\n\n /* Inserts a task in the tasks array at the right position sorted by nextExecution time. */\n private insertTask(newTask: ITaskWrapper) {\n const index = this.#tasks.findIndex(\n (task) => task.nextExecution.getTime() > newTask.nextExecution.getTime()\n )\n\n this.#tasks.splice(index, 0, newTask)\n }\n\n /* Registers a new task. */\n public registerTask(\n cron: Cron,\n task: () => unknown,\n opts?: {\n isOneTimeTask: boolean\n errorHandler?: (err: unknown) => unknown\n }\n ): number {\n const id = this.#nextTaskId\n\n this.insertTask({\n id,\n cron,\n nextExecution: cron.getNextDate(),\n task,\n isOneTimeTask: opts?.isOneTimeTask ?? false,\n errorHandler: opts?.errorHandler,\n })\n\n this.#nextTaskId += 1\n return id\n }\n\n /** Unregisters a task, causing it to no longer be executed. */\n public unregisterTask(id: number): void {\n const taskIndex = this.#tasks.findIndex((task) => task.id === id)\n if (taskIndex === -1) throw new Error('Task not found.')\n this.#tasks.splice(taskIndex, 1)\n }\n\n /* Sorts the tasks array based on the next execution time so that the next task is first in the array. */\n private sortTasks(): void {\n this.#tasks.sort((a, b) => {\n return a.nextExecution.getTime() - b.nextExecution.getTime()\n })\n }\n\n private processTasks(): void {\n const now = Date.now()\n let taskExecuted = false\n let oneTimeTaskExecuted = false\n\n // Execute all due tasks and update nextExecution for non-one-time tasks.\n for (let i = 0; i < this.#tasks.length; i += 1) {\n const task = this.#tasks[i]\n\n if (task.nextExecution.getTime() <= now) {\n wrapFunction(task.task, task.errorHandler)()\n\n if (!task.isOneTimeTask) {\n taskExecuted = true\n task.nextExecution = task.cron.getNextDate()\n } else {\n oneTimeTaskExecuted = true\n }\n } else {\n break\n }\n }\n\n if (oneTimeTaskExecuted) {\n // Remove one time tasks.\n this.#tasks = this.#tasks.filter(\n (task) => task.nextExecution.getTime() > now\n )\n }\n\n // When at least one nextExecution time got updated (at least one non-one-time-task ran),\n // we need to resort the tasks based on nextExecution.\n if (taskExecuted) {\n this.sortTasks()\n }\n }\n}\n", "import type { Cron } from '../cron'\nimport { ITimerHandle, longTimeout, wrapFunction } from '../utils'\n\n/**\n * A cron scheduler that is based on timers.\n * It will create one timer for every scheduled cron.\n * When the node timeout limit of ~24 days would be exceeded,\n * it uses multiple consecutive timeouts.\n */\nexport class TimerBasedCronScheduler {\n /**\n * Creates a timeout, which will fire the given task on the next cron date.\n * Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.\n */\n public static setTimeout(\n cron: Cron,\n task: () => unknown,\n opts?: { errorHandler?: (err: unknown) => unknown }\n ): ITimerHandle {\n const nextSchedule = cron.getNextDate()\n const timeout = nextSchedule.getTime() - Date.now()\n\n return longTimeout(wrapFunction(task, opts?.errorHandler), timeout)\n }\n\n /**\n * Creates an interval, which will fire the given task on every future cron date.\n * Returns a handle which can be used to clear the interval using clearTimeoutOrInterval.\n */\n public static setInterval(\n cron: Cron,\n task: () => unknown,\n opts?: { errorHandler?: (err: unknown) => unknown; handle?: ITimerHandle }\n ): ITimerHandle {\n const handle = opts?.handle ?? { timeoutId: undefined }\n\n const { timeoutId } = this.setTimeout(cron, () => {\n wrapFunction(task, opts?.errorHandler)()\n this.setInterval(cron, task, { ...opts, handle })\n })\n\n handle.timeoutId = timeoutId\n\n return handle\n }\n\n /** Clears a timeout or interval, making sure that the function will no longer execute. */\n public static clearTimeoutOrInterval(handle: ITimerHandle): void {\n if (handle.timeoutId) {\n clearTimeout(handle.timeoutId)\n }\n }\n}\n", "import {\n extractDateElements,\n getDaysBetweenWeekdays,\n getDaysInMonth,\n} from './utils'\n\n/**\n * An object with contains for each element of a date, which values are allowed.\n * Everything starting at 0, except for days.\n */\nexport interface ICronDefinition {\n readonly seconds: Set<number>\n readonly minutes: Set<number>\n readonly hours: Set<number>\n readonly days: Set<number>\n readonly months: Set<number>\n readonly weekdays: Set<number>\n}\n\nexport class Cron {\n // Everything starting at 0, except for days.\n public readonly seconds: ReadonlyArray<number>\n public readonly minutes: ReadonlyArray<number>\n public readonly hours: ReadonlyArray<number>\n public readonly days: ReadonlyArray<number>\n public readonly months: ReadonlyArray<number>\n public readonly weekdays: ReadonlyArray<number>\n\n public readonly reversed: {\n seconds: ReadonlyArray<number>\n minutes: ReadonlyArray<number>\n hours: ReadonlyArray<number>\n days: ReadonlyArray<number>\n months: ReadonlyArray<number>\n weekdays: ReadonlyArray<number>\n }\n\n public constructor({\n seconds,\n minutes,\n hours,\n days,\n months,\n weekdays,\n }: ICronDefinition) {\n // Validate that there are values provided.\n if (!seconds || seconds.size === 0)\n throw new Error('There must be at least one allowed second.')\n if (!minutes || minutes.size === 0)\n throw new Error('There must be at least one allowed minute.')\n if (!hours || hours.size === 0)\n throw new Error('There must be at least one allowed hour.')\n if (!months || months.size === 0)\n throw new Error('There must be at least one allowed month.')\n if ((!weekdays || weekdays.size === 0) && (!days || days.size === 0))\n throw new Error('There must be at least one allowed day or weekday.')\n\n // Convert set to array and sort in ascending order.\n this.seconds = Array.from(seconds).sort((a, b) => a - b)\n this.minutes = Array.from(minutes).sort((a, b) => a - b)\n this.hours = Array.from(hours).sort((a, b) => a - b)\n this.days = Array.from(days).sort((a, b) => a - b)\n this.months = Array.from(months).sort((a, b) => a - b)\n this.weekdays = Array.from(weekdays).sort((a, b) => a - b)\n\n // Validate that all values are integers within the constraint.\n const validateData = (\n name: string,\n data: ReadonlyArray<number>,\n constraint: { min: number; max: number }\n ) => {\n if (\n data.some(\n (x) =>\n typeof x !== 'number' ||\n x % 1 !== 0 ||\n x < constraint.min ||\n x > constraint.max\n )\n ) {\n throw new Error(\n `${name} must only consist of integers which are within the range of ${constraint.min} and ${constraint.max}`\n )\n }\n }\n\n validateData('seconds', this.seconds, { min: 0, max: 59 })\n validateData('minutes', this.minutes, { min: 0, max: 59 })\n validateData('hours', this.hours, { min: 0, max: 23 })\n validateData('days', this.days, { min: 1, max: 31 })\n validateData('months', this.months, { min: 0, max: 11 })\n validateData('weekdays', this.weekdays, { min: 0, max: 6 })\n\n // For each element, store a reversed copy in the reversed attribute for finding prev dates.\n this.reversed = {\n seconds: this.seconds.map((x) => x).reverse(),\n minutes: this.minutes.map((x) => x).reverse(),\n hours: this.hours.map((x) => x).reverse(),\n days: this.days.map((x) => x).reverse(),\n months: this.months.map((x) => x).reverse(),\n weekdays: this.weekdays.map((x) => x).reverse(),\n }\n }\n\n /**\n * Find the next or previous hour, starting from the given start hour that matches the hour constraint.\n * startHour itself might also be allowed.\n */\n private findAllowedHour(\n dir: 'next' | 'prev',\n startHour: number\n ): number | undefined {\n return dir === 'next'\n ? this.hours.find((x) => x >= startHour)\n : this.reversed.hours.find((x) => x <= startHour)\n }\n\n /**\n * Find the next or previous minute, starting from the given start minute that matches the minute constraint.\n * startMinute itself might also be allowed.\n */\n private findAllowedMinute(\n dir: 'next' | 'prev',\n startMinute: number\n ): number | undefined {\n return dir === 'next'\n ? this.minutes.find((x) => x >= startMinute)\n : this.reversed.minutes.find((x) => x <= startMinute)\n }\n\n /**\n * Find the next or previous second, starting from the given start second that matches the second constraint.\n * startSecond itself IS NOT allowed.\n */\n private findAllowedSecond(\n dir: 'next' | 'prev',\n startSecond: number\n ): number | undefined {\n return dir === 'next'\n ? this.seconds.find((x) => x > startSecond)\n : this.reversed.seconds.find((x) => x < startSecond)\n }\n\n /**\n * Find the next or previous time, starting from the given start time that matches the hour, minute\n * and second constraints. startTime itself might also be allowed.\n */\n private findAllowedTime(\n dir: 'next' | 'prev',\n startTime: { hour: number; minute: number; second: number }\n ): { hour: number; minute: number; second: number } | undefined {\n // Try to find an allowed hour.\n let hour = this.findAllowedHour(dir, startTime.hour)\n if (hour !== undefined) {\n if (hour === startTime.hour) {\n // We found an hour that is the start hour. Try to find an allowed minute.\n let minute = this.findAllowedMinute(dir, startTime.minute)\n if (minute !== undefined) {\n if (minute === startTime.minute) {\n // We found a minute that is the start minute. Try to find an allowed second.\n const second = this.findAllowedSecond(dir, startTime.second)\n if (second !== undefined) {\n // We found a second within the start hour and minute.\n return { hour, minute, second }\n } else {\n // We did not find a valid second within the start minute. Try to find another minute.\n minute = this.findAllowedMinute(\n dir,\n dir === 'next' ? startTime.minute + 1 : startTime.minute - 1\n )\n if (minute !== undefined) {\n // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.\n return {\n hour,\n minute,\n second:\n dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n }\n }\n }\n } else {\n // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.\n return {\n hour,\n minute,\n second:\n dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n }\n }\n }\n\n // We did not find an allowed minute / second combination inside the start hour. Try to find the next / previous allowed hour.\n hour = this.findAllowedHour(\n dir,\n dir === 'next' ? startTime.hour + 1 : startTime.hour - 1\n )\n if (hour !== undefined) {\n // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.\n return {\n hour,\n minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],\n second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n }\n }\n } else {\n // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.\n return {\n hour,\n minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],\n second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n }\n }\n }\n\n // No allowed time found.\n return undefined\n }\n\n /**\n * Find the next or previous day in the given month, starting from the given startDay\n * that matches either the day or the weekday constraint. startDay itself might also be allowed.\n */\n private findAllowedDayInMonth(\n dir: 'next' | 'prev',\n year: number,\n month: number,\n startDay: number\n ): number | undefined {\n if (startDay < 1) throw new Error('startDay must not be smaller than 1.')\n // If only days are restricted: allow day based on day constraint only..\n // If only weekdays are restricted: allow day based on weekday constraint only.\n // If both are restricted: allow day based on both day and weekday constraint. pick day that is closer to startDay.\n // If none are restricted: return the day closest to startDay (respecting dir) that is allowed (or startDay itself).\n\n const daysInMonth = getDaysInMonth(year, month)\n const daysRestricted = this.days.length !== 31\n const weekdaysRestricted = this.weekdays.length !== 7\n\n if (!daysRestricted && !weekdaysRestricted) {\n if (startDay > daysInMonth) {\n return dir === 'next' ? undefined : daysInMonth\n }\n\n return startDay\n }\n\n // Try to find a day based on the days constraint.\n let allowedDayByDays\n if (daysRestricted) {\n allowedDayByDays =\n dir === 'next'\n ? this.days.find((x) => x >= startDay)\n : this.reversed.days.find((x) => x <= startDay)\n\n // Make sure the day does not exceed the amount of days in month.\n if (allowedDayByDays !== undefined && allowedDayByDays > daysInMonth) {\n allowedDayByDays = undefined\n }\n }\n\n // Try to find a day based on the weekday constraint.\n let allowedDayByWeekdays\n if (weekdaysRestricted) {\n const startWeekday = new Date(year, month, startDay).getDay()\n const nearestAllowedWeekday =\n dir === 'next'\n ? this.weekdays.find((x) => x >= startWeekday) ?? this.weekdays[0]\n : this.reversed.weekdays.find((x) => x <= startWeekday) ??\n this.reversed.weekdays[0]\n\n if (nearestAllowedWeekday !== undefined) {\n const daysBetweenWeekdays =\n dir === 'next'\n ? getDaysBetweenWeekdays(startWeekday, nearestAllowedWeekday)\n : getDaysBetweenWeekdays(nearestAllowedWeekday, startWeekday)\n\n allowedDayByWeekdays =\n dir === 'next'\n ? startDay + daysBetweenWeekdays\n : startDay - daysBetweenWeekdays\n\n // Make sure the day does not exceed the month boundaries.\n if (allowedDayByWeekdays > daysInMonth || allowedDayByWeekdays < 1) {\n allowedDayByWeekdays = undefined\n }\n }\n }\n\n if (allowedDayByDays !== undefined && allowedDayByWeekdays !== undefined) {\n // If a day is found both via the days and the weekdays constraint, pick the day\n // that is closer to start date.\n return dir === 'next'\n ? Math.min(allowedDayByDays, allowedDayByWeekdays)\n : Math.max(allowedDayByDays, allowedDayByWeekdays)\n }\n\n if (allowedDayByDays !== undefined) {\n return allowedDayByDays\n }\n\n if (allowedDayByWeekdays !== undefined) {\n return allowedDayByWeekdays\n }\n\n return undefined\n }\n\n /** Gets the next date starting from the given start date or now. */\n public getNextDate(startDate: Date = new Date()): Date {\n const startDateElements = extractDateElements(startDate)\n let minYear = startDateElements.year\n\n let startIndexMonth = this.months.findIndex(\n (x) => x >= startDateElements.month\n )\n if (startIndexMonth === -1) {\n startIndexMonth = 0\n minYear++\n }\n\n // We try every month within the next 5 years to make sure that we tried to\n // find a matching date insidde a whole leap year.\n const maxIterations = this.months.length * 5\n\n for (let i = 0; i < maxIterations; i++) {\n // Get the next year and month.\n const year =\n minYear + Math.floor((startIndexMonth + i) / this.months.length)\n const month = this.months[(startIndexMonth + i) % this.months.length]\n const isStartMonth =\n year === startDateElements.year && month === startDateElements.month\n\n // Find the next day.\n let day = this.findAllowedDayInMonth(\n 'next',\n year,\n month,\n isStartMonth ? startDateElements.day : 1\n )\n let isStartDay = isStartMonth && day === startDateElements.day\n\n // If we found a day and it is the start day, try to find a valid time beginning from the start date time.\n if (day !== undefined && isStartDay) {\n const nextTime = this.findAllowedTime('next', startDateElements)\n if (nextTime !== undefined) {\n return new Date(\n year,\n month,\n day,\n nextTime.hour,\n nextTime.minute,\n nextTime.second\n )\n }\n\n // If no valid time has been found for the start date, try the next day.\n day = this.findAllowedDayInMonth('next', year, month, day + 1)\n isStartDay = false\n }\n\n // If we found a next day and it is not the start day, just use the next day with the first allowed values\n // for hours, minutes and seconds.\n if (day !== undefined && !isStartDay) {\n return new Date(\n year,\n month,\n day,\n this.hours[0],\n this.minutes[0],\n this.seconds[0]\n )\n }\n\n // No allowed day has been found for this month. Continue to search in next month.\n }\n\n throw new Error('No valid next date was found.')\n }\n\n /** Gets the specified amount of future dates starting from the given start date or now. */\n public getNextDates(amount: number, startDate?: Date): Date[] {\n const dates = []\n let nextDate\n\n for (let i = 0; i < amount; i++) {\n nextDate = this.getNextDate(nextDate ?? startDate)\n dates.push(nextDate)\n }\n\n return dates\n }\n\n /**\n * Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.\n * The iterator runs until the optional endDate is reached or forever.\n */\n public *getNextDatesIterator(\n startDate?: Date,\n endDate?: Date\n ): Generator<Date, undefined, undefined> {\n let nextDate\n\n while (true) {\n nextDate = this.getNextDate(startDate)\n startDate = nextDate\n\n if (endDate && endDate.getTime() < nextDate.getTime()) {\n return\n }\n\n yield nextDate\n }\n }\n\n /** Gets the previous date starting from the given start date or now. */\n public getPrevDate(startDate: Date = new Date()): Date {\n const startDateElements = extractDateElements(startDate)\n let maxYear = startDateElements.year\n\n let startIndexMonth = this.reversed.months.findIndex(\n (x) => x <= startDateElements.month\n )\n if (startIndexMonth === -1) {\n startIndexMonth = 0\n maxYear--\n }\n\n // We try every month within the past 5 years to make sure that we tried to\n // find a matching date insidde a whole leap year.\n const maxIterations = this.reversed.months.length * 5\n\n for (let i = 0; i < maxIterations; i++) {\n // Get the next year and month.\n const year =\n maxYear -\n Math.floor((startIndexMonth + i) / this.reversed.months.length)\n const month =\n this.reversed.months[\n (startIndexMonth + i) % this.reversed.months.length\n ]\n const isStartMonth =\n year === startDateElements.year && month === startDateElements.month\n\n // Find the previous day.\n let day = this.findAllowedDayInMonth(\n 'prev',\n year,\n month,\n isStartMonth ? startDateElements.day : 31\n )\n let isStartDay = isStartMonth && day === startDateElements.day\n\n // If we found a day and it is the start day, try to find a valid time beginning from the start date time.\n if (day !== undefined && isStartDay) {\n const prevTime = this.findAllowedTime('prev', startDateElements)\n if (prevTime !== undefined) {\n return new Date(\n year,\n month,\n day,\n prevTime.hour,\n prevTime.minute,\n prevTime.second\n )\n }\n\n // If no valid time has been found for the start date, try the previous day.\n if (day > 1) {\n day = this.findAllowedDayInMonth('prev', year, month, day - 1)\n isStartDay = false\n }\n }\n\n // If we found a previous day and it is not the start day, just use the previous day with the first allowed values\n // for hours, minutes and seconds (which will be the latest time due to using the reversed array).\n if (day !== undefined && !isStartDay) {\n return new Date(\n year,\n month,\n day,\n this.reversed.hours[0],\n this.reversed.minutes[0],\n this.reversed.seconds[0]\n )\n }\n\n // No allowed day has been found for this month. Continue to search in previous month.\n }\n\n throw new Error('No valid previous date was found.')\n }\n\n /** Gets the specified amount of previous dates starting from the given start date or now. */\n public getPrevDates(amount: number, startDate?: Date): Date[] {\n const dates = []\n let prevDate\n\n for (let i = 0; i < amount; i++) {\n prevDate = this.getPrevDate(prevDate ?? startDate)\n dates.push(prevDate)\n }\n\n return dates\n }\n\n /**\n * Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.\n * The iterator runs until the optional endDate is reached or forever.\n */\n public *getPrevDatesIterator(\n startDate?: Date,\n endDate?: Date\n ): Generator<Date, undefined, undefined> {\n let prevDate\n\n while (true) {\n prevDate = this.getPrevDate(startDate)\n startDate = prevDate\n\n if (endDate && endDate.getTime() > prevDate.getTime()) {\n return\n }\n\n yield prevDate\n }\n }\n\n /** Returns true when there is a cron date at the given date. */\n public matchDate(date: Date): boolean {\n const { second, minute, hour, day, month, weekday } =\n extractDateElements(date)\n\n return (\n this.seconds.indexOf(second) !== -1 &&\n this.minutes.indexOf(minute) !== -1 &&\n this.hours.indexOf(hour) !== -1 &&\n this.months.indexOf(month) !== -1 &&\n (this.days.indexOf(day) !== -1 || this.weekdays.indexOf(weekday) !== -1)\n )\n }\n}\n", "import { Cron } from './cron'\n\ninterface IConstraint {\n min: number\n max: number\n aliases?: Record<string, string>\n}\n\nconst secondConstraint: IConstraint = {\n min: 0,\n max: 59,\n}\n\nconst minuteConstraint: IConstraint = {\n min: 0,\n max: 59,\n}\n\nconst hourConstraint: IConstraint = {\n min: 0,\n max: 23,\n}\n\nconst dayConstraint: IConstraint = {\n min: 1,\n max: 31,\n}\n\nconst monthConstraint: IConstraint = {\n min: 1,\n max: 12,\n aliases: {\n jan: '1',\n feb: '2',\n mar: '3',\n apr: '4',\n may: '5',\n jun: '6',\n jul: '7',\n aug: '8',\n sep: '9',\n oct: '10',\n nov: '11',\n dec: '12',\n },\n}\n\nconst weekdayConstraint: IConstraint = {\n min: 0,\n max: 6,\n aliases: {\n '7': '0',\n 'sun': '0',\n 'mon': '1',\n 'tue': '2',\n 'wed': '3',\n 'thu': '4',\n 'fri': '5',\n 'sat': '6',\n },\n}\n\nconst timeNicknames: Record<string, string | undefined> = {\n '@yearly': '0 0 1 1 *',\n '@annually': '0 0 1 1 *',\n '@monthly': '0 0 1 1 *',\n '@weekly': '0 0 * * 0',\n '@daily': '0 0 * * *',\n '@hourly': '0 * * * *',\n '@minutely': '* * * * *',\n}\n\nfunction parseElement(element: string, constraint: IConstraint): Set<number> {\n const result = new Set<number>()\n\n // If returned set of numbers is empty, the scheduler class interpretes the emtpy set of numbers as all valid values of the constraint\n if (element === '*') {\n for (let i = constraint.min; i <= constraint.max; i = i + 1) {\n result.add(i)\n }\n\n return result\n }\n\n // If the element is a list, parse each element in the list.\n const listElements = element.split(',')\n if (listElements.length > 1) {\n listElements.forEach((listElement) => {\n const parsedListElement = parseElement(listElement, constraint)\n parsedListElement.forEach((x) => result.add(x))\n })\n\n return result\n }\n\n // Helper function to parse a single element, which includes checking for alias, valid number and constraint min and max.\n const parseSingleElement = (singleElement: string): number => {\n singleElement =\n constraint.aliases?.[singleElement.toLowerCase()] ?? singleElement\n const parsedElement = parseInt(singleElement, 10)\n\n if (Number.isNaN(parsedElement)) {\n throw new Error(`Failed to parse ${element}: ${singleElement} is NaN.`)\n }\n\n if (parsedElement < constraint.min || parsedElement > constraint.max) {\n throw new Error(\n `Failed to parse ${element}: ${singleElement} is outside of constraint range of ${constraint.min} - ${constraint.max}.`\n )\n }\n\n return parsedElement\n }\n\n // Detect if the element is a range.\n /* eslint-disable security/detect-unsafe-regex */\n const rangeSegments =\n /^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\\*)(\\/([0-9]+))?$/.exec(element)\n /* eslint-enable security/detect-unsafe-regex */\n\n // If not, it must be a single element.\n if (rangeSegments === null) {\n result.add(parseSingleElement(element))\n return result\n }\n\n // If it is a range, get start and end of the range.\n const parsedStart =\n rangeSegments[1] === '*'\n ? constraint.min\n : parseSingleElement(rangeSegments[3])\n\n const parsedEnd =\n rangeSegments[1] === '*'\n ? constraint.max\n : parseSingleElement(rangeSegments[4])\n\n if (parsedStart > parsedEnd) {\n throw new Error(\n `Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`\n )\n }\n\n // Check whether there is a custom step defined for the range, defaulting to 1.\n const step = rangeSegments[6] as string | undefined\n let parsedStep = 1\n\n if (step !== undefined) {\n parsedStep = parseInt(step, 10)\n if (Number.isNaN(parsedStep)) {\n throw new Error(`Failed to parse step: ${step} is NaN.`)\n } else if (parsedStep < 1) {\n throw new Error(\n `Failed to parse step: Expected ${step} to be greater than 0.`\n )\n }\n }\n\n // Go from start to end of the range by the given steps.\n for (let i = parsedStart; i <= parsedEnd; i = i + parsedStep) {\n result.add(i)\n }\n\n return result\n}\n\n/** Parses a cron expression into a Cron instance. */\nexport function parseCronExpression(cronExpression: string): Cron {\n if (typeof cronExpression !== 'string') {\n throw new TypeError('Invalid cron expression: must be of type string.')\n }\n\n // Convert time nicknames.\n cronExpression = timeNicknames[cronExpression.toLowerCase()] ?? cronExpression\n\n const elements = cronExpression.split(' ')\n if (elements.length < 5 || elements.length > 6) {\n throw new Error('Invalid cron expression: expected 5 or 6 elements.')\n }\n\n const rawSeconds = elements.length === 6 ? elements[0] : '0'\n const rawMinutes = elements.length === 6 ? elements[1] : elements[0]\n const rawHours = elements.length === 6 ? elements[2] : elements[1]\n const rawDays = elements.length === 6 ? elements[3] : elements[2]\n const rawMonths = elements.length === 6 ? elements[4] : elements[3]\n const rawWeekdays = elements.length === 6 ? elements[5] : elements[4]\n\n return new Cron({\n seconds: parseElement(rawSeconds, secondConstraint),\n minutes: parseElement(rawMinutes, minuteConstraint),\n hours: parseElement(rawHours, hourConstraint),\n days: parseElement(rawDays, dayConstraint),\n // months in cron are indexed by 1, but Cron expects indexes by 0, so we need to reduce all set values by one.\n months: new Set(\n Array.from(parseElement(rawMonths, monthConstraint)).map((x) => x - 1)\n ),\n weekdays: parseElement(rawWeekdays, weekdayConstraint),\n })\n}\n"],
5
- "mappings": "wrCAAA,2PCAO,GAAM,IAAc,WAapB,WACL,EACA,EACA,EACc,CACd,GAAI,GAAQ,EAEZ,MAAI,GAAU,YACZ,GAAQ,EAAU,WAClB,EAAU,YAGZ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I,EAAS,GAAK,EAAS,GAC1D,EAAU,EAAS,SAAW,EAAI,EAAS,GAAK,EAAS,GACzD,EAAY,EAAS,SAAW,EAAI,EAAS,GAAK,EAAS,GAC3D,EAAc,EAAS,SAAW,EAAI,EAAS,GAAK,EAAS,GAEnE,MAAO,IAAI,GAAK,CACd,QAAS,EAAa,EAAY,GAClC,QAAS,EAAa,EAAY,GAClC,MAAO,EAAa,EAAU,GAC9B,KAAM,EAAa,EAAS,GAE5B,OAAQ,GAAI,KACV,MAAM,KAAK,EAAa,EAAW,IAAkB,IAAI,AAAC,GAAM,EAAI,IAEtE,SAAU,EAAa,EAAa",
6
- "names": []
7
- }
@@ -1,2 +0,0 @@
1
- var cronSchedule=(()=>{var D=Object.defineProperty,z=Object.defineProperties,P=Object.getOwnPropertyDescriptor,B=Object.getOwnPropertyDescriptors,L=Object.getOwnPropertyNames,S=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable;var N=(r,e,n)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n,H=(r,e)=>{for(var n in e||(e={}))R.call(e,n)&&N(r,n,e[n]);if(S)for(var n of S(e))U.call(e,n)&&N(r,n,e[n]);return r},O=(r,e)=>z(r,B(e)),X=r=>D(r,"__esModule",{value:!0});var _=(r,e)=>{for(var n in e)D(r,n,{get:e[n],enumerable:!0})},j=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of L(e))!R.call(r,s)&&(n||s!=="default")&&D(r,s,{get:()=>e[s],enumerable:!(t=P(e,s))||t.enumerable});return r};var Y=(r=>(e,n)=>r&&r.get(e)||(n=j(X({}),e,1),r&&r.set(e,n),n))(typeof WeakMap!="undefined"?new WeakMap:0);var $=(r,e,n)=>{if(!e.has(r))throw TypeError("Cannot "+n)};var f=(r,e,n)=>($(r,e,"read from private field"),n?n.call(r):e.get(r)),v=(r,e,n)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,n)},p=(r,e,n,t)=>($(r,e,"write to private field"),t?t.call(r,n):e.set(r,n),n);var ne={};_(ne,{Cron:()=>M,IntervalBasedCronScheduler:()=>W,TIMEOUT_MAX:()=>re,TimerBasedCronScheduler:()=>F,extractDateElements:()=>I,getDaysBetweenWeekdays:()=>E,getDaysInMonth:()=>C,longTimeout:()=>A,parseCronExpression:()=>ee,wrapFunction:()=>g});var re=2147483647;function A(r,e,n){let t=0;return e>2147483647&&(t=e-2147483647,e=2147483647),n!=null||(n={timeoutId:void 0}),n.timeoutId=setTimeout(()=>{t>0?A(r,t,n):r()},e),n}function I(r){return{second:r.getSeconds(),minute:r.getMinutes(),hour:r.getHours(),day:r.getDate(),month:r.getMonth(),weekday:r.getDay(),year:r.getFullYear()}}function C(r,e){return new Date(r,e+1,0).getDate()}function E(r,e){return r<=e?e-r:6-r+e+1}function g(r,e){return()=>{try{let n=r();n instanceof Promise&&n.catch(t=>{e&&e(t)})}catch(n){e&&e(n)}}}var T,y,c,k,W=class{constructor(e){v(this,T,void 0);v(this,y,void 0);v(this,c,[]);v(this,k,1);p(this,T,e),this.start()}start(){if(f(this,y)!==void 0)throw new Error("Scheduler already started.");p(this,y,setInterval(this.processTasks.bind(this),f(this,T)))}stop(){f(this,y)&&(clearInterval(f(this,y)),p(this,y,void 0))}insertTask(e){let n=f(this,c).findIndex(t=>t.nextExecution.getTime()>e.nextExecution.getTime());f(this,c).splice(n,0,e)}registerTask(e,n,t){var o;let s=f(this,k);return this.insertTask({id:s,cron:e,nextExecution:e.getNextDate(),task:n,isOneTimeTask:(o=t==null?void 0:t.isOneTimeTask)!=null?o:!1,errorHandler:t==null?void 0:t.errorHandler}),p(this,k,f(this,k)+1),s}unregisterTask(e){let n=f(this,c).findIndex(t=>t.id===e);if(n===-1)throw new Error("Task not found.");f(this,c).splice(n,1)}sortTasks(){f(this,c).sort((e,n)=>e.nextExecution.getTime()-n.nextExecution.getTime())}processTasks(){let e=Date.now(),n=!1,t=!1;for(let s=0;s<f(this,c).length;s+=1){let o=f(this,c)[s];if(o.nextExecution.getTime()<=e)g(o.task,o.errorHandler)(),o.isOneTimeTask?t=!0:(n=!0,o.nextExecution=o.cron.getNextDate());else break}t&&p(this,c,f(this,c).filter(s=>s.nextExecution.getTime()>e)),n&&this.sortTasks()}};T=new WeakMap,y=new WeakMap,c=new WeakMap,k=new WeakMap;var F=class{static setTimeout(e,n,t){let o=e.getNextDate().getTime()-Date.now();return A(g(n,t==null?void 0:t.errorHandler),o)}static setInterval(e,n,t){var u;let s=(u=t==null?void 0:t.handle)!=null?u:{timeoutId:void 0},{timeoutId:o}=this.setTimeout(e,()=>{g(n,t==null?void 0:t.errorHandler)(),this.setInterval(e,n,O(H({},t),{handle:s}))});return s.timeoutId=o,s}static clearTimeoutOrInterval(e){e.timeoutId&&clearTimeout(e.timeoutId)}};var M=class{constructor({seconds:e,minutes:n,hours:t,days:s,months:o,weekdays:u}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!n||n.size===0)throw new Error("There must be at least one allowed minute.");if(!t||t.size===0)throw new Error("There must be at least one allowed hour.");if(!o||o.size===0)throw new Error("There must be at least one allowed month.");if((!u||u.size===0)&&(!s||s.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((i,d)=>i-d),this.minutes=Array.from(n).sort((i,d)=>i-d),this.hours=Array.from(t).sort((i,d)=>i-d),this.days=Array.from(s).sort((i,d)=>i-d),this.months=Array.from(o).sort((i,d)=>i-d),this.weekdays=Array.from(u).sort((i,d)=>i-d);let m=(i,d,a)=>{if(d.some(l=>typeof l!="number"||l%1!==0||l<a.min||l>a.max))throw new Error(`${i} must only consist of integers which are within the range of ${a.min} and ${a.max}`)};m("seconds",this.seconds,{min:0,max:59}),m("minutes",this.minutes,{min:0,max:59}),m("hours",this.hours,{min:0,max:23}),m("days",this.days,{min:1,max:31}),m("months",this.months,{min:0,max:11}),m("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(i=>i).reverse(),minutes:this.minutes.map(i=>i).reverse(),hours:this.hours.map(i=>i).reverse(),days:this.days.map(i=>i).reverse(),months:this.months.map(i=>i).reverse(),weekdays:this.weekdays.map(i=>i).reverse()}}findAllowedHour(e,n){return e==="next"?this.hours.find(t=>t>=n):this.reversed.hours.find(t=>t<=n)}findAllowedMinute(e,n){return e==="next"?this.minutes.find(t=>t>=n):this.reversed.minutes.find(t=>t<=n)}findAllowedSecond(e,n){return e==="next"?this.seconds.find(t=>t>n):this.reversed.seconds.find(t=>t<n)}findAllowedTime(e,n){let t=this.findAllowedHour(e,n.hour);if(t!==void 0)if(t===n.hour){let s=this.findAllowedMinute(e,n.minute);if(s!==void 0)if(s===n.minute){let o=this.findAllowedSecond(e,n.second);if(o!==void 0)return{hour:t,minute:s,second:o};if(s=this.findAllowedMinute(e,e==="next"?n.minute+1:n.minute-1),s!==void 0)return{hour:t,minute:s,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:t,minute:s,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(t=this.findAllowedHour(e,e==="next"?n.hour+1:n.hour-1),t!==void 0)return{hour:t,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:t,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,n,t,s){var a,l;if(s<1)throw new Error("startDay must not be smaller than 1.");let o=C(n,t),u=this.days.length!==31,m=this.weekdays.length!==7;if(!u&&!m)return s>o?e==="next"?void 0:o:s;let i;u&&(i=e==="next"?this.days.find(h=>h>=s):this.reversed.days.find(h=>h<=s),i!==void 0&&i>o&&(i=void 0));let d;if(m){let h=new Date(n,t,s).getDay(),x=e==="next"?(a=this.weekdays.find(b=>b>=h))!=null?a:this.weekdays[0]:(l=this.reversed.weekdays.find(b=>b<=h))!=null?l:this.reversed.weekdays[0];if(x!==void 0){let b=e==="next"?E(h,x):E(x,h);d=e==="next"?s+b:s-b,(d>o||d<1)&&(d=void 0)}}if(i!==void 0&&d!==void 0)return e==="next"?Math.min(i,d):Math.max(i,d);if(i!==void 0)return i;if(d!==void 0)return d}getNextDate(e=new Date){let n=I(e),t=n.year,s=this.months.findIndex(u=>u>=n.month);s===-1&&(s=0,t++);let o=this.months.length*5;for(let u=0;u<o;u++){let m=t+Math.floor((s+u)/this.months.length),i=this.months[(s+u)%this.months.length],d=m===n.year&&i===n.month,a=this.findAllowedDayInMonth("next",m,i,d?n.day:1),l=d&&a===n.day;if(a!==void 0&&l){let h=this.findAllowedTime("next",n);if(h!==void 0)return new Date(m,i,a,h.hour,h.minute,h.second);a=this.findAllowedDayInMonth("next",m,i,a+1),l=!1}if(a!==void 0&&!l)return new Date(m,i,a,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,n){let t=[],s;for(let o=0;o<e;o++)s=this.getNextDate(s!=null?s:n),t.push(s);return t}*getNextDatesIterator(e,n){let t;for(;;){if(t=this.getNextDate(e),e=t,n&&n.getTime()<t.getTime())return;yield t}}getPrevDate(e=new Date){let n=I(e),t=n.year,s=this.reversed.months.findIndex(u=>u<=n.month);s===-1&&(s=0,t--);let o=this.reversed.months.length*5;for(let u=0;u<o;u++){let m=t-Math.floor((s+u)/this.reversed.months.length),i=this.reversed.months[(s+u)%this.reversed.months.length],d=m===n.year&&i===n.month,a=this.findAllowedDayInMonth("prev",m,i,d?n.day:31),l=d&&a===n.day;if(a!==void 0&&l){let h=this.findAllowedTime("prev",n);if(h!==void 0)return new Date(m,i,a,h.hour,h.minute,h.second);a>1&&(a=this.findAllowedDayInMonth("prev",m,i,a-1),l=!1)}if(a!==void 0&&!l)return new Date(m,i,a,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,n){let t=[],s;for(let o=0;o<e;o++)s=this.getPrevDate(s!=null?s:n),t.push(s);return t}*getPrevDatesIterator(e,n){let t;for(;;){if(t=this.getPrevDate(e),e=t,n&&n.getTime()>t.getTime())return;yield t}}matchDate(e){let{second:n,minute:t,hour:s,day:o,month:u,weekday:m}=I(e);return this.seconds.indexOf(n)!==-1&&this.minutes.indexOf(t)!==-1&&this.hours.indexOf(s)!==-1&&this.months.indexOf(u)!==-1&&(this.days.indexOf(o)!==-1||this.weekdays.indexOf(m)!==-1)}};var G={min:0,max:59},Z={min:0,max:59},q={min:0,max:23},J={min:1,max:31},K={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Q={min:0,max:6,aliases:{"7":"0",sun:"0",mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6"}},V={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function w(r,e){let n=new Set;if(r==="*"){for(let a=e.min;a<=e.max;a=a+1)n.add(a);return n}let t=r.split(",");if(t.length>1)return t.forEach(a=>{w(a,e).forEach(h=>n.add(h))}),n;let s=a=>{var h,x;a=(x=(h=e.aliases)==null?void 0:h[a.toLowerCase()])!=null?x:a;let l=parseInt(a,10);if(Number.isNaN(l))throw new Error(`Failed to parse ${r}: ${a} is NaN.`);if(l<e.min||l>e.max)throw new Error(`Failed to parse ${r}: ${a} is outside of constraint range of ${e.min} - ${e.max}.`);return l},o=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(r);if(o===null)return n.add(s(r)),n;let u=o[1]==="*"?e.min:s(o[3]),m=o[1]==="*"?e.max:s(o[4]);if(u>m)throw new Error(`Failed to parse ${r}: Invalid range (start: ${u}, end: ${m}).`);let i=o[6],d=1;if(i!==void 0){if(d=parseInt(i,10),Number.isNaN(d))throw new Error(`Failed to parse step: ${i} is NaN.`);if(d<1)throw new Error(`Failed to parse step: Expected ${i} to be greater than 0.`)}for(let a=u;a<=m;a=a+d)n.add(a);return n}function ee(r){var i;if(typeof r!="string")throw new TypeError("Invalid cron expression: must be of type string.");r=(i=V[r.toLowerCase()])!=null?i:r;let e=r.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let n=e.length===6?e[0]:"0",t=e.length===6?e[1]:e[0],s=e.length===6?e[2]:e[1],o=e.length===6?e[3]:e[2],u=e.length===6?e[4]:e[3],m=e.length===6?e[5]:e[4];return new M({seconds:w(n,G),minutes:w(t,Z),hours:w(s,q),days:w(o,J),months:new Set(Array.from(w(u,K)).map(d=>d-1)),weekdays:w(m,Q)})}return Y(ne);})();
2
- //# sourceMappingURL=cron-schedule.iife.min.js.map