Skip to content
Myr

Merge build/507-example-datekit: a fictional date library to show the platform on

Before adoption: this commit came in with the history the project adopted, so no landing records it.

# Conflicts: # turbo.json

authored by oscabriel · committed by oscabriel · parents fceb9c2, 8165ce4 · Browse files · 29 files+1757 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

29 files+1757 added−1 removed

  • tests:+949 added−0 removed
  • other:+808 added−1 removed

29 files+1757 added−1 removed

added:examples/datekit/.myr/asks/add-months-clamp.ask.ts+13 added
added:examples/datekit/.myr/asks/format-ordinal.ask.ts+11 added
added:examples/datekit/.myr/asks/parse-iso-week.ask.ts+13 added
added:examples/datekit/.myr/project.ts+25 added
added:examples/datekit/.myr/vouched.td+11 added
1# The people vouched for in datekit, and anyone denounced.2#3# A vouch lets a person claim an ask and offer a sealed answer; anyone not4# denounced may propose an ask. A maintainer adds a line by landing it.5#6# One handle per line, without @, in alphabetical order. A `platform:`7# prefix names a handle somewhere else, a leading minus denounces, and8# whatever follows the handle after a space is a note.9bram first answer landed in 0.4.010ines-v maintainer11okonkwo maintainer, time zones
added:examples/datekit/src/add.ts+39 added
added:examples/datekit/src/calendar.ts+38 added
added:examples/datekit/src/diff.ts+45 added
added:examples/datekit/src/format.ts+134 added
1/**2 * Showing a date as text with a pattern: `format(date, "d MMMM yyyy")` is3 * `7 October 2026`. Letters are tokens; text in single quotes is printed as4 * it is (`''` prints one quote); any other character passes through. A5 * letter that is no token is refused, so a typo never prints a wrong date.6 */7import { isValid } from "./parse.ts";8import { utcParts, zonedParts } from "./tz.ts";9import type { ZonedParts } from "./tz.ts";1011/** How `format` shows a date. */12export interface FormatOptions {13 /** The IANA zone to show the date in (`America/New_York`); UTC when left out. */14 readonly timeZone?: string;15}1617const MONTHS = [18 "January",19 "February",20 "March",21 "April",22 "May",23 "June",24 "July",25 "August",26 "September",27 "October",28 "November",29 "December",30];3132const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];3334const pad = (value: number, width: number) => String(value).padStart(width, "0");3536// The English suffix by last digit: 1st, 2nd, 3rd, and th for the rest.37const SUFFIXES = ["th", "st", "nd", "rd"];3839/** A number as an English ordinal: `1st`, `2nd`, `3rd`, `4th`. */40export const ordinal = (value: number): string => `${value}${SUFFIXES[value % 10] ?? "th"}`;4142/** A UTC offset as `Z`, or `+09:00`, `-04:00`, `+05:30`. */43const offsetText = (minutes: number) => {44 if (minutes === 0) {45 return "Z";46 }4748 const sign = minutes < 0 ? "-" : "+";49 const size = Math.abs(minutes);5051 return `${sign}${pad(Math.floor(size / 60), 2)}:${pad(size % 60, 2)}`;52};5354const twelveHour = (hour: number) => hour % 12 || 12;5556/** Each token, and how it shows a date's fields. */57const TOKENS: Readonly<Record<string, (parts: ZonedParts) => string>> = {58 // Year59 yyyy: ({ year }) => pad(year, 4),60 yy: ({ year }) => pad(year % 100, 2),61 // Month62 MMMM: ({ month }) => MONTHS[month - 1] ?? "",63 MMM: ({ month }) => (MONTHS[month - 1] ?? "").slice(0, 3),64 MM: ({ month }) => pad(month, 2),65 M: ({ month }) => String(month),66 // Day of the month67 Do: ({ day }) => ordinal(day),68 dd: ({ day }) => pad(day, 2),69 d: ({ day }) => String(day),70 // Day of the week71 EEEE: ({ weekday }) => WEEKDAYS[weekday - 1] ?? "",72 EEE: ({ weekday }) => (WEEKDAYS[weekday - 1] ?? "").slice(0, 3),73 // Time74 HH: ({ hour }) => pad(hour, 2),75 H: ({ hour }) => String(hour),76 hh: ({ hour }) => pad(twelveHour(hour), 2),77 h: ({ hour }) => String(twelveHour(hour)),78 a: ({ hour }) => (hour < 12 ? "AM" : "PM"),79 mm: ({ minute }) => pad(minute, 2),80 ss: ({ second }) => pad(second, 2),81 SSS: ({ millisecond }) => pad(millisecond, 3),82 // Offset83 XXX: ({ offset }) => offsetText(offset),84};8586// A quoted literal (to its closing quote, or the end), `Do`, a run of one87// letter, or anything that isn't a letter or a quote.88const PIECES = /'(?:[^']|'')*(?:'|$)|Do|([A-Za-z])\1*|[^A-Za-z']+/gu;8990/** One piece of a pattern, shown. */91const show = (piece: string, parts: ZonedParts): string => {92 if (piece.startsWith("'")) {93 return piece === "''"94 ? "'"95 : piece.slice(1, piece.endsWith("'") ? -1 : undefined).replaceAll("''", "'");96 }9798 if (!/^[A-Za-z]/u.test(piece)) {99 return piece;100 }101102 const token = TOKENS[piece];103104 if (token === undefined) {105 throw new RangeError(`format: "${piece}" is not a token; quote literal text, like 'at'`);106 }107108 return token(parts);109};110111/**112 * Shows `date` with `pattern`, in UTC or in `options.timeZone`. Throws a113 * `RangeError` for an invalid date, an unknown token or an unknown zone.114 *115 * | Token | Shows | Example |116 * | --- | --- | --- |117 * | `yyyy`, `yy` | year | `2026`, `26` |118 * | `MMMM`, `MMM`, `MM`, `M` | month | `October`, `Oct`, `10`, `10` |119 * | `Do`, `dd`, `d` | day of the month | `7th`, `07`, `7` |120 * | `EEEE`, `EEE` | day of the week | `Wednesday`, `Wed` |121 * | `HH`, `H`, `hh`, `h`, `a` | hour, 24- and 12-hour, and AM or PM | `14`, `14`, `02`, `2`, `PM` |122 * | `mm`, `ss`, `SSS` | minute, second, millisecond | `05`, `09`, `250` |123 * | `XXX` | UTC offset | `Z`, `+09:00` |124 */125export const format = (date: Date, pattern: string, options: FormatOptions = {}): string => {126 if (!isValid(date)) {127 throw new RangeError("format: the date is invalid");128 }129130 const parts =131 options.timeZone === undefined ? utcParts(date) : zonedParts(date, options.timeZone);132133 return (pattern.match(PIECES) ?? []).map((piece) => show(piece, parts)).join("");134};
added:examples/datekit/src/index.ts+28 added
1/**2 * datekit: small, dependency-free date helpers. Dates are plain `Date`3 * instants; datekit reads and shows them in UTC unless you name a time zone.4 */5export {6 addDays,7 addHours,8 addMilliseconds,9 addMinutes,10 addMonths,11 addSeconds,12 addWeeks,13 addYears,14} from "./add.ts";15export { daysInMonth, daysInYear, isLeapYear } from "./calendar.ts";16export {17 diffInCalendarDays,18 diffInCalendarMonths,19 diffInDays,20 diffInHours,21 diffInMilliseconds,22 diffInMinutes,23 diffInSeconds,24 diffInWeeks,25} from "./diff.ts";26export { format, ordinal, type FormatOptions } from "./format.ts";27export { invalidDate, isValid, parseISO } from "./parse.ts";28export { isTimeZone, offsetIn, type ZonedParts, zonedParts } from "./tz.ts";
added:examples/datekit/src/parse.ts+140 added
1/**2 * Reading ISO 8601 text. `parseISO` reads calendar dates and ordinal dates,3 * with an optional time and UTC offset, and never throws: text it can't read4 * gives an invalid date, which `isValid` tells apart.5 */6import {7 MS_PER_HOUR,8 MS_PER_MINUTE,9 MS_PER_SECOND,10 daysInMonth,11 daysInYear,12 utcMidnight,13} from "./calendar.ts";1415/** A date that stands for no instant: what `parseISO` gives for text it can't read. */16export const invalidDate = (): Date => new Date(Number.NaN);1718/** Whether `date` stands for an instant (an invalid date doesn't). */19export const isValid = (date: Date): boolean => !Number.isNaN(date.getTime());2021/** The date forms `parseISO` reads, extended and basic. */22const CALENDAR_DATES = [23 /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u,24 /^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})$/u,25 /^(?<year>\d{4})-(?<month>\d{2})$/u,26 /^(?<year>\d{4})$/u,27];2829const ORDINAL_DATE = /^(?<year>\d{4})-?(?<ordinal>\d{3})$/u;3031const TIME =32 /^(?<hour>\d{2})(?::(?<minute>\d{2})(?::(?<second>\d{2})(?:[.,](?<fraction>\d{1,9}))?)?)?(?<offset>Z|[+-]\d{2}(?::?\d{2})?)?$/u;3334const OFFSET = /^(?<sign>[+-])(?<hours>\d{2}):?(?<minutes>\d{2})?$/u;3536const whole = (digits: string | undefined, fallback = 0): number =>37 digits === undefined ? fallback : Number(digits);3839/** A calendar date, as the instant it starts in UTC; `undefined` when it isn't a real day. */40const calendarDay = (year: number, month: number, day: number): number | undefined =>41 month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month)42 ? utcMidnight(year, month, day)43 : undefined;4445/** The start of the day the date part names, in epoch milliseconds. */46const readDate = (text: string): number | undefined => {47 for (const form of CALENDAR_DATES) {48 const groups = form.exec(text)?.groups;4950 if (groups !== undefined) {51 return calendarDay(whole(groups.year), whole(groups.month, 1), whole(groups.day, 1));52 }53 }5455 const ordinal = ORDINAL_DATE.exec(text)?.groups;5657 if (ordinal !== undefined) {58 const year = whole(ordinal.year);59 const day = whole(ordinal.ordinal);6061 return day >= 1 && day <= daysInYear(year) ? utcMidnight(year, 1, day) : undefined;62 }6364 return undefined;65};6667/** A UTC offset (`Z`, `+09:00`, `-0330`, `+05`) in minutes east of UTC. */68const readOffset = (text: string | undefined): number | undefined => {69 if (text === undefined || text === "Z") {70 return 0;71 }7273 const groups = OFFSET.exec(text)?.groups;7475 if (groups === undefined) {76 return undefined;77 }7879 const hours = whole(groups.hours);80 const minutes = whole(groups.minutes);8182 if (hours > 23 || minutes > 59) {83 return undefined;84 }8586 return (groups.sign === "-" ? -1 : 1) * (hours * 60 + minutes);87};8889/** How far past midnight the time part is, in UTC milliseconds (its offset taken off). */90const readTime = (text: string): number | undefined => {91 const groups = TIME.exec(text)?.groups;9293 if (groups === undefined) {94 return undefined;95 }9697 const hour = whole(groups.hour);98 const minute = whole(groups.minute);99 const second = whole(groups.second);100 const offset = readOffset(groups.offset);101102 if (hour > 23 || minute > 59 || second > 59 || offset === undefined) {103 return undefined;104 }105106 // Digits past the millisecond are dropped, not rounded.107 const millisecond = whole((groups.fraction ?? "").padEnd(3, "0").slice(0, 3));108109 return (110 hour * MS_PER_HOUR +111 minute * MS_PER_MINUTE +112 second * MS_PER_SECOND +113 millisecond -114 offset * MS_PER_MINUTE115 );116};117118/**119 * Reads ISO 8601 text: a date (`2026-10-07`, `20261007`, `2026-10`, `2026`,120 * or the ordinal `2026-280`), then optionally `T` and a time (`14:30`,121 * `14:30:15`, `14:30:15.250`) with a UTC offset (`Z`, `+09:00`). Text with122 * no offset is read as UTC. Anything else, or a day that doesn't exist123 * (`2026-02-29`), gives an invalid date.124 */125export const parseISO = (text: string): Date => {126 const [datePart = "", timePart, ...rest] = text.trim().split("T");127 const day = readDate(datePart);128129 if (day === undefined || rest.length > 0) {130 return invalidDate();131 }132133 if (timePart === undefined) {134 return new Date(day);135 }136137 const time = readTime(timePart);138139 return time === undefined ? invalidDate() : new Date(day + time);140};
added:examples/datekit/src/tz.ts+98 added
1/**2 * Time zones. datekit keeps every date as an instant and works in UTC; a3 * time zone matters only when a date is shown, so this module turns an4 * instant into the wall-clock fields of an IANA zone (`Europe/Lisbon`), with5 * the zone's offset at that instant. The zone data is the runtime's own6 * (`Intl`), so datekit ships none.7 */8import { MS_PER_MINUTE, isoWeekday, utcMidnight } from "./calendar.ts";910/** An instant's wall-clock fields in one zone, and the zone's offset from UTC then. */11export interface ZonedParts {12 readonly year: number;13 /** 1 to 12. */14 readonly month: number;15 readonly day: number;16 /** 0 to 23. */17 readonly hour: number;18 readonly minute: number;19 readonly second: number;20 readonly millisecond: number;21 /** The ISO weekday: Monday is 1 and Sunday is 7. */22 readonly weekday: number;23 /** Minutes east of UTC: `+09:00` is 540. */24 readonly offset: number;25}2627/** An instant's fields in UTC. */28export const utcParts = (date: Date): ZonedParts => ({29 day: date.getUTCDate(),30 hour: date.getUTCHours(),31 millisecond: date.getUTCMilliseconds(),32 minute: date.getUTCMinutes(),33 month: date.getUTCMonth() + 1,34 offset: 0,35 second: date.getUTCSeconds(),36 weekday: isoWeekday(date),37 year: date.getUTCFullYear(),38});3940/** Whether the runtime knows `name` as a time zone. */41export const isTimeZone = (name: string): boolean => {42 try {43 new Intl.DateTimeFormat("en-US", { timeZone: name });4445 return true;46 } catch {47 return false;48 }49};5051const fieldsIn = (timeZone: string) =>52 new Intl.DateTimeFormat("en-US", {53 day: "numeric",54 hour: "numeric",55 hourCycle: "h23",56 minute: "numeric",57 month: "numeric",58 second: "numeric",59 timeZone,60 year: "numeric",61 });6263/**64 * An instant's fields in the IANA zone `timeZone`. Throws a `RangeError`65 * for a zone the runtime doesn't know.66 */67export const zonedParts = (date: Date, timeZone: string): ZonedParts => {68 const parts = new Map(69 fieldsIn(timeZone)70 .formatToParts(date)71 .map(({ type, value }) => [type, Number(value)]),72 );7374 const field = (type: Intl.DateTimeFormatPartTypes) => parts.get(type) ?? 0;75 const millisecond = date.getUTCMilliseconds();76 const wall = new Date(utcMidnight(field("year"), field("month"), field("day")));7778 // The wall clock read as if it were UTC, less the instant, is the offset.79 const wallTime =80 wall.getTime() +81 ((field("hour") * 60 + field("minute")) * 60 + field("second")) * 1000 +82 millisecond;8384 return {85 day: field("day"),86 hour: field("hour"),87 millisecond,88 minute: field("minute"),89 month: field("month"),90 offset: Math.round((wallTime - date.getTime()) / MS_PER_MINUTE),91 second: field("second"),92 weekday: isoWeekday(wall),93 year: field("year"),94 };95};9697/** The offset of `timeZone` from UTC at `date`, in minutes east of UTC. */98export const offsetIn = (date: Date, timeZone: string): number => zonedParts(date, timeZone).offset;
added:examples/datekit/test/asks/add-months-clamp.test.ts+20 added
1import { expect, test } from "bun:test";23import { addMonths, addYears } from "../../src/index.ts";45const plusMonths = (text: string, amount: number) =>6 addMonths(new Date(text), amount).toISOString();78test("addMonths ends on the last day of a target month too short for the day", () => {9 // January 31 plus a month is the end of February, in leap and common years.10 expect(plusMonths("2028-01-31T00:00:00Z", 1)).toBe("2028-02-29T00:00:00.000Z");11 expect(plusMonths("2026-01-31T00:00:00Z", 1)).toBe("2026-02-28T00:00:00.000Z");12 // The time of day stays, and so does the direction.13 expect(plusMonths("2026-10-31T09:30:00Z", 1)).toBe("2026-11-30T09:30:00.000Z");14 expect(plusMonths("2026-03-31T00:00:00Z", -1)).toBe("2026-02-28T00:00:00.000Z");15 expect(plusMonths("2026-05-31T00:00:00Z", -11)).toBe("2025-06-30T00:00:00.000Z");16 // A year is twelve months, so February 29 plus a year is February 28.17 expect(addYears(new Date("2028-02-29T00:00:00Z"), 1).toISOString()).toBe(18 "2029-02-28T00:00:00.000Z",19 );20});
added:examples/datekit/test/asks/format-ordinal.test.ts+22 added
1import { expect, test } from "bun:test";23import { format } from "../../src/index.ts";45test("format's Do token prints English ordinals, the teens included", () => {6 const days = [1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 31];78 expect(days.map((day) => format(new Date(Date.UTC(2026, 0, day)), "Do"))).toStrictEqual([9 "1st",10 "2nd",11 "3rd",12 "4th",13 "11th",14 "12th",15 "13th",16 "14th",17 "21st",18 "22nd",19 "23rd",20 "31st",21 ]);22});
added:examples/datekit/test/asks/parse-iso-week.test.ts+21 added
1import { expect, test } from "bun:test";23import { isValid, parseISO } from "../../src/index.ts";45const day = (text: string) => parseISO(text).getTime();67test("parseISO reads ISO week dates to the UTC midnight of their day", () => {8 // Week 41 of 2026 runs from Monday, October 5 to Sunday, October 11.9 expect(day("2026-W41-3")).toBe(Date.UTC(2026, 9, 7));10 expect(day("2026W413")).toBe(Date.UTC(2026, 9, 7));11 // A week with no day is its Monday.12 expect(day("2026-W41")).toBe(Date.UTC(2026, 9, 5));13 // Week 1 is the week with the year's first Thursday, so it can start in14 // December, and a year that starts on a Thursday has 53 weeks.15 expect(day("2026-W01-1")).toBe(Date.UTC(2025, 11, 29));16 expect(day("2026-W53-7")).toBe(Date.UTC(2027, 0, 3));17 expect(day("2026-W41-3T14:30Z")).toBe(Date.UTC(2026, 9, 7, 14, 30));18 // 2027 starts on a Friday, so it has 52 weeks; and a week has 7 days.19 expect(isValid(parseISO("2027-W53-1"))).toBe(false);20 expect(isValid(parseISO("2026-W41-8"))).toBe(false);21});
added:examples/datekit/test/add.test.ts+79 added
1import { describe, expect, test } from "bun:test";23import {4 addDays,5 addHours,6 addMilliseconds,7 addMinutes,8 addMonths,9 addSeconds,10 addWeeks,11 addYears,12 isValid,13} from "../src/index.ts";1415const at = (text: string) => new Date(text);1617describe("addDays and addWeeks", () => {18 test("move across a month and a year, keeping the time of day", () => {19 expect(addDays(at("2026-10-07T09:30:00Z"), 1).toISOString()).toBe("2026-10-08T09:30:00.000Z");20 expect(addDays(at("2026-12-31T09:30:00Z"), 1).toISOString()).toBe("2027-01-01T09:30:00.000Z");21 expect(addDays(at("2028-02-28T00:00:00Z"), 1).toISOString()).toBe("2028-02-29T00:00:00.000Z");22 expect(addDays(at("2026-03-01T00:00:00Z"), -1).toISOString()).toBe("2026-02-28T00:00:00.000Z");23 expect(addWeeks(at("2026-10-07T00:00:00Z"), 2).toISOString()).toBe("2026-10-21T00:00:00.000Z");24 });2526 test("drop a fraction toward zero", () => {27 expect(addDays(at("2026-10-07T00:00:00Z"), 1.9).toISOString()).toBe("2026-10-08T00:00:00.000Z");28 expect(addDays(at("2026-10-07T00:00:00Z"), -1.9).toISOString()).toBe(29 "2026-10-06T00:00:00.000Z",30 );31 });3233 test("leave their argument alone", () => {34 const date = at("2026-10-07T00:00:00Z");3536 addDays(date, 3);3738 expect(date.toISOString()).toBe("2026-10-07T00:00:00.000Z");39 });40});4142describe("addHours, addMinutes, addSeconds and addMilliseconds", () => {43 test("move by exact amounts of time", () => {44 const date = at("2026-10-07T23:30:00Z");4546 expect(addHours(date, 1).toISOString()).toBe("2026-10-08T00:30:00.000Z");47 expect(addMinutes(date, -45).toISOString()).toBe("2026-10-07T22:45:00.000Z");48 expect(addSeconds(date, 90).toISOString()).toBe("2026-10-07T23:31:30.000Z");49 expect(addMilliseconds(date, 250).toISOString()).toBe("2026-10-07T23:30:00.250Z");50 });51});5253describe("addMonths and addYears", () => {54 test("keep the day of the month when the target month has it", () => {55 expect(addMonths(at("2026-01-15T00:00:00Z"), 1).toISOString()).toBe("2026-02-15T00:00:00.000Z");56 expect(addMonths(at("2026-10-07T08:00:00Z"), 3).toISOString()).toBe("2027-01-07T08:00:00.000Z");57 expect(addMonths(at("2026-03-15T00:00:00Z"), -2).toISOString()).toBe(58 "2026-01-15T00:00:00.000Z",59 );60 expect(addMonths(at("2026-10-07T00:00:00Z"), 0).toISOString()).toBe("2026-10-07T00:00:00.000Z");61 });6263 test("add twelve months a year", () => {64 expect(addYears(at("2026-10-07T00:00:00Z"), 2).toISOString()).toBe("2028-10-07T00:00:00.000Z");65 expect(addYears(at("2026-10-07T00:00:00Z"), -26).toISOString()).toBe(66 "2000-10-07T00:00:00.000Z",67 );68 });69});7071describe("an invalid date", () => {72 test("stays invalid", () => {73 const invalid = new Date(Number.NaN);7475 expect(isValid(addDays(invalid, 1))).toBe(false);76 expect(isValid(addMonths(invalid, 1))).toBe(false);77 expect(isValid(addHours(invalid, 1))).toBe(false);78 });79});
added:examples/datekit/test/diff.test.ts+73 added
1import { describe, expect, test } from "bun:test";23import {4 daysInMonth,5 diffInCalendarDays,6 diffInCalendarMonths,7 diffInDays,8 diffInHours,9 diffInMilliseconds,10 diffInMinutes,11 diffInSeconds,12 diffInWeeks,13 isLeapYear,14} from "../src/index.ts";1516const at = (text: string) => new Date(text);1718describe("diffInDays", () => {19 test("counts whole 24-hour days, toward zero", () => {20 expect(diffInDays(at("2026-10-08T00:00:00Z"), at("2026-10-07T12:00:00Z"))).toBe(0);21 expect(diffInDays(at("2026-10-09T01:00:00Z"), at("2026-10-07T00:00:00Z"))).toBe(2);22 expect(diffInDays(at("2026-10-07T00:00:00Z"), at("2026-10-09T01:00:00Z"))).toBe(-2);23 expect(diffInDays(at("2026-10-07T00:00:00Z"), at("2026-10-07T12:00:00Z"))).toBe(0);24 });2526 test("counts February 29 in a leap year", () => {27 expect(diffInDays(at("2028-03-01T00:00:00Z"), at("2028-02-01T00:00:00Z"))).toBe(29);28 expect(diffInDays(at("2026-03-01T00:00:00Z"), at("2026-02-01T00:00:00Z"))).toBe(28);29 });3031 test("gives NaN for an invalid date", () => {32 expect(diffInDays(new Date(Number.NaN), at("2026-10-07T00:00:00Z"))).toBeNaN();33 });34});3536describe("diffInCalendarDays", () => {37 test("counts the UTC midnights crossed", () => {38 expect(diffInCalendarDays(at("2026-10-08T00:00:00Z"), at("2026-10-07T23:59:00Z"))).toBe(1);39 expect(diffInCalendarDays(at("2026-10-07T23:59:00Z"), at("2026-10-07T00:00:00Z"))).toBe(0);40 expect(diffInCalendarDays(at("2027-01-01T00:00:00Z"), at("2026-01-01T00:00:00Z"))).toBe(365);41 });42});4344describe("diffInCalendarMonths", () => {45 test("counts the month boundaries crossed", () => {46 expect(diffInCalendarMonths(at("2027-01-01T00:00:00Z"), at("2026-10-31T00:00:00Z"))).toBe(3);47 expect(diffInCalendarMonths(at("2026-10-31T00:00:00Z"), at("2026-10-01T00:00:00Z"))).toBe(0);48 expect(diffInCalendarMonths(at("2026-01-01T00:00:00Z"), at("2026-10-31T00:00:00Z"))).toBe(-9);49 });50});5152describe("the smaller units", () => {53 test("count whole hours, minutes, seconds and weeks", () => {54 const start = at("2026-10-07T00:00:00Z");55 const later = at("2026-10-21T01:30:45.500Z");5657 expect(diffInMilliseconds(later, start)).toBe(1_215_045_500);58 expect(diffInSeconds(later, start)).toBe(1_215_045);59 expect(diffInMinutes(later, start)).toBe(20_250);60 expect(diffInHours(later, start)).toBe(337);61 expect(diffInWeeks(later, start)).toBe(2);62 });63});6465describe("the calendar", () => {66 test("knows the leap years and the length of each month", () => {67 expect([1900, 2000, 2026, 2028].map(isLeapYear)).toStrictEqual([false, true, false, true]);68 expect(daysInMonth(2028, 2)).toBe(29);69 expect(daysInMonth(2026, 2)).toBe(28);70 expect(daysInMonth(2026, 4)).toBe(30);71 expect(daysInMonth(2026, 12)).toBe(31);72 });73});
added:examples/datekit/test/format.test.ts+95 added
1import { describe, expect, test } from "bun:test";23import { format, isTimeZone, offsetIn } from "../src/index.ts";45// Wednesday, October 7, 2026, 14:05:09.250 UTC.6const afternoon = new Date(Date.UTC(2026, 9, 7, 14, 5, 9, 250));78const on = (year: number, month: number, day: number, hour = 0, minute = 0) =>9 new Date(Date.UTC(year, month - 1, day, hour, minute));1011describe("format", () => {12 test("shows the year, month and day by their tokens", () => {13 expect(format(afternoon, "yyyy-MM-dd")).toBe("2026-10-07");14 expect(format(afternoon, "d MMMM yyyy")).toBe("7 October 2026");15 expect(format(afternoon, "EEE, d MMM yy")).toBe("Wed, 7 Oct 26");16 expect(format(afternoon, "EEEE M/d")).toBe("Wednesday 10/7");17 });1819 test("shows the time on a 24-hour and a 12-hour clock", () => {20 expect(format(afternoon, "HH:mm:ss.SSS")).toBe("14:05:09.250");21 expect(format(afternoon, "h:mm a")).toBe("2:05 PM");22 expect(format(on(2026, 10, 7, 0, 5), "hh:mm a")).toBe("12:05 AM");23 expect(format(on(2026, 10, 7, 12), "h a")).toBe("12 PM");24 expect(format(on(2026, 10, 7, 9), "H")).toBe("9");25 });2627 test("shows the day of the month as an English ordinal", () => {28 const days = [1, 2, 3, 4, 10, 20, 21, 22, 23, 24, 30, 31];2930 expect(days.map((day) => format(on(2026, 1, day), "Do"))).toStrictEqual([31 "1st",32 "2nd",33 "3rd",34 "4th",35 "10th",36 "20th",37 "21st",38 "22nd",39 "23rd",40 "24th",41 "30th",42 "31st",43 ]);44 });4546 test("prints quoted text as it is, and '' as one quote", () => {47 expect(format(afternoon, "'Week of' MMMM d")).toBe("Week of October 7");48 expect(format(afternoon, "h 'o''clock'")).toBe("2 o'clock");49 expect(format(afternoon, "yyyy''MM")).toBe("2026'10");50 expect(format(afternoon, "'at' HH:mm 'sharp")).toBe("at 14:05 sharp");51 });5253 test("passes punctuation and spaces through", () => {54 expect(format(afternoon, "[yyyy] (MM) / dd.")).toBe("[2026] (10) / 07.");55 });5657 test("refuses a letter that is no token, an invalid date and an unknown zone", () => {58 expect(() => format(afternoon, "yyyy-MM-dd at HH")).toThrow(RangeError);59 expect(() => format(afternoon, "yyy")).toThrow(RangeError);60 expect(() => format(new Date(Number.NaN), "yyyy")).toThrow(RangeError);61 expect(() => format(afternoon, "HH", { timeZone: "Mars/Olympus_Mons" })).toThrow(RangeError);62 });6364 test("shows UTC's offset as Z", () => {65 expect(format(afternoon, "yyyy-MM-dd'T'HH:mm:ssXXX")).toBe("2026-10-07T14:05:09Z");66 });67});6869describe("format in a time zone", () => {70 test("shows the wall clock of the zone, with its offset", () => {71 const zoned = (timeZone: string) => format(afternoon, "yyyy-MM-dd HH:mm XXX EEE", { timeZone });7273 expect(zoned("Asia/Tokyo")).toBe("2026-10-07 23:05 +09:00 Wed");74 expect(zoned("Asia/Kolkata")).toBe("2026-10-07 19:35 +05:30 Wed");75 expect(zoned("America/Sao_Paulo")).toBe("2026-10-07 11:05 -03:00 Wed");76 expect(zoned("Pacific/Kiritimati")).toBe("2026-10-08 04:05 +14:00 Thu");77 expect(zoned("UTC")).toBe("2026-10-07 14:05 Z Wed");78 });7980 test("follows daylight saving time", () => {81 expect(format(on(2026, 7, 1, 12), "HH:mm XXX", { timeZone: "America/New_York" })).toBe(82 "08:00 -04:00",83 );84 expect(format(on(2026, 1, 15, 12), "HH:mm XXX", { timeZone: "America/New_York" })).toBe(85 "07:00 -05:00",86 );87 expect(offsetIn(on(2026, 7, 1), "Europe/Lisbon")).toBe(60);88 expect(offsetIn(on(2026, 12, 1), "Europe/Lisbon")).toBe(0);89 });9091 test("knows the zones the runtime knows", () => {92 expect(isTimeZone("Europe/Lisbon")).toBe(true);93 expect(isTimeZone("Mars/Olympus_Mons")).toBe(false);94 });95});
added:examples/datekit/test/parse.test.ts+78 added
1import { describe, expect, test } from "bun:test";23import { isValid, parseISO } from "../src/index.ts";45const iso = (text: string) => parseISO(text).toISOString();67describe("parseISO", () => {8 test("reads a calendar date as the UTC midnight it starts at", () => {9 expect(iso("2026-10-07")).toBe("2026-10-07T00:00:00.000Z");10 expect(iso("20261007")).toBe("2026-10-07T00:00:00.000Z");11 });1213 test("reads a year and month as the month's first day, and a year as January 1", () => {14 expect(iso("2026-10")).toBe("2026-10-01T00:00:00.000Z");15 expect(iso("2026")).toBe("2026-01-01T00:00:00.000Z");16 });1718 test("reads an ordinal date as the nth day of the year", () => {19 expect(iso("2026-280")).toBe("2026-10-07T00:00:00.000Z");20 expect(iso("2026280")).toBe("2026-10-07T00:00:00.000Z");21 expect(iso("2028-366")).toBe("2028-12-31T00:00:00.000Z");22 });2324 test("reads a time with no offset as UTC", () => {25 expect(iso("2026-10-07T14:30")).toBe("2026-10-07T14:30:00.000Z");26 expect(iso("2026-10-07T14")).toBe("2026-10-07T14:00:00.000Z");27 expect(iso("2026-10-07T14:30:15.250")).toBe("2026-10-07T14:30:15.250Z");28 });2930 test("takes a UTC offset off the time", () => {31 expect(iso("2026-10-07T09:30:00+09:00")).toBe("2026-10-07T00:30:00.000Z");32 expect(iso("2026-10-07T09:30:00+0900")).toBe("2026-10-07T00:30:00.000Z");33 expect(iso("2026-10-06T20:30:00-03:30")).toBe("2026-10-07T00:00:00.000Z");34 expect(iso("2026-10-07T14:30:00Z")).toBe("2026-10-07T14:30:00.000Z");35 expect(iso("2026-10-07T00:00+05")).toBe("2026-10-06T19:00:00.000Z");36 });3738 test("drops digits past the millisecond", () => {39 expect(iso("2026-10-07T14:30:15.123456789Z")).toBe("2026-10-07T14:30:15.123Z");40 expect(iso("2026-10-07T14:30:15,5Z")).toBe("2026-10-07T14:30:15.500Z");41 });4243 test("reads February 29 only in a leap year", () => {44 expect(iso("2028-02-29")).toBe("2028-02-29T00:00:00.000Z");45 expect(isValid(parseISO("2026-02-29"))).toBe(false);46 expect(isValid(parseISO("2100-02-29"))).toBe(false);47 expect(iso("2000-02-29")).toBe("2000-02-29T00:00:00.000Z");48 });4950 test("reads the years before 100 as written", () => {51 expect(parseISO("0042-03-01").getUTCFullYear()).toBe(42);52 });5354 test("gives an invalid date for text it can't read, and never throws", () => {55 for (const text of [56 "",57 "next tuesday",58 "2026-13-01",59 "2026-10-32",60 "2026-00-10",61 "2026-367",62 "2026-10-07T24:00",63 "2026-10-07T14:60",64 "2026-10-07T14:30:00+24:00",65 "2026-10-07T14:30T15:00",66 "26-10-07",67 ]) {68 expect(isValid(parseISO(text)), text).toBe(false);69 }70 });71});7273describe("isValid", () => {74 test("tells a real instant from an invalid date", () => {75 expect(isValid(new Date(0))).toBe(true);76 expect(isValid(new Date(Number.NaN))).toBe(false);77 });78});
added:examples/datekit/.env.schema+21 added
1# The variables datekit's docs site and release step read. Values for tests2# are in .env.test; a maintainer sets the release token, which is never3# committed.4# @currentEnv=$APP_ENV5# @defaultRequired=infer @defaultSensitive=false6# ---78# @type=enum(development, test, production)9APP_ENV=development1011# Error reporting DSN. Public: it ships in builds.12# @type=url13SENTRY_DSN=https://public@o0.ingest.example.invalid/11415# Source-map upload token. Release step only; never enters a check.16# @sensitive @required=forEnv(production) @tag(release)17# @proxy(domain="sentry.io", path="/api/**")18SENTRY_AUTH_TOKEN=1920# Where locale data lives.21DATEKIT_LOCALE_DIR=./locales
added:examples/datekit/.env.test+3 added
1# Values for APP_ENV=test. Committed: none of them is a secret.2SENTRY_DSN=https://test@o0.ingest.example.invalid/23DATEKIT_LOCALE_DIR=./locales
added:examples/datekit/.gitignore+6 added
1node_modules/23# Values stay on each machine; .env.schema and .env.test are committed.4.env5.env.local6.env.*.local
added:examples/datekit/LICENSE+21 added
1MIT License23Copyright (c) 2026 The datekit authors45Permission is hereby granted, free of charge, to any person obtaining a copy6of this software and associated documentation files (the "Software"), to deal7in the Software without restriction, including without limitation the rights8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9copies of the Software, and to permit persons to whom the Software is10furnished to do so, subject to the following conditions:1112The above copyright notice and this permission notice shall be included in all13copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21SOFTWARE.
added:examples/datekit/package.json+24 added
1{2 "name": "datekit",3 "version": "0.4.2",4 "description": "Small, dependency-free date helpers for TypeScript: read ISO 8601, format with patterns, add and diff in whole units, in UTC or any time zone.",5 "keywords": [6 "date",7 "format",8 "iso8601",9 "parse",10 "time",11 "timezone"12 ],13 "license": "MIT",14 "files": [15 "src"16 ],17 "type": "module",18 "exports": {19 ".": "./src/index.ts"20 },21 "scripts": {22 "test": "bun test"23 }24}
modified:examples/datekit/README.md+112 added-1 removed
1# datekit23datekit is a fictional TypeScript date library, made up so the platform has a small, believable project to be shown on; its maintainers are fictional too. It is a Bun project of its own, not a workspace of this repo: the root's workspaces, lint, format and typecheck leave it out, and it lints and tests with its own config. Issue 507 fills it in.3Small, dependency-free date helpers for TypeScript. datekit reads ISO 8601 text, shows dates with patterns, and adds and diffs in whole units. Dates are plain `Date` instants, and datekit works in UTC unless you name a time zone, so the same code gives the same answer on every machine.45> datekit and its maintainers are fictional: it is an example project made up to show Myr, the git platform it is hosted on.67## Install89```sh10bun add datekit11```1213datekit has no dependencies and ships its TypeScript source, which Bun, Deno and any bundler read as is. It needs a runtime with `Intl` time zone data for the `timeZone` option; Bun, Deno, Node and every current browser have it.1415## Usage1617```ts18import { addMonths, diffInDays, format, parseISO } from "datekit";1920const shipped = parseISO("2026-10-07T14:30:00+01:00");2122format(shipped, "EEE, d MMMM yyyy 'at' HH:mm"); // "Wed, 7 October 2026 at 13:30"23format(shipped, "h:mm a XXX", { timeZone: "Asia/Tokyo" }); // "10:30 PM +09:00"2425const renewal = addMonths(shipped, 3);26format(renewal, "yyyy-MM-dd"); // "2027-01-07"27diffInDays(renewal, shipped); // 9228```2930## Reading dates3132`parseISO(text)` reads ISO 8601:3334- a calendar date: `2026-10-07`, or `20261007`; `2026-10` is the month's first day and `2026` is January 1;35- an ordinal date: `2026-280` is the 280th day of 2026;36- then optionally `T` and a time, `14:30`, `14:30:15` or `14:30:15.250`, with a UTC offset, `Z`, `+09:00` or `-0330`.3738Text with no offset is read as UTC. Digits past the millisecond are dropped, not rounded.3940`parseISO` never throws. Text it can't read, or a day that doesn't exist (`2026-02-29`, `2026-04-31`), gives an invalid date; check with `isValid(date)`.4142## Showing dates4344`format(date, pattern, options?)` shows a date with a pattern, in UTC or in `options.timeZone`.4546| Token | Shows | Example |47| --- | --- | --- |48| `yyyy`, `yy` | year | `2026`, `26` |49| `MMMM`, `MMM`, `MM`, `M` | month | `October`, `Oct`, `10`, `10` |50| `Do`, `dd`, `d` | day of the month | `7th`, `07`, `7` |51| `EEEE`, `EEE` | day of the week | `Wednesday`, `Wed` |52| `HH`, `H` | hour, 24-hour clock | `14`, `14` |53| `hh`, `h`, `a` | hour, 12-hour clock, and AM or PM | `02`, `2`, `PM` |54| `mm`, `ss`, `SSS` | minute, second, millisecond | `05`, `09`, `250` |55| `XXX` | UTC offset | `Z`, `+09:00`, `-04:00` |5657### Format patterns5859- Text in single quotes is printed exactly as written: `'Week of' MMMM d` is `Week of October 7`. Two single quotes print one: `h 'o''clock'` is `2 o'clock`.60- Punctuation, digits and spaces pass through as they are.61- A letter outside quotes that is no token throws a `RangeError`, so a typo never prints a wrong date. So does an invalid date, or a time zone the runtime doesn't know.6263## Moving dates6465`addMilliseconds`, `addSeconds`, `addMinutes`, `addHours`, `addDays`, `addWeeks`, `addMonths` and `addYears` each return a new date and leave their argument alone. Amounts are whole numbers; a fraction is dropped toward zero. Every day in UTC is 24 hours long, so `addDays` adds exact days. `addMonths` keeps the day of the month and the time of day, and `addYears` adds twelve months.6667## Comparing dates6869The `diffIn…` functions take the later date first and count whole units, dropping a part unit toward zero, so the result is negative when the first date is the earlier one.7071| Function | Counts |72| --- | --- |73| `diffInMilliseconds`, `diffInSeconds`, `diffInMinutes`, `diffInHours` | exact time |74| `diffInDays`, `diffInWeeks` | whole 24-hour days and weeks |75| `diffInCalendarDays` | UTC midnights crossed |76| `diffInCalendarMonths` | month boundaries crossed |7778`isLeapYear(year)`, `daysInMonth(year, month)` (months 1 to 12) and `daysInYear(year)` answer calendar questions.7980## Time zones8182datekit keeps instants and never shifts them; a time zone only changes how a date is shown. `format` takes any IANA zone (`Europe/Lisbon`, `America/New_York`) and follows its daylight saving time. `zonedParts(date, timeZone)` gives the wall-clock fields and the offset, `offsetIn(date, timeZone)` the offset alone in minutes east of UTC, and `isTimeZone(name)` says whether the runtime knows a zone. The zone data is the runtime's own, so datekit ships none.8384## Contributing8586What we want changed is written down as asks, one file each in `.myr/asks/`: a sentence saying what should happen, and a test in `test/asks/` that fails until it does. To answer one:8788```sh89myr asks --project datekit # what is open90myr ask format-ordinal # read one in full91myr claim format-ordinal # take it; this prints your fork's remote92git remote add myr <remote> # the remote the claim printed93myr check # run its test and the suite, as the platform will94git push myr HEAD:main # offer your answer95```9697The platform runs the ask's test and the rest of the suite on your answer, and lands it on main with your name on it when both pass. An answer changes only the files its ask names. `format-ordinal` is kept for newcomers, with okonkwo as mentor.9899Claiming needs a vouch: a line in `.myr/vouched.td`. Anyone not denounced there may propose an ask with `myr propose`.100101Run the tests with `bun test`. On main, the three asks' tests fail; everything else passes.102103## Environment104105`.env.schema` declares the variables the docs site and the release step read, in varlock's `@env-spec` format. Test values are committed in `.env.test`. The source-map upload token is set by a maintainer for releases and never committed, and no check ever sees it.106107## Maintainers108109- `ines-v` decides for the whole library.110- `okonkwo` decides for time zones (`src/tz.ts`).111112## License113114MIT
added:examples/datekit/tsconfig.json+16 added
1{2 "compilerOptions": {3 "target": "ES2023",4 "lib": ["ES2023"],5 "module": "Preserve",6 "moduleResolution": "bundler",7 "allowImportingTsExtensions": true,8 "noEmit": true,9 "strict": true,10 "noUncheckedIndexedAccess": true,11 "exactOptionalPropertyTypes": true,12 "verbatimModuleSyntax": true,13 "skipLibCheck": true14 },15 "include": ["src", "test"]16}
added:packages/config/test/example-datekit.test.ts+335 added
1/**2 * The datekit example (issue 507), run as the project it pretends to be:3 * `bun test` inside `examples/datekit` is red on main for exactly the three4 * tests its asks name as their checks, each by an assertion rather than a5 * load error (what red first in GLOSSARY.md asks of a check), and green for6 * every other test. Its run block holds on main too: every lane passes, and7 * each ask's check, run alone by the block's test command, is red by an8 * assertion. The example is a Bun project of its own, outside the9 * workspaces (spec D21), so each command runs as a child process under10 * `sh -c`, the way the platform's Checker runs a project's commands.11 */12import { NodeServices } from "@effect/platform-node";13import { describe, expect, it } from "@effect/vitest";14import { Effect, FileSystem, Path, Stream } from "effect";15import { ChildProcess, ChildProcessSpawner } from "effect/process";1617import { Brand } from "../../../scripts/lib/gen.ts";18import { repoRoot } from "./root.ts";1920/** The example, from the repo root. */21const example = "examples/datekit";2223/** What one run of `bun test` printed, both streams, and how it ended. */24interface BunRun {25 readonly exitCode: number;26 readonly output: string;27}2829/** One test file's part of bun's report: the tests it failed, and its text. */30interface FileReport {31 readonly failed: readonly string[];32 readonly file: string;33 readonly text: string;34}3536/** Bun's report, read: each file it reported on, and its closing counts. */37interface BunReport {38 readonly errors: number;39 readonly failed: number;40 readonly files: readonly FileReport[];41 readonly passed: number;42 /** How many tests bun ran, across how many files. */43 readonly ran: { readonly files: number; readonly tests: number };44}4546const ANSI = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*m`, "gu");4748// Bun opens a file's part with its path and a colon, when the file has49// anything to report (a failure or an error); a passing file prints nothing.50const FILE_HEADER = /^(?<file>\S+\.test\.[cm]?[jt]sx?):$/u;5152// A failed test: `(fail) describe > test [0.24ms]`, or `✗ …` when bun53// prints in color.54const FAILED_TEST = /^(?:\(fail\)|✗) (?<name>.+?)(?: \[[\d.]+m?s\])?$/u;5556// Where the files' parts end: the recap of failed tests some runs print57// (`3 tests failed:`), or else the closing counts (` 34 pass`).58const CLOSING = /^(?:\d+ tests? failed:|\d+ pass)$/u;5960// The line bun prints under a failed `expect(…)` (the platform's classifier61// reads the same line as an assertion).62const ASSERTION = /^error: expect\(received\)/mu;6364// What bun prints when a file never reached its tests.65const LOAD_ERRORS = [66 /Cannot find (?:module|package)/u,67 /\bSyntaxError\b/u,68 /Unhandled error between tests/u,69 /\bReferenceError\b/u,70];7172// An ask file names its check file as the `path` its kind takes73// (`kinds.fix.ask({ path: "test/asks/<id>.test.ts", … })`), which the kind74// makes the ask's `RedThenGreen.path`.75const CHECK_PATH = /\bpath:\s*"(?<path>[^"]+)"/u;7677// The run block as project.ts writes it (the rules test holds it to the78// evaluated policy): the command that runs one check file, with `{path}`79// in it, and the lanes every answer must pass, `checks: { unit: "…" }`.80const TEST_COMMAND = /\btest:\s*"(?<command>[^"]*\{path\}[^"]*)"/u;8182const LANES = /\bchecks:\s*\{(?<lanes>[^}]*)\}/u;8384const LANE = /(?<lane>\w+):\s*"(?<command>[^"]+)"/gu;8586/** A closing count bun prints (` 3 fail`), or 0 when it prints none. */87const countOf = (output: string, word: string) =>88 Number(89 new RegExp(`^\\s*(?<count>\\d+) ${word}$`, "mu").exec(output)?.groups90 ?.count ?? "0"91 );9293/** The name a `(fail)` line gives, if the line is one. */94const failedIn = (line: string) => {95 const name = FAILED_TEST.exec(line)?.groups?.name;9697 return name === undefined ? [] : [name];98};99100/** Reads bun's console report into its files and counts. */101const readReport = (output: string): BunReport => {102 const lines = output.split("\n").map((line) => line.trim());103104 const starts = lines.flatMap((line, at) =>105 FILE_HEADER.test(line) ? [at] : []106 );107108 const closing = lines.findIndex((line) => CLOSING.test(line));109 const end = closing === -1 ? lines.length : closing;110111 const files = starts.map((start, index) => {112 const part = lines.slice(113 start + 1,114 Math.min(starts[index + 1] ?? end, end)115 );116117 return {118 failed: part.flatMap(failedIn),119 file: FILE_HEADER.exec(lines[start] ?? "")?.groups?.file ?? "",120 text: part.join("\n"),121 };122 });123124 const ran = /^Ran (?<tests>\d+) tests? across (?<files>\d+) files?\./mu.exec(125 output126 )?.groups;127128 return {129 errors: countOf(output, "errors?"),130 failed: countOf(output, "fail"),131 files,132 passed: countOf(output, "pass"),133 ran: { files: Number(ran?.files), tests: Number(ran?.tests) },134 };135};136137const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>138 bytes.pipe(Stream.decodeText(), Stream.mkString);139140/** Runs `command` inside the example under `sh -c`, as the Checker runs a lane. */141const inExample = (command: string) =>142 Effect.scoped(143 Effect.gen(function* () {144 const path = yield* Path.Path;145 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;146 const root = yield* repoRoot;147148 const child = yield* spawner.spawn(149 ChildProcess.make("sh", ["-c", command], {150 cwd: path.join(root, example),151 })152 );153154 const [stdout, stderr, exitCode] = yield* Effect.all(155 [text(child.stdout), text(child.stderr), child.exitCode],156 { concurrency: "unbounded" }157 );158159 return {160 exitCode,161 output: `${stdout}\n${stderr}`.replaceAll(ANSI, ""),162 } satisfies BunRun;163 })164 );165166/** The example's run block, read from its project file. */167const runBlock = Effect.gen(function* () {168 const fs = yield* FileSystem.FileSystem;169 const path = yield* Path.Path;170171 const source = yield* fs.readFileString(172 path.join(yield* repoRoot, example, Brand.configDir, "project.ts")173 );174175 const lanes = Array.from(176 (LANES.exec(source)?.groups?.lanes ?? "").matchAll(LANE),177 ({ groups }) => ({178 command: groups?.command ?? "",179 lane: groups?.lane ?? "",180 })181 );182183 return { lanes, test: TEST_COMMAND.exec(source)?.groups?.command ?? "" };184});185186/**187 * Each ask file in the example's config folder, and the check file it names;188 * none when the folder is missing.189 */190const askChecks = Effect.gen(function* () {191 const fs = yield* FileSystem.FileSystem;192 const path = yield* Path.Path;193 const asks = path.join(yield* repoRoot, example, Brand.configDir, "asks");194195 if (!(yield* fs.exists(asks))) {196 return [];197 }198199 const files = (yield* fs.readDirectory(asks))200 .filter((file) => file.endsWith(".ask.ts"))201 .toSorted();202203 return yield* Effect.forEach(files, (file) =>204 Effect.map(fs.readFileString(path.join(asks, file)), (source) => ({205 check: CHECK_PATH.exec(source)?.groups?.path ?? "",206 file,207 }))208 );209});210211/** How a file failed: how many tests, whether by an assertion, whether it loaded. */212const howFailed = ({ failed, file, text: part }: FileReport) => ({213 assertion: ASSERTION.test(part),214 file,215 loaded: !LOAD_ERRORS.some((pattern) => pattern.test(part)),216 tests: failed.length,217});218219const byFile = (a: { readonly file: string }, b: { readonly file: string }) =>220 a.file.localeCompare(b.file);221222describe("the datekit example", () => {223 it.live(224 "is red on main for exactly its three asks' checks, each by an assertion, and green elsewhere",225 () =>226 Effect.gen(function* () {227 // The example's own `package.json` test script.228 const run = yield* inExample("bun test");229 const report = readReport(run.output);230 const checks = yield* askChecks;231232 expect(checks.map(({ file }) => file)).toStrictEqual([233 "add-months-clamp.ask.ts",234 "format-ordinal.ask.ts",235 "parse-iso-week.ask.ts",236 ]);237238 // The run fails, and only by the asks' checks: one test in each, by239 // an assertion, with nothing that failed to load.240 expect({241 errors: report.errors,242 exitedNonZero: run.exitCode !== 0,243 failed: report.failed,244 failing: report.files245 .filter(({ failed }) => failed.length > 0)246 .map(howFailed)247 .toSorted(byFile),248 }).toStrictEqual({249 errors: 0,250 exitedNonZero: true,251 failed: 3,252 failing: checks253 .map(({ check }) => ({254 assertion: true,255 file: check,256 loaded: true,257 tests: 1,258 }))259 .toSorted(byFile),260 });261262 // Every other test passes, across the four suites the library keeps263 // green (parse, format, add, diff) and the three checks.264 expect({265 files: report.ran.files,266 passedOrFailed: report.passed + report.failed,267 }).toStrictEqual({ files: 7, passedOrFailed: report.ran.tests });268 expect(report.passed).toBeGreaterThan(0);269 }).pipe(Effect.provide(NodeServices.layer)),270 // One `bun test` over a small library: well under a second alone. The271 // limit catches a hang while turbo runs every package's tests at once.272 30_000273 );274275 it.live(276 "holds its run block on main: every lane green, and each ask's check red alone by an assertion",277 () =>278 Effect.gen(function* () {279 const { lanes, test } = yield* runBlock;280 const checks = yield* askChecks;281282 // A lane red on main refuses every answer (`VerifierBlocked`), so the283 // suite every answer keeps green leaves the open asks' checks out and284 // runs the four the library keeps green.285 const laneRuns = yield* Effect.forEach(lanes, ({ command, lane }) =>286 Effect.map(inExample(command), (run) => {287 const report = readReport(run.output);288289 return {290 errors: report.errors,291 exitCode: run.exitCode,292 failed: report.failed,293 files: report.ran.files,294 lane,295 };296 })297 );298299 expect(laneRuns).toStrictEqual([300 { errors: 0, exitCode: 0, failed: 0, files: 4, lane: "unit" },301 ]);302303 // The platform opens an ask only when its check is red first304 // (`NotRedFirst` otherwise): the test command, with the check's path305 // for `{path}`, fails its one test by an assertion.306 const checkRuns = yield* Effect.forEach(checks, ({ check }) =>307 Effect.map(inExample(test.replaceAll("{path}", check)), (run) => {308 const report = readReport(run.output);309310 return {311 errors: report.errors,312 exitedNonZero: run.exitCode !== 0,313 failing: report.files314 .filter(({ failed }) => failed.length > 0)315 .map(howFailed),316 };317 })318 );319320 expect(checkRuns).toStrictEqual(321 [322 "test/asks/add-months-clamp.test.ts",323 "test/asks/format-ordinal.test.ts",324 "test/asks/parse-iso-week.test.ts",325 ].map((file) => ({326 errors: 0,327 exitedNonZero: true,328 failing: [{ assertion: true, file, loaded: true, tests: 1 }],329 }))330 );331 }).pipe(Effect.provide(NodeServices.layer)),332 // Four `bun test` runs over a small library, one after another.333 30_000334 );335});
added:packages/rules/test/example-datekit.test.ts+226 added
1/**2 * The datekit example's config folder (issue 507), evaluated by the `/bun`3 * adapter as the Lander's bundle of it would be: every file in the folder,4 * keyed by its repo path, with the facts the platform would give a5 * single-package repo (no workspaces, its vouch file, `ines-v` as the6 * initializer). Its `.ts` files import the sdk by the name users write, the7 * published one, which the adapter points at the sdk.8 */9import { NodeServices } from "@effect/platform-node";10import { describe, expect, it } from "@effect/vitest";11import { CheckSpec } from "@repo/protocol/domain/check";12import { Policy } from "@repo/protocol/domain/policy";13import { RepoPath } from "@repo/protocol/ids";14import { Effect, Exit, FileSystem, Path, Schema } from "effect";1516import { EvaluationFacts, RulesEvaluator } from "../src/rules-evaluator.ts";17import type { ConfigBundle } from "../src/rules-evaluator.ts";18import { at, bunEvaluator, now } from "./world.ts";1920/** Where the example lives, from this test's folder. */21const exampleUrl = new URL("../../../examples/datekit/", import.meta.url);2223/**24 * The example's dot-folders that hold a `project.ts`: its config folder, as25 * the repo names it. `rules` never spells that name (it lives in26 * `packages/brand`), so the test finds it.27 */28const configFolders = Effect.gen(function* () {29 const fs = yield* FileSystem.FileSystem;30 const path = yield* Path.Path;31 const root = yield* path.fromFileUrl(exampleUrl);3233 const folders = yield* Effect.filter(34 (yield* fs.readDirectory(root)).filter((name) => name.startsWith(".")),35 (name) =>36 Effect.flatMap(fs.stat(path.join(root, name)), ({ type }) =>37 type === "Directory"38 ? fs.exists(path.join(root, name, "project.ts"))39 : Effect.succeed(false)40 )41 );4243 return { folders, root };44});4546/** Every file in the example's config folder, as the bundle the Lander makes of it. */47const exampleBundle = Effect.gen(function* () {48 const fs = yield* FileSystem.FileSystem;49 const path = yield* Path.Path;50 const { folders, root } = yield* configFolders;5152 const folder = yield* Effect.fromNullishOr(53 folders.length === 1 ? folders[0] : undefined54 );5556 const dir = path.join(root, folder);57 const modules: Record<string, string> = {};5859 for (const file of (yield* fs.readDirectory(dir, {60 recursive: true,61 })).toSorted()) {62 const full = path.join(dir, file);6364 if ((yield* fs.stat(full)).type === "File") {65 modules[`${folder}/${file}`] = yield* fs.readFileString(full);66 }67 }6869 return {70 bundle: {71 entry: `${folder}/project.ts`,72 modules,73 sdkVersion: "0.0.0",74 } satisfies ConfigBundle,75 folder,76 };77});7879/** The policy the example's config folder evaluates to, encoded. */80const evaluated = Effect.gen(function* () {81 const { bundle, folder } = yield* exampleBundle;82 const evaluator = yield* RulesEvaluator;8384 const facts = yield* Schema.decodeEffect(EvaluationFacts)({85 ci: [],86 initializer: "ines-v",87 now,88 project: "datekit",89 seed: 7,90 vouchFile: bundle.modules[`${folder}/vouched.td`] ?? "",91 workspaces: [],92 });9394 const policy = yield* evaluator.evaluate({ at, facts, modules: bundle });9596 return { folder, policy: yield* Schema.encodeEffect(Policy)(policy) };97});9899/** What one of the example's asks is, beside its brief. */100const askOf = (101 folder: string,102 id: string,103 territory: readonly [string, ...string[]]104) => ({105 askedBy: "ines-v",106 blockedBy: [],107 check: CheckSpec.cases.RedThenGreen.make({108 path: RepoPath.make(`test/asks/${id}.test.ts`),109 }),110 file: `${folder}/asks/${id}.ask.ts`,111 id,112 kind: "fix",113 openedAt: now,114 openedIn: at,115 project: "datekit",116 state: "open",117 territory: { module: ".", paths: territory },118});119120describe("the datekit example's config folder", () => {121 it.live("is the example's one dot-folder with a project file", () =>122 Effect.gen(function* () {123 const { folders } = yield* configFolders;124125 expect(folders).toHaveLength(1);126 }).pipe(Effect.provide(NodeServices.layer))127 );128129 it.live(130 "evaluates under /bun to a policy with its run block, its deciders and its kinds",131 () =>132 Effect.gen(function* () {133 const { folder, policy } = yield* evaluated;134135 expect(Exit.isSuccess(Schema.decodeExit(Policy)(policy))).toBeTruthy();136 expect({137 agents: policy.agents,138 deciders: policy.deciders,139 kinds: policy.kinds.map(({ name }) => name),140 run: policy.run,141 source: policy.source,142 vouch: policy.vouch,143 }).toStrictEqual({144 agents: "trailer",145 deciders: [146 { handles: ["ines-v"], paths: "**" },147 { handles: ["okonkwo"], paths: "src/tz.ts" },148 ],149 kinds: ["fix", "changeJudge"],150 run: {151 checks: { unit: "bun test --path-ignore-patterns='test/asks/**'" },152 test: "bun test {path}",153 },154 source: "config",155 vouch: { file: `${folder}/vouched.td`, mode: "forCode" },156 });157 }).pipe(Effect.provide(bunEvaluator()))158 );159160 it.live(161 "holds its three asks, each checked by its own red-then-green test",162 () =>163 Effect.gen(function* () {164 const { folder, policy } = yield* evaluated;165166 expect(167 policy.asks.map(({ brief: _brief, ...ask }) => ask)168 ).toStrictEqual([169 askOf(folder, "add-months-clamp", ["src/add.ts", "test/add.test.ts"]),170 {171 ...askOf(folder, "format-ordinal", [172 "src/format.ts",173 "test/format.test.ts",174 ]),175 mentor: "okonkwo",176 reserve: "newcomers",177 },178 askOf(folder, "parse-iso-week", [179 "src/parse.ts",180 "test/parse.test.ts",181 ]),182 ]);183 }).pipe(Effect.provide(bunEvaluator()))184 );185186 it.live(187 "states each ask's want without a path or a line, what happens today, and what is out of scope",188 () =>189 Effect.gen(function* () {190 const { policy } = yield* evaluated;191192 expect(193 policy.asks.map(({ brief, id }) => ({194 current: brief.current !== undefined,195 id,196 outOfScope: (brief.outOfScope ?? []).length > 0,197 // A want is behavioural: no file paths, no line numbers.198 wantNamesCode: /\.ts\b|:\d+|\bline \d/u.test(brief.want),199 }))200 ).toStrictEqual(201 ["add-months-clamp", "format-ordinal", "parse-iso-week"].map(202 (id) => ({203 current: true,204 id,205 outOfScope: true,206 wantNamesCode: false,207 })208 )209 );210 }).pipe(Effect.provide(bunEvaluator()))211 );212213 it.live("reads its vouch file: the two maintainers and one contributor", () =>214 Effect.gen(function* () {215 const { policy } = yield* evaluated;216217 expect(218 policy.vouches.map(({ denounced, handle }) => ({ denounced, handle }))219 ).toStrictEqual([220 { denounced: false, handle: "bram" },221 { denounced: false, handle: "ines-v" },222 { denounced: false, handle: "okonkwo" },223 ]);224 }).pipe(Effect.provide(bunEvaluator()))225 );226});
modified:turbo.json+10 added
34 unmodified lines
35 "$TURBO_ROOT$/docs/reference/commands.json"36 ],37 "outputs": []38 },39 "@repo/rules#test": {40 "dependsOn": ["types", "^types"],41 "env": ["UPDATE_GOLDEN"],42 "inputs": [43 "$TURBO_DEFAULT$",44 "$TURBO_ROOT$/examples/*/.*/**",45 "!$TURBO_ROOT$/examples/*/.env*"46 ],47 "outputs": []48 },49 "@repo/config#test": {50 "cache": false,51 "dependsOn": ["types", "^types"],52 "outputs": []
3 unmodified lines