@warlock.js/scheduler 4.0.174 → 4.1.2

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.
Files changed (69) hide show
  1. package/README.md +60 -1
  2. package/cjs/index.cjs +1132 -0
  3. package/cjs/index.cjs.map +1 -0
  4. package/esm/cron-parser.d.mts +129 -0
  5. package/esm/cron-parser.d.mts.map +1 -0
  6. package/esm/cron-parser.mjs +210 -0
  7. package/esm/cron-parser.mjs.map +1 -0
  8. package/esm/index.d.mts +5 -0
  9. package/esm/index.mjs +5 -0
  10. package/esm/job.d.mts +386 -0
  11. package/esm/job.d.mts.map +1 -0
  12. package/esm/job.mjs +633 -0
  13. package/esm/job.mjs.map +1 -0
  14. package/esm/scheduler.d.mts +193 -0
  15. package/esm/scheduler.d.mts.map +1 -0
  16. package/esm/scheduler.mjs +261 -0
  17. package/esm/scheduler.mjs.map +1 -0
  18. package/esm/types.d.mts +70 -0
  19. package/esm/types.d.mts.map +1 -0
  20. package/llms-full.txt +888 -0
  21. package/llms.txt +15 -0
  22. package/package.json +40 -28
  23. package/skills/configure-retry-and-overlap/SKILL.md +137 -0
  24. package/skills/observe-scheduler/SKILL.md +153 -0
  25. package/skills/overview/SKILL.md +92 -0
  26. package/skills/pin-schedule-timezone/SKILL.md +114 -0
  27. package/skills/schedule-fluently/SKILL.md +141 -0
  28. package/skills/schedule-with-cron/SKILL.md +123 -0
  29. package/skills/scheduler-basics/SKILL.md +94 -0
  30. package/cjs/cron-parser.d.ts +0 -98
  31. package/cjs/cron-parser.d.ts.map +0 -1
  32. package/cjs/cron-parser.js +0 -193
  33. package/cjs/cron-parser.js.map +0 -1
  34. package/cjs/index.d.ts +0 -44
  35. package/cjs/index.d.ts.map +0 -1
  36. package/cjs/index.js +0 -1
  37. package/cjs/index.js.map +0 -1
  38. package/cjs/job.d.ts +0 -332
  39. package/cjs/job.d.ts.map +0 -1
  40. package/cjs/job.js +0 -616
  41. package/cjs/job.js.map +0 -1
  42. package/cjs/scheduler.d.ts +0 -182
  43. package/cjs/scheduler.d.ts.map +0 -1
  44. package/cjs/scheduler.js +0 -316
  45. package/cjs/scheduler.js.map +0 -1
  46. package/cjs/types.d.ts +0 -63
  47. package/cjs/types.d.ts.map +0 -1
  48. package/cjs/utils.d.ts +0 -3
  49. package/cjs/utils.d.ts.map +0 -1
  50. package/esm/cron-parser.d.ts +0 -98
  51. package/esm/cron-parser.d.ts.map +0 -1
  52. package/esm/cron-parser.js +0 -193
  53. package/esm/cron-parser.js.map +0 -1
  54. package/esm/index.d.ts +0 -44
  55. package/esm/index.d.ts.map +0 -1
  56. package/esm/index.js +0 -1
  57. package/esm/index.js.map +0 -1
  58. package/esm/job.d.ts +0 -332
  59. package/esm/job.d.ts.map +0 -1
  60. package/esm/job.js +0 -616
  61. package/esm/job.js.map +0 -1
  62. package/esm/scheduler.d.ts +0 -182
  63. package/esm/scheduler.d.ts.map +0 -1
  64. package/esm/scheduler.js +0 -316
  65. package/esm/scheduler.js.map +0 -1
  66. package/esm/types.d.ts +0 -63
  67. package/esm/types.d.ts.map +0 -1
  68. package/esm/utils.d.ts +0 -3
  69. package/esm/utils.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["utc","timezone","isSameOrAfter","EventEmitter"],"sources":["../../../../../@warlock.js/scheduler/src/cron-parser.ts","../../../../../@warlock.js/scheduler/src/job.ts","../../../../../@warlock.js/scheduler/src/scheduler.ts"],"sourcesContent":["import dayjs, { type Dayjs } from \"dayjs\";\n\n/**\n * Parsed cron expression fields\n */\nexport type CronFields = {\n /** Minutes (0-59) */\n minutes: number[];\n /** Hours (0-23) */\n hours: number[];\n /** Days of month (1-31) */\n daysOfMonth: number[];\n /** Months (1-12) */\n months: number[];\n /** Days of week (0-6, Sunday = 0) */\n daysOfWeek: number[];\n};\n\n/**\n * Cron expression parser\n *\n * Supports standard 5-field cron expressions:\n * ```\n * ┌───────────── minute (0-59)\n * │ ┌───────────── hour (0-23)\n * │ │ ┌───────────── day of month (1-31)\n * │ │ │ ┌───────────── month (1-12)\n * │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)\n * │ │ │ │ │\n * * * * * *\n * ```\n *\n * Supports:\n * - `*` - any value\n * - `5` - specific value\n * - `1,3,5` - list of values\n * - `1-5` - range of values\n * - `*‍/5` - step values (every 5)\n * - `1-10/2` - range with step\n *\n * **Day-of-month / day-of-week semantics:** follows Vixie cron — when both\n * fields are restricted (neither is `*`), a date matches if it satisfies\n * EITHER constraint. When only one is restricted, the other is ignored.\n *\n * @example\n * ```typescript\n * const parser = new CronParser(\"0 9 * * 1-5\"); // 9 AM weekdays\n * const nextRun = parser.nextRun();\n * ```\n */\nexport class CronParser {\n private readonly _fields: CronFields;\n private readonly _isDayOfMonthRestricted: boolean;\n private readonly _isDayOfWeekRestricted: boolean;\n\n /**\n * Creates a new CronParser instance\n *\n * @param expression - Standard 5-field cron expression\n * @throws Error if expression is invalid\n */\n public constructor(private readonly _expression: string) {\n const parts = _expression.trim().split(/\\s+/);\n\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression: \"${_expression}\". Expected 5 fields (minute hour day month weekday).`,\n );\n }\n\n const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;\n\n this._isDayOfMonthRestricted = dayOfMonth.trim() !== \"*\";\n this._isDayOfWeekRestricted = dayOfWeek.trim() !== \"*\";\n\n this._fields = {\n minutes: this._parseField(minute, 0, 59),\n hours: this._parseField(hour, 0, 23),\n daysOfMonth: this._parseField(dayOfMonth, 1, 31),\n months: this._parseField(month, 1, 12),\n daysOfWeek: this._parseField(dayOfWeek, 0, 6),\n };\n\n this._assertSatisfiable();\n }\n\n /**\n * Get the parsed cron fields\n */\n public get fields(): Readonly<CronFields> {\n return this._fields;\n }\n\n /**\n * Get the original expression\n */\n public get expression(): string {\n return this._expression;\n }\n\n /**\n * Calculate the next run time from a given date\n *\n * @param from - Starting date (defaults to now)\n * @returns Next run time as Dayjs\n */\n public nextRun(from: Dayjs = dayjs()): Dayjs {\n let date = from.add(1, \"minute\").second(0).millisecond(0);\n\n // Defensive backstop only: impossible day-of-month / month combinations are\n // rejected eagerly in the constructor (see `_assertSatisfiable`), so a\n // satisfiable expression resolves within a single year. This bound just\n // guarantees the loop can never spin unbounded.\n const maxIterations = 366 * 24 * 60; // 1 year of minutes\n let iterations = 0;\n\n while (iterations < maxIterations) {\n iterations++;\n\n // Check month\n if (!this._fields.months.includes(date.month() + 1)) {\n date = date.add(1, \"month\").date(1).hour(0).minute(0);\n continue;\n }\n\n // Day-of-month + day-of-week — Vixie OR semantics when both restricted.\n if (!this._dayMatches(date)) {\n date = date.add(1, \"day\").hour(0).minute(0);\n continue;\n }\n\n // Check hour\n if (!this._fields.hours.includes(date.hour())) {\n date = date.add(1, \"hour\").minute(0);\n continue;\n }\n\n // Check minute\n if (!this._fields.minutes.includes(date.minute())) {\n date = date.add(1, \"minute\");\n continue;\n }\n\n // All fields match!\n return date;\n }\n\n throw new Error(\n `Could not find next run time for cron expression: ${this._expression}`,\n );\n }\n\n /**\n * Check if a given date matches the cron expression\n *\n * @param date - Date to check\n * @returns true if the date matches\n */\n public matches(date: Dayjs): boolean {\n return (\n this._fields.minutes.includes(date.minute()) &&\n this._fields.hours.includes(date.hour()) &&\n this._fields.months.includes(date.month() + 1) &&\n this._dayMatches(date)\n );\n }\n\n /**\n * Day-of-month / day-of-week match using Vixie cron semantics.\n *\n * When both fields are restricted (neither was `*`), a date matches if\n * EITHER the day-of-month or the day-of-week matches. When only one is\n * restricted, only that one needs to match (the other is the full set\n * by construction, so AND degenerates to the restricted one).\n */\n private _dayMatches(date: Dayjs): boolean {\n const dayOfMonthMatches = this._fields.daysOfMonth.includes(date.date());\n const dayOfWeekMatches = this._fields.daysOfWeek.includes(date.day());\n\n if (this._isDayOfMonthRestricted && this._isDayOfWeekRestricted) {\n return dayOfMonthMatches || dayOfWeekMatches;\n }\n\n return dayOfMonthMatches && dayOfWeekMatches;\n }\n\n /**\n * Reject expressions whose day-of-month / month combination can never occur\n * (e.g. `0 0 30 2 *` — February never has a 30th).\n *\n * Without this guard, `nextRun()` would scan its full ~1-year iteration\n * budget (527,040 passes) before throwing — seconds of synchronous CPU that\n * stalls the event loop. Catching it here makes the failure eager and cheap,\n * consistent with every other validation throw in the constructor.\n *\n * Only applies when the day-of-week field is unrestricted (`*`). Under Vixie\n * OR semantics, a restricted day-of-week keeps the schedule satisfiable via\n * the weekday path even when no listed day-of-month fits any listed month, so\n * such expressions must NOT be rejected.\n */\n private _assertSatisfiable(): void {\n if (this._isDayOfWeekRestricted) {\n return;\n }\n\n const smallestDay = this._fields.daysOfMonth[0];\n\n const reachable = this._fields.months.some(\n (month) => smallestDay <= this._maxDaysInMonth(month),\n );\n\n if (!reachable) {\n throw new Error(\n `Impossible cron expression: \"${this._expression}\". No day-of-month in [${this._fields.daysOfMonth.join(\", \")}] ever occurs in month(s) [${this._fields.months.join(\", \")}].`,\n );\n }\n }\n\n /**\n * Largest possible day number for a 1-based month, taking leap years into\n * account so February resolves to 29 (a date that does occur, just not every\n * year). Used by satisfiability checking, never for matching a concrete date.\n */\n private _maxDaysInMonth(month: number): number {\n if (month === 2) {\n return 29;\n }\n\n const thirtyDayMonths = [4, 6, 9, 11];\n\n if (thirtyDayMonths.includes(month)) {\n return 30;\n }\n\n return 31;\n }\n\n /**\n * Parse a single cron field\n *\n * @param field - Field value (e.g., \"*\", \"5\", \"1-5\", \"*‍/2\", \"1,3,5\")\n * @param min - Minimum allowed value\n * @param max - Maximum allowed value\n * @returns Array of matching values\n */\n private _parseField(field: string, min: number, max: number): number[] {\n const values = new Set<number>();\n\n // Handle lists (e.g., \"1,3,5\")\n const parts = field.split(\",\");\n\n for (const part of parts) {\n // Handle step values (e.g., \"*‍/5\" or \"1-10/2\")\n const [range, stepStr] = part.split(\"/\");\n const step = stepStr ? parseInt(stepStr, 10) : 1;\n\n if (isNaN(step) || step < 1) {\n throw new Error(`Invalid step value in cron field: \"${field}\"`);\n }\n\n let rangeStart: number;\n let rangeEnd: number;\n\n if (range === \"*\") {\n // Wildcard - all values\n rangeStart = min;\n rangeEnd = max;\n } else if (range.includes(\"-\")) {\n // Range (e.g., \"1-5\")\n const [startStr, endStr] = range.split(\"-\");\n rangeStart = parseInt(startStr, 10);\n rangeEnd = parseInt(endStr, 10);\n\n if (isNaN(rangeStart) || isNaN(rangeEnd)) {\n throw new Error(`Invalid range in cron field: \"${field}\"`);\n }\n\n if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) {\n throw new Error(\n `Range out of bounds in cron field: \"${field}\" (valid: ${min}-${max})`,\n );\n }\n } else {\n // Single value\n const value = parseInt(range, 10);\n\n if (isNaN(value)) {\n throw new Error(`Invalid value in cron field: \"${field}\"`);\n }\n\n if (value < min || value > max) {\n throw new Error(\n `Value out of bounds in cron field: \"${field}\" (valid: ${min}-${max})`,\n );\n }\n\n rangeStart = value;\n rangeEnd = value;\n }\n\n // Add values with step\n for (let i = rangeStart; i <= rangeEnd; i += step) {\n values.add(i);\n }\n }\n\n return Array.from(values).sort((a, b) => a - b);\n }\n}\n\n/**\n * Parse a cron expression string\n *\n * @param expression - Cron expression (5 fields)\n * @returns CronParser instance\n */\nexport function parseCron(expression: string): CronParser {\n return new CronParser(expression);\n}\n","import dayjs, { type Dayjs } from \"dayjs\";\nimport isSameOrAfter from \"dayjs/plugin/isSameOrAfter.js\";\nimport timezone from \"dayjs/plugin/timezone.js\";\nimport utc from \"dayjs/plugin/utc.js\";\nimport { CronParser } from \"./cron-parser\";\nimport type { Day, JobIntervals, JobResult, RetryConfig, TimeType } from \"./types\";\n\ndayjs.extend(utc);\ndayjs.extend(timezone);\ndayjs.extend(isSameOrAfter);\n\nexport type JobCallback = (job: Job) => Promise<any>;\n\n/**\n * Days of week mapping (lowercase for consistency with Day type)\n */\nconst DAYS_OF_WEEK: Day[] = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n];\n\n/**\n * Validate a `HH:mm` or `HH:mm:ss` string and return its parts.\n * Throws when the format is malformed or any part is out of range.\n */\nfunction parseTimeString(time: string): {\n hour: number;\n minute: number;\n second: number;\n} {\n if (!/^\\d{1,2}:\\d{2}(:\\d{2})?$/.test(time)) {\n throw new Error(\"Invalid time format. Use HH:mm or HH:mm:ss.\");\n }\n\n const [hour, minute, second = 0] = time.split(\":\").map(Number);\n\n if (hour < 0 || hour > 23) {\n throw new Error(`Invalid hour in time \"${time}\". Must be between 0 and 23.`);\n }\n\n if (minute < 0 || minute > 59) {\n throw new Error(`Invalid minute in time \"${time}\". Must be between 0 and 59.`);\n }\n\n if (second < 0 || second > 59) {\n throw new Error(`Invalid second in time \"${time}\". Must be between 0 and 59.`);\n }\n\n return { hour, minute, second };\n}\n\n/**\n * Job class represents a scheduled task with configurable timing and execution options.\n *\n * @example\n * ```typescript\n * const job = new Job(\"cleanup\", async () => {\n * await cleanupOldFiles();\n * })\n * .everyDay()\n * .at(\"03:00\")\n * .inTimezone(\"America/New_York\")\n * .preventOverlap()\n * .retry(3, 1000);\n * ```\n */\nexport class Job {\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Properties\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Interval configuration for scheduling\n */\n private _intervals: JobIntervals = {};\n\n /**\n * Last execution timestamp.\n *\n * Updated after every run attempt — successful or failed — so the next-run\n * calculation always advances even when a job throws. Use the `job:complete`\n * / `job:error` events if you need to distinguish success from failure.\n */\n private _lastRun: Dayjs | null = null;\n\n /**\n * Whether the job is currently executing\n */\n private _isRunning = false;\n\n /**\n * Skip execution if job is already running\n */\n private _skipIfRunning = false;\n\n /**\n * Retry configuration\n */\n private _retryConfig: RetryConfig | null = null;\n\n /**\n * Timezone for scheduling (defaults to UTC)\n */\n private _timezone = \"UTC\";\n\n /**\n * Cron expression parser (mutually exclusive with interval config)\n */\n private _cronParser: CronParser | null = null;\n\n /**\n * All pending `waitForCompletion()` resolvers — drained on every run end.\n */\n private _completionResolvers: (() => void)[] = [];\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Properties\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Next scheduled execution time\n */\n public nextRun: Dayjs | null = null;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Creates a new Job instance\n *\n * @param name - Unique identifier for the job\n * @param callback - Function to execute when the job runs\n */\n public constructor(\n public readonly name: string,\n private readonly _callback: JobCallback,\n ) {}\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Getters\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Returns true if the job is currently executing\n */\n public get isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Returns the last execution timestamp (success OR failure).\n */\n public get lastRun(): Dayjs | null {\n return this._lastRun;\n }\n\n /**\n * Returns the current interval configuration (readonly)\n */\n public get intervals(): Readonly<JobIntervals> {\n return this._intervals;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Interval Configuration Methods (Fluent API)\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Set a custom interval for job execution\n *\n * @param value - Number of time units (must be > 0)\n * @param timeType - Type of time unit\n * @returns this for chaining\n * @throws Error if `value` is not a positive finite number\n *\n * @example\n * ```typescript\n * job.every(5, \"minute\"); // Run every 5 minutes\n * job.every(2, \"hour\"); // Run every 2 hours\n * ```\n */\n public every(value: number, timeType: TimeType): this {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `Invalid interval value: ${value}. Must be a positive finite number.`,\n );\n }\n\n this._intervals.every = { type: timeType, value };\n this._determineNextRun();\n\n return this;\n }\n\n /**\n * Run job every second (use with caution - high frequency)\n */\n public everySecond(): this {\n return this.every(1, \"second\");\n }\n\n /**\n * Run job every specified number of seconds\n */\n public everySeconds(seconds: number): this {\n return this.every(seconds, \"second\");\n }\n\n /**\n * Run job every minute\n */\n public everyMinute(): this {\n return this.every(1, \"minute\");\n }\n\n /**\n * Run job every specified number of minutes\n */\n public everyMinutes(minutes: number): this {\n return this.every(minutes, \"minute\");\n }\n\n /**\n * Run job every hour\n */\n public everyHour(): this {\n return this.every(1, \"hour\");\n }\n\n /**\n * Run job every specified number of hours\n */\n public everyHours(hours: number): this {\n return this.every(hours, \"hour\");\n }\n\n /**\n * Run job every day at midnight\n */\n public everyDay(): this {\n return this.every(1, \"day\");\n }\n\n /**\n * Alias for everyDay()\n */\n public daily(): this {\n return this.everyDay();\n }\n\n /**\n * Run job twice a day (every 12 hours)\n */\n public twiceDaily(): this {\n return this.every(12, \"hour\");\n }\n\n /**\n * Run job every week\n */\n public everyWeek(): this {\n return this.every(1, \"week\");\n }\n\n /**\n * Alias for everyWeek()\n */\n public weekly(): this {\n return this.everyWeek();\n }\n\n /**\n * Run job every month\n */\n public everyMonth(): this {\n return this.every(1, \"month\");\n }\n\n /**\n * Alias for everyMonth()\n */\n public monthly(): this {\n return this.everyMonth();\n }\n\n /**\n * Run job every year\n */\n public everyYear(): this {\n return this.every(1, \"year\");\n }\n\n /**\n * Alias for everyYear()\n */\n public yearly(): this {\n return this.everyYear();\n }\n\n /**\n * Alias for everyMinute() - job runs continuously every minute\n */\n public always(): this {\n return this.everyMinute();\n }\n\n /**\n * Schedule job using a cron expression\n *\n * Supports standard 5-field cron syntax:\n * ```\n * ┌───────────── minute (0-59)\n * │ ┌───────────── hour (0-23)\n * │ │ ┌───────────── day of month (1-31)\n * │ │ │ ┌───────────── month (1-12)\n * │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)\n * │ │ │ │ │\n * * * * * *\n * ```\n *\n * Supports:\n * - '*' - any value\n * - '5' - specific value\n * - '1,3,5' - list of values\n * - '1-5' - range of values\n * - '*‍/5' - step values (every 5)\n * - '1-10/2' - range with step\n *\n * @param expression - Standard 5-field cron expression\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.cron(\"0 9 * * 1-5\"); // 9 AM weekdays\n * job.cron(\"*‍/5 * * * *\"); // Every 5 minutes\n * job.cron(\"0 0 1 * *\"); // First day of month at midnight\n * job.cron(\"0 *‍/2 * * *\"); // Every 2 hours\n * ```\n */\n public cron(expression: string): this {\n this._cronParser = new CronParser(expression);\n // Clear interval config since cron takes precedence\n this._intervals = {};\n this._determineNextRun();\n return this;\n }\n\n /**\n * Get the cron expression if one is set\n */\n public get cronExpression(): string | null {\n return this._cronParser?.expression ?? null;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Day & Time Configuration Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Schedule job on a specific day\n *\n * @param day - Day of week (string) or day of month (number 1-31)\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.on(\"monday\"); // Run on Mondays\n * job.on(15); // Run on the 15th of each month\n * ```\n */\n public on(day: Day | number): this {\n if (typeof day === \"number\" && (day < 1 || day > 31)) {\n throw new Error(\"Invalid day of the month. Must be between 1 and 31.\");\n }\n\n this._intervals.day = day;\n\n if (typeof day === \"number\") {\n this._intervals.dayOfMonthMode = \"specific\";\n }\n\n this._determineNextRun();\n\n return this;\n }\n\n /**\n * Schedule job at a specific time\n *\n * @param time - Time in HH:mm or HH:mm:ss format\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.daily().at(\"09:00\"); // Run daily at 9 AM\n * job.weekly().at(\"14:30\"); // Run weekly at 2:30 PM\n * ```\n */\n public at(time: string): this {\n parseTimeString(time);\n this._intervals.time = time;\n this._determineNextRun();\n\n return this;\n }\n\n /**\n * Run task at the beginning of the specified time period.\n *\n * - `\"day\"` → 00:00 every day\n * - `\"month\"` → 1st of every month at 00:00\n * - `\"year\"` → January 1st at 00:00 every year\n *\n * @param type - Time type (day, month, year)\n */\n public beginOf(type: TimeType): this {\n switch (type) {\n case \"day\":\n this._intervals.every = { type: \"day\", value: 1 };\n break;\n\n case \"month\":\n this._intervals.day = 1;\n this._intervals.dayOfMonthMode = \"specific\";\n this._intervals.every = { type: \"month\", value: 1 };\n break;\n\n case \"year\":\n this._intervals.month = 1;\n this._intervals.day = 1;\n this._intervals.dayOfMonthMode = \"specific\";\n this._intervals.every = { type: \"year\", value: 1 };\n break;\n\n default:\n throw new Error(`Unsupported type for beginOf: ${type}`);\n }\n\n return this.at(\"00:00\");\n }\n\n /**\n * Run task at the end of the specified time period.\n *\n * - `\"day\"` → 23:59 every day\n * - `\"month\"` → last day of every month at 23:59 (recomputed each cycle —\n * correct in February vs. March)\n * - `\"year\"` → December 31st at 23:59 every year\n *\n * @param type - Time type (day, month, year)\n */\n public endOf(type: TimeType): this {\n switch (type) {\n case \"day\":\n this._intervals.every = { type: \"day\", value: 1 };\n break;\n\n case \"month\":\n this._intervals.dayOfMonthMode = \"last\";\n this._intervals.every = { type: \"month\", value: 1 };\n break;\n\n case \"year\":\n this._intervals.month = 12;\n this._intervals.day = 31;\n this._intervals.dayOfMonthMode = \"specific\";\n this._intervals.every = { type: \"year\", value: 1 };\n break;\n\n default:\n throw new Error(`Unsupported type for endOf: ${type}`);\n }\n\n return this.at(\"23:59\");\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Timezone Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Set the timezone for this job's scheduling\n *\n * @param tz - IANA timezone string (e.g., \"America/New_York\", \"Europe/London\")\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.daily().at(\"09:00\").inTimezone(\"America/New_York\");\n * ```\n */\n public inTimezone(tz: string): this {\n this._timezone = tz;\n this._determineNextRun();\n return this;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Execution Options\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Prevent overlapping executions of this job.\n *\n * When enabled, if the job is already running when it's scheduled to run again,\n * the new execution will be skipped.\n *\n * @param skip - Whether to skip if already running (default: true)\n * @returns this for chaining\n */\n public preventOverlap(skip = true): this {\n this._skipIfRunning = skip;\n return this;\n }\n\n /**\n * Configure automatic retry on failure\n *\n * @param maxRetries - Maximum number of retry attempts (must be ≥ 0)\n * @param delay - Delay between retries in milliseconds (must be ≥ 0)\n * @param backoffMultiplier - Optional multiplier for exponential backoff (must be > 0)\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.retry(3, 1000); // Retry 3 times with 1s delay\n * job.retry(5, 1000, 2); // Exponential backoff: 1s, 2s, 4s, 8s, 16s\n * ```\n */\n public retry(maxRetries: number, delay = 1000, backoffMultiplier?: number): this {\n if (!Number.isFinite(maxRetries) || maxRetries < 0) {\n throw new Error(`Invalid maxRetries: ${maxRetries}. Must be ≥ 0.`);\n }\n\n if (!Number.isFinite(delay) || delay < 0) {\n throw new Error(`Invalid retry delay: ${delay}. Must be ≥ 0.`);\n }\n\n if (\n backoffMultiplier !== undefined &&\n (!Number.isFinite(backoffMultiplier) || backoffMultiplier <= 0)\n ) {\n throw new Error(\n `Invalid backoffMultiplier: ${backoffMultiplier}. Must be > 0.`,\n );\n }\n\n this._retryConfig = {\n maxRetries,\n delay,\n backoffMultiplier,\n };\n\n return this;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Execution Control\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Terminate the job and clear all scheduling data\n */\n public terminate(): this {\n this._intervals = {};\n this._cronParser = null;\n this.nextRun = null;\n this._lastRun = null;\n this._isRunning = false;\n return this;\n }\n\n /**\n * Prepare the job by calculating the next run time\n * Called by the scheduler when starting\n */\n public prepare(): void {\n this._determineNextRun();\n }\n\n /**\n * Returns true if the job's `nextRun` has arrived, regardless of whether\n * it is currently running. Used by the scheduler to decide whether a\n * tick is \"due\" before checking overlap state.\n */\n public isDue(): boolean {\n return this.nextRun !== null && this._now().isSameOrAfter(this.nextRun);\n }\n\n /**\n * Determine if the job should run now.\n *\n * Combines `isDue()` with the overlap-prevention rule: when\n * `preventOverlap()` is on and the job is already running, this returns\n * false even if the next-run time has arrived.\n *\n * @returns true if the job should execute\n */\n public shouldRun(): boolean {\n if (this._skipIfRunning && this._isRunning) {\n return false;\n }\n\n return this.isDue();\n }\n\n /**\n * Execute the job once.\n *\n * Always advances `lastRun` and recalculates `nextRun` (success OR failure)\n * so a permanently failing job does not re-fire on every scheduler tick.\n *\n * @returns Promise resolving to the job result\n */\n public async run(): Promise<JobResult> {\n const startTime = Date.now();\n\n this._isRunning = true;\n\n let result: JobResult;\n let executedRetries = 0;\n\n try {\n const inner = await this._executeWithRetry();\n executedRetries = inner.retries;\n\n result = {\n success: true,\n duration: Date.now() - startTime,\n retries: executedRetries,\n };\n } catch (error) {\n result = {\n success: false,\n duration: Date.now() - startTime,\n error,\n retries: this._retryConfig?.maxRetries ?? 0,\n };\n } finally {\n this._lastRun = this._now();\n this._determineNextRun();\n this._isRunning = false;\n\n // Drain ALL pending waiters (waitForCompletion may be called more than once).\n const resolvers = this._completionResolvers.splice(0);\n\n for (const resolve of resolvers) {\n resolve();\n }\n }\n\n return result;\n }\n\n /**\n * Wait for the currently executing run to complete.\n *\n * Multiple concurrent waiters are all resolved when the run finishes.\n * Useful for graceful shutdown.\n *\n * @returns Promise that resolves when the job completes\n */\n public waitForCompletion(): Promise<void> {\n if (!this._isRunning) {\n return Promise.resolve();\n }\n\n return new Promise(resolve => {\n this._completionResolvers.push(resolve);\n });\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Get current time, respecting the configured timezone.\n */\n private _now(): Dayjs {\n return dayjs().tz(this._timezone);\n }\n\n /**\n * Execute the callback with retry logic\n */\n private async _executeWithRetry(): Promise<{ retries: number }> {\n let lastError: unknown;\n let attempts = 0;\n const maxAttempts = (this._retryConfig?.maxRetries ?? 0) + 1;\n\n while (attempts < maxAttempts) {\n try {\n await this._callback(this);\n return { retries: attempts };\n } catch (error) {\n lastError = error;\n attempts++;\n\n if (attempts < maxAttempts && this._retryConfig) {\n const delay = this._calculateRetryDelay(attempts);\n await this._sleep(delay);\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Calculate retry delay with optional exponential backoff\n */\n private _calculateRetryDelay(attempt: number): number {\n if (!this._retryConfig) return 0;\n\n const { delay, backoffMultiplier } = this._retryConfig;\n\n if (backoffMultiplier) {\n return delay * Math.pow(backoffMultiplier, attempt - 1);\n }\n\n return delay;\n }\n\n /**\n * Sleep for specified milliseconds\n */\n private _sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Apply month / day-of-month / day-of-week / time constraints to a Dayjs.\n *\n * Re-applied after every interval advance inside `_determineNextRun` so\n * dynamic constraints (`dayOfMonthMode: \"last\"` recomputed per month, month\n * lock for `beginOf/endOf(\"year\")`) stay correct as the candidate moves\n * forward.\n */\n private _applyConstraints(date: Dayjs): Dayjs {\n let result = date;\n\n if (this._intervals.month !== undefined) {\n result = result.month(this._intervals.month - 1);\n }\n\n if (this._intervals.dayOfMonthMode === \"last\") {\n result = result.date(result.daysInMonth());\n } else if (this._intervals.day !== undefined) {\n if (typeof this._intervals.day === \"number\") {\n result = result.date(this._intervals.day);\n } else {\n const targetDay = DAYS_OF_WEEK.indexOf(this._intervals.day);\n\n if (targetDay !== -1) {\n result = result.day(targetDay);\n }\n }\n }\n\n if (this._intervals.time) {\n const { hour, minute, second } = parseTimeString(this._intervals.time);\n result = result.hour(hour).minute(minute).second(second).millisecond(0);\n }\n\n return result;\n }\n\n /**\n * Calculate the next run time based on interval or cron configuration.\n *\n * Strategy: apply all constraints (month, day, time) ONCE before the\n * advance loop, then advance by `every` until the candidate is in the\n * future. Static constraints (numeric day, fixed month, fixed time)\n * survive `dayjs.add()` automatically. The only dynamic constraint —\n * `dayOfMonthMode: \"last\"` — is re-applied inside the loop so the\n * candidate always lands on the *new* month's last day after each\n * advance.\n *\n * Re-applying time/day inside the loop would deadlock: with\n * `twiceDaily().at(\"06:00\")` we'd advance 06:00 → 18:00 → snap back to\n * 06:00 → 18:00 → ... forever.\n */\n private _determineNextRun(): void {\n if (this._cronParser) {\n const now = this._now();\n this.nextRun = this._cronParser.nextRun(now);\n return;\n }\n\n const intervalValue = this._intervals.every?.value;\n const intervalType = this._intervals.every?.type;\n const hasInterval = !!(intervalValue && intervalType);\n\n // After a previous run, jump ahead by EXACTLY one interval. Previously\n // we used `lastRun + 1s` and relied on the advance loop to catch up,\n // but that loop only triggers when the candidate is in the past — so\n // for fast-completing callbacks the candidate stayed at `lastRun + 1s`,\n // making `everySeconds(2)` fire every second. Honor the interval up\n // front instead.\n let date: Dayjs;\n\n if (this._lastRun && hasInterval) {\n date = this._lastRun.add(intervalValue!, intervalType);\n } else if (this._lastRun) {\n date = this._lastRun.add(1, \"second\");\n } else {\n date = this._now();\n }\n\n date = this._applyConstraints(date);\n\n while (date.isBefore(this._now())) {\n if (hasInterval) {\n date = date.add(intervalValue!, intervalType);\n } else {\n date = date.add(1, \"day\");\n }\n\n if (this._intervals.dayOfMonthMode === \"last\") {\n date = date.date(date.daysInMonth());\n }\n }\n\n this.nextRun = date;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Factory Function\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Factory function to create a new Job instance\n *\n * @param name - Unique identifier for the job\n * @param callback - Function to execute when the job runs\n * @returns New Job instance\n *\n * @example\n * ```typescript\n * const cleanupJob = job(\"cleanup\", async () => {\n * await db.deleteExpiredTokens();\n * }).daily().at(\"03:00\");\n * ```\n */\nexport function job(name: string, callback: JobCallback): Job {\n return new Job(name, callback);\n}\n","import { EventEmitter } from \"node:events\";\nimport { Job, JobCallback } from \"./job\";\nimport type { JobResult, SchedulerEvents } from \"./types\";\n\n/**\n * Type-safe event emitter interface for Scheduler events\n */\ninterface TypedEventEmitter<TEvents extends Record<string, unknown[]>> {\n on<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;\n once<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;\n off<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;\n emit<K extends keyof TEvents>(event: K, ...args: TEvents[K]): boolean;\n}\n\n/**\n * Scheduler class manages and executes scheduled jobs.\n *\n * Features:\n * - Event-based observability\n * - Parallel or sequential job execution\n * - Drift compensation for accurate timing\n * - Graceful shutdown with job draining\n *\n * @example\n * ```typescript\n * const scheduler = new Scheduler();\n *\n * scheduler.on('job:error', (jobName, error) => {\n * logger.error(`Job ${jobName} failed:`, error);\n * });\n *\n * scheduler\n * .addJob(cleanupJob)\n * .addJob(reportJob)\n * .runInParallel(true)\n * .start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', () => scheduler.shutdown());\n * ```\n */\nexport class Scheduler\n extends (EventEmitter as new () => TypedEventEmitter<SchedulerEvents>)\n implements TypedEventEmitter<SchedulerEvents>\n{\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Properties\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * List of registered jobs\n */\n private _jobs: Job[] = [];\n\n /**\n * Reference to the current timeout for stopping\n */\n private _timeoutId: NodeJS.Timeout | null = null;\n\n /**\n * Tick interval in milliseconds (how often to check for due jobs)\n */\n private _tickInterval = 1000;\n\n /**\n * Whether to run due jobs in parallel\n */\n private _runInParallel = false;\n\n /**\n * Maximum concurrent jobs when running in parallel\n */\n private _maxConcurrency = 10;\n\n /**\n * Flag indicating scheduler is shutting down\n */\n private _isShuttingDown = false;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Getters\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Returns true if the scheduler is currently running\n */\n public get isRunning(): boolean {\n return this._timeoutId !== null;\n }\n\n /**\n * Returns the number of registered jobs\n */\n public get jobCount(): number {\n return this._jobs.length;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Configuration Methods (Fluent API)\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Add a job to the scheduler\n *\n * @param job - Job instance to schedule\n * @returns this for chaining\n */\n public addJob(job: Job): this {\n this._jobs.push(job);\n\n if (this.isRunning) {\n job.prepare();\n }\n\n return this;\n }\n\n /**\n * Alias to create a new job directly and store it\n */\n public newJob(name: string, jobCallback: JobCallback) {\n const job = new Job(name, jobCallback);\n this.addJob(job);\n return job;\n }\n\n /**\n * Add multiple jobs to the scheduler.\n *\n * If the scheduler is already running, every newly-added job is prepared\n * (its initial `nextRun` is computed) so it begins firing on the next tick.\n *\n * @param jobs - Array of Job instances\n * @returns this for chaining\n */\n public addJobs(jobs: Job[]): this {\n this._jobs.push(...jobs);\n\n if (this.isRunning) {\n for (const job of jobs) {\n job.prepare();\n }\n }\n\n return this;\n }\n\n /**\n * Remove a job from the scheduler by name\n *\n * @param jobName - Name of the job to remove\n * @returns true if job was found and removed\n */\n public removeJob(jobName: string): boolean {\n const index = this._jobs.findIndex(j => j.name === jobName);\n\n if (index !== -1) {\n this._jobs.splice(index, 1);\n return true;\n }\n\n return false;\n }\n\n /**\n * Get a job by name\n *\n * @param jobName - Name of the job to find\n * @returns Job instance or undefined\n */\n public getJob(jobName: string): Job | undefined {\n return this._jobs.find(j => j.name === jobName);\n }\n\n /**\n * Get all registered jobs\n *\n * @returns Array of registered jobs (readonly)\n */\n public list(): readonly Job[] {\n return this._jobs;\n }\n\n /**\n * Set the tick interval (how often to check for due jobs)\n *\n * @param ms - Interval in milliseconds (minimum 100ms)\n * @returns this for chaining\n */\n public runEvery(ms: number): this {\n if (ms < 100) {\n throw new Error(\"Tick interval must be at least 100ms\");\n }\n\n this._tickInterval = ms;\n return this;\n }\n\n /**\n * Configure whether jobs should run in parallel\n *\n * @param parallel - Enable parallel execution\n * @param maxConcurrency - Maximum concurrent jobs (default: 10)\n * @returns this for chaining\n */\n public runInParallel(parallel: boolean, maxConcurrency = 10): this {\n this._runInParallel = parallel;\n this._maxConcurrency = maxConcurrency;\n return this;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Lifecycle Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Start the scheduler\n *\n * @throws Error if scheduler is already running\n */\n public start(): void {\n if (this.isRunning) {\n throw new Error(\"Scheduler is already running.\");\n }\n\n if (this._jobs.length === 0) {\n throw new Error(\"Cannot start scheduler with no jobs.\");\n }\n\n for (const job of this._jobs) {\n job.prepare();\n }\n\n this._isShuttingDown = false;\n this._scheduleTick(this._tickInterval);\n\n this.emit(\"scheduler:started\");\n }\n\n /**\n * Stop the scheduler immediately.\n *\n * No-op if the scheduler isn't running. Does not wait for in-flight jobs —\n * use `shutdown()` for graceful termination.\n */\n public stop(): void {\n if (!this._timeoutId) return;\n\n clearTimeout(this._timeoutId);\n this._timeoutId = null;\n\n this.emit(\"scheduler:stopped\");\n }\n\n /**\n * Gracefully shutdown the scheduler\n *\n * Stops scheduling new jobs and waits for currently running jobs to complete.\n *\n * @param timeout - Maximum time to wait for jobs (default: 30000ms)\n * @returns Promise that resolves when shutdown is complete\n */\n public async shutdown(timeout = 30000): Promise<void> {\n this._isShuttingDown = true;\n this.stop();\n\n const runningJobs = this._jobs.filter(j => j.isRunning);\n\n if (runningJobs.length > 0) {\n await Promise.race([\n Promise.all(runningJobs.map(j => j.waitForCompletion())),\n new Promise<void>(resolve => setTimeout(resolve, timeout)),\n ]);\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Schedule the next tick.\n *\n * Drift-compensated: after each tick, the next delay is `tickInterval -\n * elapsed-tick-time` (clamped to 0). A tick that takes 600 ms on a 1 000 ms\n * interval will be followed by a 400 ms delay so the *period* between tick\n * starts averages `tickInterval` instead of `tickInterval + work-time`.\n */\n private _scheduleTick(delay: number): void {\n if (this._isShuttingDown) return;\n\n this._timeoutId = setTimeout(async () => {\n const tickStart = Date.now();\n\n await this._tick();\n\n const elapsed = Date.now() - tickStart;\n const nextDelay = Math.max(this._tickInterval - elapsed, 0);\n\n this._scheduleTick(nextDelay);\n }, delay);\n }\n\n /**\n * Execute a scheduler tick - check and run due jobs\n */\n private async _tick(): Promise<void> {\n this.emit(\"scheduler:tick\", new Date());\n\n const dueJobs = this._jobs.filter(job => {\n // Time-based readiness only; running state is checked below so a\n // `job:skip` event fires whenever overlap blocks a due run.\n if (!job.isDue()) return false;\n\n if (job.isRunning) {\n this.emit(\"job:skip\", job.name, \"Job is already running\");\n return false;\n }\n\n return true;\n });\n\n if (dueJobs.length === 0) return;\n\n if (this._runInParallel) {\n await this._runJobsInParallel(dueJobs);\n } else {\n await this._runJobsSequentially(dueJobs);\n }\n }\n\n /**\n * Run jobs sequentially\n */\n private async _runJobsSequentially(jobs: Job[]): Promise<void> {\n for (const job of jobs) {\n if (this._isShuttingDown) break;\n await this._runJob(job);\n }\n }\n\n /**\n * Run jobs in parallel with concurrency limit\n */\n private async _runJobsInParallel(jobs: Job[]): Promise<void> {\n const batches: Job[][] = [];\n\n for (let i = 0; i < jobs.length; i += this._maxConcurrency) {\n batches.push(jobs.slice(i, i + this._maxConcurrency));\n }\n\n for (const batch of batches) {\n if (this._isShuttingDown) break;\n await Promise.allSettled(batch.map(job => this._runJob(job)));\n }\n }\n\n /**\n * Run a single job and emit events\n */\n private async _runJob(job: Job): Promise<JobResult> {\n this.emit(\"job:start\", job.name);\n\n const result = await job.run();\n\n if (result.success) {\n this.emit(\"job:complete\", job.name, result);\n } else {\n this.emit(\"job:error\", job.name, result.error);\n }\n\n return result;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Default Export\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Default scheduler instance for simple use cases\n *\n * @example\n * ```typescript\n * import { scheduler, job } from \"@warlock.js/scheduler\";\n *\n * scheduler.addJob(job(\"cleanup\", cleanupFn).daily());\n * scheduler.start();\n * ```\n */\nexport const scheduler = new Scheduler();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,aAAb,MAAwB;;;;;;;CAWtB,AAAO,YAAY,AAAiB,aAAqB;EAArB;EAClC,MAAM,QAAQ,YAAY,KAAK,EAAE,M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AM,wBAAwB;IACxD,OAAO;GACT;GAEA,OAAO;EACT,CAAC;EAED,IAAI,QAAQ,WAAW,GAAG;EAE1B,IAAI,KAAK,gBACP,MAAM,KAAK,mBAAmB,OAAO;OAErC,MAAM,KAAK,qBAAqB,OAAO;CAE3C;;;;CAKA,MAAc,qBAAqB,MAA4B;EAC7D,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI,KAAK,iBAAiB;GAC1B,MAAM,KAAK,QAAQ,GAAG;EACxB;CACF;;;;CAKA,MAAc,mBAAmB,MAA4B;EAC3D,MAAM,UAAmB,CAAC;EAE1B,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,KAAK,iBACzC,QAAQ,KAAK,KAAK,MAAM,GAAG,IAAI,KAAK,eAAe,CAAC;EAGtD,KAAK,MAAM,SAAS,SAAS;GAC3B,IAAI,KAAK,iBAAiB;GAC1B,MAAM,QAAQ,WAAW,MAAM,KAAI,QAAO,KAAK,QAAQ,GAAG,CAAC,CAAC;EAC9D;CACF;;;;CAKA,MAAc,QAAQ,KAA8B;EAClD,KAAK,KAAK,aAAa,IAAI,IAAI;EAE/B,MAAM,SAAS,MAAM,IAAI,IAAI;EAE7B,IAAI,OAAO,SACT,KAAK,KAAK,gBAAgB,IAAI,MAAM,MAAM;OAE1C,KAAK,KAAK,aAAa,IAAI,MAAM,OAAO,KAAK;EAG/C,OAAO;CACT;AACF;;;;;;;;;;;;AAiBA,MAAa,YAAY,IAAI,UAAU"}
