fix(scheduler): refuse dates that do not exist, and an unreadable --now in gram plan #114

Merged
abiwab merged 1 commit from fix/calendar-dates into main 2026-11-06 20:59:17 +01:00
15 changed files with 211 additions and 29 deletions

View file

@ -8,6 +8,7 @@
- `--tz Europe/Paris` sets the time zone; by default it is the new `timezone` setting of `.gram/config.yaml` (or of your global config), and only then this machine's. `--available` says when you can cook, as many times as needed: `08:00-22:00` for every day, `fri=18:00-22:00` for a day of the week, `2026-10-09=none` for a date. By default it is the new `availability` setting of `.gram/config.yaml`, written the same way (`gram config set availability 08:00-22:00`), and only then all day - `--tz Europe/Paris` sets the time zone; by default it is the new `timezone` setting of `.gram/config.yaml` (or of your global config), and only then this machine's. `--available` says when you can cook, as many times as needed: `08:00-22:00` for every day, `fri=18:00-22:00` for a day of the week, `2026-10-09=none` for a date. By default it is the new `availability` setting of `.gram/config.yaml`, written the same way (`gram config set availability 08:00-22:00`), and only then all day
- A wait written as a range (`~_{8-16h}`) is made longer or shorter to keep your own work out of the hours you are not available, and the plan says which one and why; what cannot be fixed is listed at the top - A wait written as a range (`~_{8-16h}`) is made longer or shorter to keep your own work out of the hours you are not available, and the plan says which one and why; what cannot be fixed is listed at the top
- `--find 2026-10-12/2026-10-15` lists the serving times that work between two moments, at your meal times (`--meal-times 12:30,20:00`, or the new `mealTimes` setting of `.gram/config.yaml`), best first, and why each of the others does not - `--find 2026-10-12/2026-10-15` lists the serving times that work between two moments, at your meal times (`--meal-times 12:30,20:00`, or the new `mealTimes` setting of `.gram/config.yaml`), best first, and why each of the others does not
- A date that does not exist (`--serve "2026-02-30 20:00"`, a 31st of April in `--find` or `--available`) and a `--now` that cannot be read are refused with a message saying what is expected, instead of planning for another day or stopping with an internal error
- `--format text|md|html|json` picks the output, and `--ics plan.ics` also writes a calendar file with an event for every visit to the kitchen, an alarm before it, and the lists in its description - `--format text|md|html|json` picks the output, and `--ics plan.ics` also writes a calendar file with an event for every visit to the kitchen, an alarm before it, and the lists in its description
- `--mise-en-place`, `--rests`, `--scale` and `--stock` work as they do in `gram view`; the mise en place mode also decides what goes in each visit's list of things to take out - `--mise-en-place`, `--rests`, `--scale` and `--stock` work as they do in `gram view`; the mise en place mode also decides what goes in each visit's list of things to take out
- `gram export` and `gram print` render the run sheet instead of the recipe via `--view run-sheet` (the recipe remains the default), supporting `--serve`, `--tz`, and `--available`; without `--serve`, the schedule is organized in relative countdown days (`D-2`, `D-1`, `Day D`). The print document formats one day per page, and `gram export` automatically outputs to `<recipe>.run-sheet.md` (or `.html`, `.txt`) unless `--output` is specified - `gram export` and `gram print` render the run sheet instead of the recipe via `--view run-sheet` (the recipe remains the default), supporting `--serve`, `--tz`, and `--available`; without `--serve`, the schedule is organized in relative countdown days (`D-2`, `D-1`, `Day D`). The print document formats one day per page, and `gram export` automatically outputs to `<recipe>.run-sheet.md` (or `.html`, `.txt`) unless `--output` is specified

View file

