@lowdep/cron-explain 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rushabh Shah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # cron-explain
2
+
3
+ ![Zero dependencies](https://img.shields.io/badge/dependencies-0-brightgreen) ![Node](https://img.shields.io/badge/node-%3E%3D14-blue) ![License: MIT](https://img.shields.io/badge/license-MIT-green) ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey)
4
+
5
+
6
+ Translate a cron expression into plain English **and** compute its next run times — all locally. Zero dependencies.
7
+
8
+ `cronstrue` explains but is a library, not a CLI, and doesn't tell you *when* the job actually runs next. `cron-explain` does both in one command.
9
+
10
+ ---
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install -g cron-explain
16
+ ```
17
+
18
+ Or without installing:
19
+
20
+ ```bash
21
+ npx cron-explain "0 9 * * 1-5"
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Usage
27
+
28
+ ```bash
29
+ cron-explain "*/15 * * * *" # Every 15 minutes
30
+ cron-explain "0 9 * * 1-5" # 9am on weekdays
31
+ cron-explain "0 0 1 * *" --next 3 # Monthly — show next 3 runs
32
+ cron-explain "@daily" # Macros
33
+ cron-explain "30 14 * * mon" --utc # Evaluate in UTC
34
+ cron-explain "0 9 * * 1-5" --no-next # Explanation only
35
+ ```
36
+
37
+ ---
38
+
39
+ ## Example Output
40
+
41
+ ```
42
+ cron-explain 0 9 * * 1-5
43
+
44
+ At 09:00, on weekdays (Mon–Fri).
45
+
46
+ Next 5 runs (local time)
47
+ ▸ Mon 2026-06-01 09:00 in 2d
48
+ ▸ Tue 2026-06-02 09:00 in 3d
49
+ ▸ Wed 2026-06-03 09:00 in 4d
50
+ ▸ Thu 2026-06-04 09:00 in 5d
51
+ ▸ Fri 2026-06-05 09:00 in 6d
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Supported Syntax
57
+
58
+ | Feature | Example |
59
+ |---|---|
60
+ | Standard 5-field | `0 9 * * 1-5` |
61
+ | Steps | `*/15 * * * *` |
62
+ | Ranges | `0 9-17 * * *` |
63
+ | Lists | `0 0,12 * * *` |
64
+ | Month names | `0 0 1 jan,jul *` |
65
+ | Weekday names | `30 9 * * mon-fri` |
66
+ | Macros | `@daily @hourly @weekly @monthly @yearly @midnight` |
67
+
68
+ Field order: `minute hour day-of-month month day-of-week`.
69
+
70
+ ---
71
+
72
+ ## The Day-of-Month / Day-of-Week Quirk
73
+
74
+ Cron has a well-known gotcha: when **both** the day-of-month and day-of-week fields are restricted (neither is `*`), the job runs when **either** matches — not both. `cron-explain` honors this in both the English description ("on day-of-month 1 *or* on Monday") and the computed run times.
75
+
76
+ ---
77
+
78
+ ## Options
79
+
80
+ | Flag | Description |
81
+ |---|---|
82
+ | `-n, --next <N>` | Number of upcoming runs to show (default: 5, max: 50) |
83
+ | `--utc` | Evaluate run times in UTC instead of local time |
84
+ | `--no-next` | Print only the English explanation |
85
+ | `--json` | Machine-readable output |
86
+
87
+ ---
88
+
89
+ ## License
90
+
91
+ MIT
92
+
93
+ ---
94
+
95
+ ## Keywords
96
+
97
+ `cron expression` · `explain cron` · `crontab` · `cron next run` · `cronstrue alternative` · `cron parser` · `human readable cron` · `schedule` · `zero dependencies` · `cli`
98
+
99
+ ---
100
+
101
+ <div align="center">
102
+
103
+ **Built to solve, shared to help — Rushabh Shah 🛠️✨**
104
+
105
+ <sub>One of 40+ zero-dependency developer CLI tools — no <code>node_modules</code>, ever.</sub>
106
+
107
+ </div>
@@ -0,0 +1,318 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const VERSION = '1.0.0';
5
+
6
+ // ─── ANSI ─────────────────────────────────────────────────────────────────────
7
+ const isTTY = process.stdout.isTTY;
8
+ const c = (code, t) => isTTY ? `\x1b[${code}m${t}\x1b[0m` : t;
9
+ const bold = t => c('1', t);
10
+ const dim = t => c('2', t);
11
+ const red = t => c('31', t);
12
+ const green = t => c('32', t);
13
+ const yellow = t => c('33', t);
14
+ const cyan = t => c('36', t);
15
+
16
+ // ─── Field metadata ───────────────────────────────────────────────────────────
17
+ const FIELDS = [
18
+ { name: 'minute', min: 0, max: 59 },
19
+ { name: 'hour', min: 0, max: 23 },
20
+ { name: 'dayOfMonth', min: 1, max: 31 },
21
+ { name: 'month', min: 1, max: 12 },
22
+ { name: 'dayOfWeek', min: 0, max: 6 }, // 0 = Sunday (7 also allowed → 0)
23
+ ];
24
+
25
+ const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
26
+ const DOW = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
27
+ const MON_ABBR = { jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12 };
28
+ const DOW_ABBR = { sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6 };
29
+
30
+ // Named macros
31
+ const MACROS = {
32
+ '@yearly': '0 0 1 1 *',
33
+ '@annually': '0 0 1 1 *',
34
+ '@monthly': '0 0 1 * *',
35
+ '@weekly': '0 0 * * 0',
36
+ '@daily': '0 0 * * *',
37
+ '@midnight': '0 0 * * *',
38
+ '@hourly': '0 * * * *',
39
+ };
40
+
41
+ // ─── Parse a single field into a sorted set of allowed values ─────────────────
42
+ function parseField(raw, field) {
43
+ const { min, max, name } = field;
44
+ const values = new Set();
45
+ let star = false;
46
+
47
+ const normalize = (tok) => {
48
+ const low = tok.toLowerCase();
49
+ if (name === 'month' && MON_ABBR[low] !== undefined) return MON_ABBR[low];
50
+ if (name === 'dayOfWeek' && DOW_ABBR[low] !== undefined) return DOW_ABBR[low];
51
+ const n = parseInt(tok, 10);
52
+ if (Number.isNaN(n)) throw new Error(`invalid value "${tok}" in ${name} field`);
53
+ // dayOfWeek 7 == 0 (Sunday)
54
+ if (name === 'dayOfWeek' && n === 7) return 0;
55
+ if (n < min || n > max) throw new Error(`${name} value ${n} out of range ${min}-${max}`);
56
+ return n;
57
+ };
58
+
59
+ for (const part of raw.split(',')) {
60
+ let stepBase = part, step = 1;
61
+ const slash = part.split('/');
62
+ if (slash.length === 2) { stepBase = slash[0]; step = parseInt(slash[1], 10); if (!step) throw new Error(`invalid step in ${name}`); }
63
+
64
+ let lo, hi;
65
+ if (stepBase === '*') { lo = min; hi = max; if (step > 1 || slash.length === 2) {} else star = true; }
66
+ else if (stepBase.includes('-')) {
67
+ const [a, b] = stepBase.split('-');
68
+ lo = normalize(a); hi = normalize(b);
69
+ } else {
70
+ lo = hi = normalize(stepBase);
71
+ }
72
+
73
+ if (lo > hi) { // wrap-around range (e.g. fri-mon)
74
+ for (let v = lo; v <= max; v += step) values.add(v);
75
+ for (let v = min; v <= hi; v += step) values.add(v);
76
+ } else {
77
+ for (let v = lo; v <= hi; v += step) values.add(v);
78
+ }
79
+ }
80
+
81
+ return { values: [...values].sort((a, b) => a - b), star, raw };
82
+ }
83
+
84
+ // ─── Parse full expression ────────────────────────────────────────────────────
85
+ function parseCron(expr) {
86
+ let e = expr.trim();
87
+ if (MACROS[e.toLowerCase()]) e = MACROS[e.toLowerCase()];
88
+ const parts = e.split(/\s+/);
89
+ if (parts.length !== 5) {
90
+ throw new Error(`expected 5 fields, got ${parts.length}${parts.length === 6 ? ' (seconds field not supported)' : ''}`);
91
+ }
92
+ return FIELDS.map((f, i) => parseField(parts[i], f));
93
+ }
94
+
95
+ // ─── Humanize ─────────────────────────────────────────────────────────────────
96
+ function listPhrase(values, mapFn) {
97
+ const mapped = values.map(mapFn);
98
+ if (mapped.length === 1) return mapped[0];
99
+ if (mapped.length === 2) return `${mapped[0]} and ${mapped[1]}`;
100
+ return mapped.slice(0, -1).join(', ') + ', and ' + mapped[mapped.length - 1];
101
+ }
102
+
103
+ function isContiguousStep(field) {
104
+ // Detect "*/n" style for nicer phrasing
105
+ const m = field.raw.match(/^\*\/(\d+)$/);
106
+ return m ? parseInt(m[1], 10) : null;
107
+ }
108
+
109
+ function pad2(n) { return String(n).padStart(2, '0'); }
110
+
111
+ function explain(fields) {
112
+ const [minute, hour, dom, month, dow] = fields;
113
+
114
+ // Time-of-day phrase
115
+ let timePhrase;
116
+ const minStep = isContiguousStep(minute);
117
+ const hourStep = isContiguousStep(hour);
118
+
119
+ if (minute.star && hour.star) {
120
+ timePhrase = 'every minute';
121
+ } else if (minStep && hour.star) {
122
+ timePhrase = `every ${minStep} minutes`;
123
+ } else if (minute.values.length === 1 && hour.star) {
124
+ timePhrase = `at minute ${minute.values[0]} of every hour`;
125
+ } else if (minute.star && !hour.star) {
126
+ timePhrase = `every minute of ${hour.values.length === 1 ? `hour ${hour.values[0]}` : 'the selected hours'}`;
127
+ } else if (hourStep && minute.values.length === 1) {
128
+ timePhrase = `at minute ${minute.values[0]} past every ${hourStep} hours`;
129
+ } else if (minute.values.length === 1 && hour.values.length === 1) {
130
+ timePhrase = `at ${pad2(hour.values[0])}:${pad2(minute.values[0])}`;
131
+ } else {
132
+ // General: list specific times when small, else describe
133
+ const times = [];
134
+ for (const h of hour.values) for (const m of minute.values) times.push(`${pad2(h)}:${pad2(m)}`);
135
+ timePhrase = times.length <= 6 ? `at ${listPhrase(times, t => t)}` : `at ${minute.values.length} minute(s) past ${hour.values.length} hour(s)`;
136
+ }
137
+
138
+ // Day-of-month phrase
139
+ let domPhrase = '';
140
+ if (!dom.star) {
141
+ const domStep = isContiguousStep(dom);
142
+ if (domStep) domPhrase = `every ${domStep} days of the month`;
143
+ else domPhrase = `on day-of-month ${listPhrase(dom.values, v => String(v))}`;
144
+ }
145
+
146
+ // Month phrase
147
+ let monthPhrase = '';
148
+ if (!month.star) {
149
+ monthPhrase = `in ${listPhrase(month.values, v => MONTHS[v - 1])}`;
150
+ }
151
+
152
+ // Day-of-week phrase
153
+ let dowPhrase = '';
154
+ if (!dow.star) {
155
+ // Contiguous weekday range nicety
156
+ const v = dow.values;
157
+ if (v.length === 5 && v.join() === '1,2,3,4,5') dowPhrase = 'on weekdays (Mon–Fri)';
158
+ else if (v.length === 2 && v.join() === '0,6') dowPhrase = 'on weekends (Sat–Sun)';
159
+ else dowPhrase = `on ${listPhrase(v, d => DOW[d])}`;
160
+ }
161
+
162
+ // Compose. Cron quirk: if BOTH dom and dow are restricted, it's an OR.
163
+ let dayClause;
164
+ if (!dom.star && !dow.star) {
165
+ dayClause = `${domPhrase} ${dim('or')} ${dowPhrase}`;
166
+ } else {
167
+ dayClause = [domPhrase, dowPhrase].filter(Boolean).join(' ');
168
+ }
169
+
170
+ const pieces = [timePhrase];
171
+ if (dayClause) pieces.push(dayClause);
172
+ if (monthPhrase) pieces.push(monthPhrase);
173
+
174
+ let sentence = pieces.join(', ');
175
+ return sentence.charAt(0).toUpperCase() + sentence.slice(1) + '.';
176
+ }
177
+
178
+ // ─── Next run times ───────────────────────────────────────────────────────────
179
+ function matches(fields, date, useUTC) {
180
+ const [minute, hour, dom, month, dow] = fields;
181
+ const mn = useUTC ? date.getUTCMinutes() : date.getMinutes();
182
+ const hr = useUTC ? date.getUTCHours() : date.getHours();
183
+ const dm = useUTC ? date.getUTCDate() : date.getDate();
184
+ const mo = (useUTC ? date.getUTCMonth() : date.getMonth()) + 1;
185
+ const dw = useUTC ? date.getUTCDay() : date.getDay();
186
+
187
+ if (!minute.values.includes(mn)) return false;
188
+ if (!hour.values.includes(hr)) return false;
189
+ if (!month.values.includes(mo)) return false;
190
+
191
+ // Day matching: if both dom and dow restricted → OR; if one is * → AND on the other
192
+ const domMatch = dom.values.includes(dm);
193
+ const dowMatch = dow.values.includes(dw);
194
+ if (!dom.star && !dow.star) return domMatch || dowMatch;
195
+ if (!dom.star) return domMatch;
196
+ if (!dow.star) return dowMatch;
197
+ return true;
198
+ }
199
+
200
+ function nextRuns(fields, count, from, useUTC) {
201
+ const runs = [];
202
+ const d = new Date(from.getTime());
203
+ // Advance to the next whole minute
204
+ d.setSeconds(0, 0);
205
+ d.setMinutes(d.getMinutes() + 1);
206
+
207
+ let guard = 0;
208
+ const MAX_ITER = 5 * 366 * 24 * 60; // ~5 years of minutes
209
+ while (runs.length < count && guard++ < MAX_ITER) {
210
+ if (matches(fields, d, useUTC)) runs.push(new Date(d.getTime()));
211
+ d.setMinutes(d.getMinutes() + 1);
212
+ }
213
+ return runs;
214
+ }
215
+
216
+ function fmtDate(d, useUTC) {
217
+ const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
218
+ if (useUTC) {
219
+ return `${days[d.getUTCDay()]} ${d.getUTCFullYear()}-${pad2(d.getUTCMonth()+1)}-${pad2(d.getUTCDate())} ${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())} UTC`;
220
+ }
221
+ return `${days[d.getDay()]} ${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
222
+ }
223
+
224
+ function relTime(d, from) {
225
+ const ms = d.getTime() - from.getTime();
226
+ const s = Math.round(ms / 1000);
227
+ const m = Math.round(s / 60), h = Math.round(m / 60), days = Math.round(h / 24);
228
+ if (s < 90) return `in ${s}s`;
229
+ if (m < 90) return `in ${m}m`;
230
+ if (h < 36) return `in ${h}h`;
231
+ return `in ${days}d`;
232
+ }
233
+
234
+ // ─── CLI ──────────────────────────────────────────────────────────────────────
235
+ const args = process.argv.slice(2);
236
+ const VALUE_FLAGS = new Set(['-n', '--next']);
237
+
238
+ function getFlag(...names) { for (const f of names) { const i = args.indexOf(f); if (i !== -1) return args[i + 1]; } return null; }
239
+ function hasFlag(...names) { return names.some(f => args.includes(f)); }
240
+
241
+ const positional = [];
242
+ for (let i = 0; i < args.length; i++) {
243
+ if (args[i].startsWith('-') && !/^-?\d/.test(args[i])) { if (VALUE_FLAGS.has(args[i])) i++; }
244
+ else positional.push(args[i]);
245
+ }
246
+
247
+ if (hasFlag('--version', '-v')) { console.log(`cron-explain v${VERSION}`); process.exit(0); }
248
+
249
+ if (hasFlag('--help', '-h') || !positional.length) {
250
+ console.log(`
251
+ ${bold('cron-explain')} — Explain a cron expression and show its next run times, zero deps
252
+
253
+ ${bold('USAGE')}
254
+ cron-explain "<cron expression>" [options]
255
+
256
+ ${bold('OPTIONS')}
257
+ -n, --next <N> Show the next N run times (default: 5)
258
+ --utc Evaluate run times in UTC (default: local time)
259
+ --no-next Only print the English explanation
260
+ --json JSON output
261
+ --version Show version
262
+
263
+ ${bold('SUPPORTS')}
264
+ 5-field cron · ranges (1-5) · lists (1,3,5) · steps (*/15) ·
265
+ month/day names (jan, mon) · macros (@daily, @hourly, @weekly, ...)
266
+
267
+ ${bold('EXAMPLES')}
268
+ cron-explain "*/15 * * * *" # Every 15 minutes
269
+ cron-explain "0 9 * * 1-5" # 9am on weekdays
270
+ cron-explain "0 0 1 * *" --next 3 # Monthly, next 3 runs
271
+ cron-explain "@daily" # Macro
272
+ cron-explain "30 14 * * mon" --utc
273
+ `);
274
+ process.exit(positional.length ? 0 : 1);
275
+ }
276
+
277
+ const expr = positional[0];
278
+ const count = Math.max(1, Math.min(50, parseInt(getFlag('-n', '--next') || '5', 10)));
279
+ const useUTC = hasFlag('--utc');
280
+ const noNext = hasFlag('--no-next');
281
+ const asJson = hasFlag('--json');
282
+
283
+ let fields;
284
+ try {
285
+ fields = parseCron(expr);
286
+ } catch (e) {
287
+ console.error(red(`\nInvalid cron expression: ${e.message}\n`));
288
+ process.exit(1);
289
+ }
290
+
291
+ const plainDesc = explain(fields).replace(/\x1b\[[0-9;]*m/g, '');
292
+ const now = new Date();
293
+ const runs = noNext ? [] : nextRuns(fields, count, now, useUTC);
294
+
295
+ if (asJson) {
296
+ console.log(JSON.stringify({
297
+ expression: expr.trim(),
298
+ description: plainDesc,
299
+ nextRuns: runs.map(r => r.toISOString()),
300
+ timezone: useUTC ? 'UTC' : Intl.DateTimeFormat().resolvedOptions().timeZone,
301
+ }, null, 2));
302
+ process.exit(0);
303
+ }
304
+
305
+ console.log(`\n${bold('cron-explain')} ${cyan(expr.trim())}\n`);
306
+ console.log(` ${explain(fields)}\n`);
307
+
308
+ if (!noNext) {
309
+ if (!runs.length) {
310
+ console.log(yellow(' No upcoming run times found in the next ~5 years (impossible schedule?).\n'));
311
+ } else {
312
+ console.log(` ${bold('Next ' + runs.length + ' run' + (runs.length > 1 ? 's' : ''))} ${dim(useUTC ? '(UTC)' : '(local time)')}`);
313
+ for (const r of runs) {
314
+ console.log(` ${green('▸')} ${fmtDate(r, useUTC)} ${dim(relTime(r, now))}`);
315
+ }
316
+ console.log();
317
+ }
318
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@lowdep/cron-explain",
3
+ "version": "1.0.0",
4
+ "description": "Explain a cron expression in plain English and show the next N run times — supports macros, names, steps — zero dependencies",
5
+ "bin": {
6
+ "cron-explain": "bin/cron-explain.js"
7
+ },
8
+ "keywords": [
9
+ "cron",
10
+ "crontab",
11
+ "schedule",
12
+ "explain",
13
+ "next-run",
14
+ "cli",
15
+ "developer-tools",
16
+ "zero-dependencies",
17
+ "cron expression",
18
+ "explain cron",
19
+ "cron next run",
20
+ "cronstrue alternative",
21
+ "cron parser",
22
+ "human readable cron",
23
+ "zero dependencies"
24
+ ],
25
+ "author": "Rushabh Shah",
26
+ "license": "MIT",
27
+ "engines": {
28
+ "node": ">=14"
29
+ },
30
+ "files": [
31
+ "bin/"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/Rushabh5000/cron-explain.git"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/Rushabh5000/cron-explain/issues"
39
+ },
40
+ "homepage": "https://github.com/Rushabh5000/cron-explain#readme",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ }
44
+ }