opencode/packages/cli-rs/script/gen/time.ts
Simon Klee 6b1df0cceb
feat(cli-rs): add the native CLI and TUI (#63477)
Add packages/cli-rs, an OpenCode client written in Rust on OpenTUI's Rust crates. It is a client only.
2026-11-22 00:07:01 +01:00

244 lines
9.5 KiB
TypeScript

// Writes crates/util/fixtures/time.tsv: what the TypeScript client's `Date` and `Intl` calls give under Bun, in five
// time zones, for the known-answer tests of opencode-util's `time` module. Each zone runs in a child process with `TZ`
// set, as the client reads it. Rows are `kind input output...`, tab-separated. The `parse` rows come first, then a
// `zone` line starts each zone's other rows:
//
// - `parse text`: `Date.parse(text)` (`refusalReset`, the date-time form check) in each zone, in the order of
// `zones`, `NaN` if rejected, and the date form check `validDate` (1 or 0), which reads no zone.
// - `at ms`: `toLocaleString()` (session list and export), `toDateString()` (session list, free limit),
// `toLocaleDateString()` and `toLocaleTimeString(undefined, { timeStyle: "short" })` (`Locale.datetime`,
// `Locale.time`), `formatReset`'s time and day (usage-limits.ts), `getHours()`, `getMinutes()`, `getDay()`, and the
// local day number activity-calendar.ts takes; `invalid` for an Invalid Date.
// - `iso ms`: `toISOString()`, or `invalid` where it throws.
// - `days n`: the UTC year, month, day and weekday of `n * 86_400_000`.
// - `wall y m d h:mm=ms...`: `new Date(y, m - 1, d, h, mm).getTime()` for each time of one date, as stats takes
// local midnights.
const zones = ["UTC", "America/New_York", "Australia/Lord_Howe", "Asia/Kathmandu", "America/Havana"]
if (process.argv[2] === "--zone") {
process.stdout.write(rows(process.argv[3]).join("\n") + "\n")
process.exit(0)
}
const file = new URL("../../crates/util/fixtures/time.tsv", import.meta.url).pathname
const sections = zones.map((zone) => {
const proc = Bun.spawnSync(["bun", "run", import.meta.path, "--zone", zone], {
env: { ...process.env, TZ: zone },
stderr: "inherit",
})
if (proc.exitCode !== 0) process.exit(proc.exitCode ?? 1)
return proc.stdout.toString().trimEnd().split("\n")
})
// Each zone writes `parse text ms valid`; join them into one row per text.
const parses = sections.map((rows) => rows.filter((row) => row.startsWith("parse\t")).map((row) => row.split("\t")))
const lines = [
"# Generated by script/gen/time.ts under Bun " + Bun.version + ". Do not edit.",
...parses[0].map((row, at) => {
const same = parses.every((rows) => rows[at][1] === row[1] && rows[at][3] === row[3])
if (!same) throw new Error(`parse rows differ between zones at ${row[1]}`)
return ["parse", row[1], ...parses.map((rows) => rows[at][2]), row[3]].join("\t")
}),
...zones.flatMap((zone, at) => [`zone\t${zone}`, ...sections[at].filter((row) => !row.startsWith("parse\t"))]),
]
await Bun.write(file, lines.join("\n") + "\n")
console.log(`time: ${lines.join("\n").split("\n").length - 1} lines`)
function rows(zone: string) {
const out: string[] = []
const row = (...fields: (string | number)[]) => out.push(fields.join("\t"))
const day = 86_400_000
// Kathmandu's 1986 midnight gap, both sides of the US rule change in 2007,
// and current gaps and folds (including Lord Howe's half hour).
const transitions = [
...changes(Date.UTC(1985, 6), Date.UTC(1986, 6)),
...changes(Date.UTC(2006, 0), Date.UTC(2008, 0)),
...changes(Date.UTC(2025, 0), Date.UTC(2027, 0)),
]
const instants = new Set<number>([
...range(Date.UTC(1900, 0, 1), Date.UTC(2100, 0, 1), 40 * (151 * day + 3_600_123)),
...range(Date.UTC(2025, 0, 1), Date.UTC(2026, 0, 1), 12 * (day + 7 * 3_600_000 + 61_007)),
...transitions.flatMap((at) => [at - 1, at, at + 1_800_000]),
...[0, -1, 1, 999, -999, -1000, -1001, 1_762_268_645_123],
...[253_402_300_799_999, 253_402_300_800_000, -62_167_219_200_000, -62_167_219_200_001, -62_198_755_200_000],
...[8.64e15, -8.64e15, 8.64e15 + 1, -8.64e15 - 1],
])
for (const ms of [...instants].sort((a, b) => a - b)) {
const date = new Date(ms)
if (Number.isNaN(date.getTime())) {
row("at", ms, "invalid")
continue
}
row(
"at",
ms,
date.toLocaleString(),
date.toDateString(),
date.toLocaleDateString(),
date.toLocaleTimeString(undefined, { timeStyle: "short" }),
date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }).replace(/\u202f/g, " "),
date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
date.getHours(),
date.getMinutes(),
date.getDay(),
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / day,
)
}
if (zone === "UTC") {
for (const ms of instants) {
const date = new Date(ms)
row("iso", ms, Number.isNaN(date.getTime()) ? "invalid" : date.toISOString())
}
for (const n of [...range(-100_000_000, 100_000_001, 50 * 199_999), -1, 0, 1, 59, 60, 11_016, -719_468, -719_469]) {
const date = new Date(n * day)
row("days", n, date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCDay())
}
}
// Ordinary midnights and the dates on either side of each transition. On current transition days and in
// Kathmandu's 15-minute gap, check the whole wall clock, including its missing or ambiguous readings.
const walls = new Map<string, Set<number>>()
const wall = (year: number, month: number, dom: number, minutes: number) => {
const key = `${year}\t${month}\t${dom}`
walls.set(key, (walls.get(key) ?? new Set()).add(minutes))
}
for (const year of [1900, 1970, 2000, 2038, 2100]) wall(year, 1, 1, 0)
for (let month = 1; month <= 12; month++) wall(2025, month, 1, 0)
for (const at of transitions) {
for (const shift of [-day, 0, day]) {
const date = new Date(at + shift)
const [year, month, dom] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
wall(year, month, dom, 0)
if (shift !== 0 || (year !== 2025 && year !== 2026 && zone !== "Asia/Kathmandu")) continue
for (let minutes = 0; minutes < 1440; minutes += 5) wall(year, month, dom, minutes)
}
}
for (const [date, minutes] of walls) {
const [year, month, dom] = date.split("\t").map(Number)
const times = [...minutes]
.sort((a, b) => a - b)
.map((at) => {
const [hour, minute] = [Math.floor(at / 60), at % 60]
return `${hour}:${String(minute).padStart(2, "0")}=${new Date(year, month - 1, dom, hour, minute).getTime()}`
})
row("wall", date, ...times)
}
for (const text of texts()) {
const at = Date.parse(text)
row("parse", JSON.stringify(text), Number.isNaN(at) ? "NaN" : at, validDate(text) ? 1 : 0)
}
return out
}
// The first instant of each change of offset between `from` and `to`.
function changes(from: number, to: number) {
const offset = (ms: number) => new Date(ms).getTimezoneOffset()
const found: number[] = []
for (let at = from; at < to; at += 3_600_000) {
if (offset(at) === offset(at + 3_600_000)) continue
let [low, high] = [at, at + 3_600_000]
while (high - low > 1) {
const middle = Math.floor((low + high) / 2)
if (offset(middle) === offset(low)) low = middle
else high = middle
}
found.push(high)
}
return found
}
function range(from: number, to: number, step: number) {
return Array.from({ length: Math.ceil((to - from) / step) }, (_, index) => from + index * step)
}
function validDate(value: string) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
const date = new Date(`${value}T00:00:00.000Z`)
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value
}
function texts() {
const fixed = [
"2026-11-04T15:30:00Z",
"2026-11-04t15:30:00z",
"2026-11-04 15:30:00+05:45",
"2026-11-04T15:30:00\u221203:30",
"2026-11-04T15:30:00-23:59",
"2026-11-04T15:30:00+24:00",
"2026-11-04T15:30:00+05:60",
"2026-11-04T15:30:00+0545",
"2026-11-04T15:30:00+05",
"2026-11-04T15:30:00+05:45 ",
"2026-11-04T15:30:00",
"2026-11-04T15:30:00.Z",
"2026-11-04T15:30:00.5Z",
"2026-11-04T15:30:00.123456789123Z",
"2026-11-04T15:30:00.999999999+01:00",
"2016-12-31T23:59:60Z",
"2016-12-31T23:59:60.5Z",
"2016-12-31T23:59:61Z",
"2026-02-29T00:00:00Z",
"2024-02-29T00:00:00Z",
"0000-01-01T00:00:00Z",
"9999-12-31T23:59:59.999Z",
"2026-11-04T24:00:00Z",
"2026-11-04T23:60:00Z",
"2026-11-04X15:30:00Z",
"2026/11/04T15:30:00Z",
"+2026-11-04T15:30:00Z",
" 2026-11-04T15:30:00Z",
"2026-1-04T15:30:00Z",
"2026-11-04T15:30Z",
"2026-11-04",
"2026-11-04T15:30",
"2026-11-04T15:30:00.123",
"2026-11-04T15:30:00.1234567890",
"2026-11-04T15:30:00.",
"2026-11-04 15:30:00",
"2026-11-04 15:30:00",
"2026-11-04\t15:30:00",
"2026-11-04\u300015:30:00",
"2026-11-04T1:2",
"2026-11-04T 1: 2",
"2026-11-04T15:30:60",
"2026-11-04T15:30:60.25",
"2026-11-04t15:30",
"2026-2-3",
" 2026-02-03",
"2026-02-03 ",
"2026- 2- 3",
"+2026-02-03",
"-0001-02-03",
"12026-01-01",
"+12026-01-01",
"-262144-01-01",
"+99999999999999999999-01-01",
"2023-02-29",
"2024-02-29",
"0000-01-01",
"",
"2026",
"2026-11-04T15:30:00Zjunk",
"2026-11-04T15:30:00.12Z\u00e9",
"2026-11-04T15:30:0\u00e9Z",
"2025-03-09T02:30:00",
"2025-11-02T01:30:00",
]
const generated = range(Date.UTC(1900, 0, 1), Date.UTC(2100, 0, 1), 2_011 * 86_400_000 + 3_723_456)
.concat([0, -1, 1_735_689_600_000])
.flatMap((ms) => {
const iso = new Date(ms).toISOString()
return [
iso,
iso.replace("T", " ").replace("Z", "+05:45"),
iso.replace(".", ".5").replace("Z", "-03:30"),
iso.replace(/Z$/, ""),
iso.slice(0, 16),
iso.slice(0, 19).replace("T", " "),
iso.slice(0, 10),
]
})
return [...fixed, ...generated]
}