@aidenhq/sdk 0.5.4 → 0.5.5
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/README.md +2 -2
- package/dist/assets/page-kit.css +142 -0
- package/dist/assets/page-kit.js +311 -0
- package/dist/src/card-words.d.ts +8 -0
- package/dist/src/card-words.js +29 -0
- package/dist/src/face-kit.d.ts +20 -0
- package/dist/src/face-kit.js +32 -0
- package/dist/src/module-mcp.d.ts +39 -0
- package/dist/src/module-mcp.js +80 -0
- package/dist/src/number-setting.d.ts +11 -0
- package/dist/src/number-setting.js +27 -0
- package/dist/src/reason-codes.d.ts +14 -0
- package/dist/src/reason-codes.js +45 -0
- package/dist/src/requested-parent.d.ts +33 -0
- package/dist/src/requested-parent.js +56 -0
- package/dist/src/schedule.d.ts +52 -0
- package/dist/src/schedule.js +653 -0
- package/dist/src/teammate-name.d.ts +4 -0
- package/dist/src/teammate-name.js +25 -0
- package/dist/src/url-setting.d.ts +5 -0
- package/dist/src/url-setting.js +49 -0
- package/package.json +10 -1
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
// Plain-English schedules: the one parser every schedule surface uses (compile, the board's repeats and routine fields, the task
|
|
2
|
+
// tools, Aiden's chat path). English or a five-field cron in, cron lines plus the schedule in words out. Deterministic and
|
|
3
|
+
// dependency-free; the time zone stays outside it (callers pass it to Paperclip). The board imports @aidenhq/sdk/schedule;
|
|
4
|
+
// compile and the kernel import this source.
|
|
5
|
+
//
|
|
6
|
+
// Paperclip's scheduler takes lists, ranges and steps, and a day of month AND a weekday must both match (the first Monday is days 1-7
|
|
7
|
+
// on a Monday). It has no "last day" and no every-other-week: those are refused with the reason, with two examples that work.
|
|
8
|
+
export const MIN_GAP_MINUTES = 15;
|
|
9
|
+
/** The time of day a day-only schedule ("every Monday") runs at when the owner names none, in minutes: 07:00. */
|
|
10
|
+
export const DEFAULT_TIME = 7 * 60;
|
|
11
|
+
const EXAMPLES = ["every weekday at 8am", "every 30 minutes on weekdays between 9:00 and 17:00"];
|
|
12
|
+
const refuse = (error, examples = EXAMPLES) => ({ error, examples });
|
|
13
|
+
export const isRefusal = (r) => "error" in r;
|
|
14
|
+
/** A refusal as one message that carries its examples (a tool error or a 400 is a string): "<why>. Try "<a>" or "<b>"." */
|
|
15
|
+
export const refusalText = (r) => `${r.error.replace(/[.\s]+$/, "")}. Try "${r.examples[0]}" or "${r.examples[1]}".`;
|
|
16
|
+
// ------------------------------------------------------------------ words
|
|
17
|
+
const SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
18
|
+
const LONG = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
19
|
+
const PLURAL = ["Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"];
|
|
20
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
21
|
+
const NTH = ["first", "second", "third", "fourth"];
|
|
22
|
+
const num = (s) => (/^\d+$/.test(s) ? Number(s) : NaN);
|
|
23
|
+
/** "8:45 AM" (12h) or "08:45" (24h): the board's clock words (services/board/src/clock.ts), so the one formatter's output matches. */
|
|
24
|
+
export function clockWords(hour, minute, fmt = "12h") {
|
|
25
|
+
const mm = String(minute).padStart(2, "0");
|
|
26
|
+
return fmt === "24h" ? `${String(hour).padStart(2, "0")}:${mm}` : `${hour % 12 || 12}:${mm} ${hour < 12 ? "AM" : "PM"}`;
|
|
27
|
+
}
|
|
28
|
+
const ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10 > 3 ? 0 : n % 10]}`;
|
|
29
|
+
const andList = (xs) => (xs.length < 2 ? xs.join("") : `${xs.slice(0, -1).join(", ")} and ${xs.at(-1)}`);
|
|
30
|
+
function days(dow) {
|
|
31
|
+
if (dow === "*")
|
|
32
|
+
return "daily";
|
|
33
|
+
if (dow === "1-5")
|
|
34
|
+
return "weekdays";
|
|
35
|
+
if (dow === "0,6" || dow === "6,0" || dow === "6-7" || dow === "6,7")
|
|
36
|
+
return "weekends";
|
|
37
|
+
const list = dow.split(",").map((d) => num(d) % 7);
|
|
38
|
+
if (list.some(Number.isNaN))
|
|
39
|
+
return null;
|
|
40
|
+
return list.length === 1 ? PLURAL[list[0]] : list.map((d) => SHORT[d]).join(", ");
|
|
41
|
+
}
|
|
42
|
+
/** The months field in words: "" for every month, "every 3 months" for an even step, else the month names. */
|
|
43
|
+
function monthsText(mon) {
|
|
44
|
+
if (mon === "*")
|
|
45
|
+
return "";
|
|
46
|
+
const list = mon.split(",").map(num);
|
|
47
|
+
if (list.some((m) => Number.isNaN(m) || m < 1 || m > 12))
|
|
48
|
+
return null;
|
|
49
|
+
const step = list.length > 1 ? list[1] - list[0] : 0;
|
|
50
|
+
if (step > 1 && 12 % step === 0 && list.length === 12 / step && list.every((m, i) => m === list[0] + i * step))
|
|
51
|
+
return `every ${step} months`;
|
|
52
|
+
return list.map((m) => MONTHS[m - 1]).join(", ");
|
|
53
|
+
}
|
|
54
|
+
/** A cron line in plain words ("weekdays 8:45 AM", "every 4h", "every 30 min, 8:00 AM to 8:59 PM"); the cron itself when it's unusual. */
|
|
55
|
+
export function describeCron(cron, fmt = "12h") {
|
|
56
|
+
const clock = (h, m = 0) => clockWords(h, m, fmt);
|
|
57
|
+
const f = cron.trim().split(/\s+/);
|
|
58
|
+
if (f.length !== 5)
|
|
59
|
+
return cron;
|
|
60
|
+
const [m, h, dom, mon, dow] = f;
|
|
61
|
+
const months = monthsText(mon);
|
|
62
|
+
if (months === null)
|
|
63
|
+
return cron;
|
|
64
|
+
const on = days(dow);
|
|
65
|
+
if (!on)
|
|
66
|
+
return cron;
|
|
67
|
+
const tail = `${on === "daily" ? "" : `, ${on}`}${months ? `, ${months}` : ""}`;
|
|
68
|
+
let every;
|
|
69
|
+
if ((every = /^\*\/(\d+)$/.exec(m)) && dom === "*") {
|
|
70
|
+
const range = /^(\d+)-(\d+)$/.exec(h);
|
|
71
|
+
if (h === "*")
|
|
72
|
+
return `every ${every[1]} min${tail}`;
|
|
73
|
+
if (range)
|
|
74
|
+
return `every ${every[1]} min, ${clock(Number(range[1]))} to ${clock(Number(range[2]), 59)}${tail}`;
|
|
75
|
+
return cron;
|
|
76
|
+
}
|
|
77
|
+
if (!/^\d+$/.test(m))
|
|
78
|
+
return cron;
|
|
79
|
+
if ((every = /^\*\/(\d+)$/.exec(h)) && dom === "*")
|
|
80
|
+
return `${every[1] === "1" ? "hourly" : `every ${every[1]}h`}${tail}`;
|
|
81
|
+
if (h === "*" && dom === "*")
|
|
82
|
+
return `hourly${tail}`;
|
|
83
|
+
const hours = h.split(",").map(num);
|
|
84
|
+
if (hours.some(Number.isNaN))
|
|
85
|
+
return cron;
|
|
86
|
+
const times = hours.map((x) => clock(x, Number(m))).join(" and ");
|
|
87
|
+
if (dom !== "*") {
|
|
88
|
+
const d = num(dom);
|
|
89
|
+
const week = /^(\d+)-(\d+)$/.exec(dom);
|
|
90
|
+
const mdays = months ? `${months}, ` : "";
|
|
91
|
+
// Days 1-7 on a Monday is the first Monday: the board's old "monthly_weekday" rows are crons like this.
|
|
92
|
+
if (week && dow !== "*" && !on.includes(",") && Number(week[2]) - Number(week[1]) === 6 && (Number(week[1]) - 1) % 7 === 0) {
|
|
93
|
+
const wd = LONG[num(dow) % 7];
|
|
94
|
+
return wd ? `${mdays || "monthly, "}the ${NTH[(Number(week[1]) - 1) / 7]} ${wd}, ${times}` : cron;
|
|
95
|
+
}
|
|
96
|
+
if (Number.isNaN(d) || dow !== "*")
|
|
97
|
+
return cron;
|
|
98
|
+
return `${months ? `${months}, ` : "monthly "}on the ${ordinal(d)}, ${times}`;
|
|
99
|
+
}
|
|
100
|
+
return `${on}${months ? `, ${months}` : ""} ${times}`;
|
|
101
|
+
}
|
|
102
|
+
// ------------------------------------------------------------------ cron fields
|
|
103
|
+
const RANGES = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
|
|
104
|
+
const NAMES = [{}, {}, {}, { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }, { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 }];
|
|
105
|
+
/** The most days each month can have (February's 29th exists in leap years). */
|
|
106
|
+
const MONTH_DAYS = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
107
|
+
/** The values a cron field covers (null when the field isn't valid): lists, ranges, steps, `*`, and names in month and weekday. */
|
|
108
|
+
function expand(field, i) {
|
|
109
|
+
const [lo, hi] = RANGES[i];
|
|
110
|
+
const out = new Set();
|
|
111
|
+
for (const part of field.split(",")) {
|
|
112
|
+
const [span, step, extra] = part.split("/");
|
|
113
|
+
if (extra !== undefined || span === undefined || span === "")
|
|
114
|
+
return null;
|
|
115
|
+
if (step !== undefined && !(/^\d+$/.test(step) && Number(step) > 0))
|
|
116
|
+
return null;
|
|
117
|
+
const val = (s) => (/^\d+$/.test(s) ? Number(s) : NAMES[i][s.toLowerCase()]);
|
|
118
|
+
let a;
|
|
119
|
+
let b;
|
|
120
|
+
if (span === "*")
|
|
121
|
+
[a, b] = [lo, hi];
|
|
122
|
+
else {
|
|
123
|
+
const ends = span.split("-");
|
|
124
|
+
if (ends.length > 2)
|
|
125
|
+
return null;
|
|
126
|
+
a = val(ends[0]);
|
|
127
|
+
b = ends.length === 2 ? val(ends[1]) : step !== undefined ? hi : a;
|
|
128
|
+
}
|
|
129
|
+
if (a === undefined || b === undefined || a < lo || b > hi || a > b)
|
|
130
|
+
return null;
|
|
131
|
+
for (let v = a; v <= b; v += step === undefined ? 1 : Number(step))
|
|
132
|
+
out.add(v);
|
|
133
|
+
}
|
|
134
|
+
return [...out].sort((x, y) => x - y);
|
|
135
|
+
}
|
|
136
|
+
/** The minute-of-day values a set of cron lines can fire at (minute × hour; the day fields never bring two runs closer within a day). */
|
|
137
|
+
function timesOf(crons) {
|
|
138
|
+
const at = new Set();
|
|
139
|
+
for (const c of crons) {
|
|
140
|
+
const f = c.trim().split(/\s+/);
|
|
141
|
+
if (f.length !== 5)
|
|
142
|
+
return null;
|
|
143
|
+
const [mins, hours] = [expand(f[0], 0), expand(f[1], 1)];
|
|
144
|
+
if (!mins || !hours || [2, 3, 4].some((i) => !expand(f[i], i)))
|
|
145
|
+
return null;
|
|
146
|
+
for (const h of hours)
|
|
147
|
+
for (const m of mins)
|
|
148
|
+
at.add(h * 60 + m);
|
|
149
|
+
}
|
|
150
|
+
return [...at].sort((a, b) => a - b);
|
|
151
|
+
}
|
|
152
|
+
/** The smallest gap between consecutive times of day, wrapping past midnight. */
|
|
153
|
+
const gapOf = (times) => (times.length < 2 ? 1440 : Math.min(...times.map((t, i) => (i === times.length - 1 ? times[0] + 1440 - t : times[i + 1] - t))));
|
|
154
|
+
/** Whether two of the cron lines can fire at the same moment: a time of day they share on a date both match (a day of the month and a weekday must both match). */
|
|
155
|
+
function coincide(crons) {
|
|
156
|
+
const lines = crons.map((c) => c.trim().split(/\s+/).map((x, i) => expand(x, i)));
|
|
157
|
+
if (lines.some((l) => l.length !== 5 || l.some((x) => !x)))
|
|
158
|
+
return false;
|
|
159
|
+
const share = (a, b) => a.some((x) => b.includes(x));
|
|
160
|
+
const clock = (l) => l[1].flatMap((h) => l[0].map((m) => h * 60 + m));
|
|
161
|
+
// A shared day of the month that exists in a shared month (February has no 30th), and a shared weekday.
|
|
162
|
+
const day = (a, b) => {
|
|
163
|
+
const months = a[3].filter((m) => b[3].includes(m));
|
|
164
|
+
return months.some((m) => a[2].some((d) => d <= MONTH_DAYS[m - 1] && b[2].includes(d))) && share(a[4].map((d) => d % 7), b[4].map((d) => d % 7));
|
|
165
|
+
};
|
|
166
|
+
for (let i = 0; i < lines.length; i++)
|
|
167
|
+
for (let k = i + 1; k < lines.length; k++)
|
|
168
|
+
if (day(lines[i], lines[k]) && share(clock(lines[i]), clock(lines[k])))
|
|
169
|
+
return true;
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
/** The smallest gap, in minutes, between the times of day a set of cron lines fires at: 0 when two lines fire at the same moment (null when one isn't a valid cron line). */
|
|
173
|
+
export function minGapOf(crons) {
|
|
174
|
+
const times = timesOf(crons);
|
|
175
|
+
if (!times?.length)
|
|
176
|
+
return null;
|
|
177
|
+
return coincide(crons) ? 0 : gapOf(times);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The longest gap, in minutes, between two consecutive fires of a set of cron lines (a day of the month and a weekday must both
|
|
181
|
+
* match), read over 800 days of a leap-year calendar so a monthly or yearly line shows its real gap. Infinity when a line fires
|
|
182
|
+
* fewer than twice in that time; null when one isn't a valid cron line. Without a zone, clock times only: a daylight-saving hour
|
|
183
|
+
* is not counted. With a zone, each fire is a real instant there over the 800 days from today, so the gap is elapsed time (a time
|
|
184
|
+
* a spring-forward change skips isn't fired, and a change already behind isn't counted).
|
|
185
|
+
*/
|
|
186
|
+
export function maxGapMinutes(crons, tz) {
|
|
187
|
+
const lines = crons.map((c) => c.trim().split(/\s+/)).map((f) => (f.length === 5 ? f.map((x, i) => expand(x, i)) : null));
|
|
188
|
+
if (!lines.length || lines.some((l) => !l || l.some((x) => !x)))
|
|
189
|
+
return null;
|
|
190
|
+
const fires = [];
|
|
191
|
+
// Clock times read a leap-year calendar, so a monthly or yearly line shows its real gap. A zone reads from today: a past offset
|
|
192
|
+
// change (Kazakhstan's 2024 UTC+6 to UTC+5) isn't a gap a routine running from now will see, so a valid schedule isn't refused
|
|
193
|
+
// for one, while a daylight-saving change ahead is.
|
|
194
|
+
const today = new Date();
|
|
195
|
+
const from = tz ? Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()) : Date.UTC(2024, 0, 1);
|
|
196
|
+
for (let i = 0; i < 800; i++) {
|
|
197
|
+
const day = new Date(from + i * 86_400_000);
|
|
198
|
+
const at = new Set();
|
|
199
|
+
for (const l of lines) {
|
|
200
|
+
const [mins, hours, doms, mons, dows] = l;
|
|
201
|
+
if (doms.includes(day.getUTCDate()) && mons.includes(day.getUTCMonth() + 1) && dows.some((w) => w % 7 === day.getUTCDay()))
|
|
202
|
+
for (const h of hours)
|
|
203
|
+
for (const m of mins)
|
|
204
|
+
at.add(h * 60 + m);
|
|
205
|
+
}
|
|
206
|
+
for (const t of [...at].sort((a, b) => a - b)) {
|
|
207
|
+
if (!tz) {
|
|
208
|
+
fires.push((i * 1440 + t) * 60_000);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const wall = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), Math.floor(t / 60), t % 60);
|
|
212
|
+
// The zone's offset at that wall time, then again at the instant it implies: a time the change skips has no instant.
|
|
213
|
+
const guess = wall - offsetAt(wall, tz);
|
|
214
|
+
const instant = wall - offsetAt(guess, tz);
|
|
215
|
+
if (offsetAt(instant, tz) !== wall - instant)
|
|
216
|
+
continue;
|
|
217
|
+
fires.push(instant);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (fires.length < 2)
|
|
221
|
+
return Infinity;
|
|
222
|
+
return Math.max(...fires.slice(1).map((t, i) => t - fires[i])) / 60_000;
|
|
223
|
+
}
|
|
224
|
+
function measured(crons, words) {
|
|
225
|
+
const times = timesOf(crons);
|
|
226
|
+
if (!times?.length)
|
|
227
|
+
return refuse("that isn't a schedule a cron line can say");
|
|
228
|
+
const minGapMinutes = gapOf(times);
|
|
229
|
+
if (minGapMinutes < MIN_GAP_MINUTES)
|
|
230
|
+
return refuse(`it would run every ${minGapMinutes} minutes at times; a schedule runs at most every ${MIN_GAP_MINUTES} minutes (counting past midnight)`, ["every 15 minutes", "every 30 minutes on weekdays between 9:00 and 17:00"]);
|
|
231
|
+
return { crons, words, perDay: times.length, minGapMinutes };
|
|
232
|
+
}
|
|
233
|
+
// ------------------------------------------------------------------ English
|
|
234
|
+
const DAY = "(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tues?|wed|thu(?:rs?)?|fri|sat|sun)s?";
|
|
235
|
+
const TIME = "(?:noon|midnight|\\d{1,2}(?::\\d{2})?\\s*(?:a\\.?m\\.?|p\\.?m\\.?)?)";
|
|
236
|
+
const NTH_WORD = "(?:first|second|third|fourth|1st|2nd|3rd|4th)";
|
|
237
|
+
const dayIndex = (s) => ({ sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 })[s.slice(0, 3)];
|
|
238
|
+
const nthIndex = (s) => ({ first: 1, "1st": 1, second: 2, "2nd": 2, third: 3, "3rd": 3, fourth: 4, "4th": 4 })[s];
|
|
239
|
+
/** "8am", "17:00", "5:30 pm", "noon" as minutes of the day; null when it isn't a time. */
|
|
240
|
+
function clockOf(s) {
|
|
241
|
+
const t = s.trim().toLowerCase().replace(/\./g, "").replace(/\s+/g, "");
|
|
242
|
+
if (t === "noon")
|
|
243
|
+
return 720;
|
|
244
|
+
if (t === "midnight")
|
|
245
|
+
return 0;
|
|
246
|
+
const m = /^(\d{1,2})(?::(\d{2}))?(am|pm)?$/.exec(t);
|
|
247
|
+
if (!m)
|
|
248
|
+
return null;
|
|
249
|
+
let h = Number(m[1]);
|
|
250
|
+
const min = Number(m[2] ?? 0);
|
|
251
|
+
if (min > 59)
|
|
252
|
+
return null;
|
|
253
|
+
if (m[3]) {
|
|
254
|
+
if (h < 1 || h > 12)
|
|
255
|
+
return null;
|
|
256
|
+
h = (h % 12) + (m[3] === "pm" ? 12 : 0);
|
|
257
|
+
}
|
|
258
|
+
else if (h > 23)
|
|
259
|
+
return null;
|
|
260
|
+
return h * 60 + min;
|
|
261
|
+
}
|
|
262
|
+
/** Values as a compressed cron field: a number, `*`, a list, `a-b`, and (minutes and hours only) a stepped range or "every s". */
|
|
263
|
+
function field(values, max, steps = true) {
|
|
264
|
+
const v = [...new Set(values)].sort((a, b) => a - b);
|
|
265
|
+
if (v.length === max)
|
|
266
|
+
return "*";
|
|
267
|
+
const step = v.length > 1 ? v[1] - v[0] : 0;
|
|
268
|
+
if (v.length > 1 && v.every((x, i) => x === v[0] + i * step)) {
|
|
269
|
+
if (steps && v[0] === 0 && max % step === 0 && v.length === max / step)
|
|
270
|
+
return `*/${step}`;
|
|
271
|
+
if (v.length > 2 && step === 1)
|
|
272
|
+
return `${v[0]}-${v.at(-1)}`;
|
|
273
|
+
if (steps && v.length > 2)
|
|
274
|
+
return `${v[0]}-${v.at(-1)}/${step}`;
|
|
275
|
+
}
|
|
276
|
+
const parts = [];
|
|
277
|
+
for (let i = 0; i < v.length;) {
|
|
278
|
+
let j = i;
|
|
279
|
+
while (v[j + 1] === v[j] + 1)
|
|
280
|
+
j++;
|
|
281
|
+
if (j - i >= 2)
|
|
282
|
+
parts.push(`${v[i]}-${v[j]}`);
|
|
283
|
+
else
|
|
284
|
+
for (let k = i; k <= j; k++)
|
|
285
|
+
parts.push(String(v[k]));
|
|
286
|
+
i = j + 1;
|
|
287
|
+
}
|
|
288
|
+
return parts.join(",");
|
|
289
|
+
}
|
|
290
|
+
/** Times of day as cron lines: hours sharing the same minutes share a line (5:30 and 6:00..17:30 on the half hours is two lines). */
|
|
291
|
+
function cronLines(times, tail) {
|
|
292
|
+
const byHour = new Map();
|
|
293
|
+
for (const t of times)
|
|
294
|
+
byHour.set(Math.floor(t / 60), [...(byHour.get(Math.floor(t / 60)) ?? []), t % 60]);
|
|
295
|
+
const groups = new Map();
|
|
296
|
+
for (const [h, mins] of [...byHour].sort((a, b) => a[0] - b[0])) {
|
|
297
|
+
const key = mins.join(",");
|
|
298
|
+
const g = groups.get(key) ?? { hours: [], minutes: mins };
|
|
299
|
+
g.hours.push(h);
|
|
300
|
+
groups.set(key, g);
|
|
301
|
+
}
|
|
302
|
+
return [...groups.values()].map((g) => `${field(g.minutes, 60)} ${field(g.hours, 24)} ${tail}`);
|
|
303
|
+
}
|
|
304
|
+
const dowField = (list) => field(list, 7, false);
|
|
305
|
+
function daysLabel(dow) {
|
|
306
|
+
if (dow === "*")
|
|
307
|
+
return "Every day";
|
|
308
|
+
if (dow === "1-5")
|
|
309
|
+
return "Mon–Fri";
|
|
310
|
+
if (dow === "0,6")
|
|
311
|
+
return "Sat and Sun";
|
|
312
|
+
const list = dow.split(",").flatMap((p) => (/^\d-\d$/.test(p) ? Array.from({ length: Number(p[2]) - Number(p[0]) + 1 }, (_, i) => Number(p[0]) + i) : [Number(p)]));
|
|
313
|
+
return list.length === 1 ? `Every ${LONG[list[0]]}` : andList(list.map((d) => SHORT[d]));
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Turn English (or a five-field cron) into cron lines. `fmt` is the owner's clock format for the words. A phrase the grammar can't say
|
|
317
|
+
* exactly is refused with the reason and two examples that work.
|
|
318
|
+
*/
|
|
319
|
+
export function parseSchedule(text, fmt = "12h", opts = {}) {
|
|
320
|
+
const raw = text.trim().replace(/[.,;!?\s]+$/, "");
|
|
321
|
+
if (!raw)
|
|
322
|
+
return refuse("say when it should run");
|
|
323
|
+
const clock = (t) => clockWords(Math.floor(t / 60), t % 60, fmt);
|
|
324
|
+
const fields = raw.split(/\s+/);
|
|
325
|
+
if (fields.length === 5 && /^[\d*,/-]+$/.test(fields[0]) && /^[\d*,/-]+$/.test(fields[1]) && fields.every((f) => /^[\w*,/-]+$/.test(f))) {
|
|
326
|
+
const cron = fields.join(" ");
|
|
327
|
+
if (!timesOf([cron]))
|
|
328
|
+
return refuse(`"${raw}" isn't a valid cron line (minute hour day month weekday)`);
|
|
329
|
+
// With the weekday open, only the day of the month picks the date: some chosen month must have a chosen day (a restricted weekday fires on either match).
|
|
330
|
+
if (fields[4] === "*") {
|
|
331
|
+
const [days, months] = [expand(fields[2], 2), expand(fields[3], 3)];
|
|
332
|
+
if (!months.some((m) => days.some((d) => d <= MONTH_DAYS[m - 1])))
|
|
333
|
+
return refuse(`"${raw}" never fires: that month has no such day`);
|
|
334
|
+
}
|
|
335
|
+
return measured([cron], describeCron(cron, fmt));
|
|
336
|
+
}
|
|
337
|
+
let s = ` ${raw.toLowerCase().replace(/\s+/g, " ").replace(/[–—]/g, "-")} `;
|
|
338
|
+
// A match is blanked to spaces of its own length, so the places of the days and the times stay comparable.
|
|
339
|
+
const take = (re) => {
|
|
340
|
+
const m = re.exec(s);
|
|
341
|
+
if (m)
|
|
342
|
+
s = `${s.slice(0, m.index)}${" ".repeat(m[0].length)}${s.slice(m.index + m[0].length)}`;
|
|
343
|
+
return m;
|
|
344
|
+
};
|
|
345
|
+
const dayAt = [];
|
|
346
|
+
const timeAt = [];
|
|
347
|
+
if (/\b(?:other|alternate|alternating|fortnight\w*|bi-?weekly|bi-?monthly|fortnightly)\b/.test(s))
|
|
348
|
+
return refuse("alternate days and weeks can't be said exactly in a schedule; pick every day, a weekday list, or a day of the month");
|
|
349
|
+
if (/\bor\b/.test(s))
|
|
350
|
+
return refuse("'or' can't be said exactly in a schedule (it would run at both); give each time its own schedule, or list them with 'and'", ["every weekday at 8am and 9am", "every Monday and Thursday at 9:00"]);
|
|
351
|
+
if (/\blast\b/.test(s))
|
|
352
|
+
return refuse("the last day or weekday of a month can't be said exactly (months differ in length); pick the 1st to the 28th, or the first to fourth weekday");
|
|
353
|
+
if (/\bevery\s+\d+\s*(?:days?|weeks?|months?|years?)\b/.test(s))
|
|
354
|
+
return refuse("a schedule repeats on days of the week or month, or every few minutes or hours; every N days, weeks or months can't be said exactly");
|
|
355
|
+
// A window the repeats stay inside: "between 5:30 and 18:00" (the end is excluded).
|
|
356
|
+
const win = take(new RegExp(`\\b(?:between|from)\\s+(${TIME})\\s+(?:and|to|-)\\s+(${TIME})\\b`));
|
|
357
|
+
let window = null;
|
|
358
|
+
if (win) {
|
|
359
|
+
const [a, b] = [clockOf(win[1]), clockOf(win[2])];
|
|
360
|
+
if (a === null || b === null)
|
|
361
|
+
return refuse("the times in that window aren't times of day");
|
|
362
|
+
if (b <= a)
|
|
363
|
+
return refuse("a window can't cross midnight; use one that ends the same day");
|
|
364
|
+
window = [a, b];
|
|
365
|
+
}
|
|
366
|
+
// Monthly: "the first Monday of every month", "every month on the 1st".
|
|
367
|
+
let dom = null;
|
|
368
|
+
let monthlyDow = null;
|
|
369
|
+
const nth = take(new RegExp(`\\b(?:on\\s+)?the\\s+(${NTH_WORD})\\s+(${DAY.replace(/s\?$/, "")})\\s+of\\s+(?:every|each|the)\\s+month\\b`)) ?? take(new RegExp(`\\b(?:(?:every|each)\\s+month|monthly)\\s+on\\s+the\\s+(${NTH_WORD})\\s+(${DAY.replace(/s\?$/, "")})\\b`));
|
|
370
|
+
if (nth) {
|
|
371
|
+
const n = nthIndex(nth[1]);
|
|
372
|
+
dom = `${(n - 1) * 7 + 1}-${n * 7}`;
|
|
373
|
+
monthlyDow = String(dayIndex(nth[2]));
|
|
374
|
+
}
|
|
375
|
+
const dayNo = take(/\b(?:(?:every|each)\s+month|monthly)\s+on\s+the\s+(\d{1,2})(?:st|nd|rd|th)?\b/) ?? take(/\bthe\s+(\d{1,2})(?:st|nd|rd|th)?\s+of\s+(?:every|each|the)\s+month\b/);
|
|
376
|
+
if (dayNo) {
|
|
377
|
+
const d = Number(dayNo[1]);
|
|
378
|
+
if (d < 1 || d > 28)
|
|
379
|
+
return refuse(`day ${d} would skip short months; pick a day from the 1st to the 28th`);
|
|
380
|
+
// A weekday rule already set is "the first Monday"; a date is a different rule. One cron line holds one day-of-month, so the date
|
|
381
|
+
// would overwrite the range and keep the weekday filter ("0 9 20 * 1": only a 20th that is a Monday). Ask for two schedules.
|
|
382
|
+
if (monthlyDow !== null)
|
|
383
|
+
return refuse("one schedule has one monthly rule; give the weekday and the date their own schedules ('the first Monday of every month at 9', then 'every month on the 20th at 9')", ["the first Monday of every month at 9", "every month on the 20th at 9"]);
|
|
384
|
+
dom = String(d);
|
|
385
|
+
}
|
|
386
|
+
// Repeats: "every 30 minutes", "every 2 hours", "every hour", "hourly".
|
|
387
|
+
let every = null;
|
|
388
|
+
const rep = take(/\bevery\s+(\d+)\s*(minutes?|mins?|hours?|hrs?|h)\b/);
|
|
389
|
+
if (rep)
|
|
390
|
+
every = { unit: rep[2].startsWith("m") ? "min" : "hour", n: Number(rep[1]) };
|
|
391
|
+
else if (take(/\bevery\s+minute\b/))
|
|
392
|
+
every = { unit: "min", n: 1 };
|
|
393
|
+
else if (take(/\b(?:every\s+hour|hourly)\b/))
|
|
394
|
+
every = { unit: "hour", n: 1 };
|
|
395
|
+
// Days: "every weekday", "Mondays and Thursdays", "Mon-Fri", "daily".
|
|
396
|
+
let dow = null;
|
|
397
|
+
let named;
|
|
398
|
+
if ((named = take(/\bweekdays?\b/)))
|
|
399
|
+
(dow = [1, 2, 3, 4, 5]), dayAt.push(named.index);
|
|
400
|
+
else if ((named = take(/\bweekends?\b/)))
|
|
401
|
+
(dow = [0, 6]), dayAt.push(named.index);
|
|
402
|
+
else if ((named = take(/\b(?:every\s?day|each\s+day|daily)\b/)))
|
|
403
|
+
(dow = [0, 1, 2, 3, 4, 5, 6]), dayAt.push(named.index);
|
|
404
|
+
else {
|
|
405
|
+
const range = take(new RegExp(`\\b(${DAY})\\s*(?:to|through|-)\\s*(${DAY})\\b`));
|
|
406
|
+
if (range) {
|
|
407
|
+
dayAt.push(range.index);
|
|
408
|
+
const [a, b] = [dayIndex(range[1]), dayIndex(range[2])];
|
|
409
|
+
dow = a <= b ? Array.from({ length: b - a + 1 }, (_, i) => a + i) : null;
|
|
410
|
+
if (!dow)
|
|
411
|
+
return refuse(`${range[1]} to ${range[2]} wraps past the end of the week; list the days instead`);
|
|
412
|
+
}
|
|
413
|
+
for (let m; (m = take(new RegExp(`\\b(${DAY})\\b`)));)
|
|
414
|
+
(dow = [...(dow ?? []), dayIndex(m[1])]), dayAt.push(m.index);
|
|
415
|
+
}
|
|
416
|
+
if (dow)
|
|
417
|
+
dow = [...new Set(dow)].sort((x, y) => x - y);
|
|
418
|
+
const weekly = take(/\bweekly\b/);
|
|
419
|
+
const monthly = take(/\b(?:(?:every|each)\s+month|monthly)\b/);
|
|
420
|
+
// Times of day: "at 8am", "at 5:30, 12:00 and 16:00".
|
|
421
|
+
const at = [];
|
|
422
|
+
for (let m; (m = take(new RegExp(`\\b${TIME}(?=[\\s,;]|$)`)));) {
|
|
423
|
+
const t = clockOf(m[0]);
|
|
424
|
+
if (t === null)
|
|
425
|
+
return refuse(`"${m[0].trim()}" isn't a time of day`);
|
|
426
|
+
at.push(t);
|
|
427
|
+
timeAt.push(m.index);
|
|
428
|
+
}
|
|
429
|
+
// A day given without a time takes the caller's default (the tasks tools promise 07:00 when the owner names none).
|
|
430
|
+
if (!at.length && !every && !window && (dom !== null || dow !== null) && opts.defaultTime !== undefined)
|
|
431
|
+
at.push(opts.defaultTime);
|
|
432
|
+
// Days on both sides of a time ("every Monday at 8 and every Friday at 9"): one schedule has one set of days, so it would run each time on each day.
|
|
433
|
+
if (dayAt.some((d) => timeAt.some((t) => t < d)) && dayAt.some((d) => timeAt.some((t) => t > d)))
|
|
434
|
+
return refuse("one schedule has one set of days and times; give each its own schedule ('every Monday at 8', then 'every Friday at 9')");
|
|
435
|
+
const left = s.replace(/\b(?:every|each|on|at|the|of|and|from|to|then|a|day|days|month|monthly|weekly|daily)\b/g, " ").replace(/[,;&-]/g, " ").replace(/\s+/g, " ").trim();
|
|
436
|
+
if (left)
|
|
437
|
+
return refuse(`I didn't understand "${left}"`);
|
|
438
|
+
if (dom !== null && (dow || every || window))
|
|
439
|
+
return refuse("a day of the month takes a time of day only: 'every month on the 1st at 9:00'");
|
|
440
|
+
// "monthly at 9am" or "weekly at 9am" would silently become every day: ask for the day it means.
|
|
441
|
+
if (monthly && dom === null)
|
|
442
|
+
return refuse("a monthly schedule needs the day it runs ('every month on the 1st at 9:00', or 'the first Monday of every month at 9')", ["every month on the 1st at 9:00", "the first Monday of every month at 9"]);
|
|
443
|
+
if (weekly && !dow)
|
|
444
|
+
return refuse("a weekly schedule needs the weekday it runs ('every Monday at 9:00', or 'every Monday and Thursday at 7:30pm')", ["every Monday at 9:00", "every Monday and Thursday at 7:30pm"]);
|
|
445
|
+
if (every) {
|
|
446
|
+
if (at.length)
|
|
447
|
+
return refuse("pick either a repeat ('every 2 hours') or times of day ('at 8:00 and 16:00'), not both");
|
|
448
|
+
const stepMinutes = every.unit === "min" ? every.n : every.n * 60;
|
|
449
|
+
if (every.unit === "min" && every.n < MIN_GAP_MINUTES)
|
|
450
|
+
return refuse(`a schedule runs at most every ${MIN_GAP_MINUTES} minutes, not every ${every.n}`, ["every 15 minutes", "every 30 minutes on weekdays between 9:00 and 17:00"]);
|
|
451
|
+
if (every.unit === "min" && 60 % every.n !== 0)
|
|
452
|
+
return refuse(`every ${every.n} minutes doesn't divide the hour evenly; use 15, 20, 30 or 60`, ["every 30 minutes", "every 2 hours"]);
|
|
453
|
+
if (every.unit === "hour" && 24 % every.n !== 0)
|
|
454
|
+
return refuse(`every ${every.n} hours doesn't divide the day evenly; use 1, 2, 3, 4, 6, 8, 12 or 24`, ["every 2 hours", "every 4 hours on weekdays"]);
|
|
455
|
+
const [start, end] = window ?? [0, 1440];
|
|
456
|
+
const times = [];
|
|
457
|
+
for (let t = start; t < end; t += stepMinutes)
|
|
458
|
+
times.push(t);
|
|
459
|
+
const list = dow ?? [0, 1, 2, 3, 4, 5, 6];
|
|
460
|
+
const df = list.length === 7 ? "*" : dowField(list);
|
|
461
|
+
const crons = cronLines(times, `* * ${df}`);
|
|
462
|
+
const lead = every.unit === "min" ? `Every ${every.n} min` : every.n === 1 ? "Every hour" : `Every ${every.n} hours`;
|
|
463
|
+
const where = [df === "*" ? "" : daysLabel(df), window ? `${clock(window[0])} to ${clock(window[1])}` : ""].filter(Boolean);
|
|
464
|
+
return measured(crons, [lead, ...where].join(", "));
|
|
465
|
+
}
|
|
466
|
+
if (window)
|
|
467
|
+
return refuse("a window ('between 9:00 and 17:00') goes with a repeat: 'every 30 minutes between 9:00 and 17:00'");
|
|
468
|
+
if (!at.length)
|
|
469
|
+
return refuse(dom !== null || dow ? "say a time of day: 'at 9:00'" : "I couldn't find when it should run");
|
|
470
|
+
const times = [...new Set(at)].sort((a, b) => a - b);
|
|
471
|
+
const when = `at ${andList(times.map(clock))}`;
|
|
472
|
+
if (dom !== null) {
|
|
473
|
+
const tail = monthlyDow !== null ? `${dom} * ${monthlyDow}` : `${dom} * *`;
|
|
474
|
+
const words = monthlyDow !== null ? `${cap(NTH[Number(dom.split("-")[0]) / 7 | 0])} ${LONG[Number(monthlyDow)]} of each month ${when}` : `Monthly on the ${ordinal(Number(dom))} ${when}`;
|
|
475
|
+
return measured(cronLines(times, tail), words);
|
|
476
|
+
}
|
|
477
|
+
const list = dow ?? [0, 1, 2, 3, 4, 5, 6];
|
|
478
|
+
const df = list.length === 7 ? "*" : dowField([...new Set(list)]);
|
|
479
|
+
return measured(cronLines(times, `* * ${df}`), `${daysLabel(df)} ${when}`);
|
|
480
|
+
}
|
|
481
|
+
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
482
|
+
// ------------------------------------------------------------------ next runs
|
|
483
|
+
/** One formatter per zone: a gap check reads a zone's offset at a thousand instants, and building it each time is the cost. */
|
|
484
|
+
const offsetFormats = new Map();
|
|
485
|
+
/** The zone's offset from UTC at an instant, in ms. */
|
|
486
|
+
function offsetAt(ms, tz) {
|
|
487
|
+
let f = offsetFormats.get(tz);
|
|
488
|
+
if (!f)
|
|
489
|
+
offsetFormats.set(tz, (f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" })));
|
|
490
|
+
const p = Object.fromEntries(f.formatToParts(new Date(ms)).map((x) => [x.type, Number(x.value)]));
|
|
491
|
+
return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(ms / 1000) * 1000;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* The next `count` instants after `from` a set of cron lines fires in a time zone (for a preview: the board's live runs come from Paperclip).
|
|
495
|
+
* A day of the month and a weekday must both match, as Paperclip's scheduler has it; a time a daylight-saving change skips is left out.
|
|
496
|
+
*/
|
|
497
|
+
export function nextRuns(crons, tz, from, count = 3) {
|
|
498
|
+
const lines = crons.map((c) => c.trim().split(/\s+/)).map((f) => (f.length === 5 ? f.map((x, i) => expand(x, i)) : null));
|
|
499
|
+
if (lines.some((l) => !l || l.some((x) => !x)))
|
|
500
|
+
return [];
|
|
501
|
+
const local = new Intl.DateTimeFormat("en-US", { timeZone: tz, year: "numeric", month: "numeric", day: "numeric" }).formatToParts(from);
|
|
502
|
+
const [y, m, d] = ["year", "month", "day"].map((t) => Number(local.find((x) => x.type === t).value));
|
|
503
|
+
const out = [];
|
|
504
|
+
for (let i = 0; i < 800 && out.length < count; i++) {
|
|
505
|
+
const day = new Date(Date.UTC(y, m - 1, d + i));
|
|
506
|
+
const at = new Set();
|
|
507
|
+
for (const l of lines) {
|
|
508
|
+
const [mins, hours, doms, mons, dows] = l;
|
|
509
|
+
if (doms.includes(day.getUTCDate()) && mons.includes(day.getUTCMonth() + 1) && dows.some((w) => w % 7 === day.getUTCDay()))
|
|
510
|
+
for (const h of hours)
|
|
511
|
+
for (const mm of mins)
|
|
512
|
+
at.add(h * 60 + mm);
|
|
513
|
+
}
|
|
514
|
+
for (const t of [...at].sort((a, b) => a - b)) {
|
|
515
|
+
const wall = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), Math.floor(t / 60), t % 60);
|
|
516
|
+
const guess = wall - offsetAt(wall, tz);
|
|
517
|
+
const instant = wall - offsetAt(guess, tz);
|
|
518
|
+
if (offsetAt(instant, tz) !== wall - instant)
|
|
519
|
+
continue;
|
|
520
|
+
if (instant > from.getTime() && out.length < count)
|
|
521
|
+
out.push(new Date(instant));
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return out;
|
|
525
|
+
}
|
|
526
|
+
// ------------------------------------------------------------------ a schedule inside a message
|
|
527
|
+
const ANCHOR = new RegExp(`^(?:every|each|daily|hourly|weekly|monthly|weekdays?|weekends?|${DAY}|the|on)$`, "i");
|
|
528
|
+
const DAY_WORD = new RegExp(`^${DAY}$`, "i");
|
|
529
|
+
/** Whether a word closes a sentence: "a.m." and "p.m." do only when a capitalised word follows ("at 5 p.m. Then ..."). */
|
|
530
|
+
const endsSentence = (w, nextRaw) => /[;!?]$/.test(w) || (/\.$/.test(w) && (!/\b[ap]\.m\.$/i.test(w) || /^[A-Z]/.test(nextRaw ?? "")));
|
|
531
|
+
/** Whether the words after a found schedule go on with it ("and 8:05", "at 9", "on Fridays"): then the schedule was cut short, not complete. */
|
|
532
|
+
function continues(next) {
|
|
533
|
+
const [n0, n1] = next;
|
|
534
|
+
if (!n0)
|
|
535
|
+
return false;
|
|
536
|
+
// "every 2" before "weeks" is a repeat the grammar can't say, not the time 2:00.
|
|
537
|
+
if (/^(?:days?|weeks?|months?|years?|minutes?|mins?|hours?|hrs?|fortnights?)$/.test(n0))
|
|
538
|
+
return true;
|
|
539
|
+
const more = (w) => /^(?:at|on|every|each|between|from|through|until|except|other|plus|weekdays?|weekends?|noon|midnight)$/.test(w) || DAY_WORD.test(w) || /^\d/.test(w);
|
|
540
|
+
// "starting at 9am" cuts a repeat short ("every 2 hours" alone would be midnight-aligned); "starting Monday" does not: the cadence is complete, the start date is only where the owner wants it to begin.
|
|
541
|
+
if (/^(?:starting|beginning)$/.test(n0 ?? ""))
|
|
542
|
+
return n1 !== undefined && (/^\d/.test(n1) || /^(?:at|from|noon|midnight)$/.test(n1));
|
|
543
|
+
return /^(?:and|or|&)$/.test(n0) ? n1 !== undefined && more(n1) : more(n0);
|
|
544
|
+
}
|
|
545
|
+
const MONTH_WORD = "(?:january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sept?|oct|nov|dec)";
|
|
546
|
+
const ZONE_ABBR = "(?:utc|gmt|[ecmp][sd]t|ist|cet|cest|bst|jst|gst|sgt|hkt|aest|aedt|eet|msk)";
|
|
547
|
+
/**
|
|
548
|
+
* Words after a found schedule that narrow it in a way the grammar can't say ("Pacific time", "only in December",
|
|
549
|
+
* "for the next week"): the owner meant something narrower or elsewhere than what was found, so the match is refused, not
|
|
550
|
+
* cut off. Plain trailing words ("summarise my PRs", "and send it to me") are not qualifiers.
|
|
551
|
+
*/
|
|
552
|
+
const ZONE_WORD = "(?:pacific|eastern|central|mountain|atlantic|alaska|hawaii|local|standard|daylight|british|greenwich|gulf|india|indian|japan|singapore|dubai|london|paris|berlin|tokyo|sydney|new\\s+york|los\\s+angeles)";
|
|
553
|
+
/** Places a schedule would silently ignore ("every weekday at 9 in London"): named cities and countries, not app or channel names. */
|
|
554
|
+
const PLACE_WORD = "(?:london|paris|berlin|tokyo|sydney|melbourne|dubai|abu\\s+dhabi|singapore|new\\s+york|nyc|los\\s+angeles|san\\s+francisco|chicago|toronto|vancouver|boston|seattle|austin|denver|miami|mumbai|delhi|bangalore|bengaluru|hong\\s+kong|seoul|shanghai|beijing|amsterdam|madrid|barcelona|rome|milan|zurich|lisbon|dublin|stockholm|istanbul|cairo|johannesburg|nairobi|lagos|s[aã]o\\s+paulo|mexico\\s+city|india|japan|china|germany|france|spain|italy|canada|australia|brazil|ireland|the\\s+uk|the\\s+us|the\\s+usa|europe|asia|africa)";
|
|
555
|
+
const QUALIFIER = new RegExp(`^(?:only\\s+(?:in|on|during|for|every|each|from|between|until|weekdays?|weekends?|${DAY}|${MONTH_WORD})\\b|except|excluding|unless|until|till|during` +
|
|
556
|
+
`|for\\s+(?:the\\s+)?(?:next|first|rest|coming)\\b|for\\s+(?:an?|one|two|three|\\d+)\\s+(?:days?|weeks?|months?|years?|hours?)\\b` +
|
|
557
|
+
`|in\\s+(?:the\\s+)?(?:morning|afternoon|evening|night|summer|winter|spring|fall|autumn|${MONTH_WORD}\\b)` +
|
|
558
|
+
`|(?:in\\s+|at\\s+)?${ZONE_ABBR}\\b|(?:in\\s+|my\\s+|your\\s+|our\\s+)?${ZONE_WORD}(?:\\s+(?:standard|daylight))?\\s+(?:time\\b|zone\\b)|time\\s?zone\\b` +
|
|
559
|
+
`|in\\s+(?:${ZONE_WORD}|${PLACE_WORD})\\b|(?:america|europe|asia|africa|australia|pacific|atlantic|indian)/[a-z_]+)`);
|
|
560
|
+
/**
|
|
561
|
+
* A conditional opening ("while keeping the report brief", "if anything changed", "only when it's a holiday") is an instruction for
|
|
562
|
+
* the run unless what follows narrows the schedule ("while it's a holiday", "if the first Monday is busy"): then the match is
|
|
563
|
+
* refused. `only` is read with the conditional, not as a qualifier on its own ("only include open PRs" is an instruction).
|
|
564
|
+
*/
|
|
565
|
+
const CONDITIONAL = /^(?:only\s+)?(?:when|whenever|while|if|once|provided|as\s+long\s+as)\b/;
|
|
566
|
+
const TIME_SCOPE = new RegExp(`\\b(?:${DAY}|${MONTH_WORD}|weekdays?|weekends?|business\\s+days?|holidays?|time|hour|noon|midnight|morning|afternoon|evening|night|summer|winter|spring|fall|autumn|${ZONE_ABBR}|${ZONE_WORD})\\b|\\d`, "i");
|
|
567
|
+
const NEGATION = /\b(?:don['’]?t|do\s+not|doesn['’]?t|never|stop|stopping|cancel(?:l?ing)?|no\s+longer|not\s+anymore|without|remove|delete|disable|pause|instead\s+of)\b/i;
|
|
568
|
+
/** A single quote that could open a quotation: at a word boundary, before a word, and not a closing curly one. */
|
|
569
|
+
const opensQuote = (s, at) => s[at] !== "’" && /(?:^|[\s(\[{])/.test(s[at - 1] ?? " ") && /\S/.test(s[at + 1] ?? " ");
|
|
570
|
+
/** A single quote that could close one: a closing curly apostrophe, or one before a space, punctuation or the end. */
|
|
571
|
+
const closesQuote = (s, at) => s[at] === "’" || !/\S/.test(s[at + 1] ?? " ");
|
|
572
|
+
/** The first single quote after `at` that could close one. */
|
|
573
|
+
const closerAfter = (s, at) => {
|
|
574
|
+
for (let k = at + 1; k < s.length; k++)
|
|
575
|
+
if ("'‘’".includes(s[k]) && closesQuote(s, k))
|
|
576
|
+
return k;
|
|
577
|
+
return -1;
|
|
578
|
+
};
|
|
579
|
+
/**
|
|
580
|
+
* Whether `before` ends inside a quotation: an odd count of `"`, more `“` than `”`, an odd count of backticks, or an unclosed single
|
|
581
|
+
* quote. A single quote opens only when a closer follows it in the message, so a word-initial elision ("send 'em a digest", "'til
|
|
582
|
+
* Friday") opens nothing, and neither does an apostrophe inside a word ("I'll", "don't").
|
|
583
|
+
*/
|
|
584
|
+
function inQuote(before, body) {
|
|
585
|
+
if ((before.match(/"/g) ?? []).length % 2 === 1)
|
|
586
|
+
return true;
|
|
587
|
+
if ((before.match(/`/g) ?? []).length % 2 === 1)
|
|
588
|
+
return true;
|
|
589
|
+
if ((before.match(/“/g) ?? []).length > (before.match(/”/g) ?? []).length)
|
|
590
|
+
return true;
|
|
591
|
+
let open = 0;
|
|
592
|
+
for (let at = 0; at < before.length; at++) {
|
|
593
|
+
if (!"'‘’".includes(before[at]))
|
|
594
|
+
continue;
|
|
595
|
+
if (opensQuote(before, at)) {
|
|
596
|
+
if (closerAfter(body, at) > at)
|
|
597
|
+
open++;
|
|
598
|
+
}
|
|
599
|
+
else if (open > 0 && closesQuote(before, at))
|
|
600
|
+
open--;
|
|
601
|
+
}
|
|
602
|
+
return open > 0;
|
|
603
|
+
}
|
|
604
|
+
const SCHEDULE_SIGNAL = new RegExp(`\\b(?:every\\s+(?:\\d+|day|hour|week|month|weekday|weekend|${DAY})|each\\s+(?:day|hour|week|month|weekday|weekend|${DAY})|daily|hourly|weekly|monthly|weekdays?|weekends?|noon|midnight|at|between|from|${DAY})\\b|\\d\\s*(?:a\\.?m\\.?|p\\.?m\\.?)|\\d:\\d\\d`, "i");
|
|
605
|
+
/**
|
|
606
|
+
* The schedule phrase in a chat message ("please summarise my GitHub every weekday at 8" → "every weekday at 8"), or null when there
|
|
607
|
+
* is none, it follows a negation in its clause ("don't do this every day at 8"), or it sits in quotes or a `>` quote line. The
|
|
608
|
+
* longest run of words the parser accepts, starting at the first word that can begin a schedule.
|
|
609
|
+
*/
|
|
610
|
+
export function findSchedule(message, fmt = "12h") {
|
|
611
|
+
const body = message.split("\n").map((l) => (/^\s*>/.test(l) ? " ".repeat(l.length) : l)).join("\n");
|
|
612
|
+
const tokens = [...body.matchAll(/\S+/g)].map((m) => ({ word: m[0], at: m.index }));
|
|
613
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
614
|
+
if (!ANCHOR.test(tokens[i].word.replace(/^[("'`“]+|[,.;:!?)"'`”]+$/g, "")))
|
|
615
|
+
continue;
|
|
616
|
+
for (let j = Math.min(tokens.length, i + 24); j > i; j--) {
|
|
617
|
+
const text = body.slice(tokens[i].at, tokens[j - 1].at + tokens[j - 1].word.length).replace(/[.,;:!?)"'`”]+$/, "");
|
|
618
|
+
if (/[\n]/.test(text))
|
|
619
|
+
continue;
|
|
620
|
+
const word = (t) => (t?.word ?? "").toLowerCase().replace(/^[("'`“]+|[,.;:!?)"'`”]+$/g, "");
|
|
621
|
+
if (/^(?:and|or|&|at|on|every|each|the|of|from|to|between|then)$/.test(word(tokens[j - 1])))
|
|
622
|
+
continue; // a schedule doesn't end on a connector
|
|
623
|
+
const parsed = parseSchedule(text, fmt);
|
|
624
|
+
if (isRefusal(parsed))
|
|
625
|
+
continue;
|
|
626
|
+
// A bare number after "the" or "on" ("review the 3 open PRs") is a count, not a time of day: a schedule in a message says when with a cadence word, "at", a day, or a clock time (am/pm or a colon).
|
|
627
|
+
if (!SCHEDULE_SIGNAL.test(text))
|
|
628
|
+
continue;
|
|
629
|
+
// A schedule cut short by one the parser refuses ("every other Monday at 9", "at 8am and 8:05am") is that refusal, never the shorter one.
|
|
630
|
+
// The next words continue it only within the same sentence and line.
|
|
631
|
+
const gap = j < tokens.length ? body.slice(tokens[j - 1].at + tokens[j - 1].word.length, tokens[j].at) : "";
|
|
632
|
+
const next = tokens.slice(j, j + 2).map(word);
|
|
633
|
+
// After a sentence end nothing continues it; after a line break only an explicit "and <time or day>" does.
|
|
634
|
+
const closed = endsSentence(tokens[j - 1].word, tokens[j]?.word);
|
|
635
|
+
const goesOn = closed ? false : /[\n]/.test(gap) ? /^(?:and|or|&)$/.test(next[0] ?? "") && continues(next) : continues(next);
|
|
636
|
+
// What follows in the same sentence may narrow it past what the grammar says: refused whole, never cut off.
|
|
637
|
+
const tail = body.slice(tokens[j - 1].at + tokens[j - 1].word.length).split(/(?<![ap]\.m)[.;!?\n]/i)[0].replace(/^[\s,:()\-–—]+/, "").toLowerCase();
|
|
638
|
+
if (!closed && (QUALIFIER.test(tail) || (CONDITIONAL.test(tail) && TIME_SCOPE.test(tail))))
|
|
639
|
+
return null;
|
|
640
|
+
if (goesOn || tokens.slice(Math.max(0, i - 2), i).some((t) => /^(?:other|alternate|alternating|last)$/.test(word(t))) || (i > 0 && /^or$/.test(word(tokens[i - 1]))))
|
|
641
|
+
return null;
|
|
642
|
+
const before = body.slice(0, tokens[i].at);
|
|
643
|
+
const clause = before.split(/[.;!?\n]|\bbut\b/i).at(-1) ?? "";
|
|
644
|
+
if (NEGATION.test(clause))
|
|
645
|
+
return null;
|
|
646
|
+
// Inside a quote ('…', "…", “…”, `…`): the words are someone else's example, not the owner's request.
|
|
647
|
+
if (inQuote(before, body))
|
|
648
|
+
return null;
|
|
649
|
+
return { text, parsed };
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return null;
|
|
653
|
+
}
|