@@ -0,0 +1,129 @@
1
+ import { Dayjs } from "dayjs";
2
+
3
+ //#region ../../@warlock.js/scheduler/src/cron-parser.d.ts
4
+ /**
5
+ * Parsed cron expression fields
6
+ */
7
+ type CronFields = {
8
+ /** Minutes (0-59) */minutes: number[]; /** Hours (0-23) */
9
+ hours: number[]; /** Days of month (1-31) */
10
+ daysOfMonth: number[]; /** Months (1-12) */
11
+ months: number[]; /** Days of week (0-6, Sunday = 0) */
12
+ daysOfWeek: number[];
13
+ };
14
+ /**
15
+ * Cron expression parser
16
+ *
17
+ * Supports standard 5-field cron expressions:
18
+ * ```
19
+ * ┌───────────── minute (0-59)
20
+ * │ ┌───────────── hour (0-23)
21
+ * │ │ ┌───────────── day of month (1-31)
22
+ * │ │ │ ┌───────────── month (1-12)
23
+ * │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)
24
+ * │ │ │ │ │
25
+ * * * * * *
26
+ * ```
27
+ *
28
+ * Supports:
29
+ * - `*` - any value
30
+ * - `5` - specific value
31
+ * - `1,3,5` - list of values
32
+ * - `1-5` - range of values
33
+ * - `*‍/5` - step values (every 5)
34
+ * - `1-10/2` - range with step
35
+ *
36
+ * **Day-of-month / day-of-week semantics:** follows Vixie cron — when both
37
+ * fields are restricted (neither is `*`), a date matches if it satisfies
38
+ * EITHER constraint. When only one is restricted, the other is ignored.
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * const parser = new CronParser("0 9 * * 1-5"); // 9 AM weekdays
43
+ * const nextRun = parser.nextRun();
44
+ * ```
45
+ */
46
+ declare class CronParser {
47
+ private readonly _expression;
48
+ private readonly _fields;
49
+ private readonly _isDayOfMonthRestricted;
50
+ private readonly _isDayOfWeekRestricted;
51
+ /**
52
+ * Creates a new CronParser instance
53
+ *
54
+ * @param expression - Standard 5-field cron expression
55
+ * @throws Error if expression is invalid
56
+ */
57
+ constructor(_expression: string);
58
+ /**
59
+ * Get the parsed cron fields
60
+ */
61
+ get fields(): Readonly<CronFields>;
62
+ /**
63
+ * Get the original expression
64
+ */
65
+ get expression(): string;
66
+ /**
67
+ * Calculate the next run time from a given date
68
+ *
69
+ * @param from - Starting date (defaults to now)
70
+ * @returns Next run time as Dayjs
71
+ */
72
+ nextRun(from?: Dayjs): Dayjs;
73
+ /**
74
+ * Check if a given date matches the cron expression
75
+ *
76
+ * @param date - Date to check
77
+ * @returns true if the date matches
78
+ */
79
+ matches(date: Dayjs): boolean;
80
+ /**
81
+ * Day-of-month / day-of-week match using Vixie cron semantics.
82
+ *
83
+ * When both fields are restricted (neither was `*`), a date matches if
84
+ * EITHER the day-of-month or the day-of-week matches. When only one is
85
+ * restricted, only that one needs to match (the other is the full set
86
+ * by construction, so AND degenerates to the restricted one).
87
+ */
88
+ private _dayMatches;
89
+ /**
90
+ * Reject expressions whose day-of-month / month combination can never occur
91
+ * (e.g. `0 0 30 2 *` — February never has a 30th).
92
+ *
93
+ * Without this guard, `nextRun()` would scan its full ~1-year iteration
94
+ * budget (527,040 passes) before throwing — seconds of synchronous CPU that
95
+ * stalls the event loop. Catching it here makes the failure eager and cheap,
96
+ * consistent with every other validation throw in the constructor.
97
+ *
98
+ * Only applies when the day-of-week field is unrestricted (`*`). Under Vixie
99
+ * OR semantics, a restricted day-of-week keeps the schedule satisfiable via
100
+ * the weekday path even when no listed day-of-month fits any listed month, so
101
+ * such expressions must NOT be rejected.
102
+ */
103
+ private _assertSatisfiable;
104
+ /**
105
+ * Largest possible day number for a 1-based month, taking leap years into
106
+ * account so February resolves to 29 (a date that does occur, just not every
107
+ * year). Used by satisfiability checking, never for matching a concrete date.
108
+ */
109
+ private _maxDaysInMonth;
110
+ /**
111
+ * Parse a single cron field
112
+ *
113
+ * @param field - Field value (e.g., "*", "5", "1-5", "*‍/2", "1,3,5")
114
+ * @param min - Minimum allowed value
115
+ * @param max - Maximum allowed value
116
+ * @returns Array of matching values
117
+ */
118
+ private _parseField;
119
+ }
120
+ /**
121
+ * Parse a cron expression string
122
+ *
123
+ * @param expression - Cron expression (5 fields)
124
+ * @returns CronParser instance
125
+ */
126
+ declare function parseCron(expression: string): CronParser;
127
+ //#endregion
128
+ export { CronFields, CronParser, parseCron };
129
+ //# sourceMappingURL=cron-parser.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron-parser.d.mts","names":[],"sources":["../../../../../@warlock.js/scheduler/src/cron-parser.ts"],"mappings":";;;;;AAKA;KAAY,UAAA;uBAEV,OAAA;EAEA,KAAA,YAEA;EAAA,WAAA,YAIA;EAFA,MAAA,YAEU;EAAV,UAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsOmB;AAuErB;cA1Qa,UAAA;EAAA,iBAWyB,WAAA;EAAA,iBAVnB,OAAA;EAAA,iBACA,uBAAA;EAAA,iBACA,sBAAA;;;;;;;cAQmB,WAAA;;;;MA4BzB,MAAA,CAAA,GAAU,QAAA,CAAS,UAAA;;;;MAOnB,UAAA,CAAA;;;;;;;EAUJ,OAAA,CAAQ,IAAA,GAAM,KAAA,GAAkB,KAAA;;;;;;;EAoDhC,OAAA,CAAQ,IAAA,EAAM,KAAA;;;;;;;;;UAiBb,WAAA;;;;;;;;;;;;;;;UAyBA,kBAAA;;;;;;UAuBA,eAAA;;;;;;;;;UAsBA,WAAA;AAAA;;;;;;;iBAuEM,SAAA,CAAU,UAAA,WAAqB,UAAU"}
@@ -0,0 +1,210 @@
1
+ import dayjs from "dayjs";
2
+
3
+ //#region ../../@warlock.js/scheduler/src/cron-parser.ts
4
+ /**
5
+ * Cron expression parser
6
+ *
7
+ * Supports standard 5-field cron expressions:
8
+ * ```
9
+ * ┌───────────── minute (0-59)
10
+ * │ ┌───────────── hour (0-23)
11
+ * │ │ ┌───────────── day of month (1-31)
12
+ * │ │ │ ┌───────────── month (1-12)
13
+ * │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)
14
+ * │ │ │ │ │
15
+ * * * * * *
16
+ * ```
17
+ *
18
+ * Supports:
19
+ * - `*` - any value
20
+ * - `5` - specific value
21
+ * - `1,3,5` - list of values
22
+ * - `1-5` - range of values
23
+ * - `*‍/5` - step values (every 5)
24
+ * - `1-10/2` - range with step
25
+ *
26
+ * **Day-of-month / day-of-week semantics:** follows Vixie cron — when both
27
+ * fields are restricted (neither is `*`), a date matches if it satisfies
28
+ * EITHER constraint. When only one is restricted, the other is ignored.
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * const parser = new CronParser("0 9 * * 1-5"); // 9 AM weekdays
33
+ * const nextRun = parser.nextRun();
34
+ * ```
35
+ */
36
+ var CronParser = class {
37
+ /**
38
+ * Creates a new CronParser instance
39
+ *
40
+ * @param expression - Standard 5-field cron expression
41
+ * @throws Error if expression is invalid
42
+ */
43
+ constructor(_expression) {
44
+ this._expression = _expression;
45
+ const parts = _expression.trim().split(/\s+/);
46
+ if (parts.length !== 5) throw new Error(`Invalid cron expression: "${_expression}". Expected 5 fields (minute hour day month weekday).`);
47
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;
48
+ this._isDayOfMonthRestricted = dayOfMonth.trim() !== "*";
49
+ this._isDayOfWeekRestricted = dayOfWeek.trim() !== "*";
50
+ this._fields = {
51
+ minutes: this._parseField(minute, 0, 59),
52
+ hours: this._parseField(hour, 0, 23),
53
+ daysOfMonth: this._parseField(dayOfMonth, 1, 31),
54
+ months: this._parseField(month, 1, 12),
55
+ daysOfWeek: this._parseField(dayOfWeek, 0, 6)
56
+ };
57
+ this._assertSatisfiable();
58
+ }
59
+ /**
60
+ * Get the parsed cron fields
61
+ */
62
+ get fields() {
63
+ return this._fields;
64
+ }
65
+ /**
66
+ * Get the original expression
67
+ */
68
+ get expression() {
69
+ return this._expression;
70
+ }
71
+ /**
72
+ * Calculate the next run time from a given date
73
+ *
74
+ * @param from - Starting date (defaults to now)
75
+ * @returns Next run time as Dayjs
76
+ */
77
+ nextRun(from = dayjs()) {
78
+ let date = from.add(1, "minute").second(0).millisecond(0);
79
+ const maxIterations = 366 * 24 * 60;
80
+ let iterations = 0;
81
+ while (iterations < maxIterations) {
82
+ iterations++;
83
+ if (!this._fields.months.includes(date.month() + 1)) {
84
+ date = date.add(1, "month").date(1).hour(0).minute(0);
85
+ continue;
86
+ }
87
+ if (!this._dayMatches(date)) {
88
+ date = date.add(1, "day").hour(0).minute(0);
89
+ continue;
90
+ }
91
+ if (!this._fields.hours.includes(date.hour())) {
92
+ date = date.add(1, "hour").minute(0);
93
+ continue;
94
+ }
95
+ if (!this._fields.minutes.includes(date.minute())) {
96
+ date = date.add(1, "minute");
97
+ continue;
98
+ }
99
+ return date;
100
+ }
101
+ throw new Error(`Could not find next run time for cron expression: ${this._expression}`);
102
+ }
103
+ /**
104
+ * Check if a given date matches the cron expression
105
+ *
106
+ * @param date - Date to check
107
+ * @returns true if the date matches
108
+ */
109
+ matches(date) {
110
+ return this._fields.minutes.includes(date.minute()) && this._fields.hours.includes(date.hour()) && this._fields.months.includes(date.month() + 1) && this._dayMatches(date);
111
+ }
112
+ /**
113
+ * Day-of-month / day-of-week match using Vixie cron semantics.
114
+ *
115
+ * When both fields are restricted (neither was `*`), a date matches if
116
+ * EITHER the day-of-month or the day-of-week matches. When only one is
117
+ * restricted, only that one needs to match (the other is the full set
118
+ * by construction, so AND degenerates to the restricted one).
119
+ */
120
+ _dayMatches(date) {
121
+ const dayOfMonthMatches = this._fields.daysOfMonth.includes(date.date());
122
+ const dayOfWeekMatches = this._fields.daysOfWeek.includes(date.day());
123
+ if (this._isDayOfMonthRestricted && this._isDayOfWeekRestricted) return dayOfMonthMatches || dayOfWeekMatches;
124
+ return dayOfMonthMatches && dayOfWeekMatches;
125
+ }
126
+ /**
127
+ * Reject expressions whose day-of-month / month combination can never occur
128
+ * (e.g. `0 0 30 2 *` — February never has a 30th).
129
+ *
130
+ * Without this guard, `nextRun()` would scan its full ~1-year iteration
131
+ * budget (527,040 passes) before throwing — seconds of synchronous CPU that
132
+ * stalls the event loop. Catching it here makes the failure eager and cheap,
133
+ * consistent with every other validation throw in the constructor.
134
+ *
135
+ * Only applies when the day-of-week field is unrestricted (`*`). Under Vixie
136
+ * OR semantics, a restricted day-of-week keeps the schedule satisfiable via
137
+ * the weekday path even when no listed day-of-month fits any listed month, so
138
+ * such expressions must NOT be rejected.
139
+ */
140
+ _assertSatisfiable() {
141
+ if (this._isDayOfWeekRestricted) return;
142
+ const smallestDay = this._fields.daysOfMonth[0];
143
+ if (!this._fields.months.some((month) => smallestDay <= this._maxDaysInMonth(month))) throw new Error(`Impossible cron expression: "${this._expression}". No day-of-month in [${this._fields.daysOfMonth.join(", ")}] ever occurs in month(s) [${this._fields.months.join(", ")}].`);
144
+ }
145
+ /**
146
+ * Largest possible day number for a 1-based month, taking leap years into
147
+ * account so February resolves to 29 (a date that does occur, just not every
148
+ * year). Used by satisfiability checking, never for matching a concrete date.
149
+ */
150
+ _maxDaysInMonth(month) {
151
+ if (month === 2) return 29;
152
+ if ([
153
+ 4,
154
+ 6,
155
+ 9,
156
+ 11
157
+ ].includes(month)) return 30;
158
+ return 31;
159
+ }
160
+ /**
161
+ * Parse a single cron field
162
+ *
163
+ * @param field - Field value (e.g., "*", "5", "1-5", "*‍/2", "1,3,5")
164
+ * @param min - Minimum allowed value
165
+ * @param max - Maximum allowed value
166
+ * @returns Array of matching values
167
+ */
168
+ _parseField(field, min, max) {
169
+ const values = /* @__PURE__ */ new Set();
170
+ const parts = field.split(",");
171
+ for (const part of parts) {
172
+ const [range, stepStr] = part.split("/");
173
+ const step = stepStr ? parseInt(stepStr, 10) : 1;
174
+ if (isNaN(step) || step < 1) throw new Error(`Invalid step value in cron field: "${field}"`);
175
+ let rangeStart;
176
+ let rangeEnd;
177
+ if (range === "*") {
178
+ rangeStart = min;
179
+ rangeEnd = max;
180
+ } else if (range.includes("-")) {
181
+ const [startStr, endStr] = range.split("-");
182
+ rangeStart = parseInt(startStr, 10);
183
+ rangeEnd = parseInt(endStr, 10);
184
+ if (isNaN(rangeStart) || isNaN(rangeEnd)) throw new Error(`Invalid range in cron field: "${field}"`);
185
+ if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) throw new Error(`Range out of bounds in cron field: "${field}" (valid: ${min}-${max})`);
186
+ } else {
187
+ const value = parseInt(range, 10);
188
+ if (isNaN(value)) throw new Error(`Invalid value in cron field: "${field}"`);
189
+ if (value < min || value > max) throw new Error(`Value out of bounds in cron field: "${field}" (valid: ${min}-${max})`);
190
+ rangeStart = value;
191
+ rangeEnd = value;
192
+ }
193
+ for (let i = rangeStart; i <= rangeEnd; i += step) values.add(i);
194
+ }
195
+ return Array.from(values).sort((a, b) => a - b);
196
+ }
197
+ };
198
+ /**
199
+ * Parse a cron expression string
200
+ *
201
+ * @param expression - Cron expression (5 fields)
202
+ * @returns CronParser instance
203
+ */
204
+ function parseCron(expression) {
205
+ return new CronParser(expression);
206
+ }
207
+
208
+ //#endregion
209
+ export { CronParser, parseCron };
210
+ //# sourceMappingURL=cron-parser.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron-parser.mjs","names":[],"sources":["../../../../../@warlock.js/scheduler/src/cron-parser.ts"],"sourcesContent":["import dayjs, { type Dayjs } from \"dayjs\";\n\n/**\n * Parsed cron expression fields\n */\nexport type CronFields = {\n /** Minutes (0-59) */\n minutes: number[];\n /** Hours (0-23) */\n hours: number[];\n /** Days of month (1-31) */\n daysOfMonth: number[];\n /** Months (1-12) */\n months: number[];\n /** Days of week (0-6, Sunday = 0) */\n daysOfWeek: number[];\n};\n\n/**\n * Cron expression parser\n *\n * Supports standard 5-field cron expressions:\n * ```\n * ┌───────────── minute (0-59)\n * │ ┌───────────── hour (0-23)\n * │ │ ┌───────────── day of month (1-31)\n * │ │ │ ┌───────────── month (1-12)\n * │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)\n * │ │ │ │ │\n * * * * * *\n * ```\n *\n * Supports:\n * - `*` - any value\n * - `5` - specific value\n * - `1,3,5` - list of values\n * - `1-5` - range of values\n * - `*‍/5` - step values (every 5)\n * - `1-10/2` - range with step\n *\n * **Day-of-month / day-of-week semantics:** follows Vixie cron — when both\n * fields are restricted (neither is `*`), a date matches if it satisfies\n * EITHER constraint. When only one is restricted, the other is ignored.\n *\n * @example\n * ```typescript\n * const parser = new CronParser(\"0 9 * * 1-5\"); // 9 AM weekdays\n * const nextRun = parser.nextRun();\n * ```\n */\nexport class CronParser {\n private readonly _fields: CronFields;\n private readonly _isDayOfMonthRestricted: boolean;\n private readonly _isDayOfWeekRestricted: boolean;\n\n /**\n * Creates a new CronParser instance\n *\n * @param expression - Standard 5-field cron expression\n * @throws Error if expression is invalid\n */\n public constructor(private readonly _expression: string) {\n const parts = _expression.trim().split(/\\s+/);\n\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression: \"${_expression}\". Expected 5 fields (minute hour day month weekday).`,\n );\n }\n\n const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;\n\n this._isDayOfMonthRestricted = dayOfMonth.trim() !== \"*\";\n this._isDayOfWeekRestricted = dayOfWeek.trim() !== \"*\";\n\n this._fields = {\n minutes: this._parseField(minute, 0, 59),\n hours: this._parseField(hour, 0, 23),\n daysOfMonth: this._parseField(dayOfMonth, 1, 31),\n months: this._parseField(month, 1, 12),\n daysOfWeek: this._parseField(dayOfWeek, 0, 6),\n };\n\n this._assertSatisfiable();\n }\n\n /**\n * Get the parsed cron fields\n */\n public get fields(): Readonly<CronFields> {\n return this._fields;\n }\n\n /**\n * Get the original expression\n */\n public get expression(): string {\n return this._expression;\n }\n\n /**\n * Calculate the next run time from a given date\n *\n * @param from - Starting date (defaults to now)\n * @returns Next run time as Dayjs\n */\n public nextRun(from: Dayjs = dayjs()): Dayjs {\n let date = from.add(1, \"minute\").second(0).millisecond(0);\n\n // Defensive backstop only: impossible day-of-month / month combinations are\n // rejected eagerly in the constructor (see `_assertSatisfiable`), so a\n // satisfiable expression resolves within a single year. This bound just\n // guarantees the loop can never spin unbounded.\n const maxIterations = 366 * 24 * 60; // 1 year of minutes\n let iterations = 0;\n\n while (iterations < maxIterations) {\n iterations++;\n\n // Check month\n if (!this._fields.months.includes(date.month() + 1)) {\n date = date.add(1, \"month\").date(1).hour(0).minute(0);\n continue;\n }\n\n // Day-of-month + day-of-week — Vixie OR semantics when both restricted.\n if (!this._dayMatches(date)) {\n date = date.add(1, \"day\").hour(0).minute(0);\n continue;\n }\n\n // Check hour\n if (!this._fields.hours.includes(date.hour())) {\n date = date.add(1, \"hour\").minute(0);\n continue;\n }\n\n // Check minute\n if (!this._fields.minutes.includes(date.minute())) {\n date = date.add(1, \"minute\");\n continue;\n }\n\n // All fields match!\n return date;\n }\n\n throw new Error(\n `Could not find next run time for cron expression: ${this._expression}`,\n );\n }\n\n /**\n * Check if a given date matches the cron expression\n *\n * @param date - Date to check\n * @returns true if the date matches\n */\n public matches(date: Dayjs): boolean {\n return (\n this._fields.minutes.includes(date.minute()) &&\n this._fields.hours.includes(date.hour()) &&\n this._fields.months.includes(date.month() + 1) &&\n this._dayMatches(date)\n );\n }\n\n /**\n * Day-of-month / day-of-week match using Vixie cron semantics.\n *\n * When both fields are restricted (neither was `*`), a date matches if\n * EITHER the day-of-month or the day-of-week matches. When only one is\n * restricted, only that one needs to match (the other is the full set\n * by construction, so AND degenerates to the restricted one).\n */\n private _dayMatches(date: Dayjs): boolean {\n const dayOfMonthMatches = this._fields.daysOfMonth.includes(date.date());\n const dayOfWeekMatches = this._fields.daysOfWeek.includes(date.day());\n\n if (this._isDayOfMonthRestricted && this._isDayOfWeekRestricted) {\n return dayOfMonthMatches || dayOfWeekMatches;\n }\n\n return dayOfMonthMatches && dayOfWeekMatches;\n }\n\n /**\n * Reject expressions whose day-of-month / month combination can never occur\n * (e.g. `0 0 30 2 *` — February never has a 30th).\n *\n * Without this guard, `nextRun()` would scan its full ~1-year iteration\n * budget (527,040 passes) before throwing — seconds of synchronous CPU that\n * stalls the event loop. Catching it here makes the failure eager and cheap,\n * consistent with every other validation throw in the constructor.\n *\n * Only applies when the day-of-week field is unrestricted (`*`). Under Vixie\n * OR semantics, a restricted day-of-week keeps the schedule satisfiable via\n * the weekday path even when no listed day-of-month fits any listed month, so\n * such expressions must NOT be rejected.\n */\n private _assertSatisfiable(): void {\n if (this._isDayOfWeekRestricted) {\n return;\n }\n\n const smallestDay = this._fields.daysOfMonth[0];\n\n const reachable = this._fields.months.some(\n (month) => smallestDay <= this._maxDaysInMonth(month),\n );\n\n if (!reachable) {\n throw new Error(\n `Impossible cron expression: \"${this._expression}\". No day-of-month in [${this._fields.daysOfMonth.join(\", \")}] ever occurs in month(s) [${this._fields.months.join(\", \")}].`,\n );\n }\n }\n\n /**\n * Largest possible day number for a 1-based month, taking leap years into\n * account so February resolves to 29 (a date that does occur, just not every\n * year). Used by satisfiability checking, never for matching a concrete date.\n */\n private _maxDaysInMonth(month: number): number {\n if (month === 2) {\n return 29;\n }\n\n const thirtyDayMonths = [4, 6, 9, 11];\n\n if (thirtyDayMonths.includes(month)) {\n return 30;\n }\n\n return 31;\n }\n\n /**\n * Parse a single cron field\n *\n * @param field - Field value (e.g., \"*\", \"5\", \"1-5\", \"*‍/2\", \"1,3,5\")\n * @param min - Minimum allowed value\n * @param max - Maximum allowed value\n * @returns Array of matching values\n */\n private _parseField(field: string, min: number, max: number): number[] {\n const values = new Set<number>();\n\n // Handle lists (e.g., \"1,3,5\")\n const parts = field.split(\",\");\n\n for (const part of parts) {\n // Handle step values (e.g., \"*‍/5\" or \"1-10/2\")\n const [range, stepStr] = part.split(\"/\");\n const step = stepStr ? parseInt(stepStr, 10) : 1;\n\n if (isNaN(step) || step < 1) {\n throw new Error(`Invalid step value in cron field: \"${field}\"`);\n }\n\n let rangeStart: number;\n let rangeEnd: number;\n\n if (range === \"*\") {\n // Wildcard - all values\n rangeStart = min;\n rangeEnd = max;\n } else if (range.includes(\"-\")) {\n // Range (e.g., \"1-5\")\n const [startStr, endStr] = range.split(\"-\");\n rangeStart = parseInt(startStr, 10);\n rangeEnd = parseInt(endStr, 10);\n\n if (isNaN(rangeStart) || isNaN(rangeEnd)) {\n throw new Error(`Invalid range in cron field: \"${field}\"`);\n }\n\n if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) {\n throw new Error(\n `Range out of bounds in cron field: \"${field}\" (valid: ${min}-${max})`,\n );\n }\n } else {\n // Single value\n const value = parseInt(range, 10);\n\n if (isNaN(value)) {\n throw new Error(`Invalid value in cron field: \"${field}\"`);\n }\n\n if (value < min || value > max) {\n throw new Error(\n `Value out of bounds in cron field: \"${field}\" (valid: ${min}-${max})`,\n );\n }\n\n rangeStart = value;\n rangeEnd = value;\n }\n\n // Add values with step\n for (let i = rangeStart; i <= rangeEnd; i += step) {\n values.add(i);\n }\n }\n\n return Array.from(values).sort((a, b) => a - b);\n }\n}\n\n/**\n * Parse a cron expression string\n *\n * @param expression - Cron expression (5 fields)\n * @returns CronParser instance\n */\nexport function parseCron(expression: string): CronParser {\n return new CronParser(expression);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,aAAb,MAAwB;;;;;;;CAWtB,AAAO,YAAY,AAAiB,aAAqB;EAArB;EAClC,MAAM,QAAQ,YAAY,KAAK,EAAE,MAAM,KAAK;EAE5C,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,MACR,6BAA6B,YAAY,sDAC3C;EAGF,MAAM,CAAC,QAAQ,MAAM,YAAY,OAAO,aAAa;EAErD,KAAK,0BAA0B,WAAW,KAAK,MAAM;EACrD,KAAK,yBAAyB,UAAU,KAAK,MAAM;EAEnD,KAAK,UAAU;GACb,SAAS,KAAK,YAAY,QAAQ,GAAG,EAAE;GACvC,OAAO,KAAK,YAAY,MAAM,GAAG,EAAE;GACnC,aAAa,KAAK,YAAY,YAAY,GAAG,EAAE;GAC/C,QAAQ,KAAK,YAAY,OAAO,GAAG,EAAE;GACrC,YAAY,KAAK,YAAY,WAAW,GAAG,CAAC;EAC9C;EAEA,KAAK,mBAAmB;CAC1B;;;;CAKA,IAAW,SAA+B;EACxC,OAAO,KAAK;CACd;;;;CAKA,IAAW,aAAqB;EAC9B,OAAO,KAAK;CACd;;;;;;;CAQA,AAAO,QAAQ,OAAc,MAAM,GAAU;EAC3C,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,EAAE,OAAO,CAAC,EAAE,YAAY,CAAC;EAMxD,MAAM,gBAAgB,MAAM,KAAK;EACjC,IAAI,aAAa;EAEjB,OAAO,aAAa,eAAe;GACjC;GAGA,IAAI,CAAC,KAAK,QAAQ,OAAO,SAAS,KAAK,MAAM,IAAI,CAAC,GAAG;IACnD,OA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AG,IAAI,EACtE;IAGF,aAAa;IACb,WAAW;GACb;GAGA,KAAK,IAAI,IAAI,YAAY,KAAK,UAAU,KAAK,MAC3C,OAAO,IAAI,CAAC;EAEhB;EAEA,OAAO,MAAM,KAAK,MAAM,EAAE,MAAM,GAAG,MAAM,IAAI,CAAC;CAChD;AACF;;;;;;;AAQA,SAAgB,UAAU,YAAgC;CACxD,OAAO,IAAI,WAAW,UAAU;AAClC"}
@@ -0,0 +1,5 @@
1
+ import { CronFields, CronParser, parseCron } from "./cron-parser.mjs";
2
+ import { Day, JobIntervals, JobResult, JobStatus, RetryConfig, SchedulerEvents, TimeType } from "./types.mjs";
3
+ import { Job, job } from "./job.mjs";
4
+ import { Scheduler, scheduler } from "./scheduler.mjs";
5
+ export { type CronFields, CronParser, type Day, Job, type JobIntervals, type JobResult, type JobStatus, type RetryConfig, Scheduler, type SchedulerEvents, type TimeType, job, parseCron, scheduler };
package/esm/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import { CronParser, parseCron } from "./cron-parser.mjs";
2
+ import { Job, job } from "./job.mjs";
3
+ import { Scheduler, scheduler } from "./scheduler.mjs";
4
+
5
+ export { CronParser, Job, Scheduler, job, parseCron, scheduler };