fix(domain): add month range validation to parse and monthOf

Shape-valid but out-of-range months (e.g., month 13 or 00) previously
normalized silently through ordinal arithmetic, resulting in wrong months
downstream. Now throw on invalid month values (< 1 or > 12), with the
offending value in the error message.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Lucas WintherandClaude Opus 5 committed 2026-09-01 16:33:27 +02:00
1 parent bab6fc5f3e
commit 9af581e69c
2 files changed
+34 -1

No files matched your search

+6 -1
View File
@@ -3,7 +3,10 @@ import type { IsoDate, MonthId } from "./types.ts";
function parse(id: MonthId): { year: number; month: number } {
const match = /^(\d{4})-(\d{2})$/.exec(id);
if (!match) throw new Error(`Invalid MonthId: ${id}`);
return { year: Number(match[1]), month: Number(match[2]) };
const year = Number(match[1]);
const month = Number(match[2]);
if (month < 1 || month > 12) throw new Error(`Invalid MonthId: ${id}`);
return { year, month };
}
function format(year: number, month: number): MonthId {
@@ -23,6 +26,8 @@ function fromOrdinal(ordinal: number): MonthId {
export function monthOf(date: IsoDate): MonthId {
const match = /^(\d{4})-(\d{2})/.exec(date);
if (!match) throw new Error(`Invalid IsoDate: ${date}`);
const month = Number(match[2]);
if (month < 1 || month > 12) throw new Error(`Invalid IsoDate: ${date}`);
return `${match[1]}-${match[2]}`;
}