cron-toolkit 0.0.0 → 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.
Files changed (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +245 -0
  3. package/dist/constants.d.ts +15 -0
  4. package/dist/constants.js +28 -0
  5. package/dist/core/ast.d.ts +10 -0
  6. package/dist/core/ast.js +27 -0
  7. package/dist/core/dialects.d.ts +33 -0
  8. package/dist/core/dialects.js +50 -0
  9. package/dist/core/errors.d.ts +19 -0
  10. package/dist/core/errors.js +74 -0
  11. package/dist/core/fields.d.ts +15 -0
  12. package/dist/core/fields.js +167 -0
  13. package/dist/core/format.d.ts +17 -0
  14. package/dist/core/format.js +110 -0
  15. package/dist/core/parse.d.ts +10 -0
  16. package/dist/core/parse.js +102 -0
  17. package/dist/core/types.d.ts +88 -0
  18. package/dist/core/types.js +1 -0
  19. package/dist/describe/describer.d.ts +4 -0
  20. package/dist/describe/describer.js +224 -0
  21. package/dist/describe/intl.d.ts +11 -0
  22. package/dist/describe/intl.js +32 -0
  23. package/dist/describe/locale.d.ts +64 -0
  24. package/dist/describe/locale.js +1 -0
  25. package/dist/describe.d.ts +19 -0
  26. package/dist/describe.js +14 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +4 -0
  29. package/dist/locales/en.d.ts +2 -0
  30. package/dist/locales/en.js +40 -0
  31. package/dist/locales/es.d.ts +2 -0
  32. package/dist/locales/es.js +101 -0
  33. package/dist/locales/fr.d.ts +2 -0
  34. package/dist/locales/fr.js +101 -0
  35. package/dist/recurrence/recurrence.d.ts +15 -0
  36. package/dist/recurrence/recurrence.js +222 -0
  37. package/dist/recurrence/types.d.ts +56 -0
  38. package/dist/recurrence/types.js +5 -0
  39. package/dist/schedule/civil.d.ts +26 -0
  40. package/dist/schedule/civil.js +53 -0
  41. package/dist/schedule/compile.d.ts +18 -0
  42. package/dist/schedule/compile.js +122 -0
  43. package/dist/schedule/engine.d.ts +32 -0
  44. package/dist/schedule/engine.js +97 -0
  45. package/dist/schedule/search.d.ts +9 -0
  46. package/dist/schedule/search.js +137 -0
  47. package/dist/schedule/temporal.d.ts +7 -0
  48. package/dist/schedule/temporal.js +14 -0
  49. package/dist/schedule/zone.d.ts +29 -0
  50. package/dist/schedule/zone.js +66 -0
  51. package/dist/schedule.d.ts +36 -0
  52. package/dist/schedule.js +84 -0
  53. package/dist/utils/operator-grammar.d.ts +49 -0
  54. package/dist/utils/operator-grammar.js +79 -0
  55. package/dist/utils/parse-cron-int.d.ts +1 -0
  56. package/dist/utils/parse-cron-int.js +3 -0
  57. package/package.json +69 -7
@@ -0,0 +1,224 @@
1
+ import { CANONICAL_BOUNDS } from "../constants.js";
2
+ import { startsWithWildcard } from "../core/ast.js";
3
+ import { expand } from "../schedule/compile.js";
4
+ import { capitalize, formatList, formatTime, monthName, weekdayName } from "./intl.js";
5
+ /** Up to this many distinct times are listed explicitly ("at 9:00 AM and 5:00 PM"). */
6
+ const MAX_LISTED_TIMES = 6;
7
+ export function describeCron(cron, locale, hourCycle) {
8
+ const context = { locale, hourCycle };
9
+ const pieces = [
10
+ ...describeTime(cron, context),
11
+ ...describeDays(cron, context),
12
+ describeMonths(cron.fields.month, context),
13
+ describeYears(cron.fields.year, context),
14
+ ].filter((piece) => Boolean(piece));
15
+ return capitalize(locale.code, pieces.join(", "));
16
+ }
17
+ // ── time of day ─────────────────────────────────────────────────────────────
18
+ function describeTime(cron, context) {
19
+ const { locale } = context;
20
+ const seconds = shapeOf(cron.fields.second, CANONICAL_BOUNDS.second);
21
+ const minutes = shapeOf(cron.fields.minute, CANONICAL_BOUNDS.minute);
22
+ const hours = shapeOf(cron.fields.hour, CANONICAL_BOUNDS.hour);
23
+ if (seconds.kind === "values" && minutes.kind === "values" && hours.kind === "values") {
24
+ const count = seconds.values.length * minutes.values.length * hours.values.length;
25
+ if (count <= MAX_LISTED_TIMES) {
26
+ const times = hours.values.flatMap((hour) => minutes.values.flatMap((minute) => seconds.values.map((second) => time(context, hour, minute, second))));
27
+ return [locale.atTimes(times)];
28
+ }
29
+ }
30
+ const secondsZero = isOnly(seconds, 0);
31
+ if (secondsZero && isOnly(minutes, 0)) {
32
+ if (hours.kind === "any")
33
+ return [locale.everyHour()];
34
+ if (hours.kind === "step" || (hours.kind === "range" && hours.step !== undefined)) {
35
+ return [hourPhrase(hours, context)];
36
+ }
37
+ if (hours.kind === "range")
38
+ return [locale.everyHour(), hourPhrase(hours, context)];
39
+ }
40
+ const pieces = [];
41
+ if (!secondsZero) {
42
+ pieces.push(seconds.kind === "any" ? locale.everySecond() : unitPhrase("second", seconds, context));
43
+ }
44
+ if (minutes.kind !== "any")
45
+ pieces.push(unitPhrase("minute", minutes, context));
46
+ else if (secondsZero)
47
+ pieces.push(locale.everyMinute());
48
+ if (hours.kind !== "any")
49
+ pieces.push(hourPhrase(hours, context));
50
+ return pieces;
51
+ }
52
+ function unitPhrase(unit, shape, context) {
53
+ const { locale } = context;
54
+ switch (shape.kind) {
55
+ case "any":
56
+ return unit === "second" ? locale.everySecond() : locale.everyMinute();
57
+ case "values":
58
+ return locale.atUnits(unit, shape.values);
59
+ case "step":
60
+ return stepPhrase(locale.every(unit, shape.step), shape.start, (start) => locale.startingAt(unit, start));
61
+ case "range":
62
+ return withStep(locale.unitRange(unit, shape.start, shape.end), shape.step, () => locale.every(unit, shape.step));
63
+ case "mixed":
64
+ return joinItems(shape.items, CANONICAL_BOUNDS[unit], (item) => unitPhrase(unit, item, context), context);
65
+ }
66
+ }
67
+ function hourPhrase(shape, context) {
68
+ const { locale } = context;
69
+ const startOf = (hour) => time(context, hour, 0);
70
+ const endOf = (hour) => time(context, hour, 59);
71
+ switch (shape.kind) {
72
+ case "any":
73
+ return locale.everyHour();
74
+ case "values":
75
+ return shape.values.length === 1
76
+ ? locale.betweenTimes(startOf(shape.values[0]), endOf(shape.values[0]))
77
+ : locale.duringHours(shape.values.map(startOf));
78
+ case "step":
79
+ return stepPhrase(locale.every("hour", shape.step), shape.start, (start) => locale.startingAtTime(startOf(start)));
80
+ case "range":
81
+ return withStep(locale.betweenTimes(startOf(shape.start), endOf(shape.end)), shape.step, () => locale.every("hour", shape.step));
82
+ case "mixed":
83
+ return joinItems(shape.items, CANONICAL_BOUNDS.hour, (item) => hourPhrase(item, context), context);
84
+ }
85
+ }
86
+ function time(context, hour, minute, second = 0) {
87
+ return { text: formatTime(context.locale.code, context.hourCycle, hour, minute, second), hour };
88
+ }
89
+ // ── days ────────────────────────────────────────────────────────────────────
90
+ function describeDays(cron, context) {
91
+ const { dayOfMonth, dayOfWeek } = cron.fields;
92
+ if (cron.dialect === "quartz") {
93
+ return dayOfMonth.kind === "none"
94
+ ? [dayOfWeekPhrase(dayOfWeek, true, context)]
95
+ : [dayOfMonthPhrase(dayOfMonth, context)];
96
+ }
97
+ const monthDays = dayOfMonthPhrase(dayOfMonth, context);
98
+ const weekDays = dayOfWeekPhrase(dayOfWeek, !monthDays || startsWithWildcard(dayOfMonth), context);
99
+ if (!monthDays || !weekDays)
100
+ return [monthDays ?? weekDays];
101
+ // Vixie/cronie: AND if either field starts with '*', otherwise OR.
102
+ if (startsWithWildcard(dayOfMonth) || startsWithWildcard(dayOfWeek))
103
+ return [monthDays, weekDays];
104
+ return [formatList(context.locale.code, [monthDays, weekDays], "disjunction")];
105
+ }
106
+ function dayOfMonthPhrase(expr, context) {
107
+ const { locale } = context;
108
+ if (expr.kind === "list" && expr.items.length === 1) {
109
+ const [item] = expr.items;
110
+ if (item.kind === "lastDay")
111
+ return locale.lastDayOfMonth(item.offset);
112
+ if (item.kind === "lastWeekday")
113
+ return locale.lastWeekdayOfMonth();
114
+ if (item.kind === "nearestWeekday")
115
+ return locale.nearestWeekdayTo(item.day);
116
+ }
117
+ return dayShapePhrase(shapeOf(expr, CANONICAL_BOUNDS.dayOfMonth), context);
118
+ }
119
+ function dayShapePhrase(shape, context) {
120
+ const { locale } = context;
121
+ switch (shape.kind) {
122
+ case "any":
123
+ return null;
124
+ case "values":
125
+ return locale.onDaysOfMonth(shape.values);
126
+ case "step":
127
+ return stepPhrase(locale.every("day", shape.step), shape.start, (start) => locale.startingAt("day", start));
128
+ case "range":
129
+ return withStep(locale.betweenDaysOfMonth(shape.start, shape.end), shape.step, () => locale.every("day", shape.step));
130
+ case "mixed":
131
+ return joinItems(shape.items, CANONICAL_BOUNDS.dayOfMonth, (item) => dayShapePhrase(item, context) ?? "", context);
132
+ }
133
+ }
134
+ function dayOfWeekPhrase(expr, exclusive, context) {
135
+ const { locale } = context;
136
+ const name = (weekday) => weekdayName(locale.code, weekday);
137
+ if (expr.kind !== "list")
138
+ return null;
139
+ const [first] = expr.items;
140
+ if (first.kind === "nthDayOfWeek")
141
+ return locale.nthWeekday(first.nth, name(first.weekday));
142
+ if (first.kind === "lastDayOfWeek")
143
+ return locale.lastWeekday(name(first.weekday));
144
+ const weekdays = expand(expr, CANONICAL_BOUNDS.dayOfWeek);
145
+ if (weekdays.length === 7)
146
+ return null;
147
+ if (isContiguousRun(weekdays))
148
+ return locale.weekdayRange(name(weekdays[0]), name(weekdays.at(-1)));
149
+ return locale.onWeekdays(weekdays.map(name), exclusive);
150
+ }
151
+ // ── months & years ──────────────────────────────────────────────────────────
152
+ function describeMonths(expr, context) {
153
+ const { locale } = context;
154
+ const months = expand(expr, CANONICAL_BOUNDS.month);
155
+ if (months.length === 12)
156
+ return null;
157
+ const name = (month) => monthName(locale.code, month);
158
+ if (isContiguousRun(months))
159
+ return locale.monthRange(name(months[0]), name(months.at(-1)));
160
+ return locale.inMonths(months.map(name));
161
+ }
162
+ function describeYears(expr, context) {
163
+ return yearShapePhrase(shapeOf(expr, CANONICAL_BOUNDS.year), context);
164
+ }
165
+ function yearShapePhrase(shape, context) {
166
+ const { locale } = context;
167
+ switch (shape.kind) {
168
+ case "any":
169
+ return null;
170
+ case "values":
171
+ return locale.inYears(shape.values);
172
+ case "step":
173
+ return stepPhrase(locale.every("year", shape.step), shape.start, (start) => locale.startingAt("year", start));
174
+ case "range":
175
+ return withStep(locale.yearRange(shape.start, shape.end), shape.step, () => locale.every("year", shape.step));
176
+ case "mixed":
177
+ return joinItems(shape.items, CANONICAL_BOUNDS.year, (item) => yearShapePhrase(item, context) ?? "", context);
178
+ }
179
+ }
180
+ // ── shared helpers ──────────────────────────────────────────────────────────
181
+ /** Normalizes trivial steps/ranges (`*\/1`, `0/5` = `*\/5`, full ranges) so wording stays natural. */
182
+ function shapeOf(expr, [min, max]) {
183
+ if (expr.kind !== "list")
184
+ return { kind: "any" };
185
+ const { items } = expr;
186
+ if (items.every((item) => item.kind === "value")) {
187
+ return { kind: "values", values: [...new Set(items.map((item) => item.value))].sort((a, b) => a - b) };
188
+ }
189
+ if (items.length > 1)
190
+ return { kind: "mixed", items };
191
+ const [item] = items;
192
+ if (item.kind === "step") {
193
+ const start = item.start === "any" || item.start === min ? "any" : item.start;
194
+ if (item.step === 1)
195
+ return start === "any" ? { kind: "any" } : { kind: "range", start, end: max };
196
+ return { kind: "step", start, step: item.step };
197
+ }
198
+ if (item.kind === "range") {
199
+ const step = item.step === 1 ? undefined : item.step;
200
+ if (item.start === min && item.end === max) {
201
+ return step === undefined ? { kind: "any" } : { kind: "step", start: "any", step };
202
+ }
203
+ return { kind: "range", start: item.start, end: item.end, step };
204
+ }
205
+ return { kind: "mixed", items };
206
+ }
207
+ function itemShape(item, bounds) {
208
+ return shapeOf({ kind: "list", items: [item] }, bounds);
209
+ }
210
+ function joinItems(items, bounds, phrase, context) {
211
+ return formatList(context.locale.code, items.map((item) => phrase(itemShape(item, bounds))));
212
+ }
213
+ function stepPhrase(every, start, startingAt) {
214
+ return start === "any" ? every : `${every}, ${startingAt(start)}`;
215
+ }
216
+ function withStep(range, step, every) {
217
+ return step === undefined ? range : `${every()}, ${range}`;
218
+ }
219
+ function isOnly(shape, value) {
220
+ return shape.kind === "values" && shape.values.length === 1 && shape.values[0] === value;
221
+ }
222
+ function isContiguousRun(values) {
223
+ return values.length >= 3 && values.every((value, index) => index === 0 || value === values[index - 1] + 1);
224
+ }
@@ -0,0 +1,11 @@
1
+ export type HourCycle = "h12" | "h23";
2
+ /** Joins items with the language's list grammar ("a, b, and c" / "a, b y c"). */
3
+ export declare function formatList(code: string, items: string[], type?: "conjunction" | "disjunction"): string;
4
+ /** The language's preferred clock, e.g. `h12` for `en`, `h23` for `es`/`fr`. */
5
+ export declare function defaultHourCycle(code: string): HourCycle;
6
+ export declare function formatTime(code: string, hourCycle: HourCycle, hour: number, minute: number, second?: number): string;
7
+ /** Canonical weekday (0 = Sunday) → localized long name ("Monday", "lunes", "lundi"). */
8
+ export declare function weekdayName(code: string, weekday: number): string;
9
+ /** Month 1-12 → localized long name ("January", "enero", "janvier"). */
10
+ export declare function monthName(code: string, month: number): string;
11
+ export declare function capitalize(code: string, text: string): string;
@@ -0,0 +1,32 @@
1
+ /** Joins items with the language's list grammar ("a, b, and c" / "a, b y c"). */
2
+ export function formatList(code, items, type = "conjunction") {
3
+ return new Intl.ListFormat(code, { style: "long", type }).format(items);
4
+ }
5
+ /** The language's preferred clock, e.g. `h12` for `en`, `h23` for `es`/`fr`. */
6
+ export function defaultHourCycle(code) {
7
+ // resolvedOptions().hourCycle is only defined when the formatter includes an hour.
8
+ const cycle = new Intl.DateTimeFormat(code, { hour: "numeric" }).resolvedOptions().hourCycle;
9
+ return cycle === "h11" || cycle === "h12" ? "h12" : "h23";
10
+ }
11
+ export function formatTime(code, hourCycle, hour, minute, second = 0) {
12
+ return new Intl.DateTimeFormat(code, {
13
+ timeZone: "UTC",
14
+ hourCycle,
15
+ hour: hourCycle === "h12" ? "numeric" : "2-digit",
16
+ minute: "2-digit",
17
+ ...(second === 0 ? {} : { second: "2-digit" }),
18
+ }).format(Date.UTC(2000, 0, 1, hour, minute, second));
19
+ }
20
+ /** Canonical weekday (0 = Sunday) → localized long name ("Monday", "lunes", "lundi"). */
21
+ export function weekdayName(code, weekday) {
22
+ // 2023-01-01 was a Sunday.
23
+ return new Intl.DateTimeFormat(code, { timeZone: "UTC", weekday: "long" }).format(Date.UTC(2023, 0, 1 + weekday));
24
+ }
25
+ /** Month 1-12 → localized long name ("January", "enero", "janvier"). */
26
+ export function monthName(code, month) {
27
+ return new Intl.DateTimeFormat(code, { timeZone: "UTC", month: "long" }).format(Date.UTC(2023, month - 1, 1));
28
+ }
29
+ export function capitalize(code, text) {
30
+ const [first = "", ...rest] = text;
31
+ return first.toLocaleUpperCase(code) + rest.join("");
32
+ }
@@ -0,0 +1,64 @@
1
+ import type { CronError } from "../core/types.js";
2
+ /** A formatted wall-clock time plus its hour (0-23), for languages whose articles depend on it. */
3
+ export interface TimeText {
4
+ text: string;
5
+ hour: number;
6
+ }
7
+ export type Nth = 1 | 2 | 3 | 4 | 5;
8
+ /**
9
+ * Everything a language needs to describe a cron expression. Day and month
10
+ * names, times and lists come pre-localized from `Intl` (via `code`); a
11
+ * locale only supplies sentence structure and grammar. Phrases are lowercase
12
+ * fragments — the describer joins them with ", " and capitalizes the result.
13
+ */
14
+ export interface Locale {
15
+ /** BCP 47 tag used for every `Intl` formatter (e.g. `en`, `es`, `fr-CA`). */
16
+ code: string;
17
+ everySecond(): string;
18
+ everyMinute(): string;
19
+ everyHour(): string;
20
+ /** "every 5 minutes" (n ≥ 2). */
21
+ every(unit: "second" | "minute" | "hour" | "day" | "year", n: number): string;
22
+ /** Start of a step: "starting at minute 10", "starting on day 5 of the month", "starting in 2025". */
23
+ startingAt(unit: "second" | "minute" | "day" | "year", value: number): string;
24
+ /** Start of an hour step: "starting at 6:00 AM". */
25
+ startingAtTime(time: TimeText): string;
26
+ /** "at 9:30 AM" / "at 9:00 AM and 5:00 PM". */
27
+ atTimes(times: TimeText[]): string;
28
+ /** "at minute 30 past the hour" / "at seconds 0 and 30 past the minute". */
29
+ atUnits(unit: "second" | "minute", values: number[]): string;
30
+ /** "minutes 10 through 20 past the hour". */
31
+ unitRange(unit: "second" | "minute", start: number, end: number): string;
32
+ /** "between 9:00 AM and 5:59 PM". */
33
+ betweenTimes(start: TimeText, end: TimeText): string;
34
+ /** "during the 9:00 AM and 5:00 PM hours". */
35
+ duringHours(times: TimeText[]): string;
36
+ /** "on day 1 of the month" / "on days 1 and 15 of the month". */
37
+ onDaysOfMonth(days: number[]): string;
38
+ /** "between day 1 and 10 of the month". */
39
+ betweenDaysOfMonth(start: number, end: number): string;
40
+ /** offset 0: "on the last day of the month"; n: "3 days before the last day of the month". */
41
+ lastDayOfMonth(offset: number): string;
42
+ /** "on the last weekday of the month". */
43
+ lastWeekdayOfMonth(): string;
44
+ /** "on the weekday nearest day 15 of the month". */
45
+ nearestWeekdayTo(day: number): string;
46
+ /** `exclusive`: "only on Monday and Friday"; otherwise (unix day OR) "on Monday". */
47
+ onWeekdays(names: string[], exclusive: boolean): string;
48
+ /** "Monday through Friday". */
49
+ weekdayRange(start: string, end: string): string;
50
+ /** "on the third Friday of the month". */
51
+ nthWeekday(nth: Nth, name: string): string;
52
+ /** "on the last Friday of the month". */
53
+ lastWeekday(name: string): string;
54
+ /** "only in January and July". */
55
+ inMonths(names: string[]): string;
56
+ /** "January through March". */
57
+ monthRange(start: string, end: string): string;
58
+ /** "only in 2025". */
59
+ inYears(years: number[]): string;
60
+ /** "2025 through 2030". */
61
+ yearRange(start: number, end: number): string;
62
+ /** Localized validation message. */
63
+ formatError(error: Pick<CronError, "code" | "field" | "params">): string;
64
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { Cron, CronError, DialectOption } from "./core/types.js";
2
+ import { type HourCycle } from "./describe/intl.js";
3
+ import type { Locale } from "./describe/locale.js";
4
+ export type { Locale, Nth, TimeText } from "./describe/locale.js";
5
+ export type { HourCycle } from "./describe/intl.js";
6
+ export interface DescribeOptions {
7
+ /** Defaults to English. Import others from `cron-toolkit/locales/<code>`. */
8
+ locale?: Locale;
9
+ /** `h12` / `h23`; defaults to the locale's convention (en → h12, es/fr → h23). */
10
+ hourCycle?: HourCycle;
11
+ /** Dialect for string input; defaults to `auto`. */
12
+ dialect?: DialectOption;
13
+ }
14
+ /** Plain-language description, e.g. "At 9:30 AM, Monday through Friday". */
15
+ export declare function describe(cron: string | Cron, options?: DescribeOptions): string;
16
+ /** Localized message for a validation error from `parse` / `validate`. */
17
+ export declare function formatError(error: Pick<CronError, "code" | "field" | "params">, options?: {
18
+ locale?: Locale;
19
+ }): string;
@@ -0,0 +1,14 @@
1
+ import { resolveCron } from "./core/parse.js";
2
+ import { describeCron } from "./describe/describer.js";
3
+ import { defaultHourCycle } from "./describe/intl.js";
4
+ import { en } from "./locales/en.js";
5
+ /** Plain-language description, e.g. "At 9:30 AM, Monday through Friday". */
6
+ export function describe(cron, options = {}) {
7
+ const locale = options.locale ?? en;
8
+ const hourCycle = options.hourCycle ?? defaultHourCycle(locale.code);
9
+ return describeCron(resolveCron(cron, { dialect: options.dialect }), locale, hourCycle);
10
+ }
11
+ /** Localized message for a validation error from `parse` / `validate`. */
12
+ export function formatError(error, options = {}) {
13
+ return (options.locale ?? en).formatError(error);
14
+ }
@@ -0,0 +1,6 @@
1
+ export { parse, validate, isValid } from "./core/parse.js";
2
+ export { format, convert, type FormatOptions, type ConvertOptions } from "./core/format.js";
3
+ export { CronParseError, CronConvertError } from "./core/errors.js";
4
+ export type { Cron, CronError, CronErrorCode, Dialect, DialectOption, FieldExpr, FieldItem, FieldName, ParseOptions, ParseResult, ValidationResult, } from "./core/types.js";
5
+ export { fromRecurrence, toRecurrence, CronRecurrenceError, WEEKDAYS, MINUTE_INTERVALS, HOUR_INTERVALS, } from "./recurrence/recurrence.js";
6
+ export type { Recurrence, TimeOfDay, MonthDay, Weekday, Month, MinuteInterval, HourInterval, } from "./recurrence/types.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { parse, validate, isValid } from "./core/parse.js";
2
+ export { format, convert } from "./core/format.js";
3
+ export { CronParseError, CronConvertError } from "./core/errors.js";
4
+ export { fromRecurrence, toRecurrence, CronRecurrenceError, WEEKDAYS, MINUTE_INTERVALS, HOUR_INTERVALS, } from "./recurrence/recurrence.js";
@@ -0,0 +1,2 @@
1
+ import type { Locale } from "../describe/locale.js";
2
+ export declare const en: Locale;
@@ -0,0 +1,40 @@
1
+ import { englishErrorMessage } from "../core/errors.js";
2
+ import { formatList } from "../describe/intl.js";
3
+ const list = (items) => formatList("en", items);
4
+ const plural = (count, singular, pluralForm = `${singular}s`) => (count === 1 ? singular : pluralForm);
5
+ const ORDINALS = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth" };
6
+ const PAST = { second: "past the minute", minute: "past the hour" };
7
+ export const en = {
8
+ code: "en",
9
+ everySecond: () => "every second",
10
+ everyMinute: () => "every minute",
11
+ everyHour: () => "every hour",
12
+ every: (unit, n) => `every ${n} ${unit}s`,
13
+ startingAt: (unit, value) => {
14
+ if (unit === "day")
15
+ return `starting on day ${value} of the month`;
16
+ if (unit === "year")
17
+ return `starting in ${value}`;
18
+ return `starting at ${unit} ${value}`;
19
+ },
20
+ startingAtTime: (time) => `starting at ${time.text}`,
21
+ atTimes: (times) => `at ${list(times.map((time) => time.text))}`,
22
+ atUnits: (unit, values) => `at ${plural(values.length, unit)} ${list(values.map(String))} ${PAST[unit]}`,
23
+ unitRange: (unit, start, end) => `${unit}s ${start} through ${end} ${PAST[unit]}`,
24
+ betweenTimes: (start, end) => `between ${start.text} and ${end.text}`,
25
+ duringHours: (times) => `during the ${list(times.map((time) => time.text))} hours`,
26
+ onDaysOfMonth: (days) => `on ${plural(days.length, "day")} ${list(days.map(String))} of the month`,
27
+ betweenDaysOfMonth: (start, end) => `between day ${start} and ${end} of the month`,
28
+ lastDayOfMonth: (offset) => offset === 0 ? "on the last day of the month" : `${offset} ${plural(offset, "day")} before the last day of the month`,
29
+ lastWeekdayOfMonth: () => "on the last weekday of the month",
30
+ nearestWeekdayTo: (day) => `on the weekday nearest day ${day} of the month`,
31
+ onWeekdays: (names, exclusive) => `${exclusive ? "only on" : "on"} ${list(names)}`,
32
+ weekdayRange: (start, end) => `${start} through ${end}`,
33
+ nthWeekday: (nth, name) => `on the ${ORDINALS[nth]} ${name} of the month`,
34
+ lastWeekday: (name) => `on the last ${name} of the month`,
35
+ inMonths: (names) => `only in ${list(names)}`,
36
+ monthRange: (start, end) => `${start} through ${end}`,
37
+ inYears: (years) => `only in ${list(years.map(String))}`,
38
+ yearRange: (start, end) => `${start} through ${end}`,
39
+ formatError: englishErrorMessage,
40
+ };
@@ -0,0 +1,2 @@
1
+ import type { Locale } from "../describe/locale.js";
2
+ export declare const es: Locale;
@@ -0,0 +1,101 @@
1
+ import { formatList } from "../describe/intl.js";
2
+ const list = (items) => formatList("es", items);
3
+ const plural = (count, singular, pluralForm = `${singular}s`) => (count === 1 ? singular : pluralForm);
4
+ /** "la 01:00" / "las 09:00": singular article for one o'clock. */
5
+ const article = (time) => (time.hour % 12 === 1 ? "la" : "las");
6
+ /** Recurring weekdays are plural: "los lunes", "los sábados". */
7
+ const weekdayPlural = (name) => (name.endsWith("s") ? name : `${name}s`);
8
+ const ORDINALS = { 1: "primer", 2: "segundo", 3: "tercer", 4: "cuarto", 5: "quinto" };
9
+ const UNITS = {
10
+ second: ["segundo", "segundos"],
11
+ minute: ["minuto", "minutos"],
12
+ hour: ["hora", "horas"],
13
+ day: ["día", "días"],
14
+ year: ["año", "años"],
15
+ };
16
+ const OF_EACH = { second: "de cada minuto", minute: "de cada hora" };
17
+ const FIELD_LABELS = {
18
+ second: "Segundos",
19
+ minute: "Minutos",
20
+ hour: "Horas",
21
+ dayOfMonth: "Día del mes",
22
+ month: "Mes",
23
+ dayOfWeek: "Día de la semana",
24
+ year: "Año",
25
+ };
26
+ const DIALECTS = { quartz: "Quartz", unix: "Unix" };
27
+ function formatError({ code, field, params }) {
28
+ const label = field ? `${FIELD_LABELS[field]}: ` : "";
29
+ switch (code) {
30
+ case "EMPTY_EXPRESSION":
31
+ return "La expresión cron está vacía";
32
+ case "WRONG_FIELD_COUNT": {
33
+ const got = params.count === undefined ? "" : ` (recibidos: ${params.count})`;
34
+ if (params.dialect === "quartz")
35
+ return `Las expresiones cron de Quartz deben tener 6 campos, o 7 con el año${got}`;
36
+ if (params.dialect === "unix")
37
+ return `Las expresiones cron de Unix deben tener 5 campos${got}`;
38
+ return `Las expresiones cron deben tener 5 campos (Unix) o 6-7 campos (Quartz)${got}`;
39
+ }
40
+ case "UNKNOWN_MACRO":
41
+ return `Macro desconocida '${params.macro}'`;
42
+ case "UNSUPPORTED_MACRO":
43
+ return `'${params.macro}' se ejecuta al iniciar, no según un horario, y no es compatible`;
44
+ case "INVALID_VALUE": {
45
+ const names = params.names ? `, o ${params.names}` : "";
46
+ return `${label}el valor debe estar entre ${params.min} y ${params.max}${names}`;
47
+ }
48
+ case "INVALID_RANGE":
49
+ return `${label}rango no válido '${params.token}' (el inicio no puede ser mayor que el final)`;
50
+ case "INVALID_STEP": {
51
+ const bound = params.max === undefined ? "" : ` (el incremento debe estar entre 1 y ${params.max})`;
52
+ return `${label}incremento no válido '${params.token}'${bound}`;
53
+ }
54
+ case "UNSUPPORTED_SYNTAX":
55
+ return `${label}'${params.token}' no es compatible con cron de ${DIALECTS[params.dialect] ?? params.dialect}`;
56
+ case "INVALID_NTH":
57
+ return "La ocurrencia después de '#' debe estar entre 1 y 5";
58
+ case "SPECIAL_NOT_COMBINABLE":
59
+ return `${label}'${params.token}' no se puede combinar con otros valores`;
60
+ case "DAY_FIELDS_BOTH_SET":
61
+ return "Quartz requiere '?' en el día del mes o en el día de la semana";
62
+ case "DAY_FIELDS_BOTH_UNSET":
63
+ return "'?' se puede usar en el día del mes o en el día de la semana, pero no en ambos";
64
+ }
65
+ }
66
+ export const es = {
67
+ code: "es",
68
+ everySecond: () => "cada segundo",
69
+ everyMinute: () => "cada minuto",
70
+ everyHour: () => "cada hora",
71
+ every: (unit, n) => `cada ${n} ${UNITS[unit][1]}`,
72
+ startingAt: (unit, value) => {
73
+ if (unit === "day")
74
+ return `a partir del día ${value} del mes`;
75
+ if (unit === "year")
76
+ return `a partir de ${value}`;
77
+ return `a partir del ${UNITS[unit][0]} ${value}`;
78
+ },
79
+ startingAtTime: (time) => `a partir de ${article(time)} ${time.text}`,
80
+ atTimes: (times) => times.length === 1
81
+ ? `a ${article(times[0])} ${times[0].text}`
82
+ : `a las ${list(times.map((time) => time.text))}`,
83
+ atUnits: (unit, values) => `en ${plural(values.length, "el", "los")} ${plural(values.length, ...UNITS[unit])} ${list(values.map(String))} ${OF_EACH[unit]}`,
84
+ unitRange: (unit, start, end) => `del ${UNITS[unit][0]} ${start} al ${end} ${OF_EACH[unit]}`,
85
+ betweenTimes: (start, end) => `entre ${article(start)} ${start.text} y ${article(end)} ${end.text}`,
86
+ duringHours: (times) => `durante las horas ${list(times.map((time) => time.text))}`,
87
+ onDaysOfMonth: (days) => `${plural(days.length, "el día", "los días")} ${list(days.map(String))} del mes`,
88
+ betweenDaysOfMonth: (start, end) => `entre los días ${start} y ${end} del mes`,
89
+ lastDayOfMonth: (offset) => offset === 0 ? "el último día del mes" : `${offset} ${plural(offset, "día")} antes del último día del mes`,
90
+ lastWeekdayOfMonth: () => "el último día laborable del mes",
91
+ nearestWeekdayTo: (day) => `el día laborable más cercano al día ${day} del mes`,
92
+ onWeekdays: (names, exclusive) => `${exclusive ? "solo los" : "los"} ${list(names.map(weekdayPlural))}`,
93
+ weekdayRange: (start, end) => `de ${start} a ${end}`,
94
+ nthWeekday: (nth, name) => `el ${ORDINALS[nth]} ${name} del mes`,
95
+ lastWeekday: (name) => `el último ${name} del mes`,
96
+ inMonths: (names) => `solo en ${list(names)}`,
97
+ monthRange: (start, end) => `de ${start} a ${end}`,
98
+ inYears: (years) => `solo en ${list(years.map(String))}`,
99
+ yearRange: (start, end) => `de ${start} a ${end}`,
100
+ formatError,
101
+ };
@@ -0,0 +1,2 @@
1
+ import type { Locale } from "../describe/locale.js";
2
+ export declare const fr: Locale;
@@ -0,0 +1,101 @@
1
+ import { formatList } from "../describe/intl.js";
2
+ const list = (items) => formatList("fr", items);
3
+ const plural = (count, singular, pluralForm = `${singular}s`) => (count === 1 ? singular : pluralForm);
4
+ /** Day of month as written in French: "1er", "15". */
5
+ const day = (value) => (value === 1 ? "1er" : String(value));
6
+ const ORDINALS = { 1: "premier", 2: "deuxième", 3: "troisième", 4: "quatrième", 5: "cinquième" };
7
+ const EVERY = {
8
+ second: "toutes les {n} secondes",
9
+ minute: "toutes les {n} minutes",
10
+ hour: "toutes les {n} heures",
11
+ day: "tous les {n} jours",
12
+ year: "tous les {n} ans",
13
+ };
14
+ const UNIT = {
15
+ second: ["seconde", "secondes"],
16
+ minute: ["minute", "minutes"],
17
+ };
18
+ const OF_EACH = { second: "de chaque minute", minute: "de chaque heure" };
19
+ const FIELD_LABELS = {
20
+ second: "Secondes",
21
+ minute: "Minutes",
22
+ hour: "Heures",
23
+ dayOfMonth: "Jour du mois",
24
+ month: "Mois",
25
+ dayOfWeek: "Jour de la semaine",
26
+ year: "Année",
27
+ };
28
+ const DIALECTS = { quartz: "Quartz", unix: "Unix" };
29
+ function formatError({ code, field, params }) {
30
+ const label = field ? `${FIELD_LABELS[field]} : ` : "";
31
+ switch (code) {
32
+ case "EMPTY_EXPRESSION":
33
+ return "L'expression cron est vide";
34
+ case "WRONG_FIELD_COUNT": {
35
+ const got = params.count === undefined ? "" : ` (reçu : ${params.count})`;
36
+ if (params.dialect === "quartz")
37
+ return `Les expressions cron Quartz doivent comporter 6 champs, ou 7 avec l'année${got}`;
38
+ if (params.dialect === "unix")
39
+ return `Les expressions cron Unix doivent comporter 5 champs${got}`;
40
+ return `Les expressions cron doivent comporter 5 champs (Unix) ou 6 à 7 champs (Quartz)${got}`;
41
+ }
42
+ case "UNKNOWN_MACRO":
43
+ return `Macro inconnue '${params.macro}'`;
44
+ case "UNSUPPORTED_MACRO":
45
+ return `'${params.macro}' s'exécute au démarrage, pas selon un horaire, et n'est pas pris en charge`;
46
+ case "INVALID_VALUE": {
47
+ const names = params.names ? `, ou ${params.names}` : "";
48
+ return `${label}la valeur doit être comprise entre ${params.min} et ${params.max}${names}`;
49
+ }
50
+ case "INVALID_RANGE":
51
+ return `${label}plage non valide '${params.token}' (le début ne peut pas dépasser la fin)`;
52
+ case "INVALID_STEP": {
53
+ const bound = params.max === undefined ? "" : ` (l'incrément doit être compris entre 1 et ${params.max})`;
54
+ return `${label}pas non valide '${params.token}'${bound}`;
55
+ }
56
+ case "UNSUPPORTED_SYNTAX":
57
+ return `${label}'${params.token}' n'est pas pris en charge en cron ${DIALECTS[params.dialect] ?? params.dialect}`;
58
+ case "INVALID_NTH":
59
+ return "L'occurrence après '#' doit être comprise entre 1 et 5";
60
+ case "SPECIAL_NOT_COMBINABLE":
61
+ return `${label}'${params.token}' ne peut pas être combiné avec d'autres valeurs`;
62
+ case "DAY_FIELDS_BOTH_SET":
63
+ return "Quartz exige '?' dans le jour du mois ou dans le jour de la semaine";
64
+ case "DAY_FIELDS_BOTH_UNSET":
65
+ return "'?' peut être utilisé dans le jour du mois ou dans le jour de la semaine, mais pas les deux";
66
+ }
67
+ }
68
+ export const fr = {
69
+ code: "fr",
70
+ everySecond: () => "toutes les secondes",
71
+ everyMinute: () => "toutes les minutes",
72
+ everyHour: () => "toutes les heures",
73
+ every: (unit, n) => EVERY[unit].replace("{n}", String(n)),
74
+ startingAt: (unit, value) => {
75
+ if (unit === "day")
76
+ return `à partir du ${day(value)} du mois`;
77
+ if (unit === "year")
78
+ return `à partir de ${value}`;
79
+ return `à partir de la ${UNIT[unit][0]} ${value}`;
80
+ },
81
+ startingAtTime: (time) => `à partir de ${time.text}`,
82
+ atTimes: (times) => `à ${list(times.map((time) => time.text))}`,
83
+ atUnits: (unit, values) => `${plural(values.length, "à la", "aux")} ${plural(values.length, ...UNIT[unit])} ${list(values.map(String))} ${OF_EACH[unit]}`,
84
+ unitRange: (unit, start, end) => `de la ${UNIT[unit][0]} ${start} à ${end} ${OF_EACH[unit]}`,
85
+ betweenTimes: (start, end) => `entre ${start.text} et ${end.text}`,
86
+ duringHours: (times) => `pendant les heures ${list(times.map((time) => time.text))}`,
87
+ onDaysOfMonth: (days) => `${plural(days.length, "le", "les")} ${list(days.map(day))} du mois`,
88
+ betweenDaysOfMonth: (start, end) => `du ${day(start)} au ${day(end)} du mois`,
89
+ lastDayOfMonth: (offset) => offset === 0 ? "le dernier jour du mois" : `${offset} ${plural(offset, "jour")} avant le dernier jour du mois`,
90
+ lastWeekdayOfMonth: () => "le dernier jour ouvré du mois",
91
+ nearestWeekdayTo: (value) => `le jour ouvré le plus proche du ${day(value)} du mois`,
92
+ onWeekdays: (names, exclusive) => `${exclusive ? "uniquement " : ""}${list(names.map((name) => `le ${name}`))}`,
93
+ weekdayRange: (start, end) => `du ${start} au ${end}`,
94
+ nthWeekday: (nth, name) => `le ${ORDINALS[nth]} ${name} du mois`,
95
+ lastWeekday: (name) => `le dernier ${name} du mois`,
96
+ inMonths: (names) => `uniquement en ${list(names)}`,
97
+ monthRange: (start, end) => `de ${start} à ${end}`,
98
+ inYears: (years) => `uniquement en ${list(years.map(String))}`,
99
+ yearRange: (start, end) => `de ${start} à ${end}`,
100
+ formatError,
101
+ };