@ -12,3 +12,4 @@
- `runSheet(plan)` groups a plan, or a bare schedule, into the days of the recipe (and says which mise en place mode it was made in), the visits to the kitchen (a wait of an hour or more ends one) and the waits that go on without the cook; with the graph and the context, it also says how early each visit could be done, and which exact wait holds it in place; each visit also says when each of its sections starts (`sectionStarts`) - `runSheet(plan)` groups a plan, or a bare schedule, into the days of the recipe (and says which mise en place mode it was made in), the visits to the kitchen (a wait of an hour or more ends one) and the waits that go on without the cook; with the graph and the context, it also says how early each visit could be done, and which exact wait holds it in place; each visit also says when each of its sections starts (`sectionStarts`)
- `findServeTimes()` tries each day of a range at your meal times and ranks the serving times that work, with the reasons of the others; `earliestServe()` gives the first one that works if the cook starts now - `findServeTimes()` tries each day of a range at your meal times and ranks the serving times that work, with the reasons of the others; `earliestServe()` gives the first one that works if the cook starts now
- `parseAvailability(entries)` reads when the cook is available from entries like `08:00-22:00`, `fri=18:00-22:00` or `2026-10-09=none` (the syntax of `gram plan --available` and of the `availability` setting), and says which part is wrong when it cannot - `parseAvailability(entries)` reads when the cook is available from entries like `08:00-22:00`, `fri=18:00-22:00` or `2026-10-09=none` (the syntax of `gram plan --available` and of the `availability` setting), and says which part is wrong when it cannot
- `isCalendarDate("2026-02-30")` tells a real day from a string that only looks like one; the scheduler refuses a date that does not exist (a 30th of February, a 31st of April) everywhere it reads one, instead of moving it to the next month

View file

@ -1,7 +1,9 @@
import type { Availability } from "@gram-lang/scheduler"; import type { Availability } from "@gram-lang/scheduler";
import { import {
WEEKDAYS, WEEKDAYS,
isCalendarDate,
parseAvailability as parseEntries, parseAvailability as parseEntries,
parseInstant,
} from "@gram-lang/scheduler"; } from "@gram-lang/scheduler";
import { ExitCode, GramCLIError } from "../errors"; import { ExitCode, GramCLIError } from "../errors";
@ -42,9 +44,33 @@ export function parseServe(value: unknown): string {
`Expected --serve like "2026-10-11 13:00" (a local date and time), got "${text}".`, `Expected --serve like "2026-10-11 13:00" (a local date and time), got "${text}".`,
); );
} }
if (!isCalendarDate(m[1]!)) {
return fail(`--serve "${text}": ${m[1]} is not a day of the calendar.`);
}
return `${m[1]}T${m[2]!.padStart(2, "0")}:${m[3]}`; return `${m[1]}T${m[2]!.padStart(2, "0")}:${m[3]}`;
} }
/**
* `--now`: the present, an instant with `Z` or an offset
* ("2026-10-11T11:00:00Z") or a local date and time in the time zone of the
* plan. Without it, now. Checked here so a typo is a message, not a stack
* trace raised while the plan is drawn.
*/
export function parseNow(value: unknown, timeZone: string): string {
if (value === undefined || value === null || value === "") {
return new Date().toISOString();
}
const text = String(value).trim();
try {
parseInstant(text, timeZone);
return text;
} catch {
return fail(
`Expected --now like "2026-10-11T11:00:00Z" or "2026-10-11T13:00" (a local date and time), got "${text}".`,
);
}
}
const isTimeZone = (zone: string) => { const isTimeZone = (zone: string) => {
try { try {
new Intl.DateTimeFormat("en", { timeZone: zone }); new Intl.DateTimeFormat("en", { timeZone: zone });
@ -165,7 +191,10 @@ export function parseFindRange(value: unknown): { from: string; to: string } {
const parts = text.split("/"); const parts = text.split("/");
if ( if (
parts.length !== 2 || parts.length !== 2 ||
!parts.every((p) => LOCAL_BOUND.test(p.trim())) || !parts.every(
(p) =>
LOCAL_BOUND.test(p.trim()) && isCalendarDate(p.trim().slice(0, 10)),
) ||
parts[0]!.trim() > parts[1]!.trim() parts[0]!.trim() > parts[1]!.trim()
) { ) {
return fail( return fail(

View file

@ -10,6 +10,7 @@ import { ExitCode, GramCLIError } from "../errors";
import { import {
collectFlag, collectFlag,
parseAvailability, parseAvailability,
parseNow,
parseServe, parseServe,
parseTimeZone, parseTimeZone,
} from "./plan-flags"; } from "./plan-flags";
@ -59,13 +60,14 @@ export function resolveKitchenContext(
rawArgs: string[] | undefined, rawArgs: string[] | undefined,
config: { timezone?: string; availability?: unknown }, config: { timezone?: string; availability?: unknown },
): KitchenContext { ): KitchenContext {
const timeZone = parseTimeZone(args.tz, config.timezone);
return { return {
timeZone: parseTimeZone(args.tz, config.timezone), timeZone,
availability: parseAvailability( availability: parseAvailability(
collectFlag(rawArgs ?? [], "available"), collectFlag(rawArgs ?? [], "available"),
config.availability, config.availability,
), ),
now: (args.now as string | undefined) ?? new Date().toISOString(), now: parseNow(args.now, timeZone),
}; };
} }

View file

@ -211,6 +211,29 @@ describe("gram plan", () => {
expect(code).toBe(1); expect(code).toBe(1);
} }
}); });
it("refuses a day the calendar does not have, or a present it cannot read, with a message and no stack", () => {
for (const [bad, said] of [
[
["--serve", "2026-02-30 20:00"],
"2026-02-30 is not a day of the calendar",
],
[
["--available", "2026-02-30=none"],
'Unknown --available key "2026-02-30"',
],
[["--now", "banana"], 'Expected --now like "2026-10-11T11:00:00Z"'],
] as const) {
const args = [...PLAN];
const at = args.indexOf(bad[0]);
if (at === -1) args.push(...bad);
else args[at + 1] = bad[1];
const { code, out, err } = gram(...args);
expect(code).toBe(1);
expect(out + err).toContain(said);
expect(out + err).not.toContain(" at ");
}
});
}); });
describe("gram plan without a serving time", () => { describe("gram plan without a serving time", () => {

View file

@ -5,6 +5,8 @@ import { resolveExportView } from "../src/services/plan-options";
import { import {
collectFlag, collectFlag,
parseAvailability, parseAvailability,
parseFindRange,
parseNow,
parseServe, parseServe,
parseTimeZone, parseTimeZone,
} from "../src/services/plan-flags"; } from "../src/services/plan-flags";
@ -54,6 +56,57 @@ describe("parseServe", () => {
); );
expect(messageOf(() => parseServe(undefined))).toContain("--serve"); expect(messageOf(() => parseServe(undefined))).toContain("--serve");
}); });
it("refuses a day the calendar does not have, instead of moving it to March", () => {
expect(messageOf(() => parseServe("2026-02-30 20:00"))).toBe(
'--serve "2026-02-30 20:00": 2026-02-30 is not a day of the calendar.',
);
expect(parseServe("2028-02-29 20:00")).toBe("2028-02-29T20:00");
});
});
describe("parseFindRange", () => {
it("reads two local bounds", () => {
expect(parseFindRange("2026-10-12/2026-10-15 20:00")).toEqual({
from: "2026-10-12",
to: "2026-10-15T20:00",
});
});
it("refuses a bound the calendar does not have", () => {
expect(messageOf(() => parseFindRange("2026-02-28/2026-02-31"))).toContain(
'Expected --find like "2026-10-12/2026-10-15"',
);
expect(
messageOf(() => parseFindRange("2026-02-30 12:00/2026-03-02")),
).toContain("--find");
});
});
describe("parseNow", () => {
it("is now without a value", () => {
const before = Date.now();
const now = Date.parse(parseNow(undefined, "Europe/Paris"));
expect(now).toBeGreaterThanOrEqual(before);
});
it("takes an instant or a local date and time, as written", () => {
expect(parseNow("2026-10-01T09:00:00Z", "Europe/Paris")).toBe(
"2026-10-01T09:00:00Z",
);
expect(parseNow("2026-10-10T10:00", "Europe/Paris")).toBe(
"2026-10-10T10:00",
);
});
it("refuses what it cannot read, saying what it expects", () => {
expect(messageOf(() => parseNow("banana", "Europe/Paris"))).toBe(
'Expected --now like "2026-10-11T11:00:00Z" or "2026-10-11T13:00" (a local date and time), got "banana".',
);
expect(messageOf(() => parseNow("2026-02-30T10:00", "UTC"))).toContain(
"--now",
);
});
}); });
describe("parseTimeZone", () => { describe("parseTimeZone", () => {
@ -128,6 +181,12 @@ describe("parseAvailability", () => {
}); });
}); });
it("refuses a date the calendar does not have, which would never apply", () => {
expect(messageOf(() => parseAvailability(["2026-02-30=none"]))).toContain(
'Unknown --available key "2026-02-30"',
);
});
it("reads a weekday in any case, and none as not available", () => { it("reads a weekday in any case, and none as not available", () => {
expect(parseAvailability(["SUN=none"])).toMatchObject({ expect(parseAvailability(["SUN=none"])).toMatchObject({
weekdays: { sun: [] }, weekdays: { sun: [] },

View file

@ -403,10 +403,13 @@ function parseLocalIso(value: string, timeZone: string): number; // "2026-10-11T
function parseInstant(value: string, timeZone: string): number; // ISO instant (with 'Z' or UTC offset) or local time function parseInstant(value: string, timeZone: string): number; // ISO instant (with 'Z' or UTC offset) or local time
function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00" function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00"
function toUtcIso(utcMinutes: number): string; // → "2026-10-11T11:00:00Z" function toUtcIso(utcMinutes: number): string; // → "2026-10-11T11:00:00Z"
function isCalendarDate(value: string): boolean; // "2028-02-29" → true, "2026-02-30" → false
``` ```
During daylight saving time transitions, an invalid local time (e.g. 02:30 when clocks spring forward) shifts to the next valid time; an ambiguous local time (occurring twice when clocks fall back) resolves to its first occurrence. During daylight saving time transitions, an invalid local time (e.g. 02:30 when clocks spring forward) shifts to the next valid time; an ambiguous local time (occurring twice when clocks fall back) resolves to its first occurrence.
A date that does not exist (a 30th of February, a 31st of April) is refused with a `RangeError` rather than moved to the next month.
## Related resources ## Related resources
<CardGrid> <CardGrid>

View file

@ -403,10 +403,13 @@ function parseLocalIso(value: string, timeZone: string): number; // "2026-10-11T
function parseInstant(value: string, timeZone: string): number; // instant ISO (avec 'Z' ou décalage UTC) ou heure locale function parseInstant(value: string, timeZone: string): number; // instant ISO (avec 'Z' ou décalage UTC) ou heure locale
function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00" function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00"
function toUtcIso(utcMinutes: number): string; // → "2026-10-11T11:00:00Z" function toUtcIso(utcMinutes: number): string; // → "2026-10-11T11:00:00Z"
function isCalendarDate(value: string): boolean; // "2028-02-29" → true, "2026-02-30" → false
``` ```
Lors du passage à l'heure d'été, une heure locale inexistante (par exemple 02:30 lors de l'avance des horloges) est automatiquement décalée vers la première heure valide suivante ; lors du passage à l'heure d'hiver, une heure ambiguë (apparaissant deux fois lors du recul) est résolue sur sa première occurrence. Lors du passage à l'heure d'été, une heure locale inexistante (par exemple 02:30 lors de l'avance des horloges) est automatiquement décalée vers la première heure valide suivante ; lors du passage à l'heure d'hiver, une heure ambiguë (apparaissant deux fois lors du recul) est résolue sur sa première occurrence.
Une date qui n'existe pas (un 30 février, un 31 avril) est refusée par une `RangeError` au lieu de glisser au mois suivant.
## Ressources associées ## Ressources associées
<CardGrid> <CardGrid>

View file

@ -1,4 +1,5 @@
import type { ScaleRequest } from "@gram-lang/kitchen"; import type { ScaleRequest } from "@gram-lang/kitchen";
import { isCalendarDate } from "@gram-lang/scheduler";
/** /**
* What the cook chose for this sitting with one recipe, sent by the client in * What the cook chose for this sitting with one recipe, sent by the client in
@ -23,7 +24,7 @@ const SERVE_AT = /^(\d{4}-\d{2}-\d{2})[T ](\d{1,2}):(\d{2})$/;
function parseServeAt(raw: unknown): string | undefined { function parseServeAt(raw: unknown): string | undefined {
if (typeof raw !== "string") return undefined; if (typeof raw !== "string") return undefined;
const m = SERVE_AT.exec(raw.trim()); const m = SERVE_AT.exec(raw.trim());
if (!m) return undefined; if (!m || !isCalendarDate(m[1]!)) return undefined;
const hour = Number(m[2]); const hour = Number(m[2]);
const minute = Number(m[3]); const minute = Number(m[3]);
if (hour > 23 || minute > 59) return undefined; if (hour > 23 || minute > 59) return undefined;

View file

@ -46,6 +46,8 @@ describe("parseSession", () => {
}), }),
).toEqual({}); ).toEqual({});
expect(parseSession({ serveAt: "2026-10-11T25:00" })).toEqual({}); expect(parseSession({ serveAt: "2026-10-11T25:00" })).toEqual({});
// Shaped like a date, but not a day of the calendar.
expect(parseSession({ serveAt: "2026-02-30T20:00" })).toEqual({});
expect(parseSession({ scale: { type: "target", id: "", qty: 3 } })).toEqual( expect(parseSession({ scale: { type: "target", id: "", qty: 3 } })).toEqual(
{}, {},
); );

View file

@ -65,7 +65,13 @@ export type {
TimeRange, TimeRange,
} from "./projection"; } from "./projection";
export { WEEKDAYS, type Weekday } from "./time"; export { WEEKDAYS, type Weekday } from "./time";
export { parseInstant, parseLocalIso, toLocalIso, toUtcIso } from "./time"; export {
isCalendarDate,
parseInstant,
parseLocalIso,
toLocalIso,
toUtcIso,
} from "./time";
export { export {
DEFAULT_MEAL_TIMES, DEFAULT_MEAL_TIMES,
EARLIEST_SERVE_HORIZON_DAYS, EARLIEST_SERVE_HORIZON_DAYS,

View file

@ -1,5 +1,5 @@
import type { Availability, TimeRange } from "./projection"; import type { Availability, TimeRange } from "./projection";
import { WEEKDAYS, type Weekday } from "./time"; import { WEEKDAYS, type Weekday, isCalendarDate } from "./time";
/** The cook is there all day: the availability when nothing says otherwise. */ /** The cook is there all day: the availability when nothing says otherwise. */
export const ALL_DAY: Availability = { export const ALL_DAY: Availability = {
@ -23,7 +23,6 @@ export type AvailabilityParse =
| ({ ok: false } & AvailabilityProblem); | ({ ok: false } & AvailabilityProblem);
const CLOCK = /^([01]?\d|2[0-4]):([0-5]\d)$/; const CLOCK = /^([01]?\d|2[0-4]):([0-5]\d)$/;
const DATE = /^\d{4}-\d{2}-\d{2}$/;
function parseRanges(text: string): TimeRange[] | string { function parseRanges(text: string): TimeRange[] | string {
if (text === "none") return []; if (text === "none") return [];
@ -76,7 +75,7 @@ export function parseAvailability(
} else if ((WEEKDAYS as readonly string[]).includes(key)) { } else if ((WEEKDAYS as readonly string[]).includes(key)) {
const day = key as Weekday; const day = key as Weekday;
weekdays[day] = [...(weekdays[day] ?? []), ...ranges]; weekdays[day] = [...(weekdays[day] ?? []), ...ranges];
} else if (DATE.test(key)) { } else if (isCalendarDate(key)) {
dates[key] = [...(dates[key] ?? []), ...ranges]; dates[key] = [...(dates[key] ?? []), ...ranges];
} else { } else {
return { ok: false, reason: "key", entry, part: entry.slice(0, eq) }; return { ok: false, reason: "key", entry, part: entry.slice(0, eq) };

View file

@ -107,6 +107,33 @@ export function toUtcIso(utcMinutes: number): string {
const LOCAL_ISO = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})$/; const LOCAL_ISO = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})$/;
const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/; const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
/** Days in a month (1-12) of a year, leap years included. */
const daysInMonth = (year: number, month: number) =>
new Date(Date.UTC(year, month, 0)).getUTCDate();
/** Whether a year, month (1-12) and day name a day that exists. */
const isRealDay = (year: number, month: number, day: number) =>
month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month);
/**
* Whether "YYYY-MM-DD" names a day of the calendar: "2026-02-30" has the shape
* of a date but is not one, and would otherwise roll over to March 2.
*/
export function isCalendarDate(value: string): boolean {
const m = DATE_ONLY.exec(value);
return m !== null && isRealDay(Number(m[1]), Number(m[2]), Number(m[3]));
}
/** The year, month and day of "YYYY-MM-DD", refusing a day that does not exist. */
function dateParts(date: string): [number, number, number] {
const m = DATE_ONLY.exec(date);
const parts = m?.slice(1).map(Number) as [number, number, number] | undefined;
if (!parts || !isRealDay(...parts)) {
throw new RangeError(`"${date}" is not a valid date`);
}
return parts;
}
/** Minutes since the epoch of a local wall-clock reading read as if it were UTC. */ /** Minutes since the epoch of a local wall-clock reading read as if it were UTC. */
function wallClockMinutes( function wallClockMinutes(
year: number, year: number,
@ -167,14 +194,7 @@ export function parseLocalIso(value: string, timeZone: string): number {
number, number,
number, number,
]; ];
if ( if (hour > 23 || minute > 59 || !isRealDay(year, month, day)) {
hour > 23 ||
minute > 59 ||
month < 1 ||
month > 12 ||
day < 1 ||
day > 31
) {
throw new RangeError(`"${value}" is not a valid date-time`); throw new RangeError(`"${value}" is not a valid date-time`);
} }
return localToUtc(year, month, day, hour * 60 + minute, timeZone); return localToUtc(year, month, day, hour * 60 + minute, timeZone);
@ -200,30 +220,24 @@ export function localDateTime(
minuteOfDay: number, minuteOfDay: number,
timeZone: string, timeZone: string,
): number { ): number {
const m = DATE_ONLY.exec(date); const [year, month, day] = dateParts(date);
if (!m) throw new RangeError(`"${date}" is not a valid date`);
const [year, month, day] = m.slice(1).map(Number) as [number, number, number];
return localToUtc(year, month, day, minuteOfDay, timeZone); return localToUtc(year, month, day, minuteOfDay, timeZone);
} }
/** The local date `days` after `date` (negative: before), as "YYYY-MM-DD". */ /** The local date `days` after `date` (negative: before), as "YYYY-MM-DD". */
export function addDays(date: string, days: number): string { export function addDays(date: string, days: number): string {
const m = DATE_ONLY.exec(date); const [year, month, day] = dateParts(date);
if (!m) throw new RangeError(`"${date}" is not a valid date`);
const [year, month, day] = m.slice(1).map(Number) as [number, number, number];
const shifted = new Date(Date.UTC(year, month - 1, day + days)); const shifted = new Date(Date.UTC(year, month - 1, day + days));
return `${pad(shifted.getUTCFullYear(), 4)}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`; return `${pad(shifted.getUTCFullYear(), 4)}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`;
} }
/** Whole local days from `from` to `to` (both "YYYY-MM-DD"). */ /** Whole local days from `from` to `to` (both "YYYY-MM-DD"). */
export function daysBetween(from: string, to: string): number { export function daysBetween(from: string, to: string): number {
const a = DATE_ONLY.exec(from); const ms = (date: string) => {
const b = DATE_ONLY.exec(to); const [year, month, day] = dateParts(date);
if (!a || !b) return Date.UTC(year, month - 1, day);
throw new RangeError(`"${from}" or "${to}" is not a valid date`); };
const ms = (m: RegExpExecArray) => return Math.round((ms(to) - ms(from)) / (MINUTES_PER_DAY * MS_PER_MINUTE));
Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
return Math.round((ms(b) - ms(a)) / (MINUTES_PER_DAY * MS_PER_MINUTE));
} }
/** "08:00" to minutes since midnight. */ /** "08:00" to minutes since midnight. */

View file

@ -45,6 +45,16 @@ describe("parseAvailability", () => {
entry: "someday=08:00-22:00", entry: "someday=08:00-22:00",
part: "someday", part: "someday",
}); });
// Shaped like a date, but February has no 30th: it would never apply.
expect(parseAvailability(["2026-02-30=none"])).toEqual({
ok: false,
reason: "key",
entry: "2026-02-30=none",
part: "2026-02-30",
});
expect(parseAvailability(["2028-02-29=none"])).toMatchObject({
ok: true,
});
expect(parseAvailability(["25:00-26:00"])).toMatchObject({ expect(parseAvailability(["25:00-26:00"])).toMatchObject({
ok: false, ok: false,
reason: "range", reason: "range",

View file

@ -7,6 +7,8 @@ import {
import { import {
addDays, addDays,
daysBetween, daysBetween,
isCalendarDate,
localDateTime,
parseClock, parseClock,
parseInstant, parseInstant,
parseLocalIso, parseLocalIso,
@ -75,6 +77,33 @@ describe("local time", () => {
expect(() => parseClock("8h")).toThrow(RangeError); expect(() => parseClock("8h")).toThrow(RangeError);
}); });
it("refuses a day the month does not have, instead of rolling over", () => {
expect(() => parseLocalIso("2026-02-30T20:00", PARIS)).toThrow(
'"2026-02-30T20:00" is not a valid date-time',
);
expect(() => parseLocalIso("2026-04-31T20:00", PARIS)).toThrow(RangeError);
expect(() => parseLocalIso("2026-02-29T20:00", PARIS)).toThrow(RangeError);
expect(toLocalIso(parseLocalIso("2028-02-29T20:00", PARIS), PARIS)).toBe(
"2028-02-29T20:00",
);
expect(() => addDays("2026-02-30", 1)).toThrow(RangeError);
expect(() => daysBetween("2026-02-28", "2026-02-31")).toThrow(RangeError);
expect(() => localDateTime("2026-06-31", 600, PARIS)).toThrow(
'"2026-06-31" is not a valid date',
);
});
it("tells a day of the calendar from a date-shaped string", () => {
expect(isCalendarDate("2026-02-28")).toBe(true);
expect(isCalendarDate("2028-02-29")).toBe(true);
expect(isCalendarDate("2026-02-29")).toBe(false);
expect(isCalendarDate("2026-02-30")).toBe(false);
expect(isCalendarDate("2026-13-01")).toBe(false);
expect(isCalendarDate("2026-00-10")).toBe(false);
expect(isCalendarDate("2026-1-10")).toBe(false);
expect(isCalendarDate("2026-10-11T13:00")).toBe(false);
});
it("counts days on the calendar", () => { it("counts days on the calendar", () => {
expect(addDays("2026-10-31", 1)).toBe("2026-11-01"); expect(addDays("2026-10-31", 1)).toBe("2026-11-01");
expect(addDays("2026-03-01", -1)).toBe("2026-02-28"); expect(addDays("2026-03-01", -1)).toBe("2026-02-28");