From e7e105472d0a8e8fe974afe022249d90396e3464 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 13 Nov 2026 17:21:51 +0200 Subject: [PATCH 01/12] docs(dox): track the two temporal-polyfill fix PRs on /upstream (DOX-G9, #522) Closes #522 - `upstream-filings.json`: add the fix PRs fullcalendar/temporal-polyfill#131 (Persian, fixing fullcalendar/temporal-polyfill#127) and fullcalendar/temporal-polyfill#132 (Chinese and Dangi, fixing fullcalendar/temporal-polyfill#128). Each keeps its issue's `gmtNote`, since GMT runs on `@js-temporal/polyfill`. - `context/dox/tracker.md`: add the DOX-G9 row. --- apps/dox/src/data/upstream-filings.json | 48 ++++++++++++++++++++++++- context/dox/tracker.md | 5 +-- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/apps/dox/src/data/upstream-filings.json b/apps/dox/src/data/upstream-filings.json index 5b8b3e7d8..e4f2ceeed 100644 --- a/apps/dox/src/data/upstream-filings.json +++ b/apps/dox/src/data/upstream-filings.json @@ -1,5 +1,5 @@ { - "checked": "2026-11-08T12:19:17.436335629Z", + "checked": "2026-11-13T15:18:33.593083807Z", "filings": [ { "repo": "js-temporal/temporal-polyfill", @@ -546,6 +546,52 @@ "updatedAt": "2026-11-06", "closedAt": null, "mergedAt": null + }, + { + "repo": "fullcalendar/temporal-polyfill", + "number": 131, + "kind": "pr", + "work": "fix", + "title": "Apply the ICU4X leap-year corrections to the Persian calendar", + "url": "https://github.com/fullcalendar/temporal-polyfill/pull/131", + "summary": "The Persian calendar skips the corrections ICU4X makes to 78 leap years from 1502 to 2987 AP, so from 2123 the last day of each affected year reads as the first day of the next. This applies the same corrections as ICU4X.", + "pairsWith": [], + "closes": ["fullcalendar/temporal-polyfill#127"], + "dependsOn": [], + "gmtGuard": null, + "gmtNote": "GMT runs on `@js-temporal/polyfill`, which gets these Persian years right, so this can't affect GMT. GMT's weekly swap check compares each calendar's years with native Temporal on every new `temporal-polyfill` release.", + "state": "open", + "draft": false, + "reviewDecision": null, + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-13", + "updatedAt": "2026-11-13", + "closedAt": null, + "mergedAt": null + }, + { + "repo": "fullcalendar/temporal-polyfill", + "number": 132, + "kind": "pr", + "work": "fix", + "title": "Compute the Chinese and Dangi calendars like ICU4X instead of reading Intl", + "url": "https://github.com/fullcalendar/temporal-polyfill/pull/132", + "summary": "Chinese and Dangi dates come from the host's `Intl`, which formats them with ICU4C and disagrees with native Temporal's ICU4X on some years. This computes both calendars from ICU4X's year tables and rules instead.", + "pairsWith": [], + "closes": ["fullcalendar/temporal-polyfill#128"], + "dependsOn": [], + "gmtGuard": null, + "gmtNote": "GMT runs on `@js-temporal/polyfill`, which throws on Chinese and Dangi dates under ICU 78 instead (js-temporal/temporal-polyfill#360). GMT's weekly swap check compares each calendar's years with native Temporal on every new `temporal-polyfill` release.", + "state": "open", + "draft": false, + "reviewDecision": null, + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-13", + "updatedAt": "2026-11-13", + "closedAt": null, + "mergedAt": null } ], "listings": [ diff --git a/context/dox/tracker.md b/context/dox/tracker.md index 1c56c6ecf..e8a7e02c9 100644 --- a/context/dox/tracker.md +++ b/context/dox/tracker.md @@ -1,9 +1,9 @@ ## GitHub Issues -34 sub-stories on 25 GitHub issues: #130–#142, #171 (`DOX-C0`), #240 (`DOX-C4`), #288 +35 sub-stories on 26 GitHub issues: #130–#142, #171 (`DOX-C0`), #240 (`DOX-C4`), #288 (`DOX-A6`), #289 (`DOX-E1c`), #293 (`DOX-E1d`), #430 (`DOX-G1`), #447 (`DOX-G2`), #467 (`DOX-G3`), #458 (`DOX-G4`), #448 (`DOX-G6`), #477 (`DOX-G7`, -with #475) and #487 (`DOX-G8`). What each done story shipped is in [built.md](built.md). +with #475), #487 (`DOX-G8`) and #522 (`DOX-G9`). What each done story shipped is in [built.md](built.md). A row here is a `DOX-*` story with its own GitHub issue. Add one, then run `pnpm deps:sync`, which generates `Blocked by`, only for Dox work that belongs to no realm story. The Dox pages and @@ -45,6 +45,7 @@ or `architect`, with no tool shortlist; `/pipeline` says who builds it. | 23 | DOX-G6 | — | #448 | Done⁶ | | 24 | DOX-G7 | — | #477 | Done | | 25 | DOX-G8 | — | #487 | Done | +| 26 | DOX-G9 | — | #522 | Done | ¹ Owed verification, not work: a keyboard-only pass, `prefers-reduced-*` emulation, and a real Firefox/Safari check. From 0e4ad43522f05b37756abfd5827c542624287a82 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 13 Nov 2026 19:22:14 +0200 Subject: [PATCH 02/12] docs(upstream): record every upstream filing, and probe for tc39 #3327 problem 1 (DOX-G9, #522) - Bugs doc and swap research: list fullcalendar/temporal-polyfill#127, #128, #131 and #132, the status as of 13 November, and the eleven posts corrected that day. nodejs/node#67457 gets its own section (AD). - /upstream: add nodejs/node#67457 under Native engines. Why this polyfill now lists the Persian and Chinese/Dangi bugs in temporal-polyfill 1.0.8 with our reports and fixes, and links every fullcalendar number. - upstream-filings.json: synced from GitHub. The fullcalendar/temporal-polyfill#131 summary had the misread day the wrong way round, and the tc39/proposal-temporal#3335 summary now says the fake-timer case is js-temporal's. The ICU 78 note on #128 and #132 names 0.5.1, so it stays true after the next release. - D6: two cachedDay probes (hebrew, islamic-civil) catch tc39/proposal-temporal#3327 problem 1, which js-temporal `main` has since 853fc8b. 0.5.1 passes them, so no result changes. The trigger, README and compat snapshot say so (13 probes, 11 failing). Patch changeset. - The D11 trigger and nudge-window comments name 17e12be0af42, the proposal-temporal commit on `main`. Native-suite tags for nodejs/node#67457. - Bundle budgets for chargeableDays, operatingTimeBetween and dutyViolations rise by 100 bytes for the probe rows. - context/dox/tracker.md: wrap the issue list at 100 characters. --- .changeset/d6-cached-day-probe.md | 5 + apps/dox/src/content/docs/upstream.mdx | 22 ++- apps/dox/src/data/gmt-stats.json | 4 +- apps/dox/src/data/temporal-compat.json | 6 +- apps/dox/src/data/upstream-filings.json | 26 ++-- .../domination/js-temporal-polyfill-bugs.md | 130 +++++++++++++----- .../research/temporal-polyfill-swap.md | 4 +- context/dox/tracker.md | 4 +- .../gmt/src/internal/temporalCompat/README.md | 4 +- .../temporalCompat/capabilities.test.ts | 3 + .../internal/temporalCompat/probeRepros.ts | 26 +++- .../internal/zonedDifference/nudgeWindow.ts | 2 +- .../gmt/src/test/nudgeWindowRetry.test.ts | 2 +- scripts/bundle-size.budgets.json | 6 +- scripts/lib/native-suite-tags.mjs | 14 +- scripts/lib/workarounds.mjs | 5 +- 16 files changed, 183 insertions(+), 80 deletions(-) create mode 100644 .changeset/d6-cached-day-probe.md diff --git a/.changeset/d6-cached-day-probe.md b/.changeset/d6-cached-day-probe.md new file mode 100644 index 000000000..8483c177e --- /dev/null +++ b/.changeset/d6-cached-day-probe.md @@ -0,0 +1,5 @@ +--- +"@northguild/gmt": patch +--- + +GMT checks the installed `@js-temporal/polyfill` for one more bug in counting months or years between two dates in a non-ISO calendar. The polyfill's unreleased `main` loses a day when a Hebrew or Islamic count starts on the 30th and crosses a 29-day month (tc39/proposal-temporal#3327). GMT already uses its own count while the polyfill has the older bugs in it. With this check, a later release that fixes those but has this one still gets GMT's count, so results stay correct. On 0.5.1, the release GMT depends on today, no result changes. diff --git a/apps/dox/src/content/docs/upstream.mdx b/apps/dox/src/content/docs/upstream.mdx index 66dab94a9..fd05b6075 100644 --- a/apps/dox/src/content/docs/upstream.mdx +++ b/apps/dox/src/content/docs/upstream.mdx @@ -76,16 +76,23 @@ with no test failing that passes on `@js-temporal/polyfill`. Release 1.0.7 had t - **Looking back from far ahead.** Asked for the last clock change before a date more than about three years from today, 1.0.7 returned an older one. Asked on 4 November 2026 about June 2030 in `America/New_York`, it returned the change in November 2029, not the one in March 2030. Twelve of - GMT's tests failed on this. We reported it as #125. + GMT's tests failed on this. We reported it as [#125](https://github.com/fullcalendar/temporal-polyfill/issues/125). - **Before 1847.** 1.0.7 did not find clock changes before 1847, such as `Asia/Manila` on - 31 December 1844. We reported it as #126. GMT works around the same bug in + 31 December 1844. We reported it as [#126](https://github.com/fullcalendar/temporal-polyfill/issues/126). GMT works around the same bug in `@js-temporal/polyfill`. -One bug is left, and the maintainers closed its report as a known limitation: +Three bugs are left in 1.0.8. We found the first two by comparing every calendar's years with +Node's built-in Temporal, and sent a fix for each: +- **Persian leap years.** From 1502 AP (2123), 78 years are leap years where the built-in Temporal + makes the next year the leap year, so each next year starts a day late. We reported it as + [#127](https://github.com/fullcalendar/temporal-polyfill/issues/127) and sent the fix as [#131](https://github.com/fullcalendar/temporal-polyfill/pull/131). +- **Chinese and Dangi.** It reads these calendars from `Intl.DateTimeFormat`, which disagrees with + the built-in Temporal in some years. It puts Chinese New Year 2027 on 7 February, not 6 February. + We reported it as [#128](https://github.com/fullcalendar/temporal-polyfill/issues/128) and sent the fix as [#132](https://github.com/fullcalendar/temporal-polyfill/pull/132). - **Zone names that are links.** It treats a link name such as `Asia/Calcutta` as a different - zone from `Asia/Kolkata`. FullCalendar's report of this, #118 (not ours), was closed as a known - limitation. GMT's own probe sees it in WebKit as `Etc/UTC` not equal to `UTC`. + zone from `Asia/Kolkata`. FullCalendar's report of this, [#118](https://github.com/fullcalendar/temporal-polyfill/issues/118) (not ours), was + closed as a known limitation. GMT's own probe sees it in WebKit as `Etc/UTC` not equal to `UTC`. So for now GMT stays on `@js-temporal/polyfill`. Every week, GMT runs its whole test suite on the newest `temporal-polyfill` release in Node and three browsers. It checks every zone's offsets against @@ -140,6 +147,11 @@ The built-in engines have a few bugs of their own. We report each one we find. T accept the calendar `islamic`, which the standard says to reject. - Node 26 throws when it rounds to the day on a date that starts twice, such as 6 November 2010 in `America/Goose_Bay`. Chromium 153 already has the fix, so a later Node will have it too. +- [`nodejs/node#67457`](https://github.com/nodejs/node/issues/67457): Node 26 adds an extra month + or week when it rounds up a length that is a whole number of years, months or weeks. From + 1 January 2000 to 1 January 2001, rounded up to months, it gives one year and one month. The fix + is already in `temporal_rs`, the Temporal code that Node and Chromium share, and Chromium 153 + has it. The report asks Node 26 to take it. - [`ICU-20548`](https://unicode-org.atlassian.net/browse/ICU-20548): Node, Chromium and Safari shorten a long zone name in a time range, and drop an offset name such as `GMT-5`. - [Bugzilla 1998020](https://bugzilla.mozilla.org/show_bug.cgi?id=1998020): Firefox accepts a diff --git a/apps/dox/src/data/gmt-stats.json b/apps/dox/src/data/gmt-stats.json index db97a4e71..809defbdf 100644 --- a/apps/dox/src/data/gmt-stats.json +++ b/apps/dox/src/data/gmt-stats.json @@ -1,8 +1,8 @@ { "suite": "packages/gmt", - "tests": 75852, + "tests": 75854, "files": 1001, - "executions": 2275560, + "executions": 2275620, "nodes": ["22", "24", "26"], "timezones": 10, "timezoneList": [ diff --git a/apps/dox/src/data/temporal-compat.json b/apps/dox/src/data/temporal-compat.json index 1ef3a4e3c..913da2fd3 100644 --- a/apps/dox/src/data/temporal-compat.json +++ b/apps/dox/src/data/temporal-compat.json @@ -35,8 +35,8 @@ { "defects": ["D6"], "title": "D6 — non-ISO until re-constrains the day while counting months", - "trigger": "a js-temporal release contains 10aeb98 (already on main)", - "probes": 11, + "trigger": "a js-temporal release contains 10aeb98 (already on main) and no longer writes the un-constrained day into its calendar cache (tc39/proposal-temporal#3327 problem 1, on main since 853fc8b)", + "probes": 13, "failing": 11, "state": "still-needed" }, @@ -72,7 +72,7 @@ { "defects": ["D11"], "title": "D11 — the calendar nudge window is never retried, so total, round and until with a calendar smallestUnit answer over the wrong bounds (relativeTo on the 29th-31st)", - "trigger": "a js-temporal release contains js-temporal/temporal-polyfill#361's 50d66d2, which ports proposal-temporal #3172 (5dd0b0d97ee1, the fix for tc39 #3168) and retries the nudge window; merged to main in PR #361 as 5af905f, so no new filing is needed", + "trigger": "a js-temporal release contains js-temporal/temporal-polyfill#361's 50d66d2, which ports proposal-temporal #3172 (17e12be0af42, the fix for tc39 #3168) and retries the nudge window; merged to main in PR #361 as 5af905f, so no new filing is needed", "probes": 6, "failing": 6, "state": "still-needed" diff --git a/apps/dox/src/data/upstream-filings.json b/apps/dox/src/data/upstream-filings.json index e4f2ceeed..da33ed084 100644 --- a/apps/dox/src/data/upstream-filings.json +++ b/apps/dox/src/data/upstream-filings.json @@ -1,5 +1,5 @@ { - "checked": "2026-11-13T15:18:33.593083807Z", + "checked": "2026-11-13T16:44:38.201248729Z", "filings": [ { "repo": "js-temporal/temporal-polyfill", @@ -22,7 +22,7 @@ "comments": 1, "maintainerComments": 0, "createdAt": "2026-04-22", - "updatedAt": "2026-09-21", + "updatedAt": "2026-11-13", "closedAt": "2026-09-21", "mergedAt": "2026-09-21" }, @@ -215,7 +215,7 @@ "comments": 1, "maintainerComments": 0, "createdAt": "2026-09-18", - "updatedAt": "2026-09-18", + "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null }, @@ -238,7 +238,7 @@ "comments": 1, "maintainerComments": 0, "createdAt": "2026-09-18", - "updatedAt": "2026-09-18", + "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null }, @@ -261,7 +261,7 @@ "comments": 0, "maintainerComments": 0, "createdAt": "2026-09-18", - "updatedAt": "2026-09-18", + "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null }, @@ -308,7 +308,7 @@ "comments": 1, "maintainerComments": 0, "createdAt": "2026-10-21", - "updatedAt": "2026-10-24", + "updatedAt": "2026-11-13", "closedAt": "2026-10-24", "mergedAt": null }, @@ -342,7 +342,7 @@ "work": "report", "title": "Polyfill: Temporal.Now reads a millisecond before Date.now() after a pre-1970 clock reading", "url": "https://github.com/tc39/proposal-temporal/issues/3335", - "summary": "After the clock reads a date before 1970, the next Temporal.Now reading can land a millisecond before Date.now(), so a 2027 clock can read as the last millisecond of 2026. The polyfill carries the previous reading's milliseconds modulo a million as a sub-millisecond part, and the remainder keeps its minus sign. Fake timers in tests hit this whenever they set a pre-1970 date. The issue proposes a floor modulo.", + "summary": "After the clock reads a date before 1970, the next Temporal.Now reading can land a millisecond before Date.now(), so a 2027 clock can read as the last millisecond of 2026. The polyfill carries the previous reading's milliseconds modulo a million as a sub-millisecond part, and the remainder keeps its minus sign. In js-temporal's polyfill, fake timers in tests hit this whenever they set a pre-1970 date. The issue proposes a floor modulo.", "pairsWith": [], "closes": [], "dependsOn": [], @@ -354,7 +354,7 @@ "comments": 0, "maintainerComments": 0, "createdAt": "2026-10-31", - "updatedAt": "2026-10-31", + "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null }, @@ -520,7 +520,7 @@ "comments": 2, "maintainerComments": 0, "createdAt": "2026-11-06", - "updatedAt": "2026-11-06", + "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null }, @@ -536,14 +536,14 @@ "closes": [], "dependsOn": [], "gmtGuard": null, - "gmtNote": "GMT runs on `@js-temporal/polyfill`, which throws on Chinese and Dangi dates under ICU 78 instead (js-temporal/temporal-polyfill#360). GMT's weekly swap check compares each calendar's years with native Temporal on every new `temporal-polyfill` release.", + "gmtNote": "GMT runs on `@js-temporal/polyfill`, whose 0.5.1 release throws on Chinese and Dangi dates under ICU 78 instead (js-temporal/temporal-polyfill#360, fixed on its `main` and not yet released). GMT's weekly swap check compares each calendar's years with native Temporal on every new `temporal-polyfill` release.", "state": "open", "draft": false, "reviewDecision": null, "comments": 0, "maintainerComments": 0, "createdAt": "2026-11-06", - "updatedAt": "2026-11-06", + "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null }, @@ -554,7 +554,7 @@ "work": "fix", "title": "Apply the ICU4X leap-year corrections to the Persian calendar", "url": "https://github.com/fullcalendar/temporal-polyfill/pull/131", - "summary": "The Persian calendar skips the corrections ICU4X makes to 78 leap years from 1502 to 2987 AP, so from 2123 the last day of each affected year reads as the first day of the next. This applies the same corrections as ICU4X.", + "summary": "The Persian calendar skips the corrections ICU4X makes to 78 leap years from 1502 to 2987 AP, so the first day of the year after each one reads as an extra 30th day of month 12, and every other day of that year one day early. This applies the same corrections as ICU4X.", "pairsWith": [], "closes": ["fullcalendar/temporal-polyfill#127"], "dependsOn": [], @@ -582,7 +582,7 @@ "closes": ["fullcalendar/temporal-polyfill#128"], "dependsOn": [], "gmtGuard": null, - "gmtNote": "GMT runs on `@js-temporal/polyfill`, which throws on Chinese and Dangi dates under ICU 78 instead (js-temporal/temporal-polyfill#360). GMT's weekly swap check compares each calendar's years with native Temporal on every new `temporal-polyfill` release.", + "gmtNote": "GMT runs on `@js-temporal/polyfill`, whose 0.5.1 release throws on Chinese and Dangi dates under ICU 78 instead (js-temporal/temporal-polyfill#360, fixed on its `main` and not yet released). GMT's weekly swap check compares each calendar's years with native Temporal on every new `temporal-polyfill` release.", "state": "open", "draft": false, "reviewDecision": null, diff --git a/context/domination/js-temporal-polyfill-bugs.md b/context/domination/js-temporal-polyfill-bugs.md index fa0ad30b7..d62304b44 100644 --- a/context/domination/js-temporal-polyfill-bugs.md +++ b/context/domination/js-temporal-polyfill-bugs.md @@ -3,14 +3,14 @@ Record of the defects GMT needs fixed in `js-temporal/temporal-polyfill` (and, where noted, `tc39/proposal-temporal`), the evidence for each, and what has been filed. The owner files every item, or tells an agent in plain words to post a named one: tc39 #3331 (J) and #3332 (K) were posted that way. It also lists -GMT's five reports to `fullcalendar/temporal-polyfill`, found by the swap check +GMT's seven reports and two PRs to `fullcalendar/temporal-polyfill`, found by the swap check ([research §4.6](research/temporal-polyfill-swap.md#46-upstream)). -> **Status of this document:** updated 2026-11-04. **Filed:** 14 items by us, plus a comment on the -> maintainer's own PR #361, and five reports to `fullcalendar/temporal-polyfill` (fc #119, #120, #121, #125, #126; see "Filed"). The newest is tc39 #3335 (AB, D21), 2026-10-31; before it, tc39 #3331 (J) and #3332 (K), both 2026-10-21. **All six js-temporal PRs +> **Status of this document:** updated 2026-11-13. **Filed:** 14 items by us, plus a comment on the +> maintainer's own PR #361, and nine to `fullcalendar/temporal-polyfill`: seven reports (fc #119, #120, #121, #125, #126, #127, #128) and two PRs (fc #131 fixes #127, fc #132 fixes #128); see "Filed". The newest are fc #131 and #132, 2026-11-13; the newest in js-temporal and tc39 is tc39 #3335 (AB, D21), 2026-10-31. Eleven of our posts were corrected in place, each with a dated note at its end; see "Corrected posts". **All six js-temporal PRs > (#367–#372) are closed unmerged and none was rejected** — each was routed to `tc39/proposal-temporal` first, so the polyfill's rebase stays > manageable. #373 (release) is open and answered: one release once the rebase has caught up. #361 -> merged 2026-09-21. Five tc39 issues (#3327–#3330, #3332) are open with no maintainer reply; #3331 (J) is +> merged 2026-09-21. Five tc39 issues (#3327–#3330, #3332) and #3335 are open with no maintainer reply (checked 2026-11-13); #3331 (J) is > closed as answered (the check is intended, see § J). > **Nothing is released**, so no GMT workaround retires: `node scripts/temporal-compat.mjs check` reports > 25 workarounds, 21 still needed, 1 guard (D10) and 3 out of scope (D17, a Firefox-only defect filed as Bugzilla 2085525, § Q; D18, a polyfill defect only JavaScriptCore shows, § R; and D19, another polyfill defect only JavaScriptCore shows, § U; a Node run cannot judge any of the three). The newest is § AC (D22), fixed on `main`, with its no-value lengths filed as tc39/proposal-temporal#3336, #3311 and #3310; before it come § AB (D21), filed as tc39 #3335, § U (D19) and § R (D18), neither filed yet, with § S and § T, two WebKit engine defects GMT only tags, and § AD, a Node 26 engine defect GMT only tags; § I (D12), fixed on `main` with nothing @@ -39,8 +39,8 @@ is 0.5.1, and the latest ICU4C release is 78.3. | `D21`: `Temporal.Now` reads a millisecond early after a pre-1970 clock reading (§ AB) | None. Filed as tc39 #3335 | A tc39 fix, the js-temporal rebase and a release, so the `D21` canary repro passes | | `D22`: a length in days or larger is measured from the wrong pass of a repeated hour (§ AC) | js-temporal `3c403686d39` | tc39 #3319 in the same release, or `P7D` with `largestUnit: "week"` regresses to `P1W1D`. A release that still strips the Asserts of tc39/proposal-temporal#3336, #3311 and #3310 keeps GMT's gate | | `D5`: Indian calendar before ISO year 1 | js-temporal `8de299a` (PR #361; `b6c9844` on its branch) | Nothing | -| `D6`: non-ISO `until` re-constrains the day | js-temporal `10aeb98` | `D7`. With `10aeb98` and `1c64f14` alone one Hebrew `until` by years is still wrong (Corrections, item 3) | -| `D7`: Hebrew `until` by years throws | js-temporal `1c64f14` (PR #361; `79fb327` on its branch) | The `CompareSurpasses` part of tc39 `196a3191` (C-D7b), which is not on `main`. The `D7.leapMonthEnd` probe fails until it is | +| `D6`: non-ISO `until` re-constrains the day | js-temporal `10aeb98` | `D7`. With `10aeb98` and `1c64f14` alone one Hebrew `until` by years is still wrong (Corrections, item 3). `main` since `853fc8b` also has tc39/proposal-temporal#3327 problem 1, which the `D6.cachedDay` probes catch | +| `D7`: Hebrew `until` by years throws | js-temporal `1c64f14` (PR #361; `79fb327` on its branch) | The `CompareSurpasses` part of tc39 `196a3191` (C-D7b). js-temporal `main` took all of `196a3191` in `853fc8b`, months-loop hunk included, so it also carries tc39/proposal-temporal#3327 problem 1. Whether `D7.leapMonthEnd` passes on `main` is unverified (no build) | | `D11`: the calendar nudge window is never retried | js-temporal `5af905f` (PR #361; `50d66d2` on its branch) | Nothing | | `D12`: a seconds offset matched by minutes (§ I) | js-temporal `23d1275` | Nothing | | `D13`: the transition search skips or stalls (§ K) | js-temporal `a79c6a1`, in part | A further upstream fix, filed as tc39 #3332: `main` still stalls for `Africa/El_Aaiun` in 1976 (§ K). `D13` retires only on a release where every `D13` probe passes | @@ -88,7 +88,8 @@ contain the functions the js-temporal diff touches, so transcribing it would be fix has to do, offer to adapt it properly, and carry the **C-D7b** note with it: when tc39 `196a3191` is ported, its **months-loop hunk must be left out** — that hunk is what corrupts the calendar cache and produces the wrong, non-round-tripping result at ordinary dates. Its -`CompareSurpasses` hunk is the part worth having. +`CompareSurpasses` hunk is the part worth having. js-temporal `main` took the whole commit, months-loop +hunk included, in `853fc8b` (2026-09-22), so tc39/proposal-temporal#3327 now says `main` has problem 1. - [ ] Post the #3327 comment, including the C-D7b caveat. @@ -186,17 +187,18 @@ IANA tzdb rules, and Chromium 152/153 native Temporal as recorded in GMT's canar ## Filed -14 filed under the owner's account (`craig-o-curtis`): 11 by the owner, and tc39 #3331, #3332 and #3335 by an +14 filed in js-temporal and tc39 under the owner's account (`craig-o-curtis`): 11 by the owner, and tc39 #3331, #3332 and #3335 by an agent on the owner's instruction. There is also a fifteenth entry on the `/upstream/` tracker that is **not** a filing of ours: our comment on ptomato's js-temporal PR #361 (§ H), tracked because its state is what retires GMT's `D11`. "Filed" is `createdAt`, UTC. "js" is js-temporal/temporal-polyfill, -"tc39" is tc39/proposal-temporal, "fc" is fullcalendar/temporal-polyfill. The five fc reports (#119, #120, #121, #125, #126) are not counted in the 14 above. +"tc39" is tc39/proposal-temporal, "fc" is fullcalendar/temporal-polyfill. The nine fc filings (reports #119, #120, #121, #125, #126, #127, #128 and PRs #131, #132) are not counted in the 14 above. +Reports on native engines, such as nodejs/node#67457 (§ AD), are recorded in their own sections, not in this table. -**Status as of 2026-10-24** (`gh pr view` / `gh issue view`, comments included). Nothing has moved -since 2026-09-21 except tc39 #3331: all six js PRs closed, #373 open, #361 merged, and the four older -tc39 issues open with our own cross-link as the only comment. tc39 #3332, filed 2026-10-21, has no -comments. tc39 #3331 closed as answered on 2026-10-24, with our comment linking the champions' answer -on #3014. +**Status as of 2026-11-13** (`gh api`, comments included). In js-temporal and tc39 nothing has moved +since 2026-10-24: all six js PRs closed, #373 open, #361 merged, the four older tc39 issues open with +our own cross-link as the only comment, and tc39 #3332 and #3335 with no comments. tc39 #3331 closed as +answered on 2026-10-24, with our comment linking the champions' answer on #3014. fc #127 has two +comments, both ours; fc #128, #131 and #132 have none. - **All six js PRs (#367–#372) are closed, unmerged — and none was rejected.** ptomato closed #367, #368 and #369 with "I'd prefer to keep the commits ported in order — otherwise the rebases become @@ -209,6 +211,7 @@ on #3014. - **Five tc39 issues (#3327–#3330, #3332) are open with no maintainer reply** (checked 2026-10-24); the only comments are our own cross-links. - **fc #119, #120 and #121 are closed as fixed in temporal-polyfill 1.0.7**, and **#125 and #126 in 1.0.8** (all closed 2026-11-04). They stay listed as credit. +- **fc #127 (Persian) and #128 (Chinese and Dangi) are open**, each with our fix PR open against it: fc #131 and #132. - **tc39 #3331 is closed as answered** (2026-10-24): the champions had already said on #3014 that the check is intended until tc39/ecma262#3464 lands (§ J). @@ -233,6 +236,10 @@ on #3014. | fc | 121 | issue | Wrong UTC offset all through the period between two close offset changes (follow-up to #73) | swap §4.3 | none: other polyfill | — | nothing | 2026-10-25 | | fc | 125 | issue | `getTimeZoneTransition("previous")` skips every transition more than three years after today | swap §4.4 | none: other polyfill | — | nothing | 2026-11-04 | | fc | 126 | issue | Time zone transitions before 1847 are not found (`Asia/Manila` and four Pacific zones on 1844-12-31) | E, swap §4.5 | none: other polyfill | — | nothing | 2026-11-04 | +| fc | 127 | issue | Persian calendar: 78 years from 1502 to 2987 AP get the wrong leap year | swap §4.6 | fc #131 | — | nothing | 2026-11-06 | +| fc | 128 | issue | Chinese and Dangi: dates read from Intl differ from native Temporal (Chinese New Year 2027) | swap §4.6 | fc #132 | — | nothing | 2026-11-06 | +| fc | 131 | PR | Apply the ICU4X leap-year corrections to the Persian calendar | fix for fc #127 | fc #127 | — | fc #127 | 2026-11-13 | +| fc | 132 | PR | Compute the Chinese and Dangi calendars like ICU4X instead of reading Intl | fix for fc #128 | fc #128 | — | fc #128 | 2026-11-13 | Notes on the filings: @@ -250,6 +257,27 @@ Notes on the filings: new failures or unexpected passes. This closes the "run `npm test` and `npm run test262`" item under "Not verified" for #367–#372, as the filings' claim; it was not re-run for this document. +### Corrected posts + +These posts were edited in place, with the owner's approval of the exact text. Each ends with a note, +dated 2026-11-13, that says what changed: + +| Post | What was corrected | +| ---- | ------------------ | +| js #361, our comment | the proposal-temporal commit (`5dd0b0d97ee1` → `17e12be0af42`, the one on `main`); a sentence misreporting what tc39 #3168 says about other implementations; why #3168's reproducer passes on 0.5.1, and what test262 covers (§ H) | +| tc39 #3327 | problem 1 happens in both directions, and js-temporal `main` has it since `853fc8b` (`D6.cachedDay`) | +| tc39 #3328 | the search returns `null` on 45 days; 39 of them are wrong | +| tc39 #3329 | the inclusive range is 3,285,366 calls | +| tc39 #3331, our comment | the third link is a suggestion in that thread, not an agreed plan | +| tc39 #3335 | the repro replaces `Date.now` before the polyfill loads, since the tc39 polyfill keeps its own copy from load time; the fake-timer case applies to js-temporal | +| fc #127 | the check also finds differences in `chinese` and `dangi`, so "Only `persian` differs" was wrong | +| fc #128 | the year counts come from comparing each year's first day and length | +| fc #131 | which day is misread: the first day of the year after each corrected year reads as an extra 30th of month 12 | +| fc #132 | the host's ICU throws only near the upper end of the range; the `PlainMonthDay` check covers 744 combinations, each in two overflow modes | +| nodejs/node#67457 | "How often" narrowed to the cases that give a wrong result | + +Our 2026-09-18 comment on tc39 #3327 was true when posted and is left as it is. + ### Still unfiled Re-derived 2026-09-22, after the maintainer closed all six js-temporal PRs and merged #361. @@ -718,7 +746,8 @@ _Verification log:_ calendars) #370's output equals `main`'s except 18 coptic calls before the coptic epoch, which `main` got wrong and #370 answers with round-tripping values; with #361 underneath the output is identical with and without #370. - Current `main` already fixes D2 (buddhist before 1582, `2bb6ba1`) and D6 (month-end `until`, - `10aeb98`). GMT canary on a `main` build: D2 2/2 and D6 10/10 REMOVABLE. + `10aeb98`). GMT canary on a `main` build: D2 2/2 and D6 10/10 REMOVABLE. That build predates `853fc8b`; the two + `D6.cachedDay` probes added since would fail on today's `main`. - **Old draft appendix, corrected** (`repros/appendix-claims.mjs`, reads of `2024-01-01`, `2024-06-15`, `1000-01-01`, `-000500-06-15` and a fields round trip): - "coptic and ethiopic throw at every date": true of **0.5.1 only** (`Era am (ISO year 1740) was not matched by @@ -1592,7 +1621,7 @@ calls). This is **tc39/proposal-temporal [#3168](https://github.com/tc39/proposal-temporal/issues/3168)** (closed), fixed by **[#3172](https://github.com/tc39/proposal-temporal/pull/3172)** (Normative, -commit `5dd0b0d97ee1`, merged 2025-11-19). ptomato's diagnosis there is exactly ours: "_destEpochNs_ +commit `17e12be0af42`, merged 2025-11-19). ptomato's diagnosis there is exactly ours: "_destEpochNs_ (2021-02-28T01:00Z) > _endEpochNs_ (2021-02-28T00:00Z) … _r1_ and _r2_ should be 1 and 2 instead of 0 and 1." @@ -1620,8 +1649,9 @@ than 0 (spec/duration.html, `NudgeToCalendarUnit` steps 2–9). The polyfill com its `assert(start <= dest <= end)` is compiled out of production builds, so `progress` silently exceeds 1 and the answer comes from bounds that exclude the target. -Reachable only when the duration's own month count is one short of the truth, which is exactly when -adding a month constrains the day — a `relativeTo` on the 29th, 30th or 31st. +Reachable only when the duration's own count of the unit is one short of the truth, which is exactly +when adding that unit constrains the day — a `relativeTo` on the 29th, 30th or 31st for months, or +29 February for years. ### Repro @@ -1645,8 +1675,19 @@ Temporal.Duration.from("P29DT12H") ``` Note that #3168's own reproducer (`new Temporal.Duration(1, 0, 0, 0, 1)` relative to `2020-02-29`, -unit `years`) **passes** on js-temporal 0.5.1 — there `r1` is already 1 from the duration's own years, -so no retry is needed. The month reproducers above are the ones to file. +unit `years`) gives the right answer on js-temporal 0.5.1's production build: the assertion it trips +is stripped there, and the result happens to be right. The polyfill's pinned test262 (`ac3035f0`) +does not cover this defect. tc39/test262#4662, merged after that pin, adds +`Duration/prototype/round/rounding-window.js` and `total/rounding-window.js`, and 0.5.1 fails three +of their cases: + +| Case | 0.5.1 | Expected | +| --- | --- | --- | +| `P1MT10H` from `2020-01-31`, `round` to months, `expand` | `P1M` | `P2M` | +| `P2345YT12H` from `2020-02-29`, `round` to years, `expand` | `P2345Y` | `P2346Y` | +| `P1MT10H` from `2020-01-31`, `total` in months | `1.014367816091954` | `1.0134408602150538` | + +GMT gives the expected value for every case in both files. ### Scope, as scanned (Chromium 153.0.8010.12 vs `@js-temporal/polyfill` 0.5.1) @@ -1701,9 +1742,10 @@ failures, 6 missing; `npm run lint` clean. and #361 both leave it that way. If it is a further defect it belongs upstream as a new issue, not as a local "fix". 3. **#3168's own reproducer does not expose this.** `new Temporal.Duration(1, 0, 0, 0, 1)` relative - to `2020-02-29` with unit `years` *passes* on 0.5.1 — `r1` is already 1 from the duration's own - years field, so no retry is needed. Only a `relativeTo` on the 29th–31st with unit `month` - reaches it. + to `2020-02-29` with unit `years` gives the right answer on 0.5.1's production build, because the + assertion it trips is stripped and the result happens to be right. Wrong answers need a + `relativeTo` on the 29th–31st with unit `month`, or unit `year` from 29 February (test262#4662's + `P2345YT12H` case above). ### GMT @@ -2708,38 +2750,58 @@ Chromium passes the other five D22 repros, so before `noDayCorrection` and `empt If tc39 gives these lengths a value instead, in #3336, #3311 or #3310, the rows, the throws and the repros change together. -## AD. Node 26's V8 rounds `P7D` to weeks as `P1W1D` from a zoned origin (Node only, engine) +## AD. Node 26 adds one `smallestUnit` when it rounds a whole number of years, months or weeks (Node only, engine) ### Status -Fixed upstream, waiting for Node. boa-dev/temporal#723 ("Fix ComputeNudgeWindow startEpochNs computation to check -full startDateDuration sign", merged 2026-05-28 as `d47580805556`, for tc39/proposal-temporal#3316) carries tc39 #3319. -The first `temporal_rs` release with it is 0.2.4. Chromium 153.0.8010.12 has it. Node 26.13.0 (V8 14.6.202.34-node.40) -does not. **Not a polyfill defect**: `@js-temporal/polyfill` 0.5.1 gives `P1W`. Nothing to file. GMT makes no change: -it already follows the spec text. +**Filed** as [nodejs/node#67457](https://github.com/nodejs/node/issues/67457) (2026-11-13, open). It asks v26.x +to move to `temporal_rs` 0.2.4 or later, or to take boa-dev/temporal#723 alone. The fix is upstream: +boa-dev/temporal#723 ("Fix ComputeNudgeWindow startEpochNs computation to check full startDateDuration sign", +merged 2026-05-28 as `d47580805556`, for tc39/proposal-temporal#3316) carries tc39 #3319, and test262 commit +`a70493eb104948583a7928d50eac28b6c81114bf` covers it. The first `temporal_rs` release with it is 0.2.4. Node `main` +pins 0.2.6. Node v26.x pins 0.2.3 in `deps/crates/Cargo.toml`, so 26.12.1, 26.13.0 and 26.13.1 (V8 +14.6.202.34-node.40) have the bug. Chromium 153.0.8010.12 and WebKit 26.6 do not. **Not a polyfill defect**: +`@js-temporal/polyfill` 0.5.1 is right. GMT makes no change: it already follows the spec text. ### What goes wrong `ComputeNudgeWindow` starts the window at the origin's own exact time when the start duration is empty (tc39 #3319, tc39/ecma262#3759 commit `1f4e6717ef23`). Node 26's `temporal_rs` still tests _r1_ = 0, the rule #3319 -replaced, so it starts the window a week early when `largestUnit` is `week` and `smallestUnit` is `day`. Only a zoned -`relativeTo` builds this window. A `PlainDate` `relativeTo` is right. +replaced. So when the difference is a whole number of a larger unit, the smallest unit comes out as 0, and the window +starts at the origin instead of at the end of the whole years, months or weeks. When `smallestUnit` is `months` or +`weeks`, or `days` from a zoned origin, any rounding mode that can round up (`ceil`, `expand` and the five `half` +modes) then adds one `smallestUnit`. `trunc` and `floor` are right. It shows in `until` and `since` on `PlainDate`, +`PlainDateTime` and `ZonedDateTime`, in every calendar (checked: `iso8601`, `gregory`, `hebrew`, `chinese`, +`islamic-umalqura`, `persian`, `japanese`, `coptic`, `indian`), and in `Duration#round`. These are right: +`PlainYearMonth#until`; `smallestUnit: "days"` from a `PlainDate` or `PlainDateTime` origin; and any time unit as +`smallestUnit`. From a zoned origin, `P7D` to weeks is wrong even with the default `halfExpand`. + +### Repro (Node 26.12.1, 26.13.0 and 26.13.1, V8 14.6.202.34-node.40; expected values Chromium 153.0.8010.12 native `Temporal`, which WebKit 26.6 and the polyfill also give) -### Repro (Node 26.12.1 and 26.13.0, V8 14.6.202.34-node.40; expected values Chromium 153.0.8010.12 native `Temporal`, which the polyfill also gives) +`start` is `Temporal.PlainDate.from("2000-01-01")`. | Call | Node 26 | Expected | | ---- | ------- | -------- | +| `start.until("2001-01-01", { largestUnit: "years", smallestUnit: "months", roundingMode: "halfExpand" })` | `P1Y1M` | `P1Y` | +| the same with `"2003-01-01"` and `roundingMode: "ceil"` | `P3Y1M` | `P3Y` | +| the same with `"2001-01-01"`, `smallestUnit: "weeks"` and `roundingMode: "ceil"` | `P1Y1W` | `P1Y` | +| the same with `"2001-01-01"`, `smallestUnit: "months"` and `roundingMode: "trunc"` or `"floor"` | `P1Y` | `P1Y` | +| `Temporal.Duration.from("P31D").round({ largestUnit: "months", smallestUnit: "weeks", roundingMode: "ceil", relativeTo: "2012-01-01" })` | `P1M1W` | `P1M` | | `Temporal.Duration.from("P7D").round({ largestUnit: "week", smallestUnit: "day", relativeTo: "2024-11-01T00:00:00+00:00[UTC]" })` | `P1W1D` | `P1W` | | the same with `relativeTo: "2024-06-01T12:00:00-04:00[America/New_York]"` | `P1W1D` | `P1W` | | the same with `relativeTo: "2024-11-01"` | `P1W` | `P1W` | +| `Temporal.ZonedDateTime.from("2000-03-15T00:00[UTC]").until("2000-05-15T00:00[UTC]", { largestUnit: "months", smallestUnit: "days", roundingMode: "ceil" })` | `P2M1D` | `P2M` | +| the same from `Temporal.PlainDate.from("2000-03-15")` to `"2000-05-15"` | `P2M` | `P2M` | +| `Temporal.PlainYearMonth.from("2000-01").until("2001-01", { largestUnit: "years", smallestUnit: "months", roundingMode: "ceil" })` | `P1Y` | `P1Y` | ### Effect on GMT -None in the library, which gives `P1W` on the polyfill. Only GMT run on Node 26's own `Temporal` sees it: +None in the library, which gives the spec's answers on the polyfill. Only GMT run on Node 26's own `Temporal` sees it: `normalizeDuration` returns the engine's answer when the origin is not in a repeated hour. The later-pass and earlier-pass rows of the same table pass on Node 26. The native-suite runner tags the two rows of `packages/gmt/src/test/laterPassOrigin.test.ts` that pin it, the UTC and New York noon origins, to this section (Node -leg only). When a Node release carries a `temporal_rs` with #723, the tags go stale and the runner reports it. +leg only). No other row of GMT's suite reaches it on Node 26. When a Node release carries a `temporal_rs` with #723, +the tags go stale and the runner reports it. ## AE. ICU4C 75+ counts every Persian year before year 0 as a leap year (macOS WebKit, engine) diff --git a/context/domination/research/temporal-polyfill-swap.md b/context/domination/research/temporal-polyfill-swap.md index bda2580c1..10cd87d8a 100644 --- a/context/domination/research/temporal-polyfill-swap.md +++ b/context/domination/research/temporal-polyfill-swap.md @@ -207,8 +207,10 @@ test fails; only zoned.E's probes do. | § 4.3 Wrong offset between two close offset changes (follow-up to #73) | [#121](https://github.com/fullcalendar/temporal-polyfill/issues/121) | Fixed in 1.0.7 | | § 4.4 Backward search stops about three years ahead | [#125](https://github.com/fullcalendar/temporal-polyfill/issues/125) | Fixed in 1.0.8 | | § 4.5 Transitions before 1847 not found | [#126](https://github.com/fullcalendar/temporal-polyfill/issues/126) | Fixed in 1.0.8 | +| Persian: 78 years from 1502 to 2987 AP get the wrong leap year | [#127](https://github.com/fullcalendar/temporal-polyfill/issues/127) | Open; our fix is PR [#131](https://github.com/fullcalendar/temporal-polyfill/pull/131) | +| Chinese and Dangi read from `Intl`, which differs from native Temporal | [#128](https://github.com/fullcalendar/temporal-polyfill/issues/128) | Open; our fix is PR [#132](https://github.com/fullcalendar/temporal-polyfill/pull/132) | -The `/upstream/` tracker lists all five, closed ones included, as credit. +The `/upstream/` tracker lists all seven reports and both PRs, closed ones included, as credit. ## 5. What a swap costs diff --git a/context/dox/tracker.md b/context/dox/tracker.md index e8a7e02c9..72ffffec1 100644 --- a/context/dox/tracker.md +++ b/context/dox/tracker.md @@ -2,8 +2,8 @@ 35 sub-stories on 26 GitHub issues: #130–#142, #171 (`DOX-C0`), #240 (`DOX-C4`), #288 (`DOX-A6`), #289 (`DOX-E1c`), #293 (`DOX-E1d`), #430 (`DOX-G1`), #447 (`DOX-G2`), #467 -(`DOX-G3`), #458 (`DOX-G4`), #448 (`DOX-G6`), #477 (`DOX-G7`, -with #475), #487 (`DOX-G8`) and #522 (`DOX-G9`). What each done story shipped is in [built.md](built.md). +(`DOX-G3`), #458 (`DOX-G4`), #448 (`DOX-G6`), #477 (`DOX-G7`, with #475), #487 (`DOX-G8`) and +#522 (`DOX-G9`). What each done story shipped is in [built.md](built.md). A row here is a `DOX-*` story with its own GitHub issue. Add one, then run `pnpm deps:sync`, which generates `Blocked by`, only for Dox work that belongs to no realm story. The Dox pages and diff --git a/packages/gmt/src/internal/temporalCompat/README.md b/packages/gmt/src/internal/temporalCompat/README.md index bb6d1bc69..ac6e727ea 100644 --- a/packages/gmt/src/internal/temporalCompat/README.md +++ b/packages/gmt/src/internal/temporalCompat/README.md @@ -179,12 +179,12 @@ limits) is the `D1` group. | D2 | A js-temporal release contains `2bb6ba1` (already on main) | | D3 + D4 | **Both** hold: a js-temporal release ports proposal-temporal `0df570c`, **and** GMT's `engines.node` floor bundles an ICU containing `5267bb5778` (ICU-23007) | | D5 | A js-temporal release ports proposal-temporal `314b112` | -| D6 | A js-temporal release contains `10aeb98` (already on main) | +| D6 | A js-temporal release contains `10aeb98` (already on main) **and** no longer writes the un-constrained day into its calendar cache: tc39/proposal-temporal#3327 problem 1, on js-temporal `main` since `853fc8b`. The `cachedDay` probes pass on 0.5.1 and fail on a release with that loop | | D7 | A js-temporal release ports proposal-temporal `0e32ee0` **and** C-D7b (part of proposal-temporal `196a3191`; bug doc § C). `0e32ee0` fixes the `mixedSign` probe only: the `leapMonthEnd` probe (`5784-M05L-30` → `5785-M06-29` by years) still returns `P1Y` without C-D7b | | D8 | A js-temporal release contains `2bb6ba1` **and** proposal-temporal `977d11e0` + `993e6322`: `2bb6ba1` alone still reads `1872-12-31` as `meiji` 5 | | D10 | A js-temporal release ports proposal-temporal #3292 **together with** the tc39/proposal-temporal#3329 fix. The group passes on 0.5.1 (no #3292); it fails only on a release with #3292 alone | | D9 | A js-temporal release adds and differences non-ISO months in bounded work: each `D9` probe reads at most 100 `Intl.DateTimeFormat` dates for 1,200 months | -| D11 | A js-temporal release contains js-temporal/temporal-polyfill#361's `50d66d2`, which ports proposal-temporal #3172 (`5dd0b0d97ee1`, merged 2025-11-19 — the fix for tc39/proposal-temporal#3168), so the nudge window is retried. The port reached `main` through PR #361 as `5af905fc1fa` (2026-09-21) and is in no release yet, so a release from `main` will do it and no new filing is needed. Verified locally: `50d66d2` applies cleanly on `main` alone, touches only `lib/ecmascript.ts`, and flips all three probes (`total` 1.0172413793103448 → 1.0161290322580645; `until`/`round` `PT0S` → `P1M`) with test262 clean | +| D11 | A js-temporal release contains js-temporal/temporal-polyfill#361's `50d66d2`, which ports proposal-temporal #3172 (`17e12be0af42`, merged 2025-11-19 — the fix for tc39/proposal-temporal#3168), so the nudge window is retried. The port reached `main` through PR #361 as `5af905fc1fa` (2026-09-21) and is in no release yet, so a release from `main` will do it and no new filing is needed. Verified locally: `50d66d2` applies cleanly on `main` alone, touches only `lib/ecmascript.ts`, and flips all three probes (`total` 1.0172413793103448 → 1.0161290322580645; `until`/`round` `PT0S` → `P1M`) with test262 clean | | D12 | A js-temporal release contains `23d1275` ("Normative: Require strict matching with a precise ZonedDateTime offset"), on main since 2026-04 and in no release. Expected values are test262 `intl402/Temporal/ZonedDateTime/from/zoneddatetime-sub-minute-offset.js` (bug doc § I) | | D13 | A js-temporal release on which **every** `D13` probe returns the spec value, the `stall.*` ones within 20,000 offset reads. `a79c6a1` (per-zone transition search windows, on main, in no release) is **not** enough: it fixes the zones it lists, leaves `bisect` unchanged, and gives `Africa/El_Aaiun` a 17-day window that holds three offsets in April 1976, so `stall.nextElAaiun` fails there and GMT would hang without the workaround (bug doc § K; not filed). Expected values are Node 26.10.0's native Temporal and `zdump -v` | | D14 | A js-temporal release contains the port of tc39/proposal-temporal#3312 (reference polyfill commit `59a51ea9d4`), so the `D14` probe returns `2010-03-04T00:00:00+11:00[Antarctica/Casey]`. Expected values are test262 `intl402/Temporal/ZonedDateTime/prototype/round/same-date-starts-twice.js` | diff --git a/packages/gmt/src/internal/temporalCompat/capabilities.test.ts b/packages/gmt/src/internal/temporalCompat/capabilities.test.ts index d9872932f..84ee09e58 100644 --- a/packages/gmt/src/internal/temporalCompat/capabilities.test.ts +++ b/packages/gmt/src/internal/temporalCompat/capabilities.test.ts @@ -110,11 +110,14 @@ describe("repros", () => { // D6: test262 wrapping-at-end-of-month-{hebrew,ethioaa}.js; the others are Chromium 152 grid rows, // and gregory is Chromium 153 (gregory joined CalendarSystem in CORE-8). + // D6 cachedDay: tc39/proposal-temporal#3327 problem 1, Chromium 153 (Node 26.12.1 agrees). // D7 mixedSign: Chromium 152 grid, ISO 2024-02-11 + 384 days by years. // D7 leapMonthEnd: Chromium and NonISODateSurpasses (unconstrained day 30 > 29), per // js-temporal-polyfill-bugs.md § C (C-D7b). it.each` defect | calendar | name | expected + ${"D6"} | ${"hebrew"} | ${"cachedDay"} | ${"-P1M1D"} + ${"D6"} | ${"islamic-civil"} | ${"cachedDay"} | ${"-P1Y1M1D"} ${"D6"} | ${"buddhist"} | ${"monthEnd"} | ${"P30D"} ${"D6"} | ${"gregory"} | ${"monthEnd"} | ${"P30D"} ${"D6"} | ${"japanese"} | ${"monthEnd"} | ${"P30D"} diff --git a/packages/gmt/src/internal/temporalCompat/probeRepros.ts b/packages/gmt/src/internal/temporalCompat/probeRepros.ts index fd8a0a4c3..44454d6d4 100644 --- a/packages/gmt/src/internal/temporalCompat/probeRepros.ts +++ b/packages/gmt/src/internal/temporalCompat/probeRepros.ts @@ -235,12 +235,15 @@ function isoOf(date: Temporal.PlainDate): string { return date.withCalendar("iso8601").toString(); } -function monthsUntil(calendar: string, from: string, to: string): string { +function monthsUntil( + calendar: string, + from: string, + to: string, + largestUnit: "months" | "years" = "months", +): string { return Temporal.PlainDate.from(from) .withCalendar(calendar) - .until(Temporal.PlainDate.from(to).withCalendar(calendar), { - largestUnit: "months", - }) + .until(Temporal.PlainDate.from(to).withCalendar(calendar), { largestUnit }) .toString(); } @@ -356,6 +359,21 @@ const d6Repros: ProbeRepro[] = [ .toString(), }), ), + // tc39/proposal-temporal#3327 problem 1: the months loop writes the un-constrained day into the + // cached calendar date, so a count from the 30th across a 29-day month loses a day. 0.5.1 passes; + // js-temporal `main` has the loop since 853fc8b, so a release with it must keep D6. Chromium 153. + ...( + [ + ["hebrew", "2022-05-01", "2022-03-31", "months", "-P1M1D"], + ["islamic-civil", "2023-04-21", "2022-04-01", "years", "-P1Y1M1D"], + ] as const + ).map(([calendar, from, to, largestUnit, expected]): ProbeRepro => ({ + defect: "D6", + calendar, + name: "cachedDay", + expected, + run: () => monthsUntil(calendar, from, to, largestUnit), + })), ]; /** diff --git a/packages/gmt/src/internal/zonedDifference/nudgeWindow.ts b/packages/gmt/src/internal/zonedDifference/nudgeWindow.ts index ddc756816..290c7cdfc 100644 --- a/packages/gmt/src/internal/zonedDifference/nudgeWindow.ts +++ b/packages/gmt/src/internal/zonedDifference/nudgeWindow.ts @@ -41,7 +41,7 @@ import type { * and a `relativeTo` on the 29th, 30th or 31st. The operation then takes the spec path in `./operations.ts`, * the same `nudgeToCalendarUnit` the non-ISO calendars already use. * - Retired by: a js-temporal release containing a port of proposal-temporal #3172 - * (`5dd0b0d97ee1`, merged 2025-11-19), which is the fix for tc39/proposal-temporal#3168. The + * (`17e12be0af42`, merged 2025-11-19), which is the fix for tc39/proposal-temporal#3168. The * port is on js-temporal `main` as `5af905fc1fa`, in no release yet. * - Removal: delete this file and its calls in `../zonedWallClockDifference.ts` (the * `monthTotalBySpec` and `monthRoundBySpec` operands in `durationTotal` and `durationRound`, the diff --git a/packages/gmt/src/test/nudgeWindowRetry.test.ts b/packages/gmt/src/test/nudgeWindowRetry.test.ts index 2cb1aff40..27e87e7b9 100644 --- a/packages/gmt/src/test/nudgeWindowRetry.test.ts +++ b/packages/gmt/src/test/nudgeWindowRetry.test.ts @@ -16,7 +16,7 @@ import { diffUtc } from "../utc"; * when the duration's own month count is one short of the truth, which is exactly when adding a month * constrains the day — a start on the 29th, 30th or 31st. * - * Upstream: tc39/proposal-temporal#3168, fixed by #3172 (`5dd0b0d97ee1`, merged 2025-11-19), which + * Upstream: tc39/proposal-temporal#3168, fixed by #3172 (`17e12be0af42`, merged 2025-11-19), which * `@js-temporal/polyfill` has not ported on 0.5.1 or `main`. GMT carries the spec algorithm itself * (compat defect D11) until a release does. * diff --git a/scripts/bundle-size.budgets.json b/scripts/bundle-size.budgets.json index 759435d05..a796801a1 100644 --- a/scripts/bundle-size.budgets.json +++ b/scripts/bundle-size.budgets.json @@ -16,13 +16,13 @@ "minified": 158600 }, "chargeableDays": { - "minified": 202600 + "minified": 202700 }, "operatingTimeBetween": { - "minified": 210400 + "minified": 210500 }, "dutyViolations": { - "minified": 234800 + "minified": 234900 } }, "absent": { diff --git a/scripts/lib/native-suite-tags.mjs b/scripts/lib/native-suite-tags.mjs index 1ea71428d..2b04fae73 100644 --- a/scripts/lib/native-suite-tags.mjs +++ b/scripts/lib/native-suite-tags.mjs @@ -39,8 +39,8 @@ const AE_ANCHOR = "ae-icu4c-75-counts-every-persian-year-before-year-0-as-a-leap-year-macos-webkit-engine"; const ICU_23609 = "https://unicode-org.atlassian.net/browse/ICU-23609"; const AD_ANCHOR = - "ad-node-26s-v8-rounds-p7d-to-weeks-as-p1w1d-from-a-zoned-origin-node-only-engine"; -const BOA_723 = "https://github.com/boa-dev/temporal/pull/723"; + "ad-node-26-adds-one-smallestunit-when-it-rounds-a-whole-number-of-years-months-or-weeks-node-only-engine"; +const NODE_67457 = "https://github.com/nodejs/node/issues/67457"; /** * One test that fails natively and passes on the polyfill, for a known defect. `file` is @@ -52,9 +52,9 @@ const BOA_723 = "https://github.com/boa-dev/temporal/pull/723"; * The 13 tests that fail on Node 26 and Chromium 153 (V8 on `temporal_rs`) and pass on the * polyfill. Ten are L (`ixdtf` rejects a one-character annotation key, fixed in unicode-org/icu4x#8623, * not yet in an `ixdtf` release or a V8 roll); three are M (`temporal_rs` reads `islamic` as a - * calendar, boa-dev/temporal#529). Two more fail on Node 26 alone and are AD: its V8 does not yet - * carry boa-dev/temporal#723, so it rounds `P7D` to weeks from a zoned origin as `P1W1D`; Chromium - * 153 has the fix. The 12 tests that fail on Firefox 155 (SpiderMonkey) and pass on the + * calendar, boa-dev/temporal#529). Two more fail on Node 26 alone and are AD: its `temporal_rs` 0.2.3 does + * not yet carry boa-dev/temporal#723, so it rounds `P7D` to weeks from a zoned origin as `P1W1D` + * (nodejs/node#67457); Chromium 153 has the fix. The 12 tests that fail on Firefox 155 (SpiderMonkey) and pass on the * polyfill are P: SpiderMonkey accepts a zoned string whose local date is -271821-04-19, where the * spec refuses it (Bugzilla 1998020). The 7 tests that fail on WebKit 26.6 (JavaScriptCore) and pass on * the polyfill are S (six: JavaScriptCore adds a year to Dhu al-Hijjah 30 of a year before the Hijra as @@ -314,14 +314,14 @@ export const KNOWN_NATIVE_FAILURES = [ test: "normalizeDuration from a repeated hour P7D with { largestUnit: 'week', …(1) } from 2024-11-01T00:00:00+00:00[UTC] is P1W", legs: ["node"], defect: AD_ANCHOR, - upstream: BOA_723, + upstream: NODE_67457, }, { file: "src/test/laterPassOrigin.test.ts", test: "normalizeDuration from a repeated hour P7D with { largestUnit: 'week', …(1) } from 2024-06-01T12:00:00-04:00[America/New_Y… is P1W", legs: ["node"], defect: AD_ANCHOR, - upstream: BOA_723, + upstream: NODE_67457, }, ]; /** diff --git a/scripts/lib/workarounds.mjs b/scripts/lib/workarounds.mjs index ff40e3633..8fdc2a01a 100644 --- a/scripts/lib/workarounds.mjs +++ b/scripts/lib/workarounds.mjs @@ -89,7 +89,8 @@ export const WORKAROUNDS = [ { defects: ["D6"], title: "D6 — non-ISO until re-constrains the day while counting months", - trigger: "a js-temporal release contains 10aeb98 (already on main)", + trigger: + "a js-temporal release contains 10aeb98 (already on main) and no longer writes the un-constrained day into its calendar cache (tc39/proposal-temporal#3327 problem 1, on main since 853fc8b)", steps: [ "Delete the D6 repros and the D6 terms in calendarDateArithmetic.ts.", LAST_OF_D1_D7, @@ -139,7 +140,7 @@ export const WORKAROUNDS = [ title: "D11 — the calendar nudge window is never retried, so total, round and until with a calendar smallestUnit answer over the wrong bounds (relativeTo on the 29th-31st)", trigger: - "a js-temporal release contains js-temporal/temporal-polyfill#361's 50d66d2, which ports proposal-temporal #3172 (5dd0b0d97ee1, the fix for tc39 #3168) and retries the nudge window; merged to main in PR #361 as 5af905f, so no new filing is needed", + "a js-temporal release contains js-temporal/temporal-polyfill#361's 50d66d2, which ports proposal-temporal #3172 (17e12be0af42, the fix for tc39 #3168) and retries the nudge window; merged to main in PR #361 as 5af905f, so no new filing is needed", steps: [ "Delete the D11 repros in probeRepros.ts, isNudgeWindowCompatNeeded in capabilities.ts and its export in index.ts, and internal/zonedDifference/nudgeWindow.ts with its calls in zonedWallClockDifference.ts (the monthTotalBySpec and monthRoundBySpec operands in durationTotal and durationRound, the defect-4 term in untilTakesSpecPath, and the plainUntilWithRounding re-export), the plainUntilWithRounding export in internal/index.ts, and its call in plain/calculate/diffDateTime.ts, which calls dt1.until(dt2, { largestUnit, smallestUnit, roundingIncrement, roundingMode }) again, the same object it passes to plainUntilWithRounding now. The last of defects 3–5 to go also deletes untilTakesSpecPath, the // defects 3–5 block in zonedUntil that calls untilAtLimit, and the bySpec blocks in durationTotal and durationRound. Then drop the imports and locals tsc reports unused, and the internal/zonedDifference/operations.ts exports fallow reports unused.", "Keep test/nudgeWindowRetry.test.ts and test/intervalLengthOracle.test.ts, and the progress === 0n branch in nudgeToCalendarUnit (internal/zonedDifference/operations.ts; GMT's own fix, not the polyfill's).", From a1fbabcc69557ffbb35069351496e139fc2fee0f Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sat, 14 Nov 2026 08:05:49 +0200 Subject: [PATCH 03/12] fix(core): stop the week-year crash and print the right year in formatted dates (CORE-112, #524) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - D23: GMT never calls formatToParts or formatRangeToParts on a pattern with `Y`, which aborts V8 without commit 0426b0d1045d (nodejs/node#67076). - D24: where a CLDR pattern prints the week-of-year year, single dates and ranges print the calendar year, as ECMA-402 gives it. - D25: japanese dates before 1873 print the Gregorian era. - D26: islamic dates before the Hijra give the empty value where the engine prints a negative year. - D27: ja japanese `year: 2-digit` pads the era year; 元年 stays. - D28: chinese and dangi print the related year at full width. Each repair is dormant behind its own engine probe and retires through the compat check. Records tc39/ecma402#1116 and ICU-23619, ICU-23620 and ICU-23621 on the upstream page and in the bug doc. --- .changeset/core-112-week-year.md | 5 + .fallowrc.jsonc | 15 + .../core-date-operations/formatting.mdx | 2 + apps/dox/src/content/docs/upstream.mdx | 25 + apps/dox/src/data/gmt-stats.json | 6 +- apps/dox/src/data/temporal-compat.ts | 6 + context/domination/issues/CORE-112.md | 31 + context/domination/issues/index.md | 1 + .../domination/js-temporal-polyfill-bugs.md | 135 +- .../domination/specs/CORE-112/call-sites.md | 54 + .../specs/CORE-112/canary-and-docs.md | 126 ++ context/domination/specs/CORE-112/guard.md | 150 ++ context/domination/specs/CORE-112/index.md | 138 ++ context/domination/specs/CORE-112/range.md | 168 ++ .../specs/CORE-112/single-repair.md | 120 ++ context/domination/specs/CORE-112/tests.md | 102 ++ .../specs/CORE-112/year-printing.md | 123 ++ context/domination/tracker.md | 1 + packages/gmt/bench/formatDate.bench.ts | 30 + packages/gmt/src/internal/formatterCache.ts | 81 +- .../gmt/src/internal/plainFormatOptions.ts | 3 +- .../gmt/src/internal/plainOptionEntries.ts | 41 + .../gmt/src/internal/repairRangeText.test.ts | 120 ++ packages/gmt/src/internal/repairRangeText.ts | 107 ++ .../gmt/src/internal/temporalCompat/README.md | 49 +- .../internal/temporalCompat/capabilities.ts | 116 ++ .../temporalCompat/islamicEra.test.ts | 26 + .../src/internal/temporalCompat/islamicEra.ts | 20 +- .../gmt/src/internal/temporalCompat/repros.ts | 222 ++- .../temporalCompat/weekYearSource.test.ts | 89 ++ .../temporalCompat/yearPrintingProbes.test.ts | 34 + .../gmt/src/internal/weekYearAbort.test.ts | 38 + .../gmt/src/internal/weekYearGuard.test.ts | 161 ++ packages/gmt/src/internal/weekYearGuard.ts | 383 +++++ .../gmt/src/internal/weekYearRange.test.ts | 297 ++++ packages/gmt/src/internal/weekYearRange.ts | 1378 +++++++++++++++++ .../src/internal/weekYearRangeNull.test.ts | 51 + .../src/internal/weekYearRangeText.test.ts | 134 ++ .../gmt/src/internal/weekYearSingle.test.ts | 121 ++ .../gmt/src/internal/weekYearSynth.test.ts | 93 ++ packages/gmt/src/internal/weekYearSynth.ts | 508 ++++++ packages/gmt/src/internal/weekYearText.ts | 493 ++++++ .../gmt/src/internal/yearPrinting.test.ts | 602 +++++++ packages/gmt/src/internal/yearPrinting.ts | 310 ++++ .../src/internal/yearPrintingDormant.test.ts | 198 +++ .../gmt/src/plain/format/formatDate.test.ts | 2 +- .../gmt/src/plain/format/formatDateRange.ts | 7 +- .../src/plain/format/formatDateTimeRange.ts | 12 +- packages/gmt/src/test/optionsObject.test.ts | 17 + .../gmt/src/zoned/format/formatZonedRange.ts | 80 +- .../format/formatZonedRangeBranches.test.ts | 98 ++ .../format/formatZonedRangeWeekYear.test.ts | 35 + scripts/canary/weekYear.mjs | 201 +++ scripts/lib/workarounds.mjs | 75 +- scripts/upstream.mjs | 4 +- 55 files changed, 7368 insertions(+), 76 deletions(-) create mode 100644 .changeset/core-112-week-year.md create mode 100644 context/domination/issues/CORE-112.md create mode 100644 context/domination/specs/CORE-112/call-sites.md create mode 100644 context/domination/specs/CORE-112/canary-and-docs.md create mode 100644 context/domination/specs/CORE-112/guard.md create mode 100644 context/domination/specs/CORE-112/index.md create mode 100644 context/domination/specs/CORE-112/range.md create mode 100644 context/domination/specs/CORE-112/single-repair.md create mode 100644 context/domination/specs/CORE-112/tests.md create mode 100644 context/domination/specs/CORE-112/year-printing.md create mode 100644 packages/gmt/src/internal/plainOptionEntries.ts create mode 100644 packages/gmt/src/internal/repairRangeText.test.ts create mode 100644 packages/gmt/src/internal/repairRangeText.ts create mode 100644 packages/gmt/src/internal/temporalCompat/weekYearSource.test.ts create mode 100644 packages/gmt/src/internal/temporalCompat/yearPrintingProbes.test.ts create mode 100644 packages/gmt/src/internal/weekYearAbort.test.ts create mode 100644 packages/gmt/src/internal/weekYearGuard.test.ts create mode 100644 packages/gmt/src/internal/weekYearGuard.ts create mode 100644 packages/gmt/src/internal/weekYearRange.test.ts create mode 100644 packages/gmt/src/internal/weekYearRange.ts create mode 100644 packages/gmt/src/internal/weekYearRangeNull.test.ts create mode 100644 packages/gmt/src/internal/weekYearRangeText.test.ts create mode 100644 packages/gmt/src/internal/weekYearSingle.test.ts create mode 100644 packages/gmt/src/internal/weekYearSynth.test.ts create mode 100644 packages/gmt/src/internal/weekYearSynth.ts create mode 100644 packages/gmt/src/internal/weekYearText.ts create mode 100644 packages/gmt/src/internal/yearPrinting.test.ts create mode 100644 packages/gmt/src/internal/yearPrinting.ts create mode 100644 packages/gmt/src/internal/yearPrintingDormant.test.ts create mode 100644 packages/gmt/src/zoned/format/formatZonedRangeBranches.test.ts create mode 100644 packages/gmt/src/zoned/format/formatZonedRangeWeekYear.test.ts create mode 100644 scripts/canary/weekYear.mjs diff --git a/.changeset/core-112-week-year.md b/.changeset/core-112-week-year.md new file mode 100644 index 000000000..414fdcbfa --- /dev/null +++ b/.changeset/core-112-week-year.md @@ -0,0 +1,5 @@ +--- +"@northguild/gmt": patch +--- + +Formatting no longer stops Node with a crash, and prints the right year, in languages whose date patterns print the year a week belongs to instead of the calendar year. `formatZonedRange`, `formatCalendar` and the `…ToParts` functions stopped Node 22, 24 and 26 with a crash for some languages and calendars, for example Burmese with the Buddhist calendar, and Galician with the Hebrew, Buddhist or ROC calendar and a full date style. Every format function also printed the wrong year near the start or end of a year, or all year in the Buddhist, Japanese and ROC calendars: Scottish Gaelic printed `Dùbh 2025` for 30 December 2024, and now prints `Dùbh 2024`. diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index 3b78d86bb..49fe5a583 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -6,6 +6,8 @@ "entry": [ "packages/gmt/src/test/nativeTemporal.ts", "scripts/lib/native-suite-reporter.mjs", + // The weekly D23/D24 locale sweep (CORE-112), run by hand or from a workflow. + "scripts/canary/weekYear.mjs", "packages/gmt/bench/*.bench.ts", "packages/gmt/src/test/*.browser.ts", "packages/gmt/src/test/boundedWorker.ts", @@ -41,6 +43,19 @@ "maxCrap": 30, "maxUnitSize": 60, "thresholdOverrides": [ + { + "files": ["packages/gmt/src/internal/weekYearRange.ts"], + "functions": [ + "farRange", + "shiftYears", + "digitsMatch", + "computeShift", + "movedLikeYear", + "signOf", + ], + "maxCrap": 70, + "reason": "D24 range verdict: cyclomatic and cognitive are inside the limits; the CRAP figure is estimated from export references because these helpers are not exported, and weekYearRange.test.ts covers every branch through rangeYearVerdict", + }, { "files": ["packages/gmt/src/internal/patternToken.ts"], "functions": [ diff --git a/apps/dox/src/content/docs/guides/core-date-operations/formatting.mdx b/apps/dox/src/content/docs/guides/core-date-operations/formatting.mdx index 0aa9c5ab3..de8e11625 100644 --- a/apps/dox/src/content/docs/guides/core-date-operations/formatting.mdx +++ b/apps/dox/src/content/docs/guides/core-date-operations/formatting.mdx @@ -35,6 +35,8 @@ For a birthday or a holiday with no year, see [Month-Day Values](/guides/core-da For a card expiry or a billing month, `formatYearMonth("2026-10", "fr-FR", { year: "numeric", month: "long" })` gives `"octobre 2026"`. A day or time field is dropped, and it formats through the Gregorian calendar. +Some languages' date patterns, such as Scottish Gaelic's month and year, print the year a week belongs to where the calendar year is meant, so 30 December 2024 shows 2025 in every browser, and asking Node for the parts of such a date stops the process. GMT checks each formatter once and prints the calendar year, as the ECMA-402 specification says. [Helping fix Temporal](/upstream/) lists the reports. + ## Locale-elided ranges `formatDateRange` and `formatDateTimeRange` are the plain counterparts of diff --git a/apps/dox/src/content/docs/upstream.mdx b/apps/dox/src/content/docs/upstream.mdx index fd05b6075..055269cec 100644 --- a/apps/dox/src/content/docs/upstream.mdx +++ b/apps/dox/src/content/docs/upstream.mdx @@ -152,6 +152,31 @@ The built-in engines have a few bugs of their own. We report each one we find. T 1 January 2000 to 1 January 2001, rounded up to months, it gives one year and one month. The fix is already in `temporal_rs`, the Temporal code that Node and Chromium share, and Chromium 153 has it. The report asks Node 26 to take it. +- [`nodejs/node#67076`](https://github.com/nodejs/node/issues/67076): Node 22, 24 and 26 stop with + a crash when they split a date into parts in a few languages, such as Burmese with the Buddhist + calendar, or Galician with the Hebrew calendar and a full date. These languages' date patterns + print the year a week belongs to (see the next item). V8, the JavaScript engine in Node and + Chromium, has the fix, and Chromium 158 has it. The report asks Node to take it. +- In CLDR, the data every engine formats dates with, some languages' date patterns print the year + a week belongs to instead of the calendar year. Scottish Gaelic, for example, prints December + 2025 for 30 December 2024, and Telugu with the Buddhist calendar prints 2026 all year instead of + 2569. Node, Chromium and Safari all print it. Someone else reported two of these languages as + [CLDR-19873](https://unicode-org.atlassian.net/browse/CLDR-19873), and + [our comment there](https://unicode-org.atlassian.net/browse/CLDR-19873?focusedCommentId=213171) + adds the rest. +- Node, Chromium and Safari print a few other years wrong. Japanese calendar dates before 1873 + come out in a Japanese era such as Meiji 5, where the standard gives the Gregorian era; + [`ICU-23341`](https://unicode-org.atlassian.net/browse/ICU-23341) fixes the years before Meiji + in ICU 79.1. Node and Chromium print Islamic dates before the Hijra as a negative year + ([`ICU-23327`](https://unicode-org.atlassian.net/browse/ICU-23327)). In Japanese, a two-digit + year in the Japanese calendar prints as 令和6年 instead of 令和06年, and the Chinese and Korean + calendars pad the Gregorian year shown beside the cycle year, such as 05 for the year 5. We + reported these two as [`ICU-23620`](https://unicode-org.atlassian.net/browse/ICU-23620) and + [`ICU-23621`](https://unicode-org.atlassian.net/browse/ICU-23621), and Meiji 1 to 5 as + [`ICU-23619`](https://unicode-org.atlassian.net/browse/ICU-23619). +- [`tc39/ecma402#1116`](https://github.com/tc39/ecma402/issues/1116): the standard's rule for + years before 1 fits only calendars that count those years backwards in an era of their own, such + as BC. It asks to limit the rule to those calendars. - [`ICU-20548`](https://unicode-org.atlassian.net/browse/ICU-20548): Node, Chromium and Safari shorten a long zone name in a time range, and drop an offset name such as `GMT-5`. - [Bugzilla 1998020](https://bugzilla.mozilla.org/show_bug.cgi?id=1998020): Firefox accepts a diff --git a/apps/dox/src/data/gmt-stats.json b/apps/dox/src/data/gmt-stats.json index 809defbdf..8f2d32365 100644 --- a/apps/dox/src/data/gmt-stats.json +++ b/apps/dox/src/data/gmt-stats.json @@ -1,8 +1,8 @@ { "suite": "packages/gmt", - "tests": 75854, - "files": 1001, - "executions": 2275620, + "tests": 76128, + "files": 1015, + "executions": 2283840, "nodes": ["22", "24", "26"], "timezones": 10, "timezoneList": [ diff --git a/apps/dox/src/data/temporal-compat.ts b/apps/dox/src/data/temporal-compat.ts index 1cb210e1f..420f23e0f 100644 --- a/apps/dox/src/data/temporal-compat.ts +++ b/apps/dox/src/data/temporal-compat.ts @@ -265,6 +265,12 @@ const WHAT_BREAKS: Readonly> = { D20: "A month and day with an upper-case ISO calendar tag, such as --12-25[u-ca=ISO8601], which the polyfill refuses", D21: "The current time when a test fakes a clock before 1970, which the polyfill reads one millisecond early, so a clock function can return the previous year, day or second at a boundary", D22: "A length in days or larger measured from a repeated hour, which the polyfill can measure from the wrong pass or refuse, so it can be an hour too long or missing. Where the specification has no value, which also happens after a skipped hour, GMT returns its sentinel", + D23: "Some languages and calendars, among them Scottish Gaelic, Galician, Burmese and Telugu, whose date patterns use the week-of-year year: asking Node or Chrome for the parts of such a date, or of a range, stopped the process with no error to catch", + D24: "Dates in the same languages near the start or end of a year, which every browser prints with the year the week belongs to rather than the calendar year, and with some calendars, such as Buddhist in Telugu, on every day of the year", + D25: "Japanese calendar dates before 1873, which every browser prints in a Japanese era such as Meiji 5 or Taika, where the calendar uses the Gregorian era until the end of 1872", + D26: "Islamic calendar dates before the Hijra (622 CE), which Node and Chrome print as a negative year. They have no name for the era before the Hijra, so GMT returns its empty value there", + D27: "Japanese calendar dates in Japanese with a two-digit year, which every browser prints as 令和6年 where 令和06年 is asked for. The first year of an era stays 元年", + D28: "Chinese and Korean calendar dates with a two-digit year, where the Gregorian year shown beside the cycle year was padded, such as 05 for the year 5", "zoned.A": "Zoned times within a day of the earliest or latest instant Temporal supports", "zoned.B": diff --git a/context/domination/issues/CORE-112.md b/context/domination/issues/CORE-112.md new file mode 100644 index 000000000..62fb283e2 --- /dev/null +++ b/context/domination/issues/CORE-112.md @@ -0,0 +1,31 @@ +# CORE-112 — Core: Some languages' date patterns crash Node and print the wrong year + +**Scope:** GMT never makes the `formatToParts` or `formatRangeToParts` call that stops V8 on a +CLDR pattern with `Y`, and prints the calendar year where such a pattern prints the year a week +belongs to. It also prints the year the specifications give in four more cases the range check +found (D25 to D28). Adds no library function. Lands in #523 with DOX-G9 (#522). Tracked as #524. The +spec is [specs/CORE-112/](../specs/CORE-112/index.md); the defect is +[js-temporal-polyfill-bugs.md § AF](../js-temporal-polyfill-bugs.md#af-some-languages-date-patterns-print-the-week-of-year-year-the-wrong-year-everywhere-and-a-v8-crash-in-formattoparts-engine-and-cldr). + +## Gap + +Some CLDR 48 date patterns use `Y` (UTS #35 Part 4 § 8: the year of the week-of-year) where `y`, +the calendar year, is meant: ak, de-CH, gd, gl, kok, ksh, my, sc and te. CLDR 49 adds de with its +regional variants, kek, ki and pt. ECMA-402 FormatDateTimePattern prints the calendar year. + +1. **Crash (V8, D23).** V8 without commit `0426b0d1045d` aborts in `formatToParts` and + `formatRangeToParts` on a `Y` field: exit 133, no exception (nodejs/node#67076). Every Node + from 22.22.2 to 26.13.0 has it. On `main` (`c7caa75d`) these abort Node 26.12.1: + `formatZonedRange` with `my-u-ca-buddhist` and `timeZoneName: "long"`, through the D16 + carrier's `formatRangeToParts`; and `formatCalendar` with `gl-u-ca-hebrew`, + `gl-u-ca-buddhist` or `gl-u-ca-roc`, through `joinDateTimeConnector`'s `dateStyle: "full"` + parts. +2. **Wrong year (CLDR, D24).** Every engine prints the week-year: gd `Dùbh 2025` for + 2024-12-30, te-u-ca-buddhist `జులై 2026` for 2026-07-01 (2569), gl-u-ca-hebrew `dateStyle: + "full"` 5786 for 1 Tishri 5787. [CLDR-19873](https://unicode-org.atlassian.net/browse/CLDR-19873) + (not ours) reports gl and kek. +3. **Other wrong years (D25 to D28).** Every engine prints a Japanese era for japanese dates before + 1873-01-01, where Intl era/monthCode gives the Gregorian era; V8 prints a negative year for islamic + dates before the Hijra; `ja` japanese `year: "2-digit"` prints `令和6年` for `令和06年`; and chinese + and dangi pad the related year to two digits. [specs/CORE-112/year-printing.md](../specs/CORE-112/year-printing.md) + gives each one's evidence and rule; the bug doc has them as § AG. diff --git a/context/domination/issues/index.md b/context/domination/issues/index.md index cdc5de720..8a2b62436 100644 --- a/context/domination/issues/index.md +++ b/context/domination/issues/index.md @@ -62,3 +62,4 @@ generated by `pnpm deps:sync` from [the tracker](../tracker.md); do not edit it - [CORE-107](CORE-107.md) — A changelog page in Dox, and the You-Dont-Need-Momentjs PR on `/upstream` - [CORE-110](CORE-110.md) — The weekly upgrade check compares each calendar's years with native Temporal - [CORE-111](CORE-111.md) — Public functions call internal cores, never another public function +- [CORE-112](CORE-112.md) — Some languages' date patterns crash Node and print the wrong year diff --git a/context/domination/js-temporal-polyfill-bugs.md b/context/domination/js-temporal-polyfill-bugs.md index d62304b44..30406faae 100644 --- a/context/domination/js-temporal-polyfill-bugs.md +++ b/context/domination/js-temporal-polyfill-bugs.md @@ -13,7 +13,7 @@ GMT's seven reports and two PRs to `fullcalendar/temporal-polyfill`, found by th > merged 2026-09-21. Five tc39 issues (#3327–#3330, #3332) and #3335 are open with no maintainer reply (checked 2026-11-13); #3331 (J) is > closed as answered (the check is intended, see § J). > **Nothing is released**, so no GMT workaround retires: `node scripts/temporal-compat.mjs check` reports -> 25 workarounds, 21 still needed, 1 guard (D10) and 3 out of scope (D17, a Firefox-only defect filed as Bugzilla 2085525, § Q; D18, a polyfill defect only JavaScriptCore shows, § R; and D19, another polyfill defect only JavaScriptCore shows, § U; a Node run cannot judge any of the three). The newest is § AC (D22), fixed on `main`, with its no-value lengths filed as tc39/proposal-temporal#3336, #3311 and #3310; before it come § AB (D21), filed as tc39 #3335, § U (D19) and § R (D18), neither filed yet, with § S and § T, two WebKit engine defects GMT only tags, and § AD, a Node 26 engine defect GMT only tags; § I (D12), fixed on `main` with nothing +> 31 workarounds, 27 still needed, 1 guard (D10) and 3 out of scope (D17, a Firefox-only defect filed as Bugzilla 2085525, § Q; D18, a polyfill defect only JavaScriptCore shows, § R; and D19, another polyfill defect only JavaScriptCore shows, § U; a Node run cannot judge any of the three). The newest are § AG (D25 to D28: other wrong years in formatted text, from ICU and CLDR, with ICU-23341 and ICU-23327 filed by others, the ECMA-402 wording filed as tc39/ecma402#1116, and ours as ICU-23619, ICU-23620 and ICU-23621), then § AF (D23, a V8 crash fixed in V8 `0426b0d1045d` and asked of Node as nodejs/node#67076, and D24, CLDR patterns with `Y`, reported by someone else as CLDR-19873, where our comment adds the rest), then § AC (D22), fixed on `main`, with its no-value lengths filed as tc39/proposal-temporal#3336, #3311 and #3310; before it come § AB (D21), filed as tc39 #3335, § U (D19) and § R (D18), neither filed yet, with § S and § T, two WebKit engine defects GMT only tags, and § AD, a Node 26 engine defect GMT only tags; § I (D12), fixed on `main` with nothing > to file; § K (D13), fixed there only in part, with the rest filed as tc39 #3332; § N (D14), which arrives with the catch-up; > and § O (D15), not filed yet and not fixed on either `main`. A, B, C and D are verified on production builds of js-temporal `main` `c8f344c`. > See "Filed" for the list, **"TODO — after PR #253" for what to pick up next**, and "Corrections and @@ -38,6 +38,12 @@ is 0.5.1, and the latest ICU4C release is 78.3. | `D20`: `PlainMonthDay.from` rejects an upper-case `iso8601` calendar annotation (§ V) | tc39 `385b479bf8` | A js-temporal rebase and a release | | `D21`: `Temporal.Now` reads a millisecond early after a pre-1970 clock reading (§ AB) | None. Filed as tc39 #3335 | A tc39 fix, the js-temporal rebase and a release, so the `D21` canary repro passes | | `D22`: a length in days or larger is measured from the wrong pass of a repeated hour (§ AC) | js-temporal `3c403686d39` | tc39 #3319 in the same release, or `P7D` with `largestUnit: "week"` regresses to `P1W1D`. A release that still strips the Asserts of tc39/proposal-temporal#3336, #3311 and #3310 keeps GMT's gate | +| `D23`: V8 stops the process in `formatToParts` and `formatRangeToParts` on a pattern with `Y` (§ AF) | Not a polyfill fix. V8 `0426b0d1045d`, in Chromium 158 | A Node release on every line GMT supports that takes `0426b0d1045d` (nodejs/node#67076), as GMT's `engines.node` floor: the `D23` repro passes in `pnpm compat` and in the weekly `temporal-compat-chromium` verdict. V8 is the only engine in D23's scope | +| `D24`: some languages print the year of the week-of-year for the calendar year (§ AF) | Not a polyfill fix, and not fixed on CLDR `main` | CLDR-19873 fixed for every pattern on `main` (CLDR 49 adds de, kek, ki and pt), a CLDR and ICU release with it, and engines that ship that ICU: every `D24` repro passes in every compat verdict, and the weekly `scripts/canary/weekYear.mjs` sweep flags nothing | +| `D25`: the japanese calendar prints Japanese eras before 1873-01-01 (§ AG) | Not a polyfill fix. ICU-23341, fixed for ICU 79.1, for the eras before Meiji | An ICU release with ICU-23341 and with the Gregorian era for Meiji 1 to 5, as ICU4X has (ICU-23619, open), in engines GMT supports: both `D25` repros pass in every compat verdict | +| `D26`: islamic calendars print a negative year before the Hijra (§ AG) | Not a polyfill fix. ICU-23327 is open | An ICU release that gives the `bh` era a name, in engines GMT supports: the `D26` repro passes in every compat verdict | +| `D27`: `ja` japanese `year: "2-digit"` leaves the era year unpadded (§ AG) | Not a polyfill fix. ICU-23620 is open | An ICU release whose `jpanyear` numbering keeps the minimum digit count: the `D27` repro passes in every compat verdict | +| `D28`: chinese and dangi pad the related year under `year: "2-digit"` (§ AG) | Not a polyfill fix. ICU-23621 is open: ICU's pattern generator turns `yy` into `rr` | Engines that print `relatedYear` at full width: the `D28` repro passes in every compat verdict | | `D5`: Indian calendar before ISO year 1 | js-temporal `8de299a` (PR #361; `b6c9844` on its branch) | Nothing | | `D6`: non-ISO `until` re-constrains the day | js-temporal `10aeb98` | `D7`. With `10aeb98` and `1c64f14` alone one Hebrew `until` by years is still wrong (Corrections, item 3). `main` since `853fc8b` also has tc39/proposal-temporal#3327 problem 1, which the `D6.cachedDay` probes catch | | `D7`: Hebrew `until` by years throws | js-temporal `1c64f14` (PR #361; `79fb327` on its branch) | The `CompareSurpasses` part of tc39 `196a3191` (C-D7b). js-temporal `main` took all of `196a3191` in `853fc8b`, months-loop hunk included, so it also carries tc39/proposal-temporal#3327 problem 1. Whether `D7.leapMonthEnd` passes on `main` is unverified (no build) | @@ -2904,3 +2910,130 @@ The other legacy ids work in the same WebKit on macOS: `CET`, `EET`, `MET`, `WET Why I think the four ids are valid: the time zone database release 2026e, in its file `backward`, defines them as zones: `Zone EST5EDT -5:00 USback E%sT`, `Zone CST6CDT -6:00 USback C%sT`, `Zone MST7MDT -7:00 USback M%sT` and `Zone PST8PDT -8:00 USback P%sT`. ECMA-402 section 6.5 (Use of the IANA Time Zone Database) says that each Zone in the IANA Time Zone Database must be a primary time zone identifier, so these four should be accepted and `Temporal` should treat them as named zones. What I expected: the same results as in Chromium, Firefox and Node, for example `new Intl.DateTimeFormat("en", { timeZone: "EST5EDT" }).resolvedOptions().timeZone` returns `"EST5EDT"`. + +## AF. Some languages' date patterns print the week-of-year year: the wrong year everywhere, and a V8 crash in `formatToParts` (engine and CLDR) + +### Status + +Two defects with one cause, so GMT guards them as two groups that can retire on different days. + +- **D23, the crash (V8).** **Filed** as [nodejs/node#67076](https://github.com/nodejs/node/issues/67076) + (2026-10-28, open, no reply as of 2026-11-13). It asks v22.x, v24.x and v26.x to take V8 commit + `0426b0d1045d` ("[intl] Handle UDAT_YEAR_WOY_FIELD in IcuDateFieldIdToDateType", 2026-09-01). Chromium 158 + has it. Every installed Node aborts: 22.22.2, 24.19.0, 24.21.0, 26.8.2, 26.10.0, 26.12.1 and 26.13.0, all + with CLDR 48.0. +- **D24, the wrong year (CLDR data).** [CLDR-19873](https://unicode-org.atlassian.net/browse/CLDR-19873) + (not ours, 2026-10-20, open) reports gl and kek. [Our comment](https://unicode-org.atlassian.net/browse/CLDR-19873?focusedCommentId=213171) + (2026-11-13) adds the other patterns on `main`, the gd and te repros and the D23 crash. CLDR 48 has `Y` in ak, de-CH, gd, gl, kok, ksh, my, sc and te; CLDR 49 and `main` (`c0b65ae356`) + keep them and add de with its regional variants, kek, ki and pt. Every engine that ships CLDR 48 prints it: + Node, Chromium 158 with the fix above, and WebKit 26.6. **Not a polyfill defect**: the polyfill's + `toLocaleString` and GMT both format through the host's `Intl.DateTimeFormat`. + +### What goes wrong + +UTS #35 Part 4 (Dates) § 8, the Date Field Symbol Table, gives `y` as the calendar year and `Y` as the year +of the week-of-year, which differs from the calendar year in the days around the year's end. Some CLDR 48 +patterns use `Y` where `y` is meant. ECMA-402 has no week-year field: FormatDateTimePattern prints the +`[[Year]]` of the date (the era year when the pattern has an era), `numeric` with no grouping and no +padding, `2-digit` as the last two digits, with the part type `year`. + +1. **The wrong year, on every engine.** `format`, `formatToParts` (where it does not crash), `formatRange` + and `formatRangeToParts` print the week-year. In the Gregorian calendar that is wrong only near the + year's end. In a calendar whose year does not start on 1 January, such as Buddhist, Japanese or ROC, the + pattern prints the Gregorian week-year all year, so the year is wrong on every day. WebKit gives the + part the type `unknown`. +2. **The crash, on V8 without `0426b0d1045d`.** V8 maps each ICU field to a part type and has no case for + `UDAT_YEAR_WOY_FIELD`, so `formatToParts` and `formatRangeToParts` reach `UNREACHABLE()`: the process + stops with `Fatal error … unreachable code`, signal SIGTRAP, exit code 133. No exception is thrown and + nothing can catch it. `format` and `formatRange` do not crash. The same V8 also drops `year` from + `resolvedOptions()` for such a pattern; the fix keeps it, which is the signal GMT reads. + +### Repro (Node 26.12.1, V8 14.6.202.34-node.40, ICU 78.3, CLDR 48.0; expected values from ECMA-402 and Temporal `eraYear ?? year`) + +`utc` is `{ timeZone: "UTC" }`. + +| Call | Node 26 | Expected | +| ---- | ------- | -------- | +| `new Intl.DateTimeFormat("gd", { year: "numeric", month: "short", ...utc }).format(new Date("2024-12-30"))` | `Dùbh 2025` | `Dùbh 2024` | +| the same formatter's `resolvedOptions().year` | `undefined` | `"numeric"` | +| the same formatter's `formatToParts(new Date("2024-12-30"))` | aborts, exit 133 | a `year` part `2024` | +| `new Intl.DateTimeFormat("te-u-ca-buddhist", { year: "numeric", month: "long", ...utc }).format(new Date("2026-07-01"))` | `జులై 2026` | `జులై 2569` | +| `new Intl.DateTimeFormat("gl-u-ca-hebrew", { dateStyle: "full", ...utc }).format(new Date("2026-09-12"))` | `sábado, 1 de Tishri de 5786 AM` | `5787` as the year | +| the same formatter's `formatToParts(…)` | aborts, exit 133 | parts with a `year` part `5787` | + +### Effect on GMT + +Shipped GMT aborts Node through two internal parts calls: `formatZonedRange` with `my-u-ca-buddhist` and a +`long` zone name (the D16 carrier's `formatRangeToParts`), and `formatCalendar` with `gl-u-ca-hebrew`, +`gl-u-ca-buddhist` or `gl-u-ca-roc` (the `dateStyle: "full"` parts in `joinDateTimeConnector`). Every format +function also prints the week-year. CORE-112 fixes both: + +- `internal/weekYearGuard.ts` checks each formatter once, when `formatterCache` builds it, using only + `format` and `resolvedOptions`. A formatter that passes is returned as it is. A flagged one prints the + calendar year the ECMA-402 way, and never calls a parts method that could abort. +- Range text gets its own check, because an interval pattern is not the single pattern: on a + formatter's first range call, `format` and `formatRange` probes find a year run that is not the + calendar year, and a flagged formatter's range text has that run rewritten. No range parts call + is made for it. +- D16 repairs the range string from `formatRange`; no range parts call can reach V8. D17 keeps its parts + merge, which only SpiderMonkey reaches. +- The canary groups D23 and D24 retire the code: D23 when every V8 GMT supports has `0426b0d1045d`, D24 when + CLDR prints `y` (which also ends D23). `scripts/canary/weekYear.mjs` sweeps every CLDR locale weekly, so a + new `Y` pattern is found before a user meets it. + +## AG. Other wrong years in formatted text: japanese before 1873, islamic before the Hijra, and 2-digit years (engine, ICU and CLDR) + +### Status + +Four defects found by the CORE-112 range sweep, which compared every year a range prints with Temporal's +calendar year. None is a polyfill defect: GMT and the polyfill's `toLocaleString` both format through the +host's `Intl.DateTimeFormat`. Each reaches GMT's format functions, in single dates and in ranges, on Node +22.22.2, 24.21.0, 26.12.1 and 26.13.0 (ICU 78.2 and 78.3, CLDR 48), Chromium 153 and WebKit 26.6, except +where a row says otherwise. Each is its own canary group, and the spec is +[specs/CORE-112/year-printing.md](specs/CORE-112/year-printing.md). + +- **D25, japanese before 1873 (ICU, CLDR).** [ICU-23341](https://unicode-org.atlassian.net/browse/ICU-23341) + (not ours) is fixed for ICU 79.1, which is not released: with CLDR 49 dropping the eras before Meiji + (CLDR-11400), ICU 79 prints the Gregorian era before Meiji. CLDR 49 still starts Meiji on 1868-10-23, so + ICU 79 keeps Meiji 1 to 5 for 1868-10-23 to 1872-12-31, where ICU4X prints the Gregorian era in code. + Filed as [ICU-23619](https://unicode-org.atlassian.net/browse/ICU-23619) (2026-11-14, open). +- **D26, islamic before the Hijra (ICU).** [ICU-23327](https://unicode-org.atlassian.net/browse/ICU-23327) + (not ours, open). WebKit is right (`643 Before Hijra`, WebKit 321713). +- **D27, `ja` japanese `year: "2-digit"` (ICU).** ICU-20441 gives `ja` with the japanese calendar the + `jpanyear` numbering whenever the pattern holds 年, and `jpanyear` ignores the minimum digit count. Filed + as [ICU-23620](https://unicode-org.atlassian.net/browse/ICU-23620) (2026-11-14, open). +- **D28, chinese and dangi related year under `year: "2-digit"` (ICU).** ICU's pattern generator turns a + `yy` skeleton into `rr`, a padded related year, where ECMA-402 prints the related year at full width. + Filed as [ICU-23621](https://unicode-org.atlassian.net/browse/ICU-23621) (2026-11-14, open). + +### What goes wrong + +| Call (`utc` is `{ timeZone: "UTC" }`) | Node 26.12.1 | Expected | Source of the expected value | +| ---- | ------- | -------- | ---- | +| `new Intl.DateTimeFormat("en-u-ca-japanese", { era: "short", year: "numeric", ...utc }).format(new Date("-000001-07-10"))` | `-645 Taika (645–650)` | `2 BC` | Intl era/monthCode Table 2, amended by [tc39/proposal-intl-era-monthcode#86](https://github.com/tc39/proposal-intl-era-monthcode/issues/86) (TG2 2026-01-08; test262 tc39/test262#4877, merged): Gregorian eras up to and including 1872-12-31 | +| the same formatter at `1872-12-31` | `5 Meiji` | `1872 AD` | the same | +| `new Intl.DateTimeFormat("en-u-ca-islamic-civil", { era: "short", year: "numeric", ...utc }).format(new Date("0600-07-10"))` | `-22 AH` | the year in the `bh` era | Intl era/monthCode Table 2 and § 4.1.12; test262 `intl402/DateTimeFormat/prototype/formatToParts/era.js` requires ISO 600 and 2025 to print different era names | +| `new Intl.DateTimeFormat("ja-u-ca-japanese", { year: "2-digit", ...utc }).format(new Date("2024-07-10"))` | `令和6年` | `令和06年` | ECMA-402 FormatDateTimePattern: a `2-digit` year is FormatNumeric with `minimumIntegerDigits` 2 | +| `new Intl.DateTimeFormat("en-u-ca-chinese", { year: "2-digit", ...utc }).format(new Date("0005-07-10"))` | `05(yi-chou)` | `5(yi-chou)` | ECMA-402 FormatDateTimePattern: `relatedYear` is FormatNumeric at full width, with no 2-digit form | + +Not defects: indian `-79 Śaka` and persian `-622 AP` at ISO year −1. Table 2 gives each calendar a single +era with a signed era year, and native Temporal gives `eraYear` −79 and −622 on all three engines. +ECMA-402 FormatDateTimePattern's "If partType is "year" and value ≤ 0, set value to 1 − value" fits only +a calendar with an inverse era. Filed as [tc39/ecma402#1116](https://github.com/tc39/ecma402/issues/1116) +(2026-11-14, open). + +### Effect on GMT + +`internal/yearPrinting.ts` wraps a formatter only when its defect's probe fails and the formatter can show +it (its calendar, locale and options). Every replacement text is the engine's own; GMT owns no era or +numbering data. + +- **D25:** a date before 1873-01-01 is formatted through a `calendar: "gregory"` twin. A range with + either end before 1873 prints wholly through the twin, so it stays in one calendar. +- **D26 (owner decision):** a pre-Hijra date formats to the house empty value: `""` for text and ranges, + `[]` for parts. No wrong year is printed and no era name is owned. D18 (§ R) keeps the engine's own + parts through `guardedDateTimeFormat`. +- **D27 (owner decision):** a one-digit era year is padded with the zero of the formatter's own numbering + system. 元年 stays, as CLDR's `ja` data has it. +- **D28:** a chinese or dangi `year: "2-digit"` formatter is built with `year: "numeric"`, the same + pattern at full width. diff --git a/context/domination/specs/CORE-112/call-sites.md b/context/domination/specs/CORE-112/call-sites.md new file mode 100644 index 000000000..4e656460a --- /dev/null +++ b/context/domination/specs/CORE-112/call-sites.md @@ -0,0 +1,54 @@ +# CORE-112 slice 4 — call sites and the source rule + +Read with [index.md](./index.md). With slice 1's hook in `formatterCache.construct`, every +formatter built through `cachedFormatter("DateTimeFormat", …)` is guarded, cached or not. This +slice makes that the only way library code builds one, and fixes the range call. + +## Every parts and range call in `packages/gmt/src` (tests excluded) + +| Site | Call | Can hold `Y`? | Change | +| --- | --- | --- | --- | +| `plain/format/formatDateToParts.ts:94` | `formatToParts` | yes, caller options | none: guarded through the cache | +| `plain/format/formatDateTimeToParts.ts:100` | `formatToParts` | yes | none | +| `zoned/format/formatZonedToParts.ts:97` | `formatToParts` | yes | none | +| `internal/joinDateTimeConnector.ts:63`, `:77` | `formatToParts`, `dateStyle: "full"` (+ `timeStyle`) | **yes: aborts today** (`formatCalendar`, gl-u-ca-hebrew / buddhist / roc) | none: guarded; synthesis path B (dateStyle) | +| `internal/plainFormatOptions.ts:104` (`dateStyleWidths`) | `formatToParts`, `dateStyle`, gregory, latn | yes (dateStyle) | none: guarded | +| `internal/localeNames.ts:70` (`eraNamesFor`) | `formatToParts`, era only | year by defaults | none: guarded (0 of 1,986 flagged) | +| `internal/localeNames.ts:96` (`meridiemsFor`) | `formatToParts`, hour | no (step 0) | none | +| `internal/localeMonthNames.ts:63` | `formatToParts`, month + day | no (step 0) | none | +| `zoned/format/formatTimeZoneName.ts:108` | `formatToParts`, hour + zone | no (step 0) | none | +| `internal/temporalCompat/islamicEra.ts:28`, `:42` | own `new Intl.DateTimeFormat("en-u-ca-…", { era, year, month, day })` + `formatToParts` | not in `en` today | **build through `cachedFormatter`** so the guard covers it; keep the per-calendar `Map` only if `cachedFormatter`'s cap could evict it on a hot path (measure; else delete the `Map`) | +| `zoned/format/formatZonedRange.ts:34–40` | `formatToParts` ×4, `formatRangeToParts` | **yes: aborts today** (my-u-ca-buddhist) | D16 → [range.md](./range.md) 3a; D17 branch unchanged (3b) | +| `plain/format/formatDateRange.ts:66`, `formatDateTimeRange.ts:69`, `zoned/format/formatZonedRange.ts:150` | `formatRange` | wrong year, never aborts | `formatRangeChecked` (`internal/weekYearRange.ts`): `formatRange` text only, the year repair (3c) | +| `internal/temporalCompat/probeRepros.ts:748–794` | D16/D17 probes, `"en"`, no year | no | none; listed in the source rule's allow list | +| `internal/resolveLocale.ts:37` | `new Intl.DateTimeFormat()` for `resolvedOptions().locale` | no format call | none; allow list | +| `internal/plainFormatOptions.ts:331` | JSDoc "V8 before 15.5 traps" | — | reword: "V8 without commit `0426b0d1045d` aborts (defect D23)"; the version number is unverified and the canary owns it | + +`format` calls on cached formatters need no change: a guarded formatter's `format` repairs the +year; a dormant one is the native formatter. + +## Source rule (new test) + +`packages/gmt/src/internal/temporalCompat/weekYearSource.test.ts`, reading every non-test `.ts` +file under `packages/gmt/src`: + +1. `new Intl.DateTimeFormat(` appears only in `internal/formatterCache.ts`, + `internal/weekYearGuard.ts` (twin and reference), `internal/resolveLocale.ts` and + `internal/temporalCompat/probeRepros.ts`. +2. `formatRangeToParts(` appears only in `internal/temporalCompat/probeRepros.ts` and in the D17 + branch of `zoned/format/formatZonedRange.ts` (one occurrence there). +3. `weekYearGuard` is imported only by `internal/formatterCache.ts` and `weekYearSynth` + (isolation: retiring D23 deletes two files and one line). + +Each rule names the file and line it found in its failure message. Comments and JSDoc are skipped +(strip `//…` and `/* … */` before matching). + +## Edge cases for tests + +- `formatCalendar("2026-07-01T10:00:00", "gl-u-ca-hebrew", { reference: "2026-07-01T09:00:00" })` + returns a string in a child process on Node 26.12.1 (today: exit 133). +- `formatDateToParts("2024-12-30", "gd", { year: "numeric", month: "short" })` returns + `[{ type: "month", value: "Dùbh" }, { type: "literal", value: " " }, { type: "year", value: "2024" }]`. +- `formatYearMonth` with `{ dateStyle: "full" }` in gl (the `dateStyleWidths` path) returns a + string, no abort. +- The islamicEra reads keep their values on every engine (existing D18 rows pass unchanged). diff --git a/context/domination/specs/CORE-112/canary-and-docs.md b/context/domination/specs/CORE-112/canary-and-docs.md new file mode 100644 index 000000000..8c8ad1e07 --- /dev/null +++ b/context/domination/specs/CORE-112/canary-and-docs.md @@ -0,0 +1,126 @@ +# CORE-112 slice 5 — canary groups, upstream row, docs, changeset, budget + +Read with [index.md](./index.md). Two guard groups, because the two defects end on different days: + +| Group | Defect | Engines | Upstream | Removing it deletes | +| --- | --- | --- | --- | --- | +| **D23** | `formatToParts` / `formatRangeToParts` abort on a `Y` field | `v8` (Node, Chromium) | nodejs/node#67076 (V8 `0426b0d1045d`) | `weekYearSynth.ts`, guard step 2 and path B: flagged formatters take path A (native parts, year patched) everywhere | +| **D24** | CLDR `Y` where `y` is meant: the week-year printed | every engine | CLDR ticket (owner question 2) | `weekYearGuard.ts`, its `construct` line, slice 2, the source rule's guard clause | + +D24 gone means no `Y` pattern, so D23 cannot fire either: removing D24 removes both. D23 can go +first (a fixed V8 at the `engines.node` floor and in every Chromium the native suite runs). + +## `repros.ts` + +```ts +/** Engine and CLDR defects the canary reads without a probe in `probeRepros.ts` (CORE-112). */ +export type CanaryDefectId = "D23" | "D24"; +``` + +Add it to `Repro.defect`'s union. Repro inputs are the recorded failing cases, as for every other +group (no locale list): gd `{ year: "numeric", month: "short" }`, ksh `{ year: "numeric", +month: "numeric" }`, sc `{ year: "numeric", month: "numeric" }`, te-u-ca-buddhist `{ year: +"numeric", month: "long" }`, my-u-ca-japanese `{ year, month, day: "numeric" }`, +gl-u-ca-hebrew `{ dateStyle: "full" }`, de-CH gregory `{ era: "short", year, month, day, +weekday: "short" }`, all `timeZone: "UTC"`. + +- **D24 repro** (in process, every engine, `format` only): each input at its trap date prints the + Temporal-derived calendar year ([tests.md](./tests.md) values). Passes when the native text is + already right. +- **D23 repro** (never calls parts in a browser or in the checking process): + - Find a live `Y` formatter: an input whose D24 repro fails (its year is the week-year). + None → D23 reports *removable* (no `Y` left to abort on). + - Crash-free reading: that formatter (component options) reports `resolvedOptions().year` + → the engine reads `Y` as a year (fixed V8, or not V8). `undefined` → still aborts. + - Node only, confirmation: `child_process.spawnSync(process.execPath, ["-e", ])`; + exit 133 → fails, exit 0 with a `"year"` part → passes. The two readings must agree, else the + check exits non-zero (a signal GMT relies on has changed). + - `process.versions.v8` is printed beside the verdict for the report, never decides it. + +## `scripts/upstream.mjs` + +- `REPOS` gains `"nodejs/node"`. +- `knownGuards()` regex: `/export type (?:DefectId|ZonedDefectId|BoundedWorkDefectId|CanaryDefectId) =([^;]+);/g`; + update its JSDoc line to name the fourth union. +- `apps/dox/src/data/upstream-filings.json`: the nodejs/node#67076 row with `"gmtGuard": "D23"` + and a hand-written `summary` in plain English ("Formatting some dates in Burmese, Galician, + Scottish Gaelic and a few other languages into parts stops Node with a crash…"), `work`, `role` + per the existing rules for a filing found by discovery. Run `node scripts/upstream.mjs` to fill + the fetched fields; do not hand-write them. + +## `scripts/lib/workarounds.mjs` + +Two entries after D22, shaped like D16/D17: + +- D23: `engines: ["v8"]`; title `D23 — formatToParts aborts V8 on a week-of-year year field + (nodejs/node#67076)`; trigger: every V8 the check reads (Node at the `engines.node` floor, and + the temporal-compat-chromium verdict) reports D23 removable; steps: delete `weekYearSynth.ts`, + guard step 2 and path B, keep every expected-value row; `Full wording: … § Removal steps 23.` +- D24: no `engines`; title `D24 — CLDR patterns print the week-of-year year where the calendar year + is meant`; trigger: every engine's compat verdict reports D24 removable *and* the weekly sweep + below flags nothing; steps: delete `weekYearGuard.ts`, `weekYearSynth.ts`, the `construct` + hook and the source rule's guard clause; keep every expected-value row (they are ECMA-402's). + +## `scripts/canary/weekYear.mjs` (new, weekly, Node) + +The recorded inputs cannot see a new locale's `Y`. The weekly sweep can: the locale list is the +directory listing of the `cldr-dates-full` package for the CLDR version the engine reports +(`process.versions.cldr`), fetched at run time with `npm pack` into a temporary directory, never a +dependency and never shipped, filtered by `Intl.DateTimeFormat.supportedLocalesOf`. For every +locale × `Intl.supportedValuesOf("calendar")` × the 30 option sets of the validation plus the +synthesis twin shapes ([single-repair.md](./single-repair.md) step 1): + +1. In process, `format` only: the guard's verdict; a repaired `format` that keeps the digit-run + count (slice 2 step 2); synthesis non-null and its parts joined equal to the repaired text. +2. Child processes, batched (one per locale): native `formatToParts` on every unflagged formatter + and every twin shape — any exit 133 is a guard false negative and fails the run. + +Output: counts per group, every failing case, `process.versions`. Exit non-zero on any failure. +Matrix: the CI Node versions (22 floor, 24, 26). + +## `packages/gmt/src/internal/temporalCompat/README.md` + +- Defect table: rows **D23** and **D24** after D22, in the existing column shape (defect, + where it is fixed, when it fires). D23 text names the abort, the V8 commit, the crash signal and + the source rule; D24 names the CLDR patterns, the text verdict and the ECMA-402 expected value. +- § Removal triggers: one row each, wording as in `workarounds.mjs`. +- § Removal steps: 23 and 24, as above, with "keep every expected-value row". + +## Bug doc + +`context/domination/js-temporal-polyfill-bugs.md` gains **§ AF. Some languages' date patterns use +the week-of-year year: wrong year everywhere, and a V8 crash in `formatToParts` (engine and CLDR)**, +after § AE, in the shape of § AD/AE: what happens, smallest repro (gd 2024-12-30, and the +my-u-ca-buddhist range), affected engines and versions measured, the spec text that decides the +right value (UTS #35 `y`/`Y`; ECMA-402 FormatDateTimePattern), the upstream links (nodejs/node#67076, +V8 `0426b0d1045d`, the CLDR ticket when filed) and the GMT guards (D23, D24). + +## Changeset — `.changeset/core-112-week-year.md` + +```md +--- +"@northguild/gmt": patch +--- + +Formatting no longer stops Node with a crash, and prints the right year, for languages whose date +patterns print the week-of-year year instead of the calendar year. `formatZonedRange`, +`formatCalendar` and the `…ToParts` functions crashed Node 22, 24 and 26 for some languages and +calendars (for example Burmese with the Buddhist calendar, and Galician with the Hebrew, Buddhist +or ROC calendar and a full date style). Every format function also printed the wrong year near the +start or end of a year, or all year in the Buddhist, Japanese and ROC calendars: Scottish Gaelic +printed `Dùbh 2025` for 30 December 2024, and now prints `Dùbh 2024`. +``` + +The `/changelog` skill polishes it at finalize time. + +## READMEs + +The landing READMEs get no section (house rule: no per-fix sections). The guide that documents +locale formatting (`apps/dox/src/content/docs/…` where `formatDate` is documented) gets one +sentence under its compatibility notes; `dox: none` stands because no tool changes. + +## Bundle budget + +`scripts/bundle-size.budgets.json` `entries.root.minified`: raise by the measured growth of the +guard and synthesis in one reviewed edit (owner question 7). Measure after slices 1–4 with the +repo's bundle-size script in the worktree (never a build in the main checkout). diff --git a/context/domination/specs/CORE-112/guard.md b/context/domination/specs/CORE-112/guard.md new file mode 100644 index 000000000..7b5f66945 --- /dev/null +++ b/context/domination/specs/CORE-112/guard.md @@ -0,0 +1,150 @@ +# CORE-112 slice 1 — the guard: verdict, proof, cache, hook + +Read with [index.md](./index.md). New module `packages/gmt/src/internal/weekYearGuard.ts`. It is the +only place in `src` that knows about `Y`; deleting it (and its hook line) retires the workaround. + +## Signature + +```ts +/** + * The formatter itself when its pattern cannot print a week-of-year year (defect D23), else a + * formatter whose year is the calendar year and whose parts never reach the engine's `Y` field. + */ +export function guardDateTimeFormat( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, +): Intl.DateTimeFormat; +``` + +Called once per construction, from `formatterCache.ts` `construct` only: + +```ts +case "DateTimeFormat": + return guardDateTimeFormat(new Intl.DateTimeFormat(locale, options), options); +``` + +`construct` runs for cached and uncacheable keys alike, so both paths are guarded. + +## Step 0 — does the formatter print a year? (zero cost when not) + +Dormant, with no further call, unless one of these holds (ECMA-402 CreateDateTimeFormat, the +`needDefaults` step with required ~any~ and defaults ~date~: `era` is not one of the fields it +checks, so `{ era }` alone gets year, month and day): + +- `options.year !== undefined`; +- `options.dateStyle !== undefined`; +- none of `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, + `fractionalSecondDigits`, `dateStyle`, `timeStyle` is present (the defaults add a year). + +Time-only, month-day and weekday formatters stop here. Their single patterns never held `Y` in the +validation (0 of 317,760 aborts outside this gate); their *range* patterns can, which is why no +range parts call is made anywhere ([range.md](./range.md)). + +## Step 1 — the verdict cache + +Key: `${ro.locale}|${ro.calendar}|${ro.numberingSystem}|${ro.hourCycle ?? ""}|` plus the options' +plain entries minus `timeZone`, `locale`-free (reuse `plainOptionEntries` from `formatterCache.ts`). +The zone is left out on purpose: a zone moves the instant, never the pattern. The key uses the +resolved locale, so a default-locale formatter (uncacheable in `formatterCache`) still reuses its +verdict. Bounded at `MAX_ENTRIES_PER_KIND` (clear when full) and cleared with the formatter cache +when `Intl.DateTimeFormat` is replaced (`forgetIfReplaced`). The verdict value holds the +*analysis* (below), so slice 2 never recomputes it. + +## Step 2 — crash signal (unfixed V8 only, exact) + +```text +crashes = options.dateStyle === undefined + && ro.year === undefined + && ro.calendar !== "chinese" && ro.calendar !== "dangi" +``` + +Why exact: unfixed V8's `BuildPatternItems` has no entry for `Y`, so a pattern with `Y` resolves +without `year`; the fix (`0426b0d1045d`) adds `Y` and `YY` there in the same commit that maps +`UDAT_YEAR_WOY_FIELD`. A step-0 formatter without +`dateStyle` always has a year field in its pattern (the request or the defaults put one there), so +a missing `year` means a letter V8 does not list: `Y`, or `r`/`U` in the two cyclic calendars, +which V8 handles in parts and which never abort. Fixed V8, SpiderMonkey and JavaScriptCore report +`year` for `Y`, so the signal never fires there. Measured: 81/81 component-option aborts, FP 0, +FN 0 over 233,024 cases. It is blind to `dateStyle` (resolvedOptions has no field members then): +24 of the 105 aborts are `dateStyle` and step 3 finds them. + +## Step 3 — text verdict (every engine; the data defect) + +Calls only `format`, on the formatter or a twin. Prototype: +`/woy/detector6.mjs` (`verdict`), `detector.mjs` (`digitRuns`). + +1. **Twin.** When the options carry a time field (`hour`, `minute`, `second`, + `fractionalSecondDigits`, `dayPeriod`, `timeZoneName`, `timeStyle`) or `ro.timeZone` is not + `UTC`, build `new Intl.DateTimeFormat(ro.locale, { calendar, numberingSystem, timeZone: "UTC", + ...the options' era, year, month, day, weekday, dateStyle })` directly (not through the cache: + no recursion). Else use the formatter. The twin keeps the date pattern and drops digit runs + that would move with the time. +2. **Reference.** Per `calendar|numberingSystem`, cached: `new Intl.DateTimeFormat("und", + { calendar, numberingSystem, year: "numeric", timeZone: "UTC" })`, and the digit set + `new Intl.NumberFormat("und", { numberingSystem, useGrouping: false }).format(1234567890)` + plus `\p{Nd}`. Its single digit run at a date is the calendar's year as ICU counts it. +3. **Digit runs** of a text: maximal runs of those digits, walked by code point (Chakma, Adlam + and other digits lie outside the BMP). +4. **Year runs `J`.** `y0` = the calendar year of 2024-07-01 (Temporal `withCalendar(cal).year`). + `m0` = month 1 day 15 of `y0`; `b` = `m0 + 7 days`; `c` = month 1 day 15 of the first year in + `y0+1 … y0+14` whose weekday equals `m0`'s. A run index is in `J` when its text is equal at + `m0` and `b` and different at `c`. Equal weekdays keep a weekday name with digits ("J4" in luy) + out of `J`. Different run counts at the three dates → `clean` (shape); `J` empty → `clean`. +5. **Boundaries.** For `y` in `y0+1 … y0+3`: `d1` = the reference's first day of `y` (start at + Temporal month 1 day 1, step at most 4 days until the reference year changes between `d1 - 1` + and `d1`); `L = d1 - 1 day`. Check `d1` against `d1 + 14 days` and `L` against `L - 14 days`. +6. **Check.** Every `J` run's text at the boundary date must equal its text at the inside date, + *unless* the inside text holds the reference year in full or as its last two digits and is + longer than that (a year glued to another number): then the boundary run must contain the + boundary date's reference year in the same form. Any failure → `flagged` (with that date). + +Cost: about 27 `format` calls, 0.18 ms per new key on Node 26.12.1 (owner question 6 in +[index.md](./index.md)). + +### Proof sketch — every `Y` year run fails step 6, no `y` run does + +- *No false flag.* A `y` run is the calendar year, constant from `d1` to `d1 + 14` and from + `L - 14` to `L`, because `d1` is the reference's own year start (same ICU calendar). The glued + case compares the year inside the run with the reference year at the same date. So a `y` + pattern never fails. +- *Every `Y` is found.* UTS #35 defines `Y` by weeks: week 1 is the first week (starting on the + locale's first day `F`) with at least `minDays` days in the year. The week holding the year + boundary is given wholly to one year, so `Y ≠ y` at `L` or at `d1` unless the year starts on + `F` (UTS #35 Part 4 §8, `Y` and `w`). That week lies within 6 days of the boundary, so the + points 14 days inside are outside it and print `y`; the boundary run therefore differs from the + inside run. Of three consecutive year starts, at most two share a weekday: Gregorian-length + years move it 1 or 2 days; a Hebrew year of 385 days moves it 0, but leap years are never + adjacent in the 19-year cycle. So at least one of the three years fails. +- *Buddhist, Japanese, ROC.* ICU prints the Gregorian week-year there all year. Their years start + on 1 January as the Gregorian year does, so the same straddling week makes the run jump at `L` + or `d1`; the argument above holds with the Gregorian week-year in place of `Y`. +- *What the proof leaves out*, closed by measurement: a pattern whose digit-run count changes + between the three dates of step 4 (returns `clean`). 0 cases in 317,760; the data canary fails + on any (slice 5). + +## Step 4 — what the guard returns + +| Crash signal | Text verdict | Returns | +| --- | --- | --- | +| off | clean | the native formatter, unchanged (dormant) | +| any | flagged | a guarded formatter ([single-repair.md](./single-repair.md)) | +| on | clean | a guarded formatter whose `format` and `formatRange` are native and whose parts are synthesised (not seen in the population; the guard still never lets parts reach a `Y` field) | + +The guarded formatter is a plain object built once per verdict, typed `Intl.DateTimeFormat`: +`format`, `formatToParts`, `formatRange` and `resolvedOptions` as in slice 2; +`formatRangeToParts` throws `TypeError` (no library code calls it, slice 4's source test). +`resolvedOptions()` returns the native object, and for component options without `year` adds +`year: "numeric"` or `"2-digit"` from the run style, since ECMA-402 resolvedOptions reports the +pattern's year field and GMT now prints one in that form. + +## Edge cases for tests (values in [tests.md](./tests.md)) + +- A step-0 miss calls neither `resolvedOptions` nor `format` (spy on a stub constructor). +- `gd { year: "numeric", month: "short" }`, `gl-u-ca-hebrew { dateStyle: "full" }`, + `te-u-ca-buddhist { year: "numeric", month: "long" }`: flagged on every engine. +- `en`, `de`, `ja-u-ca-japanese` with the same options: dormant (`===` the native formatter). +- `zh-u-ca-chinese { year: "numeric", month: "long" }`: crash signal off despite no `year`. +- `{ era: "short" }` alone in `de-CH`: step 0 passes (defaults), verdict runs and is clean + (0 of 1,986 era-only Gregorian formatters flagged). +- A default-locale formatter twice: one verdict (spy on the reference constructor). +- Replacing `Intl.DateTimeFormat` clears verdicts. diff --git a/context/domination/specs/CORE-112/index.md b/context/domination/specs/CORE-112/index.md new file mode 100644 index 000000000..2feb43568 --- /dev/null +++ b/context/domination/specs/CORE-112/index.md @@ -0,0 +1,138 @@ +--- +story: CORE-112 +issue: 522 +status: draft +dox: none +--- + +# CORE-112 — Week-year `Y` in ICU patterns: no V8 abort, the calendar year printed (D23, D24) + +## Scope + +Lands as a phase of PR #523 (DOX-G9, #522). `CORE-*` ids are for `packages/gmt` work and this is +a library fix; `CORE-112` is the next free one ([tracker](../../tracker.md)). No issue file or tracker +row exists yet: see owner question 1. + +Some CLDR 48 patterns use `Y` (year of the week-of-year) where `y` (calendar year) is meant. +Two separate defects follow: + +1. **Abort (engine).** V8 without commit `0426b0d1045d` hits a fatal check in + `formatToParts` and `formatRangeToParts` on a `Y` field: SIGTRAP, exit 133, no exception + (nodejs/node#67076). Every installed Node aborts (22.22.2, 24.19.0, 24.21.0, 26.8.2, 26.10.0, + 26.12.1, 26.13.0; CLDR 48.0); GMT cannot catch it. **Shipped GMT aborts Node today** (worktree + `dist`, Node 26.12.1, exit 133): + - `formatZonedRange("2026-07-01T09:30:00+06:30[Asia/Yangon]", "2026-07-04T09:30:00+06:30[Asia/Yangon]", + "my-u-ca-buddhist", { hour: "numeric", minute: "numeric", timeZoneName: "long" })` — the D16 + carrier's `formatRangeToParts`; + - `formatCalendar("2026-07-01T10:00:00", "gl-u-ca-hebrew", { reference: "2026-07-01T09:00:00" })` + — `joinDateTimeConnector`'s `dateStyle: "full"` parts (also `-u-ca-buddhist`, `-u-ca-roc`). +2. **Wrong year (data).** Every engine with CLDR 48 data prints the week-year, in `format` and + `formatRange` alike: gd `Dùbh 2025` for 2024-12-30, te-u-ca-buddhist `జులై 2026` for 2026-07-01 + (the Gregorian week-year all year), gl-u-ca-hebrew `1 de Tishri de 5786` for 5787. Fixed V8 + (Chromium 158) and WebKit 26.6 print the same wrong text; WebKit types the part `unknown`. + Fixed text is the calendar year: gd `Dùbh 2024`, te `జులై 2569`, gl `5787`. + +The fix: one isolated module decides per formatter, behaviourally and without ever calling a parts +method on a formatter that might hold `Y`, whether the year it prints can be wrong or crash; GMT +then prints the calendar year in the form ECMA-402 gives `numeric` and `2-digit`. Dormant on every +formatter that passes. No range parts call can reach V8: D16 repairs the range string, and D17's +parts merge stays only where its gate is on (SpiderMonkey). Retired by two canary groups: D23 (the V8 abort) and D24 (the CLDR data). + +## Decisions (settled here) + +- **Expected value** is the ECMA-402 one, never ICU's: the calendar year (Temporal `eraYear` + when the pattern has an era, else `year`), `numeric` unpadded and ungrouped, `2-digit` the last + two digits zero-padded, in the formatter's numbering system; the part type is `year`. ECMA-402 + outranks CLDR in [the precedence order](../../../../apps/dox/src/content/docs/guides/concepts/standards.mdx). + So gl-u-ca-roc `dateStyle: "full"` prints `115`, not `0115`. +- **Only the year changes.** Every other CLDR choice stays, even a wrong one (de-CH prints + `12.30.2025`, month and day swapped: GMT replaces the year only). GMT owns no CLDR data. +- **No engine sniffing in the library.** `process.versions.v8` is read only inside the canary. +- **Crash signal is exact and cheap.** V8's fix also keeps `year` in `resolvedOptions` for a `Y` + pattern (commit message of `0426b0d1045d`), so on an unfixed V8 a component `year` request with + `resolvedOptions().year === undefined` (calendar not `chinese`/`dangi`) is a `Y` pattern. + Checked on Node 22.22.2, 24.21.0 and 26.13.0 (gd, my-u-ca-japanese, te-u-ca-buddhist). +- **No parts call can reach a `Y` range pattern, so none is made.** Range patterns are not visible + through `resolvedOptions`, and some aborting range formatters never print a wrong year + (kok and kok-Deva with coptic, ethiopic, roc: 0 wrong in a 120-year scan of 4,680 ranges + each), so no text test can find them. D16 moves to string repair; D17 keeps parts because + no aborting V8 ever turns its gate on ([range.md](./range.md)). + +## Signatures and files + +| File | Change | +| --- | --- | +| `packages/gmt/src/internal/weekYearGuard.ts` (new) | `guardDateTimeFormat(formatter, options): Intl.DateTimeFormat` — returns `formatter` itself when dormant, else a guarded formatter. Internal only | +| `packages/gmt/src/internal/weekYearSynth.ts` (new) | `synthesizeParts(formatter, options, ms): Intl.DateTimeFormatPart[]` for a formatter whose native parts may abort | +| `packages/gmt/src/internal/formatterCache.ts` | `construct` wraps every `DateTimeFormat` in `guardDateTimeFormat`; a verdict cache keyed by resolved locale, calendar, numbering system and the zone-free options | +| `packages/gmt/src/internal/repairRangeText.ts` (new) | `repairRangeText(text, carrierNames, wantedNames): string \| null` for D16 ([range.md](./range.md)); `repairRangeParts.ts` stays for D17 | +| `packages/gmt/src/zoned/format/formatZonedRange.ts` | D16 branch calls `formatRange` and `repairRangeText`; `formatRangeToParts` stays only in the D17 branch (SpiderMonkey) | +| `packages/gmt/src/internal/temporalCompat/islamicEra.ts` | Builds through `cachedFormatter` | +| `packages/gmt/src/internal/temporalCompat/repros.ts` | `CanaryDefectId = "D23" \| "D24"` and their repros | +| `scripts/upstream.mjs` | `nodejs/node` in `REPOS`; `knownGuards()` reads `CanaryDefectId` too | +| `scripts/lib/workarounds.mjs` | D23 (`engines: ["v8"]`) and D24 (every engine) | +| `scripts/canary/weekYear.mjs` (new) | Child-process crash check and in-process data sweep | + +## Authority — what each rule rests on + +| Rule | Source | +| --- | --- | +| `y` is the calendar year; `Y` is the year of week-of-year, which can differ near year ends | UTS #35 Part 4 (Dates) §8 Date Field Symbol Table, rows `y` and `Y` | +| The year field's value is the calendar's year of the date (era year in an era calendar) | ECMA-402 ToLocalTime, the `[[Year]]` field of the record it returns; Temporal `PlainDate.prototype.eraYear` / `year` (Temporal CalendarISOToDate, `[[EraYear]]` / `[[Year]]`) | +| `numeric` → no grouping, no padding; `2-digit` → last two digits, padded to two | ECMA-402 FormatDateTimePattern, the `year` steps (`nf` with `useGrouping: false`; `nf2` with `minimumIntegerDigits: 2`, then the last two characters) | +| Part type `year` for the year field | ECMA-402 FormatDateTimePattern: each part's `[[Type]]` is the field name | +| Digits in the formatter's numbering system | ECMA-402 Table "Numbering systems with simple digit mappings" (Intl.NumberFormat chapter) | +| Range parts come from the range pattern; each field is `startRange`, `endRange` or `shared` | ECMA-402 PartitionDateTimeRangePattern; UTS #35 Part 4 §2.6 Interval Formats (split at the first repeated field) | +| Expected values when CLDR is wrong | ECMA-402 outranks CLDR: [The Standards § When sources disagree](../../../../apps/dox/src/content/docs/guides/concepts/standards.mdx#when-sources-disagree) (ECMA-402 is 2, CLDR 4) | +| V8 aborts on `UDAT_YEAR_WOY_FIELD`; fixed in `0426b0d1045d` with `resolvedOptions` keeping `year` | V8 commit `0426b0d1045d` message (crbug 553923523); nodejs/node#67076 | +| Verdict boundaries, synthesis tie-breaks, string range repair | **GMT rule**, reasoning in each slice | + +## Slices + +| Slice | File | Covers | +| --- | --- | --- | +| 1 | [guard.md](./guard.md) | Crash signal, text verdict, proof sketch, verdict cache, `formatterCache` hook | +| 2 | [single-repair.md](./single-repair.md) | `format` text repair; `formatToParts` native-patch or synthesis | +| 3 | [range.md](./range.md) | D16/D17 on strings; `formatRange` year repair (3c, `internal/weekYearRange.ts`) | +| 4 | [call-sites.md](./call-sites.md) | Every internal parts call routed; the no-`formatRangeToParts` rule | +| 5 | [canary-and-docs.md](./canary-and-docs.md) | D23/D24 groups, weekly sweep, upstream row, READMEs, bug doc § AF, changeset, budget | +| 6 | [tests.md](./tests.md) | Test matrix and expected values | + +Order: 3a first (it removes the `formatZonedRange` abort with no new detector), then 1 and 4 +(which remove the `formatCalendar` abort), 2, 5, 6; 3c after its gate, which passed (owner question 5). + +## Validation (Node 26.12.1, child processes, 662 locales) + +| Check | Cases | Result | +| --- | --- | --- | +| Single-format aborts (`formatToParts`) | 317,760 (662 × 16 calendars × 30 option sets) | 105 abort | +| Crash signal (`resolvedOptions`) on component options | 233,024 | 81/81 aborts found, FP 0, FN 0, 0.077 ms with construction | +| Text verdict ([guard.md](./guard.md)) | 317,760 | flags exactly the 105: FN 0, FP 0, 0.18 ms each | +| Era-only Gregorian formatters (locale × era width) | 1,986 | 0 affected | +| Repaired parts vs WebKit 26.6 (`unknown` → `year`, year value per Decisions) | 2,520 points | 2,520/2,520 identical; Chromium 158: 312/312 where its trimmed data matches | +| Synthesis forced on unaffected formatters vs native parts | 7,014 points | 6,976 identical (99.46%) — never used there | +| D16 string repair vs today's parts merge | 379,200 ranges | 379,200 identical | +| Range aborts (`formatRangeToParts`) | single-format population × boundary ranges | 955 aborts on 217 formatters, 12 of them `{hour, minute}` (`my`, non-Gregorian) | +| Range year verdict prototype | 3,360-formatter sample incl. all 217 | FN 0 against aborts; FP 48 to 175 by variant: **not converged** | + +## Open questions — owner + +1. **Story id.** (a) `CORE-112` with issue file and tracker row, added in this PR (recommended); + (b) record it under DOX-G9 only (breaks "CORE is gmt-only"). +2. **CLDR ticket** for the `Y` patterns (gd, gl, ksh, my, sc, te, de-CH, ak, kok; de-CH's month/day + swap separately). (a) Draft the text for approval, then file (recommended); (b) track only. +3. **Native parts where safe** (slice 2 path A). (a) Native parts with the year patched when the + crash signal is off and options are component-based, synthesis otherwise (recommended: the + engine's own split wherever it cannot abort); (b) synthesis for every flagged formatter. +4. **D17.** (a) Keep its parts merge, reachable only on SpiderMonkey (recommended: no aborting V8 + turns the gate on, checked on 7 Node builds); (b) string repair via AM/PM twins, validated in + Firefox CI only. +5. **Range year (slice 3c).** Built with the rest of the phase, on the verdict that passed the + gate in range.md (FN 0, FP 0): the verdict runs lazily on a formatter's first range call. +6. **Verdict cost**: ~0.18 ms once per year-printing formatter key, every engine (the data defect + is everywhere). (a) Accept (recommended); (b) skip the text verdict and fix only the abort, + leaving wrong years in place (a known defect, so not offered as equal). +7. **Bundle.** (a) Raise `entries.root.minified` by the measured growth in one reviewed edit + (recommended); (b) none: a dynamic import would make sync functions async. +8. **D16 `null`** (zone name not attributable, 0 of 379,200): (a) `formatZonedRange` returns `""` + (recommended: never the defect's own text); (b) return the carrier text unrepaired. diff --git a/context/domination/specs/CORE-112/range.md b/context/domination/specs/CORE-112/range.md new file mode 100644 index 000000000..e94c4a7ac --- /dev/null +++ b/context/domination/specs/CORE-112/range.md @@ -0,0 +1,168 @@ +# CORE-112 slice 3 — ranges: D16 on strings, D17, and the range year + +Read with [index.md](./index.md). Three parts with different status: + +| Part | Status | +| --- | --- | +| 3a. D16 zone-name repair on the `formatRange` string | **ready**, first in the build order (removes the live abort) | +| 3b. D17 day-period repair | **ready**, keeps its parts call on SpiderMonkey only (reasoned below) | +| 3c. Calendar year in `formatRange` text | built: the acceptance gate passed (below); `internal/weekYearRange.ts` | + +## Why no range parts call may reach V8 + +A range pattern is ICU's interval pattern, not the single pattern: `resolvedOptions` does not +describe it, and it adds date fields to a time-only skeleton when the endpoints are on different +days. On Node 26.12.1, 955 `formatRangeToParts` calls abort across 217 formatters, 12 of them +`{ hour, minute }` (my, non-Gregorian calendars). The crash signal is read off the single +pattern, which is not the interval pattern, so it cannot clear a range formatter: the only safe +rule is that `formatRangeToParts` is never called on V8. + +## 3a. D16 — `repairRangeText` + +New `packages/gmt/src/internal/repairRangeText.ts` beside `repairRangeParts.ts` (which stays for +D17, 3b): + +```ts +/** + * The range text with the carrier's zone names replaced by the requested ones (defect D16). + * @returns the repaired text, or `null` when a zone name cannot be given to an endpoint + */ +export function repairRangeText( + text: string, + carrierNames: readonly [string | undefined, string | undefined], + wantedNames: readonly [string | undefined, string | undefined], +): string | null; +``` + +`rangeWithRepairedParts` in `zoned/format/formatZonedRange.ts`, zone branch: + +1. `want` and `carrier` from `cachedFormatter` as today (both guarded by slice 1). +2. `ca`, `cb` = the `timeZoneName` part of `carrier.formatToParts(ms1)` and `(ms2)`; + `wa`, `wb` = the same from `want`. These are single-date parts and go through the guard. +3. `text = carrier.formatRange(ms1, ms2)`; return `repairRangeText(text, [ca, cb], [wa, wb])`. + +The rule (prototype `textRepair`, `/woy/d16text.mjs`). **GMT rule**, the same +attribution `repairRangeParts` uses today, read off the string: + +- `ca` or `cb` undefined → `null`. +- `ca !== cb`: find every occurrence of the longer name first, then the shorter, skipping any + overlapping an earlier hit; each hit of `ca` becomes `wa`, each hit of `cb` becomes `wb`. + Reason: a name printed for one endpoint only is that endpoint's (ECMA-402 + PartitionDateTimeRangePattern gives each part one source). +- `ca === cb`: two hits → the first is the start's (`wa`), the second the end's (`wb`), since an + interval pattern writes the start's fields before the end's (UTS #35 Part 4 §2.6); one hit → + a shared part, `wa` (today's shared rule: `cb` only when it differs from `ca`); zero or more than + two → `null`. +- Replace hits left to right; text outside hits is untouched. + +`null` → `formatZonedRange` returns `""`. It never happened in the validation (below). Returning the +carrier's short name instead would be the defect's own output, which GMT does not ship. + +Measured: 662 locales × 8 zones (America/New_York, Europe/London, Asia/Kolkata, +Australia/Lord_Howe, UTC, Europe/Dublin, America/Sao_Paulo, Pacific/Chatham) × 4 styles +(`long`, `longGeneric`, `shortOffset`, `longOffset`) × 3 option sets × 6 pairs (1 h apart, across +the 2026 March and October changes, 2 to 9 days apart): **379,200 of 379,200 identical** to today's parts merge, 0 +`null`. 352 year-bearing formatters (2,112 cases) in the affected locale families were left out +of the comparison because the parts merge itself would abort; with slice 1 they take guarded +single parts and the same rule. + +## 3b. D17 — keep the parts merge, SpiderMonkey only + +The D17 gate (`isRangeDayPeriodCompatNeeded()`) is a behavioural probe that is true only on +SpiderMonkey, which has no `UDAT_YEAR_WOY_FIELD` abort. Every V8 without the fix prints the +flexible day period in ranges (checked: Node 22.22.2, 24.19.0, 24.21.0, 26.8.2, 26.10.0, 26.12.1, +26.13.0 all print `10 in the morning – 12 noon`), so the D17 branch is unreachable on any V8 that +can abort, and a later V8 carries `0426b0d1045d`. So the D17 branch keeps `formatRangeToParts` +and `repairRangeParts` stays for it unchanged. +Owner question 4 offers the alternative: a string repair through AM/PM markers from an +`{ hour: "numeric", hour12: true }` twin, which can only be validated in Firefox CI. + +Branch order in `rangeWithRepairedParts`: when the D17 gate is on, the parts merge handles both +types as today (the gate being on already rules out an aborting V8); otherwise the D16 branch is +the string repair of 3a. No engine has both today (D16: V8, JSC; D17: SpiderMonkey); a test with +both gates stubbed on pins the order. + +## 3c. The calendar year in `formatRange` + +`formatDateRange`, `formatDateTimeRange` and `formatZonedRange` print the week-year in range text +too, on every engine: kok-u-ca-japanese 2018-12-27 → 2019-12-27 prints +`27-12-30 H – 27-12-2019 R` (end year should be `1`); my-u-ca-buddhist prints `2026` for 2569; +kok-u-ca-roc prints `बुधवार, 10-7-2024 ROC – शुक्रार-12-7-113` (113 is right; 2024 should be 113). +The single-date verdict does not decide it: the interval pattern is a different pattern. + +Prototype: `/woy3c/core.mjs` (`format` and `formatRange` calls only). + +```ts +/** + * Whether the formatter's range pattern prints a week-based year where the calendar year is meant + * (defect D24 in ranges). Computed once per formatter, on its first range call. + */ +export function rangeYearVerdict(formatter: Intl.DateTimeFormat, options: Intl.DateTimeFormatOptions): boolean; + +/** + * The range text with each week-based year run replaced by the endpoint's calendar year. + * @returns the repaired text, or `null` when the year runs cannot be located or a run is not + * one whole week-year value + */ +export function repairRangeYear( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, + startMs: number, + endMs: number, +): string | null; +``` + +**Verdict.** Probe ranges from the locale's first day of the week (`Intl.Locale` week info): +ICU calendar-year boundaries from 2024 on weekday offsets 1–6 from that day, where `Y` and `y` +differ, with day, month, year and time ranges on both sides, and day, month, year, time and +cross-era ranges in an earlier era. A digit run is a year run when it moves exactly as a year +under a shift of one or both endpoints by k years (k never a multiple of 100; for chinese and +dangi including multiples of 60; the weekday held still when the pattern prints one, except at +multiples of 60; a run whose value is unchanged does not count). Each year run is compared with +ICU's calendar year for its endpoint (`und-u-ca-`, `{ year: "numeric" }`, the source the +single repair uses), signed with the locale's minus; under `year: "2-digit"` only the last two +digits (ECMA-402 FormatDateTimePattern), except chinese and dangi, whose related year prints at +full width. A formatter whose range text holds no decimal year is not flagged. A probe whose year +runs cannot be located counts as flagged. + +**Repair.** Only the runs found wrong, and only when the run holds one whole week-year value +(within one of the extended or ISO year, or its last two digits). The run is rewritten with the +locale's minus and ICU's calendar year in the formatter's numbering system, ungrouped, at the +width printed (full, or the last two digits padded); every other character is kept. `null` → +the caller returns `""`, as in 3a. + +**Where.** The verdict is lazy: no range probe runs when a formatter is built, only on its first +range call, and the verdict is kept per formatter (dropped with the formatter cache). Every +`formatRange` call in the library goes through it: `formatDateRange`, `formatDateTimeRange`, both +`formatZonedRange` paths, and the guarded stand-in's `formatRange`. + +**Gate (passed).** 662 locales × 16 calendars × 30 option sets = 317,760 formatters, in child +processes on Node 26.12.1: + +| Check | Result | +| --- | --- | +| Verdict against the aborting set (a `Y` in the interval pattern) | flagged 217, `Y` 217, FP 0, FN 0, unlocated 0 | +| Repair on the flagged set (217 × 7 ranges) | `null` 0 | +| Brute-force Temporal oracle (`formatRangeToParts` on every formatter that does not abort, 2.22M range calls) | `Y` not flagged 0, flagged not `Y` 0 | +| Repair against WebKit 26.6 `formatRangeToParts` (2,604 cases) | 2,510 match Temporal, 94 match ICU's year (pre-epoch, below), wrong 0 | + +Cost: verdict mean 5.77 ms (p50 3.78, p99 25.4, max 172.5), about 93 `format`/`formatRange` +calls; chinese, dangi and japanese are the slowest (p99 ≈ 40–48 ms). Repair: mean 0.22 ms per +range, flagged formatters only. + +**Pre-epoch years.** At ISO year −1 the repair writes ICU's calendar year, as every unflagged +formatter prints it. For indian (`-79 Śaka`) and persian (`-622 AP`) that is Temporal's `eraYear` +too (intl era/monthCode Table 2: one era, signed era year). For islamic (`-642 AH`, Temporal +`643 bh`) and japanese (`-645 Taika`, Temporal `2 bce`) ICU 78 is wrong on every formatter; those +are defects of their own (ICU-23327; ICU-23341, fixed in ICU 79.1), not part of `Y`. + +## Edge cases for tests (values in [tests.md](./tests.md)) + +- The my-u-ca-buddhist zoned range above returns a string, no abort (child process on unfixed V8). +- `ca !== cb` across a change (Europe/London 2026-03-28 → 03-30, `long`): `Greenwich Mean Time` + / `British Summer Time` each on its endpoint. +- `ca === cb` with two hits (3 days apart, `longOffset`), with one hit (1 h apart, shared). +- A zone name that contains the other (`GMT` inside `GMT+1`): the longer is matched first. +- `shortOffset` / `longOffset`, where the engine prints no zone name at all in the range: the + carrier's `short` is in the text and is replaced. +- The source test of slice 4: `formatRangeToParts` appears only in the D17 branch and the probes. diff --git a/context/domination/specs/CORE-112/single-repair.md b/context/domination/specs/CORE-112/single-repair.md new file mode 100644 index 000000000..ec7cd1013 --- /dev/null +++ b/context/domination/specs/CORE-112/single-repair.md @@ -0,0 +1,120 @@ +# CORE-112 slice 2 — single-date repair: `format` and `formatToParts` + +Read with [index.md](./index.md) and [guard.md](./guard.md). Code in `weekYearGuard.ts` (the +guarded formatter, text repair) and `weekYearSynth.ts` (parts synthesis, kept apart so its size is +measured on its own). Prototype: `/woy/repair.mjs` (`analyse`, `repairText`, +`synthParts`). + +## The analysis (once per verdict, stored with it) + +Built from `format` calls only, on the formatter itself (its zone, its time fields): + +- `J`, the year run indexes, as in guard step 4, at `m0` = month 1 day 15 of `y0`, 10:20:30.456 + in `ro.timeZone`. +- `count`, the digit-run count at `m0`. +- `style[n]` per year run, read at mid-year (month 6 day 1) against the reference year `em`: + - run text `=== em` → `full`; + - two code points equal to `em`'s last two → `two`; + - longer than `em` and starts with / ends with `em` → `full`, glued at the end / start, with the + other number's length; + - otherwise (the run is wrong all year: buddhist, japanese, roc) → `two` if two code points, + else `full`. +- `labels[j]` for every other run, by moving one field at a time from `m0` (+1 day, month, hour, + minute, second, millisecond): the one field that changes it; none → `literal`; several → + `text` (digits inside a name, haw "P3"). + +## Year text — the ECMA-402 value + +`yearText(ms, style)`: the reference formatter (guard step 2, but in `ro.timeZone`) at `ms`, its +single digit run `c`: + +- `full` → `c` (ECMA-402 FormatDateTimePattern `numeric`: `useGrouping: false`, no minimum + digits; so roc 115 is `115`, never `0115`); +- `two` → the last two code points of `c`; a one-digit `c` gets the numbering system's zero in + front (`2-digit`: `minimumIntegerDigits: 2`, then the last two characters). + +The reference is the right source, not Temporal: it is the same ICU calendar that prints the month +and day beside the year, so the three fields can never come from different calendar arithmetic. +Tests derive their expected years independently from Temporal `eraYear ?? year` ([tests.md](./tests.md)). + +## `format(ms)` on a guarded formatter + +1. `text = native.format(ms)`; `runs = digitRuns(text)`. +2. `runs.length !== count` → return `text` unchanged. Not seen in the validation; the data canary + (slice 5) fails on any such date, so a CLDR change that causes one is caught, not shipped. +3. For each year run in order, replace its span (narrowed by the glue length) with `yearText`. + Keep the year spans' new offsets for synthesis. + +Expected (Node 26.12.1, native → GMT): gd `{ year: "numeric", month: "short" }` 2024-12-30 +`Dùbh 2025` → `Dùbh 2024`; de-CH `{ era: "short", year, month, day: "numeric", weekday: "short" }` +2024-12-30 `Mo., 12.30.2025 n. Chr.` → `Mo., 12.30.2024 n. Chr.` (month and day stay swapped: +CLDR's choice, not GMT's). + +## `formatToParts(ms)` on a guarded formatter + +Two paths. Owner question 3 picks whether path A exists. + +**A — native parts, year patched.** Taken only when the crash signal is off *and* the options are +component-based (no `dateStyle`). Then the pattern has no `Y` on an unfixed V8, or the engine is +fixed. Call native `formatToParts`, map each year run to the part covering it (walk part offsets +against the native text), set that part's `type` to `"year"` (WebKit types it `unknown`) and its +value to `yearText`. A part that covers more than the run (glue) has the run's slice replaced. + +**B — synthesis** (`weekYearSynth.ts`), every other flagged formatter: + +```ts +export function synthesizeParts( + formatter: Intl.DateTimeFormat, + analysis: WeekYearAnalysis, + ms: number, +): Intl.DateTimeFormatPart[] | null; +``` + +1. **Twins** (built through `cachedFormatter`, cached per guarded formatter): year-free formatters + in the same locale, calendar, numbering system and zone whose parts name the text fields: + - `{ weekday }` and `{ weekday, month: "long", day: "numeric" }` per weekday width used + (both `long` and `short` under `dateStyle`); + - `{ month }` and `{ month, day: "numeric" }` per text month width used; + - `{ era, month: "numeric", day: "numeric" }` per era width used (all three under `dateStyle`); + - `{ month: "numeric", day: "numeric" }`, `{ month: "2-digit", day: "2-digit" }`; + - the time fields with `hourCycle` from `ro` (a `timeStyle` becomes `hour`, `minute`, and + `timeZoneName` `short` for `long`, `long` for `full`). + A twin that prints a year is skipped. Twins pass guard step 0 as year-free; the crash canary + runs every twin shape in child processes (slice 5). +2. **Candidates at `ms`**: every non-literal, non-blank twin part except numeric fields + (`day`, `month` from numeric twins are kept as numeric candidates), longest value first. +3. **Spans**: the repaired text cut at the numeric runs (`J` runs take their new spans; other + runs typed by `labels`, widened to a numeric candidate that contains them, e.g. `09`). +4. **Template** (once per formatter): for five dates in `y0` (01-15 10:20, 01-15 22:20, + 03-09 22:20, 05-20 03:20, 08-03 15:20), segment each text span greedily by candidates. + `fits`: a candidate of 1–2 characters may not start or end inside a run of letters. **GMT rule + (tie-break):** if two field types claim the same longest text at one position, that date's + template is rejected and the next date is tried; the first unambiguous date wins. Reason: a + type chosen on a tie would be a guess; a later date where the names differ decides it from data. +5. **Parts at `ms`**: walk each span by the template's field list, taking for each field the + earliest fitting candidate value of that field's keys; text between fields is `literal`; then + the span's numeric part. Adjacent literals merge. +6. Any step without an answer → `null`. + +`null` makes the public `…ToParts` function return its sentinel `[]` (the parts cannot be known +without risking the abort). The data canary runs synthesis over every flagged formatter of the +population and fails on any `null` or any mismatch with the WebKit oracle, so none ships. + +## Measured + +- Synthesis on all 105 flagged formatters × 24 dates vs WebKit 26.6 `formatToParts` (with + `unknown` → `year` and the ECMA-402 year value): 2,520/2,520 identical; vs Chromium 158 where its + trimmed locale data matches: 312/312. +- Synthesis forced on 7,014 unflagged points: 6,976 identical. The 38 misses are tie cases on + formatters that never take path B (ko `12월`, kgp `12-Kysã`); they bound how general the + segmentation is, not a shipped result. + +## Edge cases (values in [tests.md](./tests.md)) + +- Year-end and year-start dates on both sides, and a mid-year control that is unchanged. +- `2-digit` (ksh `{ year: "2-digit", month: "2-digit" }` → `24-12`). +- Non-Latin digits (my: `၂၀၂၆` → `၂၅၆၉`; japanese era year 8 as `၈`, 2-digit `၀၈`). +- `dateStyle: "full"` (gl-u-ca-hebrew, Tishri dates; gl-u-ca-roc `115`). +- A time field next to the date (the twin path): gd `{ year, month: "short", hour, minute }`. +- Part types: the year part is `"year"`, never `"unknown"` or `"relatedYear"`. +- Parts concatenate to the repaired `format` text exactly. diff --git a/context/domination/specs/CORE-112/tests.md b/context/domination/specs/CORE-112/tests.md new file mode 100644 index 000000000..9cf7081b3 --- /dev/null +++ b/context/domination/specs/CORE-112/tests.md @@ -0,0 +1,102 @@ +# CORE-112 slice 6 — tests and expected values + +Read with [index.md](./index.md). House rules: [testing standards](../../../testing-standards/references/index.md). + +## Rules for these tests + +1. **Expected years come from Temporal**, never from the engine or the guard: + `Temporal.PlainDate.from(iso).withCalendar(cal)`, `eraYear` when the pattern has an era (japanese, + roc, buddhist, `era` option), else `year`; written in the numbering system's digits + (`Intl.NumberFormat(…, { numberingSystem, useGrouping: false })`). Each row cites + ECMA-402 FormatDateTimePattern (`numeric` / `2-digit`) as its authority. +2. **No test process calls a parts or range-parts method on a native formatter that might hold + `Y`.** On an unfixed V8 that kills the whole Vitest worker. Tests call public GMT functions + (guarded), or native `format` / `formatRange` only. +3. **Abort repros run only in a child process** (`spawnSync(process.execPath, ["--input-type=module", + "-e", src])`, importing the built-from-source module through the test's own resolver, or + asserting on the native call alone). Assert exit status 133 or 0 as the row says. +4. Rows whose *native* text is quoted are engine-data facts of Node 26.12.1 / CLDR 48.0: assert + GMT's output only. Do not assert the native wrong text (it changes when CLDR is fixed, and the + expected value does not). +5. Browser legs run the same files: rows hold on every engine because the expected value is + ECMA-402's, not the engine's. + +## Single-date matrix (`formatDate`-family and `…ToParts`; UTC) + +| Locale | Options | Date | Native today (Node 26.12.1) | Expected from GMT | +| --- | --- | --- | --- | --- | +| gd | `{ year: "numeric", month: "short" }` | 2024-12-30 | `Dùbh 2025` | `Dùbh 2024` | +| gd | same | 2027-01-01 | `Faoi 2026` | `Faoi 2027` | +| gd | same (control) | 2025-07-01 | `Iuch 2025` | `Iuch 2025` | +| ksh | `{ year: "numeric", month: "numeric" }` | 2024-12-30 | `2025-12` | `2024-12` | +| ksh | same | 2027-01-01 | `2026-01` | `2027-01` | +| ksh | `{ year: "2-digit", month: "2-digit" }` | 2024-12-30 | `25-12` | `24-12` | +| sc | `{ year: "numeric", month: "numeric" }` | 2024-12-30 | `12/2025` | `12/2024` | +| sc | same | 2027-01-01 | `01/2026` | `01/2027` | +| te-u-ca-buddhist | `{ year: "numeric", month: "long" }` | 2026-07-01 | `జులై 2026` | `జులై 2569` | +| te-u-ca-buddhist | same | 2026-12-31 | `డిసెంబర్ 2027` | `డిసెంబర్ 2569` | +| my-u-ca-japanese | `{ year, month, day: "numeric" }` | 2026-07-01 | `R ၀၁/၀၇/၂၀၂၆` | `R ၀၁/၀၇/၈` | +| my-u-ca-japanese | `{ year, month, day: "2-digit" }` | 2026-07-01 | `R ၀၁/၀၇/၂၆` | `R ၀၁/၀၇/၀၈` | +| my-u-ca-japanese | `{ year, month, day: "numeric" }` | 2024-12-30 | `R ၃၀/၁၂/၂၀၂၅` | `R ၃၀/၁၂/၆` | +| my-u-ca-buddhist | `{ year, month, day: "numeric" }` | 2026-07-01 | `BE ၀၁/၀၇/၂၀၂၆` | `BE ၀၁/၀၇/၂၅၆၉` | +| de-CH | `{ era: "short", year, month, day: "numeric", weekday: "short" }` | 2024-12-30 | `Mo., 12.30.2025 n. Chr.` | `Mo., 12.30.2024 n. Chr.` (only the year changes) | +| gl-u-ca-hebrew | `{ dateStyle: "full" }` | 2026-09-12 | `sábado, 1 de Tishri de 5786 AM` | `sábado, 1 de Tishri de 5787 AM` | +| gl-u-ca-hebrew | same | 2026-09-13 | `domingo, 2 de Tishri de 5786 AM` | `domingo, 2 de Tishri de 5787 AM` | +| gl-u-ca-roc | `{ dateStyle: "full" }` | 2026-07-01 | `mércores, 1 de xullo de 2026 ROC` | `mércores, 1 de xullo de 115 ROC` (unpadded) | +| gd | `{ year: "numeric", month: "short", hour: "numeric", minute: "numeric" }` | 2024-12-30T14:05 | `Dùbh 2025, 14:05` | `Dùbh 2024, 14:05` | + +For each row, through the matching `…ToParts` function: the joined values equal the expected +text, exactly one part has `type: "year"`, its value is the expected year, and no part has type +`unknown`. gd row 1 parts: `[{ month, "Dùbh" }, { literal, " " }, { year, "2024" }]`. + +Dormant controls (the guard returns the native formatter; assert identity in a unit test of +`guardDateTimeFormat`, and unchanged output through the public function): `en`, `de`, `fr`, +`ja-u-ca-japanese`, `zh-u-ca-chinese` with `{ year: "numeric", month: "long" }`; `en` with +`{ dateStyle: "full" }`; any locale with `{ hour, minute }` or `{ month, day }`. + +## Abort rows (child process, Node only; skip on browser legs) + +| Call | Today | After | +| --- | --- | --- | +| `formatZonedRange("2026-07-01T09:30:00+06:30[Asia/Yangon]", "2026-07-04T09:30:00+06:30[Asia/Yangon]", "my-u-ca-buddhist", { hour: "numeric", minute: "numeric", timeZoneName: "long" })` | exit 133 | exit 0, a non-empty string whose two zone names are the `long` ones from `formatZonedToParts` at each end | +| `formatCalendar("2026-07-01T10:00:00", "gl-u-ca-hebrew", { reference: "2026-07-01T09:00:00" })` | exit 133 | exit 0, non-empty | +| same with `gl-u-ca-buddhist`, `gl-u-ca-roc` | exit 133 | exit 0 | +| `formatDateToParts` over all single-matrix rows | exit 133 (unfixed V8) | exit 0 | +| native `new Intl.DateTimeFormat("gd", { year: "numeric", month: "short", timeZone: "UTC" }).formatToParts(0)` | exit 133 | exit 133 while V8 is unfixed (this row is the D23 repro's confirmation; it flips on a fixed V8, and the canary, not the test, reports that) | + +## D16 string repair (`repairRangeText.test.ts`, pure) + +- `ca !== cb`: `"28 Mar 2026, 12:00 GMT – 30 Mar 2026, 12:00 BST"`, carrier `[GMT, BST]`, wanted + `[Greenwich Mean Time, British Summer Time]` → each replaced on its own side. +- `ca === cb`, two hits → first `wa`, second `wb`; one hit → `wa`; zero or three hits → `null`. +- Containment: carrier `["GMT", "GMT+1"]` in `"… GMT – … GMT+1"` → `GMT+1` matched as a whole. +- `ca` or `cb` undefined → `null`. +- Every existing `formatZonedRange` row passes unchanged (the 379,200-case equivalence is the + reason; the rows are the guard). +- With both D16 and D17 gates stubbed on, the parts merge handles both (range.md 3b). + +## Guard units (`weekYearGuard.test.ts`) + +From [guard.md](./guard.md) § Edge cases: step-0 short-circuit (spy), one verdict per key across +default-locale constructions, cache cleared when `Intl.DateTimeFormat` is replaced, crash-signal +truth table on stubbed `resolvedOptions` (`year` undefined + gregory → on; + chinese → off; +`dateStyle` → off), guarded `resolvedOptions().year` filled for component options, guarded +`formatRangeToParts` throws `TypeError`. + +## Synthesis units (`weekYearSynth.test.ts`) + +- The tie-break: a stub where two twins give the same text for two field types at the first + template date and different texts at the second → the second date's template is used. +- No answer at any template date → `null` → the public `…ToParts` returns `[]`. +- Parts join to the repaired text for every single-matrix row. + +## Source rule + +`weekYearSource.test.ts` as in [call-sites.md](./call-sites.md). + +## Bench rows + +The verdict is per formatter key, not per call. Add to `packages/gmt/bench/formatDate.bench.ts`: +`formatDate gd first call` (verdict + format) and `formatDate gd cached` (guarded format only), +plus `formatDate en cached` to show the dormant path unchanged. Target: dormant path within noise +of today; guarded cached `format` under 2× native `format`. diff --git a/context/domination/specs/CORE-112/year-printing.md b/context/domination/specs/CORE-112/year-printing.md new file mode 100644 index 000000000..08496960b --- /dev/null +++ b/context/domination/specs/CORE-112/year-printing.md @@ -0,0 +1,123 @@ +# CORE-112 slice 7 — other wrong years in formatted text + +Read with [index.md](./index.md). The slice 3c sweep compared every year in range parts with +Temporal's calendar year and found four more defects, none of them `Y`. Each one reaches GMT's +format functions, in single dates and in ranges, on every engine checked: Node 22.22.2, 24.21.0, +26.12.1 and 26.13.0 (ICU 78.2 and 78.3, CLDR 48), Chromium 153 and WebKit 26.6. SpiderMonkey was +not observed. Research outputs: `/preepoch/`. + +## Not defects + +Indian (`-79 Śaka`) and persian (`-622 AP`) at ISO year −1 are right. Intl era/monthCode Table 2 +gives each a single era with a signed era year, and native Temporal on all three engines gives +`eraYear` −79 and −622. ECMA-402 FormatDateTimePattern's "If partType is "year" and value ≤ 0, set +value to 1 − value" fits only a calendar with an inverse era; that wording is an ECMA-402 issue, +filed as tc39/ecma402#1116, not a GMT change. + +## Rules every part follows + +- Dormant: one engine probe per defect decides whether the engine has it. A formatter is wrapped + only when the probe fails and the formatter can show the defect (its calendar, locale and + options), so a fixed engine runs none of this code. +- `format` and `formatRange` calls only. No parts method on a pattern that can hold `Y` (D23). +- No GMT data: every replacement text comes from the engine's own formatters. +- Each part is its own canary group with a repro whose expected value comes from the + specifications, and retires when every engine passes it. +- Apply in `format`, `formatToParts` and `formatRange`, composed with the D24 week-year repair. + +## D25 — japanese years before 1873 (ICU-23341, fixed in ICU 79.1, before Meiji; ICU-23619, Meiji 1–5) + +`en-u-ca-japanese` at ISO −0001-07-10 prints `Jul 12, -645 Taika (645–650)`; `ja` prints +`大化-645年`. Intl era/monthCode Table 2, as amended by +[tc39/proposal-intl-era-monthcode#86](https://github.com/tc39/proposal-intl-era-monthcode/issues/86) +(TG2, 2026-01-08; test262 tc39/test262#4877, merged): "For dates up to and including 1872-12-31, +the calendar "japanese" uses Gregorian eras. For dates of 1873-01-01 and later, the calendar +"japanese" uses the solar Japanese eras." So ISO −0001-07-10 is `2 BC`, and 1872-12-31 is +`1872 AD`, where ICU 78 prints `Meiji 5`. CLDR 49 drops the pre-Meiji eras (CLDR-11400) and ICU 79 +then prints the Gregorian era before Meiji, but CLDR 49 still starts Meiji on 1868-10-23, so ICU 79 +keeps Meiji 1–5 for 1868-10-23 to 1872-12-31. + +- Probe: `en-u-ca-japanese`, `{ era: "short", year: "numeric" }` prints the same text as + `en-u-ca-gregory` at both ISO −0001-07-10 and 1872-12-31. +- Repair: for a date before 1873-01-01, format with the same locale, options and + `calendar: "gregory"`. The text is the engine's own. +- Upstream: the years before Meiji are fixed in ICU 79.1. Meiji 1–5 is filed as ICU-23619. CLDR's + Meiji start (1868-10-23, CLDR-11375) is the era's historical start and stays; ICU4X keeps it too + and prints the Gregorian era for Meiji 1–5 in code (`components/calendar/src/cal/japanese.rs`, + citing tc39 era/monthCode #86). Exact text to the owner first. + +## D26 — islamic dates before the Hijra (ICU-23327, open) + +V8 prints `Dhuʻl-Q. 9, -642 AH` for ISO −0001-07-10 in `en-u-ca-islamic-civil`. Intl era/monthCode +Table 2 and § 4.1.12 give the `bh` era, and native Temporal gives `643 bh`. test262 +`intl402/DateTimeFormat/prototype/formatToParts/era.js` requires ISO 600 and 2025 to print +different era names. WebKit is right (`643 Before Hijra`, WebKit 321713). V8's ICU has no BH era +name, so no repair is possible without GMT data. + +**Owner decision:** on an engine that prints a negative AH year, a pre-Hijra date in any `islamic*` +calendar formats to the house empty value (`""`; the parts and range functions return their own +empty values). No wrong year is printed and no data is owned. The probe: +`en-u-ca-islamic-civil`, `{ era: "short", year: "numeric" }` at ISO 0600-07-10 prints an era that +differs from the one at ISO 2025-07-10. A range with either endpoint before the Hijra is empty too. + +## D27 — `ja-u-ca-japanese` with `year: "2-digit"` (ICU-23620) + +`{ year: "2-digit" }` resolves `2-digit` but prints `令和6年` for 2024-07-10. ECMA-402 +FormatDateTimePattern, "2-digit" branch: FormatNumeric with `minimumIntegerDigits: 2`, so +`令和06年`. ICU forces the `jpanyear` numbering for `ja` with the japanese calendar whenever the +pattern holds 年, and `jpanyear` ignores the minimum digit count. Numeric-only patterns are right +(`R06/7/10`). + +**Owner decision:** keep 元年 for year 1, in both styles. It comes from CLDR's `ja` data and is the +Japanese convention. Pad every other year. + +- Probe: `ja-u-ca-japanese`, `{ year: "2-digit" }` at 2024-07-10 prints a two-digit year. +- Repair: only for a formatter that resolves `year: "2-digit"`, when the year run printed is one + digit. Pad it with the zero of the formatter's own numbering system, taken from the engine's + `NumberFormat`. + +## D28 — chinese and dangi `relatedYear` under `year: "2-digit"` (ICU-23621) + +ECMA-402 FormatDateTimePattern: `relatedYear` is FormatNumeric of the related year at full width, +with no 2-digit form. Engines print ICU's `rr`, which pads to two digits: `05(yi-chou)` for ISO +0005, and `06/-01` for ISO −0001 with `month: "2-digit"`. Four-digit years are unaffected. The +number is right; only the padding is wrong. + +- Probe: `en-u-ca-chinese`, `{ year: "2-digit" }` at ISO 0005-07-10 prints the related year `5`. +- Repair: chinese and dangi, `year: "2-digit"` only. Replace the related-year run with the engine's + `NumberFormat` of the signed related year (`useGrouping: false`, the formatter's numbering + system, the locale's minus). +- `internal/weekYearRange.ts` treats a two-digit chinese or dangi run as ICU's `rr` width. It must + follow the repaired width. + +## D29 — yo interval patterns (CLDR 48 yo, ICU span labels) + +CLDR 48 yo gregorian `yMMMEd`, greatestDifference `y`, is `y MMM d y, E – MMM d, E y`. UTS #35 +Part 4 § intervalFormats splits a pattern at the first repeated field, so the start's half is +`y MMM d `. `formatDateRange("2024-07-10", "2025-07-10", "yo", { year, month: "short", day, +weekday })` prints `2024 Oṣù Agẹmọ 10 2025, Ọjọ́bọ – Oṣù Agẹmọ 10, Ọjọ́bọ 2025`: the start's weekday +(Ọjọ́rú) is lost. CLDR 49 fixes `yMMMEd`. `yMEd`, greatestDifference `d`, stays wrong in CLDR 49: +`E, dd/MM/y – E, dd/MM/y, E`. ICU's `addOverlapSpans` also labels the end's year and weekday +`startRange` (ECMA-402 PartitionDateTimeRangePattern: [[Source]] names the date formatted). +`yo-BJ` is the same. Chromium 153 falls back to English for `yo`. + +- First, a sweep: every locale × option set × greatestDifference for interval patterns that drop or + repeat a field. It uses `formatRangeToParts` in child processes, as an oracle only. Gate: the + detector uses `format` and `formatRange` only, with FN 0 and FP 0 against that oracle. +- Repair: rebuild a flagged range from the engine's own single `format` of each endpoint, joined by + the separator the same locale's `{ year: "numeric" }` range prints. +- `repairRangeParts` (D16, D17) trusts `source`. yo ranges with a time or zone field use the + `{0} – {1}` form and are labelled right, so it is not misled. Keep a test that pins this. + +## Upstream (exact text to the owner before filing) + +- Filed: ICU-23620, `jpanyear` loses `yy` padding (D27). +- Filed: ICU-23621, the pattern generator turns a `yy` skeleton into `rr` where the pattern has a + related year (`dtptngen.cpp` `adjustFieldTypes` keeps the requested length), which V8 and + JavaScriptCore both inherit (D28). +- A CLDR ticket: yo `yMEd`, greatestDifference `d` (D29). Optionally an ICU ticket for the + `addOverlapSpans` span guess. +- Filed: tc39/ecma402#1116, limit the "value ≤ 0" step to calendars with an inverse era. +- Filed: ICU-23619, the `japanese` calendar prints Meiji 1–5 for 1868-10-23 to 1872-12-31, where tc39 + era/monthCode #86 and ICU4X give the Gregorian era (D25). +- D25's years before Meiji and D26 are already filed (ICU-23341 fixed, ICU-23327 open). diff --git a/context/domination/tracker.md b/context/domination/tracker.md index 2f11b19be..ceb46b137 100644 --- a/context/domination/tracker.md +++ b/context/domination/tracker.md @@ -132,6 +132,7 @@ ending with lengths of time counted from now, ahead of the remaining realms. | 57 | CORE-107 | Core | A changelog page in Dox, and the
You-Dont-Need-Momentjs PR on `/upstream` | — | #451 | — | Done | | 58 | CORE-110 | Core | The weekly upgrade check compares
each calendar's years with native Temporal | — | #468 | — | Done | | 59 | CORE-111 | Core | Public functions call internal cores,
never another public function | — | #508 | — | Done | +| 60 | CORE-112 | Core | Some languages' date patterns crash
Node and print the wrong year | — | #524 | — | In progress | **`CORE-8` sits at slot 8, ahead of the realm work.** It gates everything after it: it is the standards and consistency pass over the whole public surface before 1.16.0 ships, and a realm diff --git a/packages/gmt/bench/formatDate.bench.ts b/packages/gmt/bench/formatDate.bench.ts index 53465a0cb..5107eaa53 100644 --- a/packages/gmt/bench/formatDate.bench.ts +++ b/packages/gmt/bench/formatDate.bench.ts @@ -1,4 +1,5 @@ import { describe } from "vitest"; +import { clearFormatterCache } from "../src/internal/formatterCache"; import { formatDate, getLocaleMonthNames } from "../src/plain"; import { bench } from "./fixtures"; @@ -23,3 +24,32 @@ describe("formatDate and getLocaleMonthNames", () => { { time: 500 }, ); }); + +// CORE-112: the week-year guard. `en` is the dormant path (the native formatter, unchanged); `gd` +// prints the week-year in CLDR 48, so its formatter is a guarded stand-in whose `format` repairs +// the year. The first call pays the verdict once per pattern; a repeat call pays the repair only. +describe("formatDate, week-year guard", () => { + const options = { year: "numeric", month: "short" } as const; + bench( + "formatDate gd first call", + () => { + clearFormatterCache(); + formatDate("2024-12-30", "gd", options); + }, + { time: 500 }, + ); + bench( + "formatDate gd cached", + () => { + formatDate("2024-12-30", "gd", options); + }, + { time: 500 }, + ); + bench( + "formatDate en cached", + () => { + formatDate("2024-12-30", "en", options); + }, + { time: 500 }, + ); +}); diff --git a/packages/gmt/src/internal/formatterCache.ts b/packages/gmt/src/internal/formatterCache.ts index 00ab9eec3..9d3b5d118 100644 --- a/packages/gmt/src/internal/formatterCache.ts +++ b/packages/gmt/src/internal/formatterCache.ts @@ -1,3 +1,7 @@ +import { plainOptionEntries } from "./plainOptionEntries"; +import { forgetWeekYearVerdicts, guardDateTimeFormat } from "./weekYearGuard"; +import { repairYearPrinting, widenRelatedYear } from "./yearPrinting"; + /** The `Intl` formatter classes this module builds. */ type FormatterKind = | "DateTimeFormat" @@ -29,6 +33,43 @@ function forgetIfReplaced(kind: FormatterKind): void { } } +/** The options to build with: widened (D28) when the formatter's calendar is chinese or dangi. */ +function widened( + native: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, +): Intl.DateTimeFormatOptions { + try { + return widenRelatedYear(options, native.resolvedOptions().calendar); + } catch { + return options; + } +} + +/** + * A date formatter with the week-year guard (D23, D24) and no year repair (D25 to D27): its parts + * are the engine's own, as a caller that reads the engine's era needs them (D18, `islamicEra.ts`). + * Not cached; the caller keeps it. + * + * @param locale BCP 47 locale + * @param options the formatter's options, built by GMT code + * @returns the guarded formatter + * + * @example guardedDateTimeFormat("en-u-ca-islamic-civil", { era: "short", timeZone: "UTC" }).formatToParts(0) // the engine's parts + */ +export function guardedDateTimeFormat( + locale: FormatterLocale, + options: Intl.DateTimeFormatOptions, +): Intl.DateTimeFormat { + const native = new Intl.DateTimeFormat(locale, options); + // CORE-112 D28: a chinese or dangi `year: "2-digit"` is built as `"numeric"` where the engine + // pads the related year. + const built = options.year === "2-digit" ? widened(native, options) : options; + return guardDateTimeFormat( + built === options ? native : new Intl.DateTimeFormat(locale, built), + built, + ); +} + function construct( kind: FormatterKind, locale: FormatterLocale, @@ -36,9 +77,10 @@ function construct( ): object { switch (kind) { case "DateTimeFormat": - return new Intl.DateTimeFormat( - locale, + return repairYearPrinting( + guardedDateTimeFormat(locale, options as Intl.DateTimeFormatOptions), options as Intl.DateTimeFormatOptions, + (twin) => cachedFormatter("DateTimeFormat", locale, twin), ); case "NumberFormat": return new Intl.NumberFormat(locale, options as Intl.NumberFormatOptions); @@ -62,40 +104,6 @@ function isCacheableLocale(locale: FormatterLocale): boolean { ); } -/** Whether `Intl` can read this option value without running caller code. */ -function isPlainOptionValue(value: unknown): boolean { - return ( - typeof value === "string" || - typeof value === "boolean" || - (typeof value === "number" && Number.isFinite(value)) - ); -} - -/** - * The own enumerable options as `[name, value]` pairs, read through property descriptors so a - * getter is never run, or `null` when one is an accessor or holds a value `Intl` would coerce - * by running caller code (anything but a string, a finite number or a boolean). An `undefined` - * value is skipped, as `Intl` reads it as absent. - */ -function plainOptionEntries(options: object): [string, unknown][] | null { - const entries: [string, unknown][] = []; - for (const name of Object.keys(options)) { - const descriptor = Object.getOwnPropertyDescriptor(options, name); - if (descriptor === undefined || !("value" in descriptor)) { - return null; - } - const value: unknown = descriptor.value; - if (value === undefined) { - continue; - } - if (!isPlainOptionValue(value)) { - return null; - } - entries.push([name, value]); - } - return entries; -} - /** Whether these entries carry a `timeZone` string. */ function hasZoneString(entries: [string, unknown][]): boolean { return entries.some( @@ -226,4 +234,5 @@ export function clearFormatterCache(): void { formatters.clear(); checked.clear(); builtWith.clear(); + forgetWeekYearVerdicts(); } diff --git a/packages/gmt/src/internal/plainFormatOptions.ts b/packages/gmt/src/internal/plainFormatOptions.ts index 484e53119..b7a815f9a 100644 --- a/packages/gmt/src/internal/plainFormatOptions.ts +++ b/packages/gmt/src/internal/plainFormatOptions.ts @@ -329,7 +329,8 @@ export function plainMonthDayFormatOptions( * `dayPeriod`, `hour`, `minute`, `second` or `fractionalSecondDigits` gives `null` * (anyPresent); otherwise year and month default to `"numeric"`, keeping a copied `era`. * - **V8 `Y` crash.** The result passes `year`, so it must only be given to `format`, never to - * `formatToParts` or `formatRangeToParts`, where V8 before 15.5 traps. + * `formatToParts` or `formatRangeToParts` on a formatter the week-year guard has not covered: + * V8 without commit `0426b0d1045d` aborts there (defect D23, CORE-112). * - Returns `null` for a `timeStyle` (a year-month has no time format). * * @param options caller's `Intl.DateTimeFormatOptions` diff --git a/packages/gmt/src/internal/plainOptionEntries.ts b/packages/gmt/src/internal/plainOptionEntries.ts new file mode 100644 index 000000000..310542711 --- /dev/null +++ b/packages/gmt/src/internal/plainOptionEntries.ts @@ -0,0 +1,41 @@ +/** Whether `Intl` can read this option value without running caller code. */ +function isPlainOptionValue(value: unknown): boolean { + return ( + typeof value === "string" || + typeof value === "boolean" || + (typeof value === "number" && Number.isFinite(value)) + ); +} + +/** + * The own enumerable options as `[name, value]` pairs, read through property descriptors so a + * getter is never run, or `null` when one is an accessor or holds a value `Intl` would coerce + * by running caller code (anything but a string, a finite number or a boolean). An `undefined` + * value is skipped, as `Intl` reads it as absent. + * + * @param options the options object to read + * @returns the pairs, or `null` when the options cannot be keyed safely + * + * @example plainOptionEntries({ year: "numeric", day: undefined }) // [["year", "numeric"]] + * @example plainOptionEntries({ get year() { return "numeric"; } }) // null + */ +export function plainOptionEntries( + options: object, +): [string, unknown][] | null { + const entries: [string, unknown][] = []; + for (const name of Object.keys(options)) { + const descriptor = Object.getOwnPropertyDescriptor(options, name); + if (descriptor === undefined || !("value" in descriptor)) { + return null; + } + const value: unknown = descriptor.value; + if (value === undefined) { + continue; + } + if (!isPlainOptionValue(value)) { + return null; + } + entries.push([name, value]); + } + return entries; +} diff --git a/packages/gmt/src/internal/repairRangeText.test.ts b/packages/gmt/src/internal/repairRangeText.test.ts new file mode 100644 index 000000000..6f4f6f85c --- /dev/null +++ b/packages/gmt/src/internal/repairRangeText.test.ts @@ -0,0 +1,120 @@ +import { repairRangeText } from "./repairRangeText"; + +/** + * The D16 text repair (CORE-112 slice 3a): an engine cuts a requested `timeZoneName` width in a + * range (ICU-20548) and keeps the `short` one, so the range text of a `short` carrier formatter has + * each endpoint's short name in it, and GMT writes the requested name over it. + * + * Expected values follow the rule in the spec: a name printed for one endpoint only is that + * endpoint's; when both endpoints print the same name, an interval pattern writes the start's + * fields before the end's (UTS #35 Part 4 §2.6), so the first hit is the start's and the second the + * end's; one hit is a shared part and takes the start's. The carrier strings are the text V8 returns + * for en-GB Europe/London (recorded: `28/03/2026, 12:00 GMT – 30/03/2026, 13:00 BST`). + */ +describe("repairRangeText", () => { + it("writes each requested name on its own endpoint when the carrier names differ", () => { + expect( + repairRangeText( + "28/03/2026, 12:00 GMT – 30/03/2026, 13:00 BST", + ["GMT", "BST"], + ["Greenwich Mean Time", "British Summer Time"], + ), + ).toBe( + "28/03/2026, 12:00 Greenwich Mean Time – 30/03/2026, 13:00 British Summer Time", + ); + }); + + it("writes the start's name on the first hit and the end's on the second when both print one name", () => { + expect( + repairRangeText( + "15/01/2026, 12:00 GMT – 18/01/2026, 13:00 GMT", + ["GMT", "GMT"], + ["GMT+00:00", "GMT+00:00"], + ), + ).toBe("15/01/2026, 12:00 GMT+00:00 – 18/01/2026, 13:00 GMT+00:00"); + }); + + it("writes the start's and the end's own name on two hits of one carrier name", () => { + expect( + repairRangeText( + "10:00 EST – 11:00 EST", + ["EST", "EST"], + ["start-name", "end-name"], + ), + ).toBe("10:00 start-name – 11:00 end-name"); + }); + + it("writes the start's name on a single shared hit", () => { + expect( + repairRangeText( + "12:00–13:00 GMT", + ["GMT", "GMT"], + ["Greenwich Mean Time", "Greenwich Mean Time"], + ), + ).toBe("12:00–13:00 Greenwich Mean Time"); + }); + + it("returns null when one carrier name has no hit", () => { + expect( + repairRangeText( + "12:00–13:00", + ["GMT", "GMT"], + ["Greenwich Mean Time", "x"], + ), + ).toBeNull(); + }); + + it("returns null when one carrier name has three hits", () => { + expect( + repairRangeText("GMT 12:00 GMT – 13:00 GMT", ["GMT", "GMT"], ["a", "b"]), + ).toBeNull(); + }); + + it("matches the longer name first when one carrier name contains the other", () => { + expect( + repairRangeText( + "10:00 GMT – 11:00 GMT+1", + ["GMT", "GMT+1"], + ["Greenwich Mean Time", "Central European Time"], + ), + ).toBe("10:00 Greenwich Mean Time – 11:00 Central European Time"); + }); + + it("matches the longer name first when it is the start's", () => { + expect( + repairRangeText( + "10:00 GMT+1 – 11:00 GMT", + ["GMT+1", "GMT"], + ["Central European Time", "Greenwich Mean Time"], + ), + ).toBe("10:00 Central European Time – 11:00 Greenwich Mean Time"); + }); + + it("returns null when the start's carrier name is undefined", () => { + expect( + repairRangeText("10:00 – 11:00 GMT", [undefined, "GMT"], ["a", "b"]), + ).toBeNull(); + }); + + it("returns null when the end's carrier name is undefined", () => { + expect( + repairRangeText("10:00 GMT – 11:00", ["GMT", undefined], ["a", "b"]), + ).toBeNull(); + }); + + it("leaves the text outside every hit untouched", () => { + expect(repairRangeText("a GMT b BST c", ["GMT", "BST"], ["X", "Y"])).toBe( + "a X b Y c", + ); + }); + + it("returns null when a requested name is undefined for a hit", () => { + expect( + repairRangeText( + "10:00 GMT – 11:00 BST", + ["GMT", "BST"], + [undefined, "Y"], + ), + ).toBeNull(); + }); +}); diff --git a/packages/gmt/src/internal/repairRangeText.ts b/packages/gmt/src/internal/repairRangeText.ts new file mode 100644 index 000000000..3fbf102a6 --- /dev/null +++ b/packages/gmt/src/internal/repairRangeText.ts @@ -0,0 +1,107 @@ +/** Which endpoint a zone name belongs to: the start (`a`) or the end (`b`). */ +type Endpoint = "a" | "b"; + +/** One occurrence of a carrier name in the range text. `who` is `null` until it is attributed. */ +interface Hit { + readonly index: number; + readonly length: number; + who: Endpoint | null; +} + +/** + * Every occurrence of each name in `text`, longest name first, skipping an occurrence that + * overlaps one already taken (so `GMT` inside `GMT+1` is not a second hit). + */ +function findHits( + text: string, + names: readonly (readonly [string, Endpoint | null])[], +): Hit[] { + const taken = Array.from({ length: text.length }, () => false); + const hits: Hit[] = []; + for (const [name, who] of names) { + for ( + let index = text.indexOf(name); + index >= 0; + index = text.indexOf(name, index + 1) + ) { + const end = index + name.length; + if (taken.slice(index, end).some(Boolean)) { + continue; + } + taken.fill(true, index, end); + hits.push({ index, length: name.length, who }); + } + } + return hits.sort((first, second) => first.index - second.index); +} + +/** + * The range text with the carrier's zone names replaced by the requested ones (defect D16, + * ICU-20548: an affected engine keeps the `short` zone name in a range and drops the requested + * width). Pure over strings, so a test can feed it the text an engine really returned. + * + * Each hit is attributed to an endpoint by a GMT rule, the same attribution `repairRangeParts` reads + * off the parts (CORE-112): + * + * - Carrier names that differ: a name printed for one endpoint only is that endpoint's + * (ECMA-402 PartitionDateTimeRangePattern gives each part one source). The longer name is found + * first, so a name inside the other is not a second hit. + * - Carrier names that are equal: two hits are the start's then the end's, because an interval + * pattern writes the start's fields before the end's (UTS #35 Part 4 §2.6); one hit is a shared + * part and takes the start's; no hit or more than two cannot be attributed. + * + * @param text the carrier's `formatRange` text + * @param carrierNames the carrier's zone name at the start and at the end + * @param wantedNames the requested zone name at the start and at the end + * @returns the repaired text, or `null` when a zone name cannot be given to an endpoint + * + * @example repairRangeText("28/03/2026, 12:00 GMT – 30/03/2026, 13:00 BST", ["GMT", "BST"], ["Greenwich Mean Time", "British Summer Time"]) // "28/03/2026, 12:00 Greenwich Mean Time – 30/03/2026, 13:00 British Summer Time" + * @example repairRangeText("12:00–13:00 GMT", ["GMT", "GMT"], ["GMT+00:00", "GMT+00:00"]) // "12:00–13:00 GMT+00:00" (one shared hit) + * @example repairRangeText("12:00–13:00", ["GMT", "GMT"], ["GMT+00:00", "GMT+00:00"]) // null (no hit) + * @example repairRangeText("12:00–13:00", [undefined, "GMT"], ["a", "b"]) // null (no carrier name) + */ +export function repairRangeText( + text: string, + carrierNames: readonly [string | undefined, string | undefined], + wantedNames: readonly [string | undefined, string | undefined], +): string | null { + const [start, end] = carrierNames; + if (start === undefined || end === undefined) { + return null; + } + let hits: Hit[]; + if (start === end) { + hits = findHits(text, [[start, null]]); + if (hits.length === 2) { + hits[0]!.who = "a"; + hits[1]!.who = "b"; + } else if (hits.length === 1) { + hits[0]!.who = "a"; + } else { + return null; + } + } else { + const names: (readonly [string, Endpoint])[] = + start.length >= end.length + ? [ + [start, "a"], + [end, "b"], + ] + : [ + [end, "b"], + [start, "a"], + ]; + hits = findHits(text, names); + } + let out = ""; + let at = 0; + for (const hit of hits) { + const wanted = hit.who === "a" ? wantedNames[0] : wantedNames[1]; + if (wanted === undefined) { + return null; + } + out += text.slice(at, hit.index) + wanted; + at = hit.index + hit.length; + } + return out + text.slice(at); +} diff --git a/packages/gmt/src/internal/temporalCompat/README.md b/packages/gmt/src/internal/temporalCompat/README.md index ac6e727ea..648d96942 100644 --- a/packages/gmt/src/internal/temporalCompat/README.md +++ b/packages/gmt/src/internal/temporalCompat/README.md @@ -52,13 +52,19 @@ Decisions: `context/domination/issues/CORE-6.md` § Decisions. Owner choices: | **D13** | The time zone transition search samples the offset every 14 days and bisects a step whose ends differ. Two changes inside one step break it. A pair that returns to the same offset is skipped: `getTimeZoneTransition("next")` from 2000-10-01 in `America/Boa_Vista` misses 2000-10-08 and 2000-10-15 (601,200 s apart), and the start of 2000-10-08, whose midnight that change skips, throws a TypeError there and is 2001-10-14 in `America/Noronha`. Three different offsets in one step make the bisection loop for ever: `next` from 1944-04-15 in `Europe/Riga` never returns. Not a calendar defect: named zones. | `internal/zonedTransitionSearch.ts` (`nextTransitionAfter`, `previousTransitionBefore`), called by `zonedNextTransition` and `zonedPreviousTransition` in `internal/zonedWallClockOperations.ts`, which every GMT transition walk goes through; `needsOwnStartOfDaySearch` and `needsOwnDayBoundsSearch` in `internal/zonedWallClock.ts` send a skipped midnight to GMT's own `GetStartOfDay` | While the probe fails: every transition search in a named zone (the polyfill's search cannot be tried first, because it may not return), and a start of day, `hoursInDay` or day rounding whose midnight is skipped. Offset zones and `UTC` pass straight through | | **D14** | `ZonedDateTime#round` to `day` does not clamp an instant in the second piece of a date that starts twice. A fall-back across midnight re-enters a date: `America/Goose_Bay` on 2010-11-06 (from 23:01−04:00), `Antarctica/Casey` on 2010-03-04 (from 23:00+08:00). `Temporal.ZonedDateTime.prototype.round` clamps the instant to the date's last nanosecond (tc39/ecma262#3966, commit `5f44331e0a11`; tc39/proposal-temporal#3312); without it `floor` and `trunc` give the next date's midnight, `ceil` and `expand` the end of the next date, and the half modes are wrong where the clock went back by about a day (`America/Sitka`, 1867-10-18: the second midnight instead of the first). Node 26's V8 throws `RangeError: ZonedDateTime is outside the expected day bounds`. Not a calendar defect: named zones. | `internal/zonedWallClockOperations.ts` `roundZonedDateTime` (the day branch) and `roundToDayFromOwnStartOfDay` (the clamp), called by `roundZoned` and `roundUnix` | While the probe fails: every day rounding in a named zone. Offset zones and `UTC` pass straight through | | **D15** | `ToTemporalZonedDateTime` applies `offset: "ignore"` to a `Z` string and reads the wall clock in the zone, where TC39 keeps the string's own instant: it sets `offsetBehaviour` to ~exact~ for a UTC designator, and `InterpretISODateTimeOffset` applies `ignore` only when `offsetBehaviour` is ~option~. `2022-07-08T00:14:07Z[Europe/London]` with `offset: "ignore"` is `2022-07-08T00:14:07Z` by the spec and `2022-07-07T23:14:07Z` on the polyfill (native V8 in Node 24.21 with `--harmony-temporal` agrees with the polyfill). Near a range limit the wrong reading can also throw for an instant the spec accepts. Not a calendar defect: ISO strings, any zone with a non-zero offset. Not filed upstream yet. js-temporal `main` (`c55b211`) and tc39/proposal-temporal `main` (`e8cc03f`) still have it (bug doc § O). | `internal/zonedWallClock.ts` `zExactOptions`, called by `zonedDateTimeFrom`, which every GMT zoned-string parse goes through (`classifyStoredZoned`, `calendarSystemOfZonedValue` and `parseCalendarZonedValue` pass `offset`) | A string with a `Z` or `z` designator read with `offset: "ignore"`, while the probe fails; GMT reads it with `offset: "use"`, the exact reading. Every other string passes straight through | -| **D16** | ICU-20548: `DateIntervalFormat` drops the `timeZoneName` width in a range. V8 and JSC print `long` and `longGeneric` as short names ("EST", "ET") and drop `shortOffset` and `longOffset` (no `timeZoneName` part at all), where UTS #35 (Matching Skeletons) expects "fields in the skeleton and pattern ... to be adjusted in parallel" and ECMA-402 §11.5.8 builds each range part with FormatDateTimePattern over the range pattern's own fields. The ICU skeleton code (`getDateTimeSkeleton`) drops `O` and cuts `zzzz` and `vvvv` to `z` and `v`. Seen on Node 22.22.2 (ICU 78.2), 24.21.0 and 26.12.1 (ICU 78.3), Chromium 153 and WebKit 26.6; Firefox 155 carries `intl/icu-patches/bug-1856290-ICU-20548-dateinterval-timezone.diff` and is right. Not a calendar defect: any locale and zone, only `Intl.DateTimeFormat#formatRange`. | `internal/repairRangeParts.ts` (the part merge), called by `zoned/format/formatZonedRange.ts` for the zone name branch, gated by `isRangeZoneNameCompatNeeded(style)` | A `formatZonedRange` call with `timeZoneName` `long`, `longGeneric`, `shortOffset` or `longOffset`, while the probe for that style fails. It formats the range with `short`, and writes the requested names (from `formatToParts` of each endpoint) into the zone parts. No `timeZoneName`, `short` and `shortGeneric` pass straight through | +| **D16** | ICU-20548: `DateIntervalFormat` drops the `timeZoneName` width in a range. V8 and JSC print `long` and `longGeneric` as short names ("EST", "ET") and drop `shortOffset` and `longOffset` (no `timeZoneName` part at all), where UTS #35 (Matching Skeletons) expects "fields in the skeleton and pattern ... to be adjusted in parallel" and ECMA-402 §11.5.8 builds each range part with FormatDateTimePattern over the range pattern's own fields. The ICU skeleton code (`getDateTimeSkeleton`) drops `O` and cuts `zzzz` and `vvvv` to `z` and `v`. Seen on Node 22.22.2 (ICU 78.2), 24.21.0 and 26.12.1 (ICU 78.3), Chromium 153 and WebKit 26.6; Firefox 155 carries `intl/icu-patches/bug-1856290-ICU-20548-dateinterval-timezone.diff` and is right. Not a calendar defect: any locale and zone, only `Intl.DateTimeFormat#formatRange`. | `internal/repairRangeText.ts` (the text repair), called by `rangeWithRepairedZoneNames` in `zoned/format/formatZonedRange.ts`, gated by `isRangeZoneNameCompatNeeded(style)`; with D17 also on, `internal/repairRangeParts.ts` (the part merge) through `rangeWithRepairedParts` | A `formatZonedRange` call with `timeZoneName` `long`, `longGeneric`, `shortOffset` or `longOffset`, while the probe for that style fails. It formats the range with `short`, and writes the requested names (from `formatToParts` of each endpoint) over the short ones in the `formatRange` text, so no range parts call reaches a V8 that aborts on one (D23). No `timeZoneName`, `short` and `shortGeneric` pass straight through | | **D17** | SpiderMonkey (Firefox 155) `formatRange` writes the AM/PM day period where `dayPeriod` asks for a flexible one ("10 AM GMT-5 – 12 PM GMT-5" for 10:00 to 12:00 in New York with `{ hour, dayPeriod: "short", timeZoneName: "shortOffset" }`), when `timeZoneName` is set and neither `hourCycle` nor `hour12` is. Its single format is right ("10 in the morning GMT-5", "12 noon GMT-5"). Not a width rule (UTS #35 treats a, b and B as close matches): ECMA-402 §11.5.8 picks the range pattern by the resolved [[HourCycle]] only, en-US resolves to h12 with or without `hourCycle: "h12"`, yet only the explicit one prints the flexible period. It happens with `short`, `long` and the offset zone styles, with and without minutes, and not with no `timeZoneName`, `hourCycle: "h12"` or `hour12: true`. An affected range always prints each endpoint whole (`startRange` and `endRange` parts, never a shared `dayPeriod`). V8 and JSC are right. Not a calendar defect. Filed as [Bugzilla 2085525](https://bugzilla.mozilla.org/show_bug.cgi?id=2085525); engine record Q in the bug doc. | `internal/repairRangeParts.ts` (the part merge), called by `zoned/format/formatZonedRange.ts` for the day period branch, gated by `isRangeDayPeriodCompatNeeded()` | A `formatZonedRange` call with `dayPeriod` and `timeZoneName`, while the probe fails. It replaces each day period part with the endpoint's single-format day period. Everything else passes straight through | | **D18** | WebKit (JavaScriptCore: Safari and Playwright WebKit 26.6) prints an `islamic-civil`, `islamic-tbla` or `islamic-umalqura` date before the Hijra as a positive year in a second era (`Before Hijra`), where V8 and SpiderMonkey print a negative year in the one era. Polyfill 0.5.1 (`IslamicBaseHelper`, no era) takes the year as printed, so ISO `0621-01-01` reads as year 2 instead of -1 and `-271821-04-19` as 280805 instead of -280804; month, month code and day read correctly. The polyfill's fields → ISO conversion, add and until for an Islamic year <= 1 then do not return in WebKit, or land in the mirror year (year 1 and year 0 print the same digits, and the epoch day itself, 1 Muharram of year 1, prints as year 0 in the earlier era): `diffDateAsDuration` over the Islamic minimum hung the WebKit control pass of the native suite. The Intl era/monthCode proposal numbers the years through the epoch (`bh` era year n is year 1 - n); Node 26 native Temporal gives the expected values. Not filed yet; record R in the bug doc (`main` declares the Islamic eras, which may or may not read WebKit's spelling). | Reads: `calendarFields.ts` → `islamicEra.ts` (the date's era part compared with a modern date's, from the runtime's own formatter). Fields → ISO: `calendarDateFromFields.ts` → `fieldSearch.ts` for years <= 1 (`polyfillCannotReturn`), and for any Islamic year whose polyfill answer does not read back. Arithmetic: `calendarDateArithmetic.ts` → `nonIsoArithmetic.ts` over `readArithmeticModel.ts`, whose month steps for such years are `fixedMonthArithmetic.ts` at the runtime's month count | Reads: an Islamic date whose era part is not a modern date's, while the probe fails (year becomes `1 - read`). Fields → ISO and arithmetic: an Islamic year <= 1 at either end or within 2 years of the sum, while the probe fails. Every other date, year and engine passes straight through | | **D19** | `ZonedDateTime#equals` answers false for two identifiers of one time zone on a host whose `Intl.DateTimeFormat#resolvedOptions` returns the identifier as written. The polyfill's `GetAvailableNamedTimeZoneIdentifier` finds a primary identifier in `Intl.supportedValuesOf("timeZone")` and takes a non-primary identifier's primary from `resolvedOptions().timeZone`. ECMA-262 TimeZoneEquals compares the two [[PrimaryIdentifier]]s, and ECMA-402 §6.5 (Time Zone Identifiers) fixes `"UTC"` as primary with `"Etc/UTC"`, `"Etc/GMT"` and `"GMT"` resolving to it; the IANA backward links (`Asia/Calcutta` → `Asia/Kolkata`) are the rest. JavaScriptCore (WebKit 26.6 in Playwright, Safari 27) keeps the identifier as written, the rule of the Stage 3 Time Zone Canonicalization proposal, so there the polyfill compares `Etc/UTC` with `UTC` and `Asia/Calcutta` with `Asia/Kolkata` and answers false, and `diffZoned` and `intervalLengthZoned` refuse a calendar unit across the pair. V8 and SpiderMonkey return the primary identifier and are right; native WebKit `Temporal` is right. Not a calendar defect: any pair of identifiers of one zone. Polyfill record U in the bug doc, not filed yet. | `temporalCompat/timeZoneEquals.ts`, called by `isCalendarDifferenceAcrossZones` (`internal/zonedWallClockDifference.ts`) for `diffZoned`, `diffZonedAsDuration` and `intervalLengthZoned`, gated by `isTimeZoneEqualsCompatNeeded()` | Two different identifiers while the probe fails: GMT resolves `Etc/UTC`, `Etc/GMT` and `GMT` to `UTC` by name (ECMA-402 §6.5, on every host, Safari 27 included), then asks the host's own `Temporal.ZonedDateTime#equals` when `globalThis.Temporal` exists (WebKit 26.6). On a host without `Temporal` (Safari 27) the polyfill's answer stands for any other pair, so the IANA links (`Asia/Calcutta`, `Etc/UCT`) stay two zones there: resolving a link needs IANA data that no Intl API exposes (bug doc § U). Equal identifiers, and every pair while the probe passes, go straight through | | **D20** | `Temporal.PlainMonthDay.from` and `Temporal.PlainYearMonth.from` throw "MM-DD format is only valid with iso8601 calendar" and "YYYY-MM format is only valid with iso8601 calendar" for an upper-case calendar annotation (`--12-25[u-ca=ISO8601]`, `2026-10[!u-ca=Iso8601]`). `ParseTemporalMonthDayString` and `ParseTemporalYearMonthString` in polyfill 0.5.1 (`lib/ecmascript.ts`) compare the `u-ca` value with `'iso8601'` as written. Temporal ParseISODateTime, for the goals TemporalMonthDayString with no DateYear and TemporalYearMonthString with no DateDay, lowercases it first: "If _calendar_ is not ~empty~ and the ASCII-lowercase of _calendar_ is not *"iso8601"*, throw a *RangeError* exception". tc39 `385b479bf8` (2026-02-26) aligned the reference polyfill; js-temporal `main` at `c55b211` still has the old check. Polyfill record V in the bug doc. | `temporalCompat/isoCalendarFrom.ts` (`monthDayFrom`, `yearMonthFrom`), called by `plainMonthDayOf` and `plainYearMonthOf` (`internal/inputChecks.ts`) for `isValidMonthDay`, `parseMonthDay`, `isValidYearMonth` and `parseYearMonth`, gated by `isIsoCalendarCaseCompatNeeded()` | None: the rewrite is pure string work. While the probe fails, the value of every `[u-ca=…]` and `[!u-ca=…]` annotation is lower-cased in ASCII (never `toLowerCase()`, which folds non-ASCII letters) and the string goes to `Temporal.PlainMonthDay.from` or `Temporal.PlainYearMonth.from`; every other part is passed unchanged, so every other error is Temporal's own | | **D21** | `Temporal.Now` reads one millisecond early after a clock before 1970. Polyfill 0.5.1's `SystemUTCEpochNanoSeconds` (`lib/ecmascript.ts`) adds the previous reading's `ms % 1e6` as a sub-millisecond tail; `%` keeps the sign, so after a `Date.now()` before 1970 the tail is negative and the next reading lands in the millisecond before `Date.now()` (a faked 1960-01-01T00:00:00Z reads 1959-12-31T23:59:59.9998Z, and a later 2027-01-01T00:00:00Z reads in 2026). The Temporal proposal defines SystemUTCEpochMilliseconds as the floor of SystemUTCEpochNanoseconds over 1e6 (`spec/temporal.html`) and wires it into `Date.now()` (`spec/mainadditions.html`), and test262 `built-ins/Temporal/Now/instant/return-value-value.js` asserts a reading is not earlier than a `Date.now()` taken before it (tc39/proposal-temporal#3335). | `clock.ts` (`nowInstant`, `nowZonedDateTimeISO` and the three plain readers derived from it); every production `Temporal.Now` call goes through it, and `internal/temporal.test.ts` fails on a direct call | Only a reading in the millisecond before `Date.now()`; one millisecond is added, clamped to the Instant range. No probe: a fixed runtime never produces such a reading | | **D22** | A zoned `relativeTo` or start in a repeated hour is measured from the wrong instant. TC39 `ComputeNudgeWindow` takes the window's start from the origin's own exact time when no date unit has been added (tc39/ecma262#3759, commit `1f4e6717ef23`), and `DifferenceZonedDateTime` subtracts the exact times when both fall on one local date. Polyfill 0.5.1 does neither: it turns the wall clock back into an exact time with `"compatible"`, which takes the earlier pass. From `2024-11-03T01:30:00-05:00[America/New_York]`, `PT0S` totals 0.04 days (TC39: 0), `PT11H45M` rounds to `P1D` (TC39: `PT0S`), and `until` an hour later with `largestUnit: "day"` gives `PT2H` (TC39: `PT1H`). From the `-04:00` pass, `PT30M` totals 0.0208 days (TC39: 0.02) and `until` the same end throws (TC39: `PT30M`). Where a TC39 Assert fails no value exists (tc39/proposal-temporal#3336), so GMT returns its sentinel where the polyfill extrapolates: `PT24H30M` from `2024-11-02T01:30:00-04:00[America/New_York]` in days is `null` (polyfill: 1.0208). A skipped hour reaches the same Assert: `-PT23H20M` from `2024-03-11T02:30:00-04:00[America/New_York]` in days is `null` (polyfill: -1.0145), because the window's end bound `2024-03-10T02:30` is in the gap and `"compatible"` moves it past the target. Bug doc § AC. | `internal/zonedDifference/nudgeOrigin.ts`, called from `durationTotal`, `durationRound` and the repeated-hour term in `untilTakesSpecPath` (`internal/zonedWallClockDifference.ts`) | A date unit (`total`) or date `largestUnit` (`round`, `until`) when the origin or the target names two instants, or the target is earlier and a window's end bound falls in a gap, while the probe fails | +| **D23** | V8 without commit `0426b0d1045d` ("[intl] Handle UDAT_YEAR_WOY_FIELD in IcuDateFieldIdToDateType") has no part type for ICU's week-of-year year field, so `formatToParts` and `formatRangeToParts` on a pattern with `Y` (D24) stop the process: SIGTRAP, exit code 133, no exception, nothing can catch it. The same V8 resolves no `year` in `resolvedOptions()` for such a pattern. Seen on every installed Node, 22.22.2 to 26.13.0; Chromium 158 has the fix, and SpiderMonkey and JavaScriptCore are right. On `main` before CORE-112, `formatZonedRange` (`my-u-ca-buddhist`, `timeZoneName: "long"`, through the D16 carrier's `formatRangeToParts`) and `formatCalendar` (`gl-u-ca-hebrew`, `-buddhist` or `-roc`, through `dateStyle: "full"` parts) aborted. Filed as nodejs/node#67076; bug doc § AF. | `internal/weekYearGuard.ts` (`guardDateTimeFormat`), called by `construct` in `internal/formatterCache.ts`, so every `cachedFormatter("DateTimeFormat", …)` goes through it; `internal/weekYearSynth.ts` builds the parts from the `format` text of twin formatters. `formatZonedRange` makes no range parts call for D16 (`rangeWithRepairedZoneNames`) | A formatter that prints a year, has no `dateStyle`, and resolves no `year` (`chinese` and `dangi` excepted: V8 lists no year letter for them and handles them in parts). Its `formatToParts` is built from `format` text and never reaches the engine; its `formatRangeToParts` throws a `TypeError` (only the D17 branch calls one, on Firefox). A `dateStyle` formatter is flagged by D24's check, and a flagged formatter with `dateStyle` never calls the native parts. Every other formatter is returned as built | +| **D24** | CLDR 48 date patterns use `Y` (UTS #35 Part 4 § 8, the year of the week-of-year) where `y`, the calendar year, is meant: ak, de-CH, gd, gl, kok, ksh, my, sc and te. CLDR 49 keeps them and adds de with its regional variants, kek, ki and pt. ECMA-402 FormatDateTimePattern prints the calendar year (the era year with an era). Every engine prints the week-year: gd `Dùbh 2025` for 2024-12-30, `te-u-ca-buddhist` `జులై 2026` for 2026-07-01 (the Gregorian week-year; the Buddhist year is 2569, so it is wrong every day), `gl-u-ca-hebrew` with `dateStyle: "full"` 5786 for 1 Tishri 5787. [CLDR-19873](https://unicode-org.atlassian.net/browse/CLDR-19873) (not ours) reports gl and kek, and our comment there the rest; bug doc § AF. | `internal/weekYearGuard.ts` (`isFlagged`, `guarded`), called by `construct` in `internal/formatterCache.ts`; `internal/weekYearText.ts` finds the year's digit runs and writes the calendar year in their digits and width; `internal/weekYearSynth.ts` (parts); `internal/weekYearRange.ts` (`formatRangeChecked`: the same repair on `formatRange` text, with a lazy verdict per formatter, called by `formatDateRange`, `formatDateTimeRange`, `formatZonedRange` and the stand-in's `formatRange`; no parts call) | A formatter that prints a year whose `format` text, at the starts and ends of three calendar years, holds a year other than the calendar year (`isWeekYear`, `format` calls only). The verdict is kept per locale, calendar, numbering system, hour cycle and options (at most 256). A flagged formatter's `format` and `formatToParts` give the calendar year; every other formatter is returned as built. Options with a getter are left unguarded: library code snapshots a caller's options into plain values first | +| **D25** | ICU-23341 and ICU-23619: the `japanese` calendar prints a Japanese era for dates before 1873-01-01. Intl era/monthCode Table 2, as amended by [tc39/proposal-intl-era-monthcode#86](https://github.com/tc39/proposal-intl-era-monthcode/issues/86) (test262 tc39/test262#4877), uses the Gregorian eras up to and including 1872-12-31 and the solar Japanese eras from 1873-01-01 (Meiji 6). Seen on Node 26.12.1 (ICU 78.3): `en-u-ca-japanese` with `{ era: "short", year: "numeric" }` prints `-645 Taika` for ISO -0001-07-10 (specification: `2 BC`) and `5 Meiji` for 1872-12-31 (specification: `1872 AD`). | `internal/yearPrinting.ts` (`repairYearPrinting`), called by `construct` in `internal/formatterCache.ts`, gated by `isJapaneseEraCompatNeeded()` | A formatter on the `japanese` calendar that can print an era or a year, while the probe fails. `format`, `formatToParts` and `formatRange` send a date before 1873-01-01 (in the formatter's zone) through a `calendar: "gregory"` twin built from the same locale and options; a range with either end before it prints wholly through the twin, in one calendar | +| **D26** | ICU-23327: an `islamic*` calendar prints a date before the Hijra as a negative year in the one era (`-22 AH` for `islamic-civil` at ISO 600-07-10 on Node 26.12.1). Intl era/monthCode Table 2 and § 4.1.12 give a second era, `bh`, and test262 `intl402/DateTimeFormat/prototype/formatToParts/era.js` requires two era names. The engine has no name for it that GMT could use without owning era data, so the date has no printable year. | `internal/yearPrinting.ts` (`repairYearPrinting`), gated by `isIslamicEraCompatNeeded()`; `internal/temporalCompat/islamicEra.ts` (D18) reads its era through `guardedDateTimeFormat`, which skips this repair | An `islamic*` formatter that can print an era or a year, while the probe fails. A date (or a range endpoint) that Temporal places before the Hijra (era `bh`, or year 0 or less in the calendar) gives the function's empty value: `""` for a text, `[]` for parts. Later dates are the engine's own text | +| **D27** | ICU-23620: with `year: "2-digit"` the `ja` locale's `japanese` calendar prints the era year unpadded (`令和6年` for 2024-07-10 on Node 26.12.1). ECMA-402 FormatDateTimePattern formats a `2-digit` year with FormatNumeric at `minimumIntegerDigits` 2, so the specification gives `令和06年`. CLDR keeps 元年 for year 1, and so does GMT (owner decision). | `internal/yearPrinting.ts` (`repairYearPrinting`), gated by `isJapaneseTwoDigitYearCompatNeeded()` | A `ja` formatter on the `japanese` calendar built with `year: "2-digit"`, while the probe fails. A one-digit `year` part gains the formatter's own numbering-system zero (`format` joins the padded parts). In a range text the digit run that moves when an endpoint moves by whole years is the era year, and gains the zero when it has one digit; 元 is no digit run and is never touched. Numeric-only patterns (`R06/7/10`) are the engine's own | +| **D28** | ICU-23621: `year: "2-digit"` on `chinese` and `dangi` pads the related year to two digits (`05` for ISO 0005-07-10 on Node 26.12.1, `-01` for ISO -0001). ECMA-402 FormatDateTimePattern prints `relatedYear` with FormatNumeric at full width and gives it no 2-digit form (`5`, `-1`). | `widenRelatedYear` in `internal/yearPrinting.ts`, called by `guardedDateTimeFormat` in `internal/formatterCache.ts`; `internal/weekYearRange.ts` already measures a chinese or dangi year at full width, so its width rule follows | A `chinese` or `dangi` formatter built with `year: "2-digit"`, while `isRelatedYearWidthCompatNeeded()` fails. It is built with `year: "numeric"` instead, the same pattern at full width, so `format`, `formatToParts` and `formatRange` all print the related year unpadded; no per-format work runs | Fields → ISO (`calendarDateFromFields`): asks the polyfill first. It keeps the result when the fields read back unchanged through `calendarFieldsOf`. Otherwise, inside a D1 window or a corrected read @@ -196,6 +202,12 @@ limits) is the `D1` group. | D20 | A js-temporal release carrying tc39 `385b479bf8` ("Canonicalize calendar before checking YYYY-MM or MM-DD format"), so the `D20` probe (`--12-25[u-ca=ISO8601]` reads as `12-25` and `2026-10[u-ca=ISO8601]` as `2026-10`) passes on Node. The expected value is the specification's, so GMT owns no calendar data | | D21 | A js-temporal release whose `SystemUTCEpochNanoSeconds` carries a floored modulo (or none), so the `D21` repro (the second `Temporal.Now.instant()` with `Date.now()` at 1960-01-01T00:00:00Z reads 1960) passes on Node; tc39/proposal-temporal#3335. The expected value is the specification's and test262's, not an oracle run | | D22 | A js-temporal release contains `3c403686d39` ("fix for issues #3141, #3148 and #3149", on `main`, no filing needed) and tc39/proposal-temporal#3319, so every `D22` repro passes, `P7D` with `largestUnit: "week"` giving `P1W` among them. `3c403686d39` alone is not enough: it tests `r1 = 0`, where #3319 and tc39/ecma262#3759 test for an empty date duration. `main` (read, not run) does not yet carry #3319, so by its source `P7D` gives `P1W1D` there, where TC39 and Chromium 153 give `P1W`. The release must also give no value for every read in `totalsWithNoValue`, `noDayCorrection` and `emptyDaySpan`: `main` has the window, sign and day-correction Asserts in its source and strips them from a production build, so by that reading it fails those repros. The repros are samples of each shape, so `test/noSpecValue.test.ts` must also pass on the release (bug doc § AC) | +| D23 | Every V8 the checks read passes the `D23` repro (a `gd` formatter with `{ year: "numeric", month: "short" }` resolves `year: "numeric"`): the V8 of GMT's `engines.node` floor (`pnpm compat`) and the Chromium of the weekly `temporal-oracle` run (`temporal-compat-chromium`) carry `0426b0d1045d`, and the child-process confirmation of `scripts/canary/weekYear.mjs` exits 0 with a `year` part. D23 names `engines: ["v8"]` (`scripts/lib/workarounds.mjs`), so the Firefox and WebKit checks report it out of scope, never removable. The expected value is ECMA-402 CreateDateTimeFormat's, so GMT owns no CLDR string | +| D24 | CLDR uses `y` in these patterns (CLDR-19873) and every engine ships that data: every engine's compat check passes every `D24` repro, and the weekly sweep of `scripts/canary/weekYear.mjs` flags no locale, calendar or option set. D24 goes with or after D23: once no pattern holds `Y`, the D23 abort cannot be reached. The expected values are ECMA-402's calendar year | +| D25 | Every engine's compat check passes every `D25` repro: the japanese calendar prints `2 BC` for ISO -0001-07-10 and `1872 AD` for 1872-12-31 in `en` (ICU 78 prints Taika and Meiji eras there). The expected values are the rule of tc39/proposal-intl-era-monthcode#86 and test262 tc39/test262#4877, so GMT owns no era data | +| D26 | Every engine's compat check passes the `D26` repro: `en-u-ca-islamic-civil` prints a different era text (digits and signs aside) for ISO 600-07-10 and 2025-07-10. WebKit already does (D18 reads that era), so `engines` is not narrowed. The expected value is Intl era/monthCode Table 2's two eras | +| D27 | Every engine's compat check passes the `D27` repro: `ja-u-ca-japanese` with `year: "2-digit"` prints `令和06年` for 2024-07-10. The expected value is ECMA-402's FormatNumeric at two digits | +| D28 | Every engine's compat check passes the `D28` repro: `en-u-ca-chinese` with `year: "2-digit"` prints the related year `5` for ISO 0005-07-10. The expected value is ECMA-402's full-width FormatNumeric | | zoned.A | A js-temporal release contains `05ce7a3` (maximum) **and** `95237e0` (minimum), both on main. `05ce7a3` alone fixes only the `max.*` probes: a 0.5.1 build with just that commit still throws for every `min.*` probe | | zoned.B | A js-temporal release fixes `GetNamedTimeZoneNextTransition` near the maximum. Not fixed on main; the verified patch is in bug doc § B | | zoned.D | A js-temporal release ports proposal-temporal #3205 (`d90d432`), which validates the `"UTC"` fast path of `GetPossibleEpochNanoseconds` (bug doc § D) | @@ -287,7 +299,7 @@ In every case the fix must be in the release that becomes GMT's `@js-temporal/po either way. 14. **D14:** delete the probe-gated routing: the `isDayRoundClampCompatNeeded()` term in the day branch of `roundZonedDateTime` (`internal/zonedWallClockOperations.ts`; the branch itself stays for the D13 and pre-1847 cases), `isDayRoundClampCompatNeeded` in `capabilities.ts` and its export in `index.ts`, and the `D14` repros. Keep the `min(thisNs, endNs - 1)` clamp in `roundToDayFromOwnStartOfDay`: it is the spec step, and the D13, pre-1847 and range-edge paths use it. Keep the same-date-starts-twice rows in `roundZoned.test.ts` and `roundUnix.test.ts`: their values are test262's and hold either way. 15. **D15:** delete `zExactOptions` and its call in `zonedDateTimeFrom` (`internal/zonedWallClock.ts`, with defect 6 in that file's header note), `UTC_DESIGNATOR`, `isZIgnoreExactCompatNeeded` in `capabilities.ts` and its export in `index.ts`, and the `D15` repros. Keep the `Z` rows in `zonedWallClock.test.ts` and `calendarValueOfZoned.test.ts`, and the all-16-cells row in `classifyStoredZoned.test.ts`: their values are the specification's and hold either way. -16. **D16:** delete the `zoneNames` branch of `rangeWithRepairedParts` (the `timeZoneName` entry in its type list) and its gate in `zoned/format/formatZonedRange.ts`, `isRangeZoneNameCompatNeeded` in `capabilities.ts` and its export in `index.ts`, and the `D16` repros. Keep every `formatZonedRange` row: their values are the field formats and hold either way. +16. **D16:** delete `rangeWithRepairedZoneNames`, the `zoneNames` branch of `rangeWithRepairedParts` (the `timeZoneName` entry in its type list) and their gate in `zoned/format/formatZonedRange.ts`, `internal/repairRangeText.ts` and its test, `isRangeZoneNameCompatNeeded` in `capabilities.ts` and its export in `index.ts`, and the `D16` repros. Keep every `formatZonedRange` row: their values are the field formats and hold either way. 17. **D17:** delete the `dayPeriods` branch of `rangeWithRepairedParts` (the `dayPeriod` entry in its type list) and its gate in `zoned/format/formatZonedRange.ts`, `isRangeDayPeriodCompatNeeded` in `capabilities.ts` and its export in `index.ts`, and the `D17` repros. Keep every `formatZonedRange` row and the `D17` rows of `internal/repairRangeParts.test.ts`: the values are the requested forms and hold either way (delete `repairRangeParts` only with the last of D16 and D17). 18. **D18:** delete `islamicEra.ts`, `fixedMonthArithmetic.ts` and their tests, `islamicFields`, `ISLAMIC_CALENDARS`, `polyfillMisreadsIslamicEra` and `polyfillCannotReturn` in `calendarFields.ts` (the `default` case of `calendarFieldsOf` returns the runtime read and the `default` case of `hasReadCorrection` returns false), the D18 branch at the top of `calendarDateFromFields` and the D18 term of `needsFieldSearch`, `fixedMonthsIfPolyfillCannotReturn` and its two uses in `readArithmeticModel.ts`, `reachesPolyfillLimit`, `lowestYearOfSum` and their two branches in `calendarDateArithmetic.ts`, `fixedMonthsPerYearOf` in `largeMonthSpan.ts`, and the `D18` repros. Keep every Islamic row of `diffDateAsDuration.edges.test.ts` and `addDate.edges.test.ts`: the values are the spec's and hold either way. 19. **D19:** delete `temporalCompat/timeZoneEquals.ts` and its exports in `index.ts`, `isTimeZoneEqualsCompatNeeded` in `capabilities.ts` and its export in `index.ts`, and the `D19` repro; `isCalendarDifferenceAcrossZones` (`internal/zonedWallClockDifference.ts`) compares with `new Temporal.ZonedDateTime(0n, id).equals(...)` again. Keep every `diffZoned`, `diffZonedAsDuration` and `intervalLengthZoned` row: the values are TimeZoneEquals answers and hold either way. @@ -317,7 +329,38 @@ In every case the fix must be in the release that becomes GMT's `@js-temporal/po the release first, with the probe passing and so the gate off. If a row fails, D22 stays. If tc39/proposal-temporal#3336, #3311 or #3310 gives these lengths a value instead, the rows, the throws and the repros change together. -23. **After every step:** run the calendar test files (`plain/convert`, `zoned/convert`, +23. **D23:** delete `internal/weekYearSynth.ts` and its test, the `crashes` signal in + `guardDateTimeFormat` and the synthesis path in `guarded` (`internal/weekYearGuard.ts`): a + flagged formatter's `formatToParts` then takes the native parts with the year patched + (`patchYearParts`), and its `formatRangeToParts` is the native one. Delete the `D23` repro in + `repros.ts` (and `"D23"` in `CanaryDefectId`), the child-process confirmation in + `scripts/canary/weekYear.mjs`, the D23 entry in `scripts/lib/workarounds.mjs` and + `WHAT_BREAKS.D23` in `apps/dox/src/data/temporal-compat.ts`. Keep every row of + `internal/weekYearAbort.test.ts` and `internal/weekYearSingle.test.ts`: the values are + ECMA-402's and hold either way. +24. **D24:** delete `internal/weekYearGuard.ts`, `internal/weekYearText.ts`, + `internal/weekYearRange.ts` and its tests (`weekYearRange.test.ts`, `weekYearRangeNull.test.ts`, + `weekYearRangeText.test.ts`), the `formatRangeChecked` calls in `formatDateRange`, + `formatDateTimeRange` and `formatZonedRange` (each goes back to `formatRange`), + `internal/weekYearSynth.ts` (if D23 is still there, with step 23) and their tests, the + `guardDateTimeFormat` call in `construct` and the `forgetWeekYearVerdicts` call in + `clearFormatterCache` (`internal/formatterCache.ts`), `internal/temporalCompat/weekYearSource.test.ts`, + the `D24` repros and `weekYearInputs` in `repros.ts` (and `CanaryDefectId` with its last member), + `scripts/canary/weekYear.mjs` and its entry in `.fallowrc.jsonc`, the D24 entry in + `scripts/lib/workarounds.mjs` and `WHAT_BREAKS.D24`. `internal/plainOptionEntries.ts` stays: + `formatterCache.ts` reads it too. Keep every row of `internal/weekYearSingle.test.ts`, + `internal/weekYearAbort.test.ts` and `zoned/format/formatZonedRangeWeekYear.test.ts`: the values + are ECMA-402's and hold either way. `weekYearRange.ts` also carries two polyfill stand-ins that + go with it: `coptic` and `ethiopic` are read through `ethioaa` (the polyfill 0.5.1 throws "Era + am ... was not matched by any era" for every date in those two; the years differ by a fixed + 5776 and 5500, Calendrical Calculations ch. 4), and a range the polyfill cannot project (`indian` + before ISO year 1, V8 bug 10529) keeps ICU's text. Retire both when the polyfill reads those + calendars. +25. **D25:** delete the era branch of `repairYearPrinting` in `internal/yearPrinting.ts` (`beforeEras`, the Gregorian twin and the `era` flag), `isJapaneseEraCompatNeeded` in `capabilities.ts`, the `D25` repros in `repros.ts` (and `"D25"` in `CanaryDefectId`), the D25 entry in `scripts/lib/workarounds.mjs` and `WHAT_BREAKS.D25` in `apps/dox/src/data/temporal-compat.ts`. Keep every `D25` row in `internal/yearPrinting.test.ts`: the values are the proposal's and hold either way. +26. **D26:** delete the Hijra branch of `repairYearPrinting` (`beforeHijra` and the `islamic` flag), `isIslamicEraCompatNeeded`, the `D26` repro and `"D26"`, the D26 entry in `scripts/lib/workarounds.mjs` and `WHAT_BREAKS.D26`. `guardedDateTimeFormat` in `internal/formatterCache.ts` and its use in `temporalCompat/islamicEra.ts` stay while D18 does: they give D18 the engine's own parts. Keep the `D26` rows in `internal/yearPrinting.test.ts` except those that assert the empty value, which a fixed engine replaces with the era's text. +27. **D27:** delete the padding branch of `repairYearPrinting` (`padPart`, `paddedRange`, `shiftOf` and the `pad` flag), `isJapaneseTwoDigitYearCompatNeeded`, the `D27` repro and `"D27"`, the D27 entry in `scripts/lib/workarounds.mjs` and `WHAT_BREAKS.D27`. Keep the `D27` rows: `令和06年` and 元 are ECMA-402's and CLDR's values either way. +28. **D28:** delete `widenRelatedYear` and its call in `guardedDateTimeFormat` (`internal/formatterCache.ts`), `isRelatedYearWidthCompatNeeded`, the `D28` repro and `"D28"`, the D28 entry in `scripts/lib/workarounds.mjs` and `WHAT_BREAKS.D28`. When steps 25 to 28 are all done, delete `internal/yearPrinting.ts`, its hook in `construct`, `yearPrintingDormant.test.ts` and `temporalCompat/yearPrintingProbes.test.ts`, and drop `yearPrinting` from `weekYearSource.test.ts`. Keep the `D28` rows. +29. **After every step:** run the calendar test files (`plain/convert`, `zoned/convert`, `plain/validate/isValidCalendarDate`, `plain/calculate/{addDate,subtractDate,diffDate,diffDateAsDuration}`, `plain/interval/{intervalLengthDate,intervalCountDate,intervalFromDurationDate,splitIntervalByUnitDate}`, `zoned/calculate/{addZoned,subtractZoned,diffZoned,diffZonedAsDuration}`, diff --git a/packages/gmt/src/internal/temporalCompat/capabilities.ts b/packages/gmt/src/internal/temporalCompat/capabilities.ts index 1602a4265..f51f42b66 100644 --- a/packages/gmt/src/internal/temporalCompat/capabilities.ts +++ b/packages/gmt/src/internal/temporalCompat/capabilities.ts @@ -1,3 +1,4 @@ +import { Temporal } from "../temporal"; import { type DefectId, type ProbeRepro, probeRepros } from "./probeRepros"; /* @@ -239,3 +240,118 @@ export function isCalendarArithmeticCompatNeeded(calendarId: string): boolean { ARITHMETIC_DEFECTS.some((defect) => isDefectPresent(defect, calendarId)) ); } + +const engineProbeCache = new Map(); + +/** `Intl.DateTimeFormat` text for a UTC date given as year, month and day (any year, 0 to 99 too). */ +function textAt( + locale: string, + options: Intl.DateTimeFormatOptions, + date: readonly [number, number, number], +): string { + const time = Temporal.PlainDate.from({ + year: date[0], + month: date[1], + day: date[2], + }).toZonedDateTime("UTC").epochMilliseconds; + return new Intl.DateTimeFormat(locale, { + ...options, + timeZone: "UTC", + }).format(time); +} + +/** One engine probe, answered the first time it is asked and kept: `true` when the engine has the defect. */ +function engineDefect(key: string, fails: () => boolean): boolean { + const cached = engineProbeCache.get(key); + if (cached !== undefined) { + return cached; + } + let present: boolean; + try { + present = fails(); + } catch { + // An engine that cannot run the probe cannot print the calendar either: nothing to repair. + present = false; + } + engineProbeCache.set(key, present); + return present; +} + +/** + * True when this runtime's japanese calendar prints a Japanese era for a date the Gregorian + * eras cover (defect D25, ICU-23341 and ICU-23619). + * + * Intl era/monthCode Table 2, as amended by tc39/proposal-intl-era-monthcode#86 (test262 + * tc39/test262#4877): for dates up to and including 1872-12-31 the japanese calendar uses the + * Gregorian eras. ICU 78 prints `-645 Taika` for ISO -0001-07-10 and `5 Meiji` for 1872-12-31. The + * probe compares the japanese calendar's era and year with the Gregorian calendar's at both dates. + */ +export function isJapaneseEraCompatNeeded(): boolean { + return engineDefect("D25", () => + ( + [ + [-1, 7, 10], + [1872, 12, 31], + ] as const + ).some( + (date) => + textAt("en-u-ca-japanese", { era: "short", year: "numeric" }, date) !== + textAt("en-u-ca-gregory", { era: "short", year: "numeric" }, date), + ), + ); +} + +/** + * True when this runtime prints a date before the Hijra in the one Islamic era, as a negative year + * (defect D26, ICU-23327). + * + * Intl era/monthCode Table 2 and § 4.1.12 give the `bh` era, and test262 + * `intl402/DateTimeFormat/prototype/formatToParts/era.js` requires ISO 600 and 2025 to print + * different era names. The probe compares the text with its digits and signs taken out. + */ +export function isIslamicEraCompatNeeded(): boolean { + const eraOf = (date: readonly [number, number, number]): string => + textAt( + "en-u-ca-islamic-civil", + { era: "short", year: "numeric" }, + date, + ).replace(/[\p{Nd}\p{Pd}\p{Z}−]/gu, ""); + return engineDefect( + "D26", + () => eraOf([600, 7, 10]) === eraOf([2025, 7, 10]), + ); +} + +/** + * True when this runtime does not pad a Japanese era year under `year: "2-digit"` (defect D27, + * ICU-23620). + * + * ECMA-402 FormatDateTimePattern, the "2-digit" branch: FormatNumeric with `minimumIntegerDigits: + * 2`, so Reiwa 6 is `06`. ICU's `jpanyear` numbering ignores the minimum digit count. + */ +export function isJapaneseTwoDigitYearCompatNeeded(): boolean { + return engineDefect( + "D27", + () => + !/\p{Nd}{2}/u.test( + textAt("ja-u-ca-japanese", { year: "2-digit" }, [2024, 7, 10]), + ), + ); +} + +/** + * True when this runtime pads the related year of the chinese and dangi calendars under `year: + * "2-digit"` (defect D28, ICU-23621). + * + * ECMA-402 FormatDateTimePattern: `relatedYear` is FormatNumeric of the related year at full width, + * with no 2-digit form. ICU prints its `rr` field, padded to two digits: `05` for ISO 0005. + */ +export function isRelatedYearWidthCompatNeeded(): boolean { + return engineDefect( + "D28", + () => + /\p{Nd}+/u.exec( + textAt("en-u-ca-chinese", { year: "2-digit" }, [5, 7, 10]), + )?.[0] !== "5", + ); +} diff --git a/packages/gmt/src/internal/temporalCompat/islamicEra.test.ts b/packages/gmt/src/internal/temporalCompat/islamicEra.test.ts index a07083065..8611c8bc7 100644 --- a/packages/gmt/src/internal/temporalCompat/islamicEra.test.ts +++ b/packages/gmt/src/internal/temporalCompat/islamicEra.test.ts @@ -45,6 +45,32 @@ describe("printsInModernEra", () => { }, ); + // CORE-112 D26 gives a pre-Hijra date the empty value in the public functions. This file reads + // the era the engine prints there (D18), so it must be built without that repair: with it the + // parts would be `[]`, the era `undefined`, and a V8 date would read as not modern. + it.each(calendars.map((calendarId) => ({ calendarId })))( + "reads the era the engine prints before the Hijra for $calendarId, not the empty value", + ({ calendarId }) => { + const eraAt = (iso: string): string | undefined => + new Intl.DateTimeFormat(`en-u-ca-${calendarId}`, { + era: "short", + year: "numeric", + month: "numeric", + day: "numeric", + timeZone: "UTC", + }) + .formatToParts( + Temporal.PlainDate.from(iso).toZonedDateTime("UTC") + .epochMilliseconds, + ) + .find((part) => part.type === "era")?.value; + expect(eraAt("0600-07-10")).toBeDefined(); + expect( + printsInModernEra(Temporal.PlainDate.from("0600-07-10"), calendarId), + ).toBe(eraAt("0600-07-10") === eraAt("2000-01-01")); + }, + ); + it("reads a date of another calendar by its ISO day", () => { const date = Temporal.PlainDate.from("2024-03-15[u-ca=hebrew]"); expect(printsInModernEra(date, "islamic-civil")).toBe(true); diff --git a/packages/gmt/src/internal/temporalCompat/islamicEra.ts b/packages/gmt/src/internal/temporalCompat/islamicEra.ts index afaecdb00..df100c96b 100644 --- a/packages/gmt/src/internal/temporalCompat/islamicEra.ts +++ b/packages/gmt/src/internal/temporalCompat/islamicEra.ts @@ -1,3 +1,4 @@ +import { guardedDateTimeFormat } from "../formatterCache"; import { Temporal } from "../temporal"; /* @@ -12,7 +13,6 @@ import { Temporal } from "../temporal"; * no era name and no epoch. */ -const formatters = new Map(); const modernEras = new Map(); /** A date after the epoch of every calendar GMT supports: the era every modern date prints in. */ @@ -21,20 +21,28 @@ const MODERN_DATE_MS = "UTC", ).epochMilliseconds; +/** + * The formatter whose parts the polyfill reads. Built with the week-year guard (CORE-112: + * `formatToParts` is never called on a formatter that could abort) and without the year repairs, + * which answer `[]` for a date before the Hijra (D26): the era printed there is what this file + * reads. + */ +const formatters = new Map(); + function formatterFor(calendarId: string): Intl.DateTimeFormat { - let format = formatters.get(calendarId); - if (format === undefined) { + let formatter = formatters.get(calendarId); + if (formatter === undefined) { // The options the polyfill reads its fields with, so the parts are the ones it saw. - format = new Intl.DateTimeFormat(`en-u-ca-${calendarId}`, { + formatter = guardedDateTimeFormat(`en-u-ca-${calendarId}`, { era: "short", year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC", }); - formatters.set(calendarId, format); + formatters.set(calendarId, formatter); } - return format; + return formatter; } function eraPartAt(calendarId: string, ms: number): string | undefined { diff --git a/packages/gmt/src/internal/temporalCompat/repros.ts b/packages/gmt/src/internal/temporalCompat/repros.ts index caf14af0a..ba5fe6599 100644 --- a/packages/gmt/src/internal/temporalCompat/repros.ts +++ b/packages/gmt/src/internal/temporalCompat/repros.ts @@ -8,7 +8,7 @@ import { /* * Every upstream repro for each `@js-temporal/polyfill` defect GMT works around, with the * spec-correct answer: the probe groups from `probeRepros.ts` plus the canary-only groups below - * (zoned.A, zoned.B, zoned.D, zoned.E, D9 and D21). No shipped module imports this file: a repro the + * (zoned.A, zoned.B, zoned.D, zoned.E, D9, D21 and D23 to D28). No shipped module imports this file: a repro the * shipped probes do not read lives here, so it never reaches a bundle. It imports ONLY the * polyfill (through `../temporal`) and `probeRepros.ts`, so a canary script can load its compiled copy straight from * `dist` and report which workarounds are still needed. @@ -39,8 +39,20 @@ export type ZonedDefectId = "zoned.A" | "zoned.B" | "zoned.D" | "zoned.E"; */ export type BoundedWorkDefectId = "D9" | "D21"; +/** + * Engine and CLDR defects the canary reads without a probe in `probeRepros.ts` (CORE-112). D23: + * V8 without commit 0426b0d1045d aborts the process in `formatToParts` and `formatRangeToParts` on + * a pattern with the week-of-year year field (nodejs/node#67076). D24: CLDR 48 patterns print that + * week-year where the calendar year is meant. The guard in `weekYearGuard.ts` covers both and + * changes no output once the engine and the data are right. D25 to D28 (`yearPrinting.ts`): the + * japanese calendar prints Japanese eras before 1873-01-01 (ICU-23341, ICU-23619), an islamic calendar prints + * a negative year before the Hijra (ICU-23327), `ja` japanese leaves a `2-digit` era year unpadded + * (ICU-23620), and chinese and dangi pad the related year under `2-digit` (ICU-23621). + */ +export type CanaryDefectId = "D23" | "D24" | "D25" | "D26" | "D27" | "D28"; + export interface Repro extends Omit { - defect: DefectId | ZonedDefectId | BoundedWorkDefectId; + defect: DefectId | ZonedDefectId | BoundedWorkDefectId | CanaryDefectId; } const MAX_EPOCH_NANOSECONDS = 8_640_000_000_000_000_000_000n; @@ -384,8 +396,212 @@ const d21Repros: readonly Repro[] = [ }, ]; +/** + * The recorded inputs of D23 and D24, all `timeZone: "UTC"`. Each is a pattern whose CLDR 48 data + * uses the week-of-year year (UTS #35 Part 4 §8, `Y`) where the calendar year (`y`) is meant. + */ +const weekYearInputs: readonly { + name: string; + locale: string; + options: Intl.DateTimeFormatOptions; + date: [number, number, number]; + expected: string; +}[] = [ + { + name: "gdMonthShortYearEnd", + locale: "gd", + options: { year: "numeric", month: "short" }, + date: [2024, 12, 30], + expected: "Dùbh 2024", + }, + { + name: "kshNumericYearStart", + locale: "ksh", + options: { year: "numeric", month: "numeric" }, + date: [2027, 1, 1], + expected: "2027-01", + }, + { + name: "scNumericYearStart", + locale: "sc", + options: { year: "numeric", month: "numeric" }, + date: [2027, 1, 1], + expected: "01/2027", + }, + { + name: "teBuddhistYearEnd", + locale: "te-u-ca-buddhist", + options: { year: "numeric", month: "long" }, + date: [2026, 12, 31], + expected: "డిసెంబర్ 2569", + }, + { + name: "myJapaneseMidYear", + locale: "my-u-ca-japanese", + options: { year: "numeric", month: "numeric", day: "numeric" }, + date: [2026, 7, 1], + expected: "R ၀၁/၀၇/၈", + }, + { + name: "glHebrewDateStyleFull", + locale: "gl-u-ca-hebrew", + options: { dateStyle: "full" }, + date: [2026, 9, 12], + expected: "sábado, 1 de Tishri de 5787 AM", + }, + { + name: "deChEraShortYearEnd", + locale: "de-CH", + options: { + era: "short", + year: "numeric", + month: "numeric", + day: "numeric", + weekday: "short", + }, + date: [2024, 12, 30], + expected: "Mo., 12.30.2024 n. Chr.", + }, +]; + +/** + * D24: each input prints the calendar year, with the text the locale data otherwise gives + * (ECMA-402 FormatDateTimePattern, `year`: the calendar year, or the era year with an era). Only + * `format` is called, so no engine can abort on it. + */ +const d24Repros: readonly Repro[] = weekYearInputs.map((input) => ({ + defect: "D24", + calendar: "iso8601", + name: input.name, + expected: input.expected, + run: () => + new Intl.DateTimeFormat(input.locale, { + ...input.options, + timeZone: "UTC", + }).format( + Temporal.PlainDate.from({ + year: input.date[0], + month: input.date[1], + day: input.date[2], + }).toZonedDateTime("UTC").epochMilliseconds, + ), +})); + +/** + * D23: a component-option formatter resolves a year field for a pattern that holds the week-year. + * V8 without commit 0426b0d1045d resolves `undefined` there and aborts in `formatToParts`, and + * a fixed V8, SpiderMonkey and JavaScriptCore resolve `numeric` (ECMA-402 CreateDateTimeFormat). + * No parts call is made: the canary script confirms the abort in a child process, on Node only. + */ +const d23Repros: readonly Repro[] = [ + { + defect: "D23", + calendar: "iso8601", + name: "resolvedYearOfWeekYearPattern", + expected: "numeric", + run: () => + String( + new Intl.DateTimeFormat("gd", { + year: "numeric", + month: "short", + timeZone: "UTC", + }).resolvedOptions().year, + ), + }, +]; + +/** The epoch milliseconds of noon UTC on an ISO date, years before 0000 included. */ +function noonMs(year: number, month: number, day: number): number { + return Temporal.PlainDate.from({ year, month, day }).toZonedDateTime({ + timeZone: "UTC", + plainTime: "12:00", + }).epochMilliseconds; +} + +/** A UTC `Intl.DateTimeFormat` text at an ISO date. */ +function printed( + locale: string, + options: Intl.DateTimeFormatOptions, + date: readonly [number, number, number], +): string { + return new Intl.DateTimeFormat(locale, { + ...options, + timeZone: "UTC", + }).format(noonMs(date[0], date[1], date[2])); +} + +/** + * D25 to D28, text only (`format`), so no engine can abort on a repro. The expected values are the + * specifications': Intl era/monthCode Table 2 as amended by tc39/proposal-intl-era-monthcode#86 and + * test262 tc39/test262#4877 (japanese before 1873-01-01 is Gregorian, and Meiji 6 starts it), + * Table 2 and § 4.1.12 (the islamic calendars have a second era before the Hijra), ECMA-402 + * FormatDateTimePattern (`2-digit` pads the era year to two digits; the related year is + * FormatNumeric at full width). + */ +const yearPrintingRepros: readonly Repro[] = [ + { + defect: "D25", + calendar: "iso8601", + name: "japaneseTwoBc", + expected: "2 BC", + run: () => + printed( + "en-u-ca-japanese", + { era: "short", year: "numeric" }, + [-1, 7, 10], + ), + }, + { + defect: "D25", + calendar: "iso8601", + name: "japaneseLastGregorianDay", + expected: "1872 AD", + run: () => + printed( + "en-u-ca-japanese", + { era: "short", year: "numeric" }, + [1872, 12, 31], + ), + }, + { + defect: "D26", + calendar: "iso8601", + name: "islamicCivilEraBeforeHijra", + expected: "two eras", + run: () => { + const era = (year: number) => + printed("en-u-ca-islamic-civil", { era: "short", year: "numeric" }, [ + year, + 7, + 10, + ]).replace(/[\p{Nd}\p{Pd}\p{Z}−]/gu, ""); + return era(600) === era(2025) ? "one era" : "two eras"; + }, + }, + { + defect: "D27", + calendar: "iso8601", + name: "jaJapaneseTwoDigitEraYear", + expected: "令和06年", + run: () => printed("ja-u-ca-japanese", { year: "2-digit" }, [2024, 7, 10]), + }, + { + defect: "D28", + calendar: "iso8601", + name: "chineseRelatedYearFullWidth", + expected: "5", + run: () => + /\p{Nd}+/u.exec( + printed("en-u-ca-chinese", { year: "2-digit" }, [5, 7, 10]), + )?.[0] ?? "", + }, +]; + export const repros: readonly Repro[] = [ ...d21Repros, + ...d23Repros, + ...d24Repros, + ...yearPrintingRepros, ...d9Repros, ...zonedARepros, ...zonedBRepros, @@ -412,7 +628,7 @@ export const repros: readonly Repro[] = [ /** The repro with this defect, calendar and name, if any. */ export function findRepro( - defect: DefectId | ZonedDefectId | BoundedWorkDefectId, + defect: DefectId | ZonedDefectId | BoundedWorkDefectId | CanaryDefectId, calendar: string, name: string, ): Repro | undefined { diff --git a/packages/gmt/src/internal/temporalCompat/weekYearSource.test.ts b/packages/gmt/src/internal/temporalCompat/weekYearSource.test.ts new file mode 100644 index 000000000..5af367a1c --- /dev/null +++ b/packages/gmt/src/internal/temporalCompat/weekYearSource.test.ts @@ -0,0 +1,89 @@ +import { sourceTree } from "../../test/sourceTree"; + +/* + * CORE-112 (D23): the rule that keeps the V8 abort out of every library path. A formatter built + * anywhere but the guarded places could reach `formatToParts` or `formatRangeToParts` on a `Y` + * pattern, and V8 without commit 0426b0d1045d aborts the whole process there (nodejs/node#67076, + * uncatchable). So library code builds a date formatter only through `cachedFormatter` (the guard's + * hook), and the engine's range parts are called only where no week-year can be: the D17 branch of + * `formatZonedRange` (SpiderMonkey only) and the probes. Comments are skipped. + */ +const files = [...sourceTree("src")].filter( + ([name]) => !name.endsWith(".test.ts") && !name.startsWith("src/test/"), +); + +/** The text without block comments and line comments, keeping line numbers. */ +function code(text: string): string { + return text + .replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, " ")) + .replace(/(^|\s)\/\/.*$/gm, "$1"); +} + +/** `file:line` of every match of `pattern` in the files, outside `allowed`. */ +function found(pattern: RegExp, allowed: readonly string[]): string[] { + return files.flatMap(([name, text]) => + allowed.includes(name) + ? [] + : code(text) + .split("\n") + .flatMap((line, index) => + pattern.test(line) ? [`${name}:${index + 1}`] : [], + ), + ); +} + +describe("week-year source rule", () => { + it("constructs a date formatter only in the cache, the guard and the probes (the D25 to D28 probes included)", () => { + expect( + found(/new Intl\.DateTimeFormat\(/, [ + "src/internal/formatterCache.ts", + "src/internal/weekYearGuard.ts", + "src/internal/weekYearRange.ts", + "src/internal/weekYearSynth.ts", + "src/internal/weekYearText.ts", + "src/internal/resolveLocale.ts", + "src/internal/temporalCompat/capabilities.ts", + "src/internal/temporalCompat/probeRepros.ts", + "src/internal/temporalCompat/repros.ts", + ]), + ).toEqual([]); + }); + + it("calls formatRangeToParts only in the probes and the zoned range D17 branch", () => { + expect( + found(/formatRangeToParts\(/, [ + "src/internal/temporalCompat/probeRepros.ts", + "src/internal/weekYearGuard.ts", + "src/internal/yearPrinting.ts", + "src/zoned/format/formatZonedRange.ts", + ]), + ).toEqual([]); + const range = files.find( + ([name]) => name === "src/zoned/format/formatZonedRange.ts", + ); + expect(code(range?.[1] ?? "").match(/formatRangeToParts\(/g)).toHaveLength( + 1, + ); + }); + + it("calls a formatter's formatRange only in the range check, so every range gets the year repair", () => { + expect(found(/\.formatRange\(/, ["src/internal/weekYearRange.ts"])).toEqual( + [], + ); + }); + + it.each` + module | importers + ${"weekYearGuard"} | ${["src/internal/formatterCache.ts"]} + ${"weekYearSynth"} | ${["src/internal/weekYearGuard.ts"]} + ${"yearPrinting"} | ${["src/internal/formatterCache.ts"]} + ${"weekYearRange"} | ${["src/internal/weekYearGuard.ts", "src/internal/yearPrinting.ts", "src/plain/format/formatDateRange.ts", "src/plain/format/formatDateTimeRange.ts", "src/zoned/format/formatZonedRange.ts"]} + `( + "imports $module only from $importers", + ({ module, importers }: { module: string; importers: string[] }) => { + expect(found(new RegExp(`from "[./]*/${module}"`), importers)).toEqual( + [], + ); + }, + ); +}); diff --git a/packages/gmt/src/internal/temporalCompat/yearPrintingProbes.test.ts b/packages/gmt/src/internal/temporalCompat/yearPrintingProbes.test.ts new file mode 100644 index 000000000..0c0bd5884 --- /dev/null +++ b/packages/gmt/src/internal/temporalCompat/yearPrintingProbes.test.ts @@ -0,0 +1,34 @@ +import { + isIslamicEraCompatNeeded, + isJapaneseEraCompatNeeded, + isJapaneseTwoDigitYearCompatNeeded, + isRelatedYearWidthCompatNeeded, + runRepro, + reproPasses, +} from "./capabilities"; +import { repros } from "./repros"; + +/* + * CORE-112 slice 7: each shipped probe (D25 to D28) reads the same defect as its canary repros. + * The probe says "needed" exactly when some repro of its defect fails on this engine, so the + * canary's verdict and the library's gate cannot disagree. The test never asserts which way: that + * would fail the day an engine ships the fix, which is the canary's job. + */ +describe("year printing probes agree with their repros", () => { + it.each` + defect | probe + ${"D25"} | ${isJapaneseEraCompatNeeded} + ${"D26"} | ${isIslamicEraCompatNeeded} + ${"D27"} | ${isJapaneseTwoDigitYearCompatNeeded} + ${"D28"} | ${isRelatedYearWidthCompatNeeded} + `( + "$defect probe is true exactly when a $defect repro fails", + ({ defect, probe }) => { + const own = repros.filter((repro) => repro.defect === defect); + expect(own.length).toBeGreaterThan(0); + expect(probe()).toBe( + own.some((repro) => !reproPasses(repro, runRepro(repro))), + ); + }, + ); +}); diff --git a/packages/gmt/src/internal/weekYearAbort.test.ts b/packages/gmt/src/internal/weekYearAbort.test.ts new file mode 100644 index 000000000..23e804f69 --- /dev/null +++ b/packages/gmt/src/internal/weekYearAbort.test.ts @@ -0,0 +1,38 @@ +import { runInBoundedChild } from "../test/boundedChild"; + +/* + * CORE-112 (D23): V8 without commit 0426b0d1045d aborts the whole process (SIGTRAP, exit 133, + * nodejs/node#67076) in `formatToParts` and `formatRangeToParts` on a pattern with the week-of-year + * year field. Each call below reached that abort through a library function before the guard. It + * runs in a child process, so the failing state is the child crashing, never the Vitest worker. + * The native abort itself is confirmed by the D23 canary (`scripts/canary/weekYear.mjs`), not here: + * a test cannot assert an engine defect without failing on the engine that fixed it. + */ +describe("public functions on week-year patterns do not abort the process (D23)", () => { + it.each` + expression | label + ${'gmt.formatCalendar("2026-07-01T10:00:00", "gl-u-ca-hebrew", { reference: "2026-07-01T09:00:00" })'} | ${"formatCalendar gl hebrew"} + ${'gmt.formatCalendar("2026-07-01T10:00:00", "gl-u-ca-buddhist", { reference: "2026-07-01T09:00:00" })'} | ${"formatCalendar gl buddhist"} + ${'gmt.formatCalendar("2026-07-01T10:00:00", "gl-u-ca-roc", { reference: "2026-07-01T09:00:00" })'} | ${"formatCalendar gl roc"} + ${'gmt.formatDateToParts("2024-12-30", "gd", { year: "numeric", month: "short" })'} | ${"formatDateToParts gd month short"} + ${'gmt.formatDateToParts("2026-09-12", "gl-u-ca-hebrew", { dateStyle: "full" })'} | ${"formatDateToParts gl hebrew dateStyle full"} + ${'gmt.formatDateToParts("2026-07-01", "my-u-ca-japanese", { year: "numeric", month: "numeric", day: "numeric" })'} | ${"formatDateToParts my japanese"} + ${'gmt.formatDateTimeToParts("2024-12-30T14:05:00", "gd", { year: "numeric", month: "short", hour: "numeric", minute: "numeric" })'} | ${"formatDateTimeToParts gd with time"} + ${'gmt.formatYearMonth("2026-10", "gl", { dateStyle: "full" })'} | ${"formatYearMonth gl dateStyle full"} + `("returns from $label", async ({ expression }) => { + const run = await runInBoundedChild([expression]); + expect( + { timedOut: run.timedOut, crashed: run.crashed }, + run.stderr, + ).toEqual({ timedOut: false, crashed: false }); + expect(run.calls).toHaveLength(1); + }); + + it("returns a string from formatCalendar on the Hebrew calendar", async () => { + const run = await runInBoundedChild([ + 'gmt.formatCalendar("2026-07-01T10:00:00", "gl-u-ca-hebrew", { reference: "2026-07-01T09:00:00" })', + ]); + expect(run.calls[0]?.value).toEqual(expect.any(String)); + expect(run.calls[0]?.value).not.toBe(""); + }); +}); diff --git a/packages/gmt/src/internal/weekYearGuard.test.ts b/packages/gmt/src/internal/weekYearGuard.test.ts new file mode 100644 index 000000000..3a9040827 --- /dev/null +++ b/packages/gmt/src/internal/weekYearGuard.test.ts @@ -0,0 +1,161 @@ +import { forgetWeekYearVerdicts, guardDateTimeFormat } from "./weekYearGuard"; + +/* + * CORE-112 (D23, D24): which formatters the guard leaves alone and which it replaces. The decision + * rests on the formatter's own text (a year that moves where the calendar year does not, at a + * year boundary) and, on an unfixed V8, on a `resolvedOptions()` with no `year` for a pattern that + * must have one (ECMA-402 CreateDateTimeFormat gives every date formatter without `dateStyle` a + * year field when it asks for one). + */ +const utc = { timeZone: "UTC" } as const; + +function build(locale: string, options: Intl.DateTimeFormatOptions) { + const formatter = new Intl.DateTimeFormat(locale, { ...options, ...utc }); + return { + formatter, + guarded: guardDateTimeFormat(formatter, { ...options, ...utc }), + }; +} + +afterEach(() => { + vi.restoreAllMocks(); + forgetWeekYearVerdicts(); +}); + +describe("guardDateTimeFormat: formatters that pass are returned unchanged", () => { + it.each` + locale | options + ${"en"} | ${{ year: "numeric", month: "long" }} + ${"de"} | ${{ year: "numeric", month: "long" }} + ${"fr"} | ${{ year: "numeric", month: "long" }} + ${"ja-u-ca-japanese"} | ${{ year: "numeric", month: "long" }} + ${"zh-u-ca-chinese"} | ${{ year: "numeric", month: "long" }} + ${"en"} | ${{ dateStyle: "full" }} + ${"de-CH"} | ${{ era: "short" }} + ${"gd"} | ${{ hour: "numeric", minute: "numeric" }} + ${"gd"} | ${{ month: "short", day: "numeric" }} + `( + "returns the native formatter for '$locale' $options", + ({ locale, options }) => { + const { formatter, guarded } = build(locale, options); + expect(guarded).toBe(formatter); + }, + ); +}); + +describe("guardDateTimeFormat: formatters that print the week-year are replaced", () => { + it.each` + locale | options + ${"gd"} | ${{ year: "numeric", month: "short" }} + ${"gl-u-ca-hebrew"} | ${{ dateStyle: "full" }} + ${"te-u-ca-buddhist"} | ${{ year: "numeric", month: "long" }} + `("replaces the formatter for '$locale' $options", ({ locale, options }) => { + const { formatter, guarded } = build(locale, options); + expect(guarded).not.toBe(formatter); + }); + + it("gives the calendar year from format", () => { + const { guarded } = build("gd", { year: "numeric", month: "short" }); + expect(guarded.format(1735516800000)).toBe("Dùbh 2024"); + }); + + it("makes formatRangeToParts throw a TypeError, so no caller can reach the engine's range parts", () => { + const { guarded } = build("gd", { year: "numeric", month: "short" }); + expect(() => guarded.formatRangeToParts(0, 1)).toThrow(TypeError); + }); + + it("reports the year field the formatter now prints in resolvedOptions", () => { + const { guarded } = build("gd", { year: "numeric", month: "short" }); + expect(guarded.resolvedOptions().year).toBe("numeric"); + }); + + it("reports a 2-digit year for a 2-digit request", () => { + const { guarded } = build("ksh", { year: "2-digit", month: "2-digit" }); + expect(guarded.resolvedOptions().year).toBe("2-digit"); + }); +}); + +describe("guardDateTimeFormat: the crash signal", () => { + /** A formatter whose `resolvedOptions()` omits `year`, as unfixed V8 does for a `Y` pattern. */ + function withoutYear(calendar: string) { + const real = new Intl.DateTimeFormat(`en-u-ca-${calendar}`, { + month: "long", + ...utc, + }); + return { + resolvedOptions: () => ({ ...real.resolvedOptions(), year: undefined }), + format: (ms: number) => real.format(ms), + formatToParts: (ms: number) => real.formatToParts(ms), + } as unknown as Intl.DateTimeFormat; + } + + it.each` + calendar | options | replaced + ${"gregory"} | ${{ year: "numeric", month: "long" }} | ${true} + ${"buddhist"} | ${{ year: "numeric", month: "long" }} | ${true} + ${"chinese"} | ${{ year: "numeric", month: "long" }} | ${false} + ${"dangi"} | ${{ year: "numeric", month: "long" }} | ${false} + ${"gregory"} | ${{ dateStyle: "long" }} | ${false} + `( + "year missing from resolvedOptions in '$calendar' with $options replaces the formatter: $replaced", + ({ calendar, options, replaced }) => { + const stub = withoutYear(calendar); + expect(guardDateTimeFormat(stub, options) !== stub).toBe(replaced); + }, + ); + + it("never reads resolvedOptions or format when the options print no year", () => { + const resolvedOptions = vi.fn(); + const format = vi.fn(); + const stub = { resolvedOptions, format } as unknown as Intl.DateTimeFormat; + expect(guardDateTimeFormat(stub, { hour: "numeric" })).toBe(stub); + expect(resolvedOptions).not.toHaveBeenCalled(); + expect(format).not.toHaveBeenCalled(); + }); +}); + +describe("guardDateTimeFormat: one verdict per pattern", () => { + /** + * How many UTC twins a call builds for a formatter in a non-UTC zone. `dateStyle` is the case the + * crash signal cannot see, so only the text verdict decides it. + */ + function twinsBuilt(run: () => void): number { + const spy = vi.spyOn(Intl, "DateTimeFormat"); + run(); + return spy.mock.calls.filter( + ([, options]) => + (options as Intl.DateTimeFormatOptions | undefined)?.timeZone === + "UTC" && + (options as Intl.DateTimeFormatOptions | undefined)?.dateStyle === + "full", + ).length; + } + + const options = { + dateStyle: "full", + timeZone: "America/New_York", + } as const; + + it("reads the text of a pattern once for formatters in different zones", () => { + const first = new Intl.DateTimeFormat("gl-u-ca-hebrew", options); + const second = new Intl.DateTimeFormat("gl-u-ca-hebrew", { + ...options, + timeZone: "Asia/Tokyo", + }); + forgetWeekYearVerdicts(); + const built = twinsBuilt(() => { + guardDateTimeFormat(first, options); + guardDateTimeFormat(second, { ...options, timeZone: "Asia/Tokyo" }); + }); + expect(built).toBe(1); + }); + + it("reads the text again after Intl.DateTimeFormat is replaced", () => { + const formatter = new Intl.DateTimeFormat("gl-u-ca-hebrew", options); + guardDateTimeFormat(formatter, options); + const built = twinsBuilt(() => { + guardDateTimeFormat(formatter, options); + }); + expect(built).toBe(1); + }); +}); diff --git a/packages/gmt/src/internal/weekYearGuard.ts b/packages/gmt/src/internal/weekYearGuard.ts new file mode 100644 index 000000000..e8ac41ef7 --- /dev/null +++ b/packages/gmt/src/internal/weekYearGuard.ts @@ -0,0 +1,383 @@ +import { plainOptionEntries } from "./plainOptionEntries"; +import { Temporal } from "./temporal"; +import { nowInstant } from "./temporalCompat/clock"; +import { + forgetWeekYearRange, + formatRangeChecked, + markRangeHandled, +} from "./weekYearRange"; +import { createPartsSynth } from "./weekYearSynth"; +import { + analyse, + anchorYear, + checkYearRuns, + dateIn, + digitRuns, + forgetWeekYearText, + patchYearParts, + referenceFor, + referenceYear, + repairText, + yearRunIndexes, + type RepairedText, + type WeekYearAnalysis, +} from "./weekYearText"; + +/* + * CORE-112, defects D23 and D24: the formatters that print or abort on the week-of-year year. + * + * D24: CLDR 48 patterns for some locales and calendars use `Y` (the year of the week-of-year) + * where `y` (the calendar year) is meant, so a date near a year end prints next year's number. + * D23: V8 without commit 0426b0d1045d aborts the process (nodejs/node#67076) in `formatToParts` + * and `formatRangeToParts` on such a pattern. + * + * This module is the only place in `src` that decides which formatters are affected. A formatter + * that passes is returned as it is. Deleting this file, `weekYearSynth.ts`, `weekYearText.ts` and + * the one hook line in `formatterCache.ts` retires the workaround (the D24 canary says when). + */ + +/** The options that make a formatter print time. */ +const TIME_KEYS = [ + "hour", + "minute", + "second", + "fractionalSecondDigits", + "dayPeriod", + "timeZoneName", + "timeStyle", +] as const; + +/** The options that give a formatter a date pattern. */ +const DATE_KEYS = [ + "era", + "year", + "month", + "day", + "weekday", + "dateStyle", +] as const; + +/** ECMA-402 CreateDateTimeFormat reads these to decide whether to add the date defaults. */ +const FIELD_KEYS = [ + "weekday", + "year", + "month", + "day", + "dayPeriod", + "hour", + "minute", + "second", + "fractionalSecondDigits", + "dateStyle", + "timeStyle", +] as const; + +/** At most this many verdicts; past it the map clears. */ +const MAX_VERDICTS = 256; + +const verdicts = new Map(); +let verdictsBuiltWith: unknown; + +/** Forget every verdict (the `Intl.DateTimeFormat` constructor was replaced, a test seam). */ +export function forgetWeekYearVerdicts(): void { + verdicts.clear(); + verdictsBuiltWith = undefined; + forgetWeekYearText(); + forgetWeekYearRange(); +} + +/** + * Whether the formatter can print a year at all (ECMA-402 CreateDateTimeFormat, the `needDefaults` + * step with required ~any~ and defaults ~date~: `era` is not one of the fields it checks, so + * `{ era }` alone gets year, month and day). + */ +function printsYear(options: Intl.DateTimeFormatOptions): boolean { + return ( + options.year !== undefined || + options.dateStyle !== undefined || + FIELD_KEYS.every((key) => options[key] === undefined) + ); +} + +/** The noon of a date in UTC, as epoch milliseconds. */ +function noonUtc(date: Temporal.PlainDate): number { + return date.toZonedDateTime({ timeZone: "UTC", plainTime: "12:00" }) + .epochMilliseconds; +} + +/** + * The first day of calendar year `year` as the reference (ICU's own calendar) counts it: month 1 + * day 1 by Temporal, moved by at most four days until the reference's year changes there. + */ +function yearStart( + reference: ReturnType, + calendar: string, + year: number, +): Temporal.PlainDate { + const at = (date: Temporal.PlainDate) => + referenceYear(reference, noonUtc(date)); + const middle = at(dateIn(calendar, year, 1, 15)); + let start = dateIn(calendar, year, 1, 1); + for (let step = 0; step < 4; step++) { + const previous = start.subtract({ days: 1 }); + if (at(previous) !== at(start)) { + break; + } + start = at(start) === middle ? previous : start.add({ days: 1 }); + } + return start; +} + +/** + * Whether the year runs of a formatter hold a year other than the calendar year at a year + * boundary: read from `format` alone, on the formatter or a UTC twin. + * + * @param format the formatter's (or its twin's) `format` + */ +function isWeekYear( + format: (ms: number) => string, + calendar: string, + numberingSystem: string, +): boolean { + const reference = referenceFor(calendar, numberingSystem, "UTC"); + const digits = new Set( + new Intl.NumberFormat("und", { + numberingSystem, + useGrouping: false, + }).format(1234567890), + ); + const runsAt = (date: Temporal.PlainDate) => + digitRuns(format(noonUtc(date)), digits); + const yearRuns = yearRunIndexes(calendar, runsAt); + if (yearRuns === null || yearRuns.length === 0) { + return false; + } + const first = anchorYear(calendar); + for (let year = first + 1; year <= first + 3; year++) { + const start = yearStart(reference, calendar, year); + const last = start.subtract({ days: 1 }); + for (const [date, inside] of [ + [start, start.add({ days: 14 })], + [last, last.subtract({ days: 14 })], + ] as const) { + const at = runsAt(date); + const mid = runsAt(inside); + if ( + at.length === mid.length && + !checkYearRuns( + yearRuns, + at, + mid, + referenceYear(reference, noonUtc(date)), + referenceYear(reference, noonUtc(inside)), + ) + ) { + return true; + } + } + } + return false; +} + +/** The formatter's own, or a UTC date-only twin when a time field or a zone would move digits. */ +function textSource( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, + resolved: Intl.ResolvedDateTimeFormatOptions, +): Intl.DateTimeFormat { + if ( + resolved.timeZone === "UTC" && + TIME_KEYS.every((key) => options[key] === undefined) + ) { + return formatter; + } + const twin: Intl.DateTimeFormatOptions = { + calendar: resolved.calendar, + numberingSystem: resolved.numberingSystem, + timeZone: "UTC", + }; + for (const key of DATE_KEYS) { + if (options[key] !== undefined) { + Object.assign(twin, { [key]: options[key] }); + } + } + return new Intl.DateTimeFormat(resolved.locale, twin); +} + +/** The verdict-cache key: the pattern, never the zone (a zone moves the instant, not the pattern). */ +function verdictKey( + options: Intl.DateTimeFormatOptions, + resolved: Intl.ResolvedDateTimeFormatOptions, +): string | null { + const entries = plainOptionEntries(options); + if (entries === null) { + return null; + } + const rest = entries.filter(([name]) => name !== "timeZone"); + return JSON.stringify([ + resolved.locale, + resolved.calendar, + resolved.numberingSystem, + resolved.hourCycle ?? "", + rest, + ]); +} + +/** Whether the text of this pattern prints a year other than the calendar year, remembered per pattern. */ +function isFlagged( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, + resolved: Intl.ResolvedDateTimeFormatOptions, +): boolean { + if (verdictsBuiltWith !== Intl.DateTimeFormat) { + verdicts.clear(); + verdictsBuiltWith = Intl.DateTimeFormat; + } + const key = verdictKey(options, resolved); + const known = key === null ? undefined : verdicts.get(key); + if (known !== undefined) { + return known; + } + const source = textSource(formatter, options, resolved); + const flagged = isWeekYear( + (ms) => source.format(ms), + resolved.calendar, + resolved.numberingSystem, + ); + if (key !== null) { + if (verdicts.size >= MAX_VERDICTS) { + verdicts.clear(); + } + verdicts.set(key, flagged); + } + return flagged; +} + +/** A time value as `Intl` reads it: a number, a `Date`, or `undefined` for now. */ +function toMilliseconds(date: Date | number | undefined): number { + if (typeof date === "number") { + return date; + } + return date === undefined ? nowInstant().epochMilliseconds : Number(date); +} + +/** The formatter that stands in for a flagged one; `format` and the parts hold the calendar year. */ +function guarded( + native: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, + resolved: Intl.ResolvedDateTimeFormatOptions, + crashes: boolean, +): Intl.DateTimeFormat { + let analysis: WeekYearAnalysis | null | undefined; + const read = (): WeekYearAnalysis | null => { + analysis ??= analyse((ms) => native.format(ms), resolved); + return analysis; + }; + const repaired = (ms: number): RepairedText | null => { + const read1 = read(); + return read1 === null ? null : repairText(read1, native.format(ms), ms); + }; + let synth: ((ms: number) => Intl.DateTimeFormatPart[] | null) | undefined; + const standIn = { + format(date?: Date | number): string { + const ms = toMilliseconds(date); + return repaired(ms)?.text ?? native.format(ms); + }, + formatToParts(date?: Date | number): Intl.DateTimeFormatPart[] { + const ms = toMilliseconds(date); + const text = repaired(ms); + if (text === null) { + return []; + } + if (!crashes && options.dateStyle === undefined) { + const patched = patchYearParts(native.formatToParts(ms), text); + if (patched !== null) { + return patched; + } + } + const known = read(); + if (known === null) { + return []; + } + synth ??= createPartsSynth(options, resolved, known, repaired); + return synth(ms) ?? []; + }, + formatRange(start: Date | number, end: Date | number): string { + // Slice 3c: the range pattern is another pattern, so the year is repaired here too. `null` + // (a year run that cannot be located) is the empty string, as in the library's range + // functions. + return ( + formatRangeChecked( + native, + options, + toMilliseconds(start), + toMilliseconds(end), + ) ?? "" + ); + }, + formatRangeToParts(): never { + throw new TypeError( + "formatRangeToParts is not available on a formatter that can print the week-year (CORE-112)", + ); + }, + resolvedOptions(): Intl.ResolvedDateTimeFormatOptions { + const own = native.resolvedOptions(); + const known = read(); + if (own.year !== undefined || known === null) { + return own; + } + return { + ...own, + year: known.styles[0]?.kind === "two" ? "2-digit" : "numeric", + }; + }, + }; + markRangeHandled(standIn); + return standIn as Intl.DateTimeFormat; +} + +/** + * The formatter itself when its pattern cannot print the week-of-year year (defects D23, D24), + * else a formatter whose year is the calendar year and whose parts never reach the engine's `Y` + * field. + * + * @param formatter the formatter just built + * @param callerOptions the options it was built with; options that are not plain values are + * left unguarded + * @returns the formatter, or its stand-in + * + * @example guardDateTimeFormat(new Intl.DateTimeFormat("en", { year: "numeric" }), { year: "numeric" }) // the same formatter + * @example guardDateTimeFormat(new Intl.DateTimeFormat("gd", { year: "numeric", month: "short", timeZone: "UTC" }), { year: "numeric", month: "short", timeZone: "UTC" }).format(Date.UTC(2024, 11, 30)) // "Dùbh 2024" + */ +export function guardDateTimeFormat( + formatter: Intl.DateTimeFormat, + callerOptions: Intl.DateTimeFormatOptions, +): Intl.DateTimeFormat { + // Options with a getter or a value `Intl` coerces by running caller code are never read again + // here (`formatterCache` builds no key from them either). Library code snapshots a caller's + // options into plain values first, so this is only a hand-built object. + const entries = plainOptionEntries(callerOptions); + if (entries === null) { + return formatter; + } + const options: Intl.DateTimeFormatOptions = Object.fromEntries(entries); + if (!printsYear(options)) { + return formatter; + } + try { + const resolved = formatter.resolvedOptions(); + // Unfixed V8 resolves a pattern with `Y` without `year`; the fix reports it (0426b0d1045d). The + // two cyclic calendars have no year letter V8 lists, and V8 handles them in parts. + const crashes = + options.dateStyle === undefined && + resolved.year === undefined && + resolved.calendar !== "chinese" && + resolved.calendar !== "dangi"; + if (!crashes && !isFlagged(formatter, options, resolved)) { + return formatter; + } + return guarded(formatter, options, resolved, crashes); + } catch { + return formatter; + } +} diff --git a/packages/gmt/src/internal/weekYearRange.test.ts b/packages/gmt/src/internal/weekYearRange.test.ts new file mode 100644 index 000000000..a2a2b94e0 --- /dev/null +++ b/packages/gmt/src/internal/weekYearRange.test.ts @@ -0,0 +1,297 @@ +import { Temporal } from "./temporal"; +import { + formatRangeChecked, + forgetWeekYearRange, + markRangeHandled, + repairRangeYear, + rangeYearVerdict, +} from "./weekYearRange"; + +/* + * CORE-112 slice 3c (D24 in ranges). The range pattern is another pattern from the single-date + * one, so a formatter whose `format` is right can print the week-year in `formatRange`. Two kinds + * of formatter are used: + * + * - Real engine formatters, where the expected years are the Temporal calendar year of each + * endpoint (ECMA-402 FormatDateTimePattern prints the calendar year, the era year with an era). + * - A stand-in whose `formatRange` prints a year we choose, so the repair and the verdict are + * tested without reading any CLDR text: a Gregorian year printed one too high is the shape of a + * week-year at a year end, and a year printed five too high is not a week-year at all. + */ +const utc = { timeZone: "UTC" } as const; + +const ms = (date: string): number => + Temporal.PlainDate.from(date).toZonedDateTime("UTC").epochMilliseconds; + +const at = (dateTime: string): number => + Temporal.ZonedDateTime.from(`${dateTime}+00:00[UTC]`).epochMilliseconds; + +/** The digit runs of a text, in order. */ +const digits = (text: string | null): string[] => text?.match(/\d+/g) ?? []; + +/** + * An English formatter whose range text has every digit run rewritten by `rewrite`: the engine's + * own layout and separators, with the years we choose. `resolvedOptions` and the rest come from + * the real formatter, so the library reads it as it reads any other. + */ +function printing( + options: Intl.DateTimeFormatOptions, + rewrite: (run: string) => string, +): Intl.DateTimeFormat { + const real = new Intl.DateTimeFormat("en", { ...options, ...utc }); + return { + resolvedOptions: () => real.resolvedOptions(), + formatRange: (start: number, end: number) => + real.formatRange(start, end).replace(/\d+/g, rewrite), + } as unknown as Intl.DateTimeFormat; +} + +const plusOne = (run: string): string => String(Number(run) + 1); +const plusFive = (run: string): string => String(Number(run) + 5); +const timesThree = (run: string): string => String(Number(run) * 3); + +afterEach(() => { + vi.restoreAllMocks(); + forgetWeekYearRange(); +}); + +describe("repairRangeYear: a year printed above the calendar year", () => { + const yearly = { year: "numeric" } as const; + + it.each` + start | end | printed | expected + ${"2024-12-30"} | ${"2025-01-02"} | ${["2025", "2026"]} | ${["2024", "2025"]} + ${"2026-07-01"} | ${"2026-09-04"} | ${["2027"]} | ${["2026"]} + ${"2023-03-05"} | ${"2025-03-05"} | ${["2024", "2026"]} | ${["2023", "2025"]} + `( + "writes the calendar years of $start and $end over $printed", + ({ start, end, printed, expected }) => { + const formatter = printing(yearly, plusOne); + expect(digits(formatter.formatRange(ms(start), ms(end)))).toEqual( + printed, + ); + expect( + digits(repairRangeYear(formatter, yearly, ms(start), ms(end))), + ).toEqual(expected); + }, + ); + + it("keeps every character outside the year runs", () => { + const real = new Intl.DateTimeFormat("en", { ...yearly, ...utc }); + const formatter = printing(yearly, plusOne); + expect( + repairRangeYear(formatter, yearly, ms("2024-12-30"), ms("2025-01-02")), + ).toBe(real.formatRange(ms("2024-12-30"), ms("2025-01-02"))); + }); + + it("writes the last two digits, padded, for year 2-digit", () => { + const options = { year: "2-digit" } as const; + const formatter = printing(options, (run) => + String((Number(run) + 1) % 100).padStart(2, "0"), + ); + expect( + digits( + repairRangeYear(formatter, options, ms("2008-12-30"), ms("2009-01-02")), + ), + ).toEqual(["08", "09"]); + }); + + it("returns null when a year run is more than one away from the calendar year", () => { + const formatter = printing(yearly, plusFive); + expect( + repairRangeYear(formatter, yearly, ms("2024-12-30"), ms("2025-01-02")), + ).toBeNull(); + }); + + it("returns null when the year runs cannot be located", () => { + // Three times the year moves by three times the shift, so no digit run moves as a year. + const formatter = printing(yearly, timesThree); + expect( + repairRangeYear(formatter, yearly, ms("2024-12-30"), ms("2025-01-02")), + ).toBeNull(); + }); +}); + +describe("rangeYearVerdict: stand-in formatters", () => { + const yearly = { year: "numeric" } as const; + + it.each` + label | rewrite | flagged + ${"the calendar year"} | ${(run: string) => run} | ${false} + ${"the calendar year plus one"} | ${plusOne} | ${true} + ${"the calendar year plus five"} | ${plusFive} | ${true} + `("is $flagged for a range that prints $label", ({ rewrite, flagged }) => { + expect(rangeYearVerdict(printing(yearly, rewrite), yearly)).toBe(flagged); + }); + + it("is false for a range text with no decimal year", () => { + const formatter = printing(yearly, () => "year"); + expect(rangeYearVerdict(formatter, yearly)).toBe(false); + }); +}); + +describe("repairRangeYear: calendars the polyfill cannot project", () => { + const monthly = { + year: "numeric", + month: "short", + timeZone: "UTC", + } as const; + + // Temporal's own coptic and ethiopic years, read from the `ethioaa` calendar the polyfill can + // project: 2024-07-10 to 2024-09-10 lies in coptic year 1740 and ethiopic year 2016 throughout. + it.each` + calendar | year + ${"coptic"} | ${"1740"} + ${"ethiopic"} | ${"2016"} + `( + "prints $year once for a $calendar range inside one year", + ({ calendar, year }) => { + const options = { ...monthly, calendar }; + const formatter = new Intl.DateTimeFormat("ak", options); + const start = at("2024-07-10T12:00:00"); + const end = at("2024-09-10T12:00:00"); + expect(digits(repairRangeYear(formatter, options, start, end))).toEqual([ + year, + ]); + }, + ); + + // Before ISO year 1 (native Temporal: coptic year -285 and -283, printed 286 and 284 by + // ECMA-402's "1 - year" for a year <= 0; ethiopic era `aa` 5491 and 5493; indian -79 and -77). + // The polyfill cannot read coptic or ethiopic at all, so `TEMPORAL_STAND_IN` computes the years + // and the printed years must be accepted as the calendar years. + it.each` + calendar | years + ${"coptic"} | ${["286", "284"]} + ${"ethiopic"} | ${["5491", "5493"]} + `( + "accepts the printed years $years of a $calendar range before ISO year 1", + ({ calendar, years }) => { + const options = { ...monthly, calendar }; + const formatter = new Intl.DateTimeFormat("ak", options); + const start = at("-000001-07-10T12:00:00"); + const end = at("+000001-07-10T12:00:00"); + expect(digits(repairRangeYear(formatter, options, start, end))).toEqual( + years, + ); + }, + ); + + // The polyfill throws for `indian` before ISO year 1 (V8 bug 10529), so nothing is measured + // and ICU's own text is the answer. + it("returns the engine text for an indian range before ISO year 1", () => { + const options = { ...monthly, calendar: "indian" }; + const formatter = new Intl.DateTimeFormat("ak", options); + const start = at("-000001-07-10T12:00:00"); + const end = at("+000001-07-10T12:00:00"); + expect(repairRangeYear(formatter, options, start, end)).toBe( + formatter.formatRange(start, end), + ); + }); +}); + +describe("rangeYearVerdict: real formatters", () => { + it.each` + locale | options + ${"en"} | ${{ year: "numeric", month: "short", day: "numeric" }} + ${"de"} | ${{ year: "numeric", month: "long" }} + ${"ja-u-ca-japanese"} | ${{ year: "numeric", month: "long", day: "numeric" }} + ${"zh-u-ca-chinese"} | ${{ year: "numeric", month: "long", day: "numeric" }} + ${"kok-u-ca-ethioaa"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"kok-u-ca-indian"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"ak-u-ca-coptic"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"ak-u-ca-ethiopic"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"ak-u-ca-indian"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"en"} | ${{ hour: "numeric", minute: "numeric" }} + `("does not flag '$locale' $options", ({ locale, options }) => { + const formatter = new Intl.DateTimeFormat(locale, { ...options, ...utc }); + expect(rangeYearVerdict(formatter, options)).toBe(false); + }); + + it.each` + locale | options + ${"kok-u-ca-japanese"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"kok-u-ca-coptic"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"kok-Deva-u-ca-coptic"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"kok-u-ca-ethiopic"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"my-u-ca-buddhist"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} + ${"kok-u-ca-roc"} | ${{ year: "numeric", month: "numeric", day: "numeric", weekday: "short" }} + ${"kok-u-ca-roc"} | ${{ era: "short", year: "numeric", month: "numeric", day: "numeric", weekday: "short" }} + `("flags '$locale' $options", ({ locale, options }) => { + const formatter = new Intl.DateTimeFormat(locale, { ...options, ...utc }); + expect(rangeYearVerdict(formatter, options)).toBe(true); + }); +}); + +describe("rangeYearVerdict: laziness", () => { + const options = { + year: "numeric", + month: "numeric", + day: "numeric", + } as const; + + it("makes no range call when the formatter is built", () => { + const spy = vi.spyOn(Intl.DateTimeFormat.prototype, "formatRange"); + new Intl.DateTimeFormat("kok-u-ca-japanese", { ...options, ...utc }); + expect(spy).not.toHaveBeenCalled(); + }); + + it("probes on the first call and answers later calls from the kept verdict", () => { + const formatter = new Intl.DateTimeFormat("kok-u-ca-japanese", { + ...options, + ...utc, + }); + const spy = vi.spyOn(formatter, "formatRange"); + const first = rangeYearVerdict(formatter, options); + const probed = spy.mock.calls.length; + expect(probed).toBeGreaterThan(0); + expect(rangeYearVerdict(formatter, options)).toBe(first); + expect(spy.mock.calls.length).toBe(probed); + }); + + it("probes again for a formatter built after the verdicts were forgotten", () => { + const formatter = new Intl.DateTimeFormat("en", { ...options, ...utc }); + rangeYearVerdict(formatter, options); + const spy = vi.spyOn(formatter, "formatRange"); + forgetWeekYearRange(); + rangeYearVerdict(formatter, options); + expect(spy.mock.calls.length).toBeGreaterThan(0); + }); +}); + +describe("formatRangeChecked", () => { + const yearly = { year: "numeric" } as const; + const start = ms("2024-12-30"); + const end = ms("2025-01-02"); + + it("answers with the engine's own text for a formatter that is not flagged", () => { + const formatter = new Intl.DateTimeFormat("en", { ...yearly, ...utc }); + expect(formatRangeChecked(formatter, yearly, start, end)).toBe( + formatter.formatRange(start, end), + ); + }); + + it("answers with the repaired text for a flagged formatter", () => { + const formatter = printing(yearly, plusOne); + expect(digits(formatRangeChecked(formatter, yearly, start, end))).toEqual([ + "2024", + "2025", + ]); + }); + + it("answers null for a flagged formatter whose year runs cannot be repaired", () => { + const formatter = printing(yearly, plusFive); + expect(formatRangeChecked(formatter, yearly, start, end)).toBeNull(); + }); + + it("calls a stand-in that repairs its own range as it is, without a verdict", () => { + const standIn = printing(yearly, plusOne); + const spy = vi.spyOn(standIn, "formatRange"); + markRangeHandled(standIn); + expect(digits(formatRangeChecked(standIn, yearly, start, end))).toEqual([ + "2025", + "2026", + ]); + expect(spy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/gmt/src/internal/weekYearRange.ts b/packages/gmt/src/internal/weekYearRange.ts new file mode 100644 index 000000000..0d0ea37e3 --- /dev/null +++ b/packages/gmt/src/internal/weekYearRange.ts @@ -0,0 +1,1378 @@ +import { Temporal } from "./temporal"; +import { + digitRuns as textDigitRuns, + digitsOf, + referenceFor, +} from "./weekYearText"; + +/* + * CORE-112 slice 3c (defect D24 in ranges): the calendar year in `formatRange` text. + * + * A range pattern is a different pattern from the single-date one, so a formatter whose `format` + * is right can still print the week-based year (`Y`) in `formatRange` (UTS #35 Part 4 §8, rows `y` + * and `Y`): kok-u-ca-japanese 2018-12-27 to 2019-12-27 ends in the year `2019` where the Reiwa + * year `1` is meant, my-u-ca-buddhist prints `2026` for 2569. ECMA-402 FormatDateTimePattern + * prints the calendar year (the era year with an era), so the verdict compares each year run with + * ICU's own calendar year and the repair writes that year. + * + * This module reads range text with `format` and `formatRange` only. It never calls a parts + * method: V8 without commit 0426b0d1045d aborts the process there on a `Y` pattern (defect D23, + * nodejs/node#67076). The verdict is lazy, computed on a formatter's first range call and kept + * per formatter. The reference year is the one the single repair uses (`und`, `year: "numeric"`, + * the formatter's calendar, numbering system and zone). + * + * Deleting this file and its hook lines retires the workaround with the rest of D24. + */ + +const ANY_DIGIT = /\p{Nd}/u; +const MINUS = new Set(["-", "−", "‐", "‑", "‒", "–", "﹣", "-"]); +const BIDI = new Set(["‎", "‏", "؜"]); +const RELATED = new Set(["chinese", "dangi"]); + +/** + * The polyfill (0.5.1) throws "Era am ... was not matched by any era" for every `coptic` and + * `ethiopic` date, so their dates are computed in `ethioaa`, which it handles. The three calendars + * have the same twelve 30-day months, five or six epagomenal days and leap rule; they differ only + * in the year number. The Ethiopian (Amete Mihret) year is the Amete Alem year less 5500, and the + * Coptic year is the Ethiopian year less 276 (Calendrical Calculations, chapter 4; the CLDR/ICU + * calendars of the same names). Only the year number is converted; ICU still prints the text. + */ +const TEMPORAL_STAND_IN: Readonly< + Record +> = { + coptic: { calendar: "ethioaa", bias: 5776 }, + ethiopic: { calendar: "ethioaa", bias: 5500 }, +}; + +/** A digit run with its value (in the formatter's numbering system) and code point count. */ +interface Run { + readonly start: number; + readonly end: number; + readonly text: string; + readonly count: number; + readonly value: number; +} + +/** ICU's calendar year at a moment: its digits, value and sign. */ +interface RefYear { + readonly digits: string; + readonly count: number; + readonly value: number; + readonly negative: boolean; +} + +/** What is read from a formatter once and shared by every range of its calendar, zone and locale. */ +interface Env { + readonly weekday: boolean; + readonly calendar: string; + /** The Temporal calendar that computes this one's dates (see `TEMPORAL_STAND_IN`). */ + readonly temporalCalendar: string; + /** What `temporalCalendar` adds to this calendar's year number. */ + readonly yearBias: number; + readonly timeZone: string; + readonly numberingSystem: string; + readonly digits: ReadonlySet; + readonly digitValue: ReadonlyMap; + readonly zero: string; + readonly reference: Intl.DateTimeFormat; + readonly eraFormat: Intl.DateTimeFormat; + readonly monthDayFormat: Intl.DateTimeFormat; + readonly monthDay: Map; + readonly eras: Map; + readonly years: Map; + readonly minusSign: string; + readonly referenceMinus: string; + readonly firstDay: number | undefined; +} + +const MAX_ENVS = 64; +let envs = new Map(); +let verdicts = new WeakMap(); +/** Stand-ins whose own `formatRange` already repairs the year. */ +const handled = new WeakSet(); + +/** Forget every verdict and environment (a replaced `Intl`, a test seam). */ +export function forgetWeekYearRange(): void { + envs = new Map(); + verdicts = new WeakMap(); +} + +/** Record a stand-in whose `formatRange` is `formatRangeChecked` already. */ +export function markRangeHandled(standIn: object): void { + handled.add(standIn); +} + +/** The text a negative number carries before its digits, as ECMA-402 FormatNumeric prints it. */ +function negativePrefix(locale: string, numberingSystem: string): string { + const text = new Intl.NumberFormat(locale, { + numberingSystem, + useGrouping: false, + }).format(-1); + return text.slice(0, text.search(ANY_DIGIT)); +} + +/** The first day of the week of a locale (1 = Monday), when the engine says. */ +function firstDayOf(locale: string): number | undefined { + try { + const intlLocale = new Intl.Locale(locale) as Intl.Locale & { + getWeekInfo?: () => { firstDay?: number }; + weekInfo?: { firstDay?: number }; + }; + const info = + typeof intlLocale.getWeekInfo === "function" + ? intlLocale.getWeekInfo() + : intlLocale.weekInfo; + return info?.firstDay; + } catch { + return undefined; + } +} + +function envOf(formatter: Intl.DateTimeFormat): Env { + const resolved = formatter.resolvedOptions(); + // A weekday can be printed by `weekday` or by any `dateStyle`; its digits (vi "Thứ 4") must not + // move, so shifted dates keep the weekday only for such formatters. + const weekday = + resolved.weekday !== undefined || resolved.dateStyle !== undefined; + const key = `${resolved.locale}|${resolved.calendar}|${resolved.numberingSystem}|${resolved.timeZone}|${weekday}`; + const known = envs.get(key); + if (known !== undefined) { + return known; + } + const { calendar, numberingSystem, timeZone } = resolved; + const base = { calendar, numberingSystem, timeZone }; + const digitList = digitsOf(numberingSystem); + const digitValue = new Map(); + digitList.forEach((digit, value) => digitValue.set(digit, value)); + const env: Env = { + weekday, + calendar, + temporalCalendar: TEMPORAL_STAND_IN[calendar]?.calendar ?? calendar, + yearBias: TEMPORAL_STAND_IN[calendar]?.bias ?? 0, + timeZone, + numberingSystem, + digits: new Set(digitList), + digitValue, + zero: digitList[0] ?? "0", + reference: referenceFor(calendar, numberingSystem, timeZone).format, + eraFormat: new Intl.DateTimeFormat("und", { + ...base, + era: "short", + year: "numeric", + }), + monthDayFormat: new Intl.DateTimeFormat("und", { + ...base, + month: "numeric", + day: "numeric", + }), + monthDay: new Map(), + eras: new Map(), + years: new Map(), + minusSign: negativePrefix(resolved.locale, numberingSystem), + referenceMinus: negativePrefix("und", numberingSystem), + firstDay: firstDayOf(resolved.locale), + }; + if (envs.size >= MAX_ENVS) { + envs.clear(); + } + envs.set(key, env); + return env; +} + +// ---------- text helpers ---------- + +/** The value of one digit character: its place in the numbering system, else in its Unicode block. */ +function digitValueOf(character: string, env: Env): number { + const known = env.digitValue.get(character); + if (known !== undefined) { + return known; + } + // Unicode Nd characters come in aligned 0-9 blocks: walk back to the block's zero. + const codePoint = character.codePointAt(0) ?? 0; + let steps = 0; + while ( + steps < 10 && + ANY_DIGIT.test(String.fromCodePoint(codePoint - steps - 1)) + ) { + steps++; + } + return steps % 10; +} + +function runsOf(text: string, env: Env): Run[] { + return textDigitRuns(text, env.digits).map((run) => { + const characters = [...run.text]; + return { + ...run, + count: characters.length, + value: characters.reduce( + (sum, character) => sum * 10 + digitValueOf(character, env), + 0, + ), + }; + }); +} + +const isSignish = (character: string): boolean => + MINUS.has(character) || BIDI.has(character); + +/** How many copies of the minus text `minus` end at position `at`. */ +function zoneCount(text: string, at: number, minus: string): number { + let count = 0; + while ( + minus.length > 0 && + at - minus.length * (count + 1) >= 0 && + text.slice(at - minus.length * (count + 1), at - minus.length * count) === + minus + ) { + count++; + } + return count; +} + +const range = ( + formatter: Intl.DateTimeFormat, + start: number, + end: number, +): string => formatter.formatRange(start, end); + +function monthDayText(ms: number, env: Env): string { + let text = env.monthDay.get(ms); + if (text === undefined) { + text = env.monthDayFormat.format(ms); + env.monthDay.set(ms, text); + } + return text; +} + +function eraText(ms: number, env: Env): string { + let text = env.eras.get(ms); + if (text === undefined) { + text = env.eraFormat.format(ms); + env.eras.set(ms, text); + } + return text; +} + +const maskEra = (text: string): string => + [...text].filter((c) => !ANY_DIGIT.test(c) && !isSignish(c)).join(""); + +/** ICU's calendar year at `ms`, the source the single repair uses. */ +function refYear(ms: number, env: Env): RefYear { + let year = env.years.get(ms); + if (year === undefined) { + const text = env.reference.format(ms); + const run = runsOf(text, env)[0]; + year = + run === undefined + ? { digits: "", count: 0, value: 0, negative: false } + : { + digits: run.text, + count: run.count, + value: run.value, + negative: zoneCount(text, run.start, env.referenceMinus) > 0, + }; + env.years.set(ms, year); + } + return year; +} + +// ---------- Temporal helpers ---------- + +const zonedOf = (ms: number, env: Env): Temporal.ZonedDateTime => + Temporal.Instant.fromEpochMilliseconds(ms) + .toZonedDateTimeISO(env.timeZone) + .withCalendar(env.temporalCalendar); + +/** + * Move a moment by `k` calendar years, keeping month code, day and wall time. `exact` (used to + * locate year runs) also keeps the weekday and ICU's own month and day, so only year fields can + * change; the loose form (used to read a pattern's literals) keeps only the time. + */ +function computeShift( + ms: number, + k: number, + env: Env, + exact: boolean, + keepWeekday: boolean, +): number | null { + const zoned = zonedOf(ms, env); + let moved: Temporal.ZonedDateTime; + try { + moved = zoned.with( + { year: zoned.year + k, monthCode: zoned.monthCode, day: zoned.day }, + { + overflow: exact ? "reject" : "constrain", + disambiguation: "compatible", + offset: "ignore", + }, + ); + } catch { + return null; + } + if ( + moved.hour !== zoned.hour || + moved.minute !== zoned.minute || + moved.second !== zoned.second || + moved.millisecond !== zoned.millisecond + ) { + return null; + } + if (!exact) { + return moved.epochMilliseconds; + } + // ICU's lunisolar and pre-1582 dates can be a day or two off Temporal's: take the nearby day on + // which ICU prints the same month and day, with the same weekday. + const want = monthDayText(ms, env); + for (const adjust of [0, -1, 1, -2, 2]) { + const candidate = adjust === 0 ? moved : moved.add({ days: adjust }); + if (keepWeekday && candidate.dayOfWeek !== zoned.dayOfWeek) { + continue; + } + if (monthDayText(candidate.epochMilliseconds, env) === want) { + return candidate.epochMilliseconds; + } + } + return null; +} + +/** `computeShift` answers, kept per environment: they depend on its calendar and zone only. */ +const shiftCache = new WeakMap>(); + +/** `computeShift`, remembered: every formatter of an environment probes the same moments. */ +function shiftYears( + ms: number, + k: number, + env: Env, + exact: boolean, + keepWeekday: boolean, +): number | null { + let byKey = shiftCache.get(env); + if (byKey === undefined) { + byKey = new Map(); + shiftCache.set(env, byKey); + } + const key = `${ms}|${k}|${exact}|${keepWeekday}`; + const known = byKey.get(key); + if (known !== undefined || byKey.has(key)) { + return known ?? null; + } + const moved = computeShift(ms, k, env, exact, keepWeekday); + byKey.set(key, moved); + return moved; +} + +// Multiples of 60 keep a sexagenary year name; multiples of 100 are left out, since they would +// leave a two-digit year unchanged. +const K_ORDER = [ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 60, 120, 180, 240, 360, 420, 480, 540, 660, + 720, 780, 840, 960, 1020, 1080, 1140, 1260, 1320, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, +]; + +const kCandidates = (direction: number): number[] => [ + ...K_ORDER.map((k) => direction * k), + ...K_ORDER.map((k) => -direction * k), +]; + +/** A year in the calendar and in ISO 8601 at `ms`. */ +function yearsOf(ms: number, env: Env): { calendar: number; iso: number } { + const zoned = zonedOf(ms, env); + return { + calendar: zoned.year - env.yearBias, + iso: zoned.withCalendar("iso8601").year, + }; +} + +// ---------- locating the year runs of a range text ---------- + +/** Digit runs of one text with the placeholder `\0` in place of the runs at `indexes`. */ +function masked(text: string, runs: readonly Run[], indexes: number[]): string { + let out = ""; + let position = 0; + for (const index of indexes) { + const run = runs[index]; + if (run !== undefined) { + out += text.slice(position, run.start) + "\u0000"; + position = run.end; + } + } + return out + text.slice(position); +} + +function changedRuns(before: readonly Run[], after: readonly Run[]): number[] { + const changed: number[] = []; + before.forEach((run, index) => { + if (run.text !== after[index]?.text) { + changed.push(index); + } + }); + return changed; +} + +/** The glued form of a year in front of another numeric field (ha `yyyyMM`). */ +function movedGlued(before: Run, after: Run, k: number): boolean { + const size = Math.abs(k); + for (let m = 1; m <= 2 && m < Math.min(before.count, after.count); m++) { + const first = [...before.text]; + const second = [...after.text]; + if (first.slice(-m).join("") !== second.slice(-m).join("")) { + continue; + } + const shift = Math.abs( + Math.floor(after.value / 10 ** m) - Math.floor(before.value / 10 ** m), + ); + if (Math.abs(shift - size) <= 1) { + return true; + } + } + return false; +} + +/** + * Whether a run moved as a year under a shift of `k` years: by `k` (era years count down, a + * week-year may differ by one), modulo 100 for a two-digit run, modulo 60 for a sexagenary number. + */ +function movedLikeYear(before: Run, after: Run, k: number, env: Env): boolean { + // Padding alone ("01" to "1") is a pattern change, not a year that moved. + if (after.value === before.value) { + return false; + } + if ( + RELATED.has(env.calendar) && + k % 60 !== 0 && + before.value >= 1 && + before.value <= 60 && + after.value >= 1 && + after.value <= 60 + ) { + // A sexagenary year number wraps at 60. + const wrapped = (((after.value - before.value) % 60) + 60) % 60; + if ([k - 1, k, k + 1].some((want) => wrapped === ((want % 60) + 60) % 60)) { + return true; + } + } + if (Math.abs(Math.abs(after.value - before.value) - Math.abs(k)) <= 1) { + return true; + } + if (movedGlued(before, after, k)) { + return true; + } + if (before.count <= 2 && after.count <= 2) { + const wrapped = (((after.value - before.value) % 100) + 100) % 100; + return [k - 1, k, k + 1, -k - 1, -k, -k + 1].some( + (want) => wrapped === ((want % 100) + 100) % 100, + ); + } + return false; +} + +const unlettered = (text: string): string => + text.replace(/[\p{L}\p{M}]+/gu, ""); + +/** A pair of moments for the range under a shift of `k` years, or `null` when it cannot be made. */ +type Reshift = (k: number) => [number, number] | null; + +/** One shifted trial's result. */ +interface Trial { + readonly runs: Run[]; + readonly changed: number[]; +} + +/** + * A shift by a multiple of 60 keeps a sexagenary year number, so an unchanged text there could + * hide one. A small shift changes it: when the digit runs all stay the same under one (letters, + * such as a year name or weekday, may change), no digit run depends on the year. + */ +function noDigitYear( + formatter: Intl.DateTimeFormat, + before: readonly Run[], + env: Env, + reshift: Reshift, +): boolean { + // From 2: under a one-year shift a week-year can stay the same (2025-12-29 and 2026-12-29 are + // both in week-year 2026); under 2..12 every year number, era year and sexagenary number moves. + for (let k = 2; k <= 12; k++) { + const pair = reshift(k); + if (pair === null) { + continue; + } + const after = runsOf(range(formatter, pair[0], pair[1]), env); + if (after.length !== before.length) { + continue; + } + return changedRuns(before, after).length === 0; + } + return false; +} + +/** + * One shifted trial: same run count, same text outside the runs that changed, and every run that + * changed moved like a year. + */ +function trial( + formatter: Intl.DateTimeFormat, + original: { text: string; runs: Run[] }, + start: number, + end: number, + env: Env, + k: number, + reshift: Reshift, +): Trial | null { + const text = range(formatter, start, end); + const runs = runsOf(text, env); + if (runs.length !== original.runs.length) { + return null; + } + const changed = changedRuns(original.runs, runs); + // No run moved: the text prints no year, unless k keeps a sexagenary year number unchanged. + if ( + changed.length === 0 && + RELATED.has(env.calendar) && + k % 60 === 0 && + !noDigitYear(formatter, original.runs, env, reshift) + ) { + return null; + } + // Letters and marks are set aside: weekday, month and sexagenary year names change with the + // date; the digit runs and the punctuation between them are the evidence. + if ( + unlettered(masked(original.text, original.runs, changed)) !== + unlettered(masked(text, runs, changed)) + ) { + return null; + } + const moved = changed.every((index) => { + const before = original.runs[index]; + const after = runs[index]; + return ( + before !== undefined && + after !== undefined && + movedLikeYear(before, after, k, env) + ); + }); + return moved ? { runs, changed } : null; +} + +/** A year run found in a range text: its index, whose endpoint it holds, and its shifted text. */ +interface YearRun { + readonly index: number; + readonly owner: "a" | "b"; + readonly shiftedText: string; + readonly shiftedMs: number; +} + +/** A range text with the runs that hold a year. */ +interface Located { + readonly text: string; + readonly runs: Run[]; + readonly years: YearRun[]; +} + +/** + * A printed weekday must stay put under small shifts, since a weekday digit (vi "Thứ 4") moving by + * up to 6 could pass for a two-digit year moved by k. Under a multiple of 60 that is not a + * multiple of 100 it cannot: no rule in `movedLikeYear` accepts a change of -6..6 there. + */ +const keepsWeekday = (k: number): boolean => k % 60 !== 0; + +const yearRunsOf = ( + found: Trial, + owner: "a" | "b", + shiftedMs: number, +): YearRun[] => + found.changed.map((index) => ({ + index, + owner, + shiftedText: found.runs[index]?.text ?? "", + shiftedMs, + })); + +/** Locate the year runs when both endpoints are in one era: both move together. */ +function locateTogether( + formatter: Intl.DateTimeFormat, + original: { text: string; runs: Run[] }, + a: number, + b: number, + env: Env, + both: Reshift, +): YearRun[] | null { + const ya = yearsOf(a, env); + const direction = ya.calendar <= 0 || ya.iso <= 0 ? -1 : 1; + for (const k of kCandidates(direction)) { + const shiftedStart = shiftYears(a, k, env, true, keepsWeekday(k)); + if (shiftedStart === null) { + continue; + } + const shiftedEnd = shiftYears(b, k, env, true, keepsWeekday(k)); + if (shiftedEnd === null) { + continue; + } + const found = trial( + formatter, + original, + shiftedStart, + shiftedEnd, + env, + k, + both, + ); + if (found !== null) { + return yearRunsOf(found, "a", shiftedStart); + } + } + return null; +} + +/** + * Locate one endpoint's year runs by moving that endpoint alone, away from the other; `side` is + * the direction of the move (the start goes back, the end goes forward). + */ +function locateAlone( + formatter: Intl.DateTimeFormat, + original: { text: string; runs: Run[] }, + a: number, + b: number, + env: Env, + owner: "a" | "b", +): { runs: YearRun[]; changed: number[] } | null { + const own = owner === "a" ? a : b; + const other = owner === "a" ? b : a; + const direction = owner === "a" ? -1 : 1; + const pair = (moved: number): [number, number] => + owner === "a" ? [moved, b] : [a, moved]; + for (const k of kCandidates(direction)) { + const moved = shiftYears(own, k, env, true, keepsWeekday(k)); + if (moved === null || eraText(moved, env) === eraText(other, env)) { + continue; + } + const alone: Reshift = (kk) => { + const shifted = shiftYears(own, direction * kk, env, true, false); + return shifted === null || eraText(shifted, env) === eraText(other, env) + ? null + : pair(shifted); + }; + const [from, to] = pair(moved); + const found = trial(formatter, original, from, to, env, k, alone); + if (found !== null) { + return { runs: yearRunsOf(found, owner, moved), changed: found.changed }; + } + } + return null; +} + +/** The year runs of `formatRange(a, b)`, or `null` when no shift keeps the pattern. */ +function locate( + formatter: Intl.DateTimeFormat, + a: number, + b: number, + env: Env, + text = range(formatter, a, b), +): Located | null { + const runs = runsOf(text, env); + const original = { text, runs }; + const both: Reshift = (k) => { + const start = shiftYears(a, k, env, true, false); + const end = shiftYears(b, k, env, true, false); + return start === null || end === null ? null : [start, end]; + }; + const none = (): Located | null => + noDigitYear(formatter, runs, env, both) ? { text, runs, years: [] } : null; + if (eraText(a, env) === eraText(b, env)) { + const years = locateTogether(formatter, original, a, b, env, both); + return years === null ? none() : { text, runs, years }; + } + // Different calendar years: move each endpoint alone, away from the other. + const first = locateAlone(formatter, original, a, b, env, "a"); + if (first === null) { + return none(); + } + const second = locateAlone(formatter, original, a, b, env, "b"); + if (second === null) { + return none(); + } + if (first.changed.some((index) => second.changed.includes(index))) { + return none(); + } + return { + text, + runs, + years: [...first.runs, ...second.runs].sort((x, y) => x.index - y.index), + }; +} + +// ---------- the sign of a year run ---------- + +/** + * Week-years lie within one of the extended or ISO year, so both >= 1 means no value below 0. + */ +function surelyPositive(ms: number, env: Env): boolean { + const years = yearsOf(ms, env); + return years.calendar >= 1 && years.iso >= 1 && !refYear(ms, env).negative; +} + +/** + * The pattern's skeleton: the punctuation between consecutive digit runs, with letters, marks, + * spaces and bidi marks left out, and the minus copies before each year run (those are what is + * being measured). + */ +function skeleton( + text: string, + runs: readonly Run[], + yearIndexes: ReadonlySet, + env: Env, +): string { + const out: string[] = []; + for (let index = 1; index < runs.length; index++) { + const previous = runs[index - 1]; + const current = runs[index]; + if (previous === undefined || current === undefined) { + continue; + } + let literal = text.slice(previous.end, current.start); + if (yearIndexes.has(index)) { + const copies = zoneCount(text, current.start, env.minusSign); + literal = literal.slice( + 0, + literal.length - copies * env.minusSign.length, + ); + } + // A letter takes its abbreviation dots with it ("B.R.O.C." against "Minguo"). + out.push( + literal.replace(/[\p{L}\p{M}]+\.?/gu, "").replace(/[\p{Z}\s‎‏؜]+/gu, ""), + ); + } + return out.join("#"); +} + +/** The same range moved by whole years to where both endpoints are positive. */ +interface Far { + readonly text: string; + readonly runs: Run[]; +} + +function farRange( + formatter: Intl.DateTimeFormat, + located: Located, + a: number, + b: number, + env: Env, +): Far | null { + const ya = yearsOf(a, env); + const yb = yearsOf(b, env); + const k0 = 2000 - Math.min(ya.iso, ya.calendar, yb.iso, yb.calendar); + // Prefer a move that keeps both weekdays, so weekday names and numbers stay put. + const weekday = (ms: number): number => zonedOf(ms, env).dayOfWeek; + let pick: [number, number] | null = null; + for (let k = k0; k < k0 + 400 && pick === null; k++) { + const start = shiftYears(a, k, env, false, false); + const end = shiftYears(b, k, env, false, false); + if ( + start !== null && + end !== null && + weekday(start) === weekday(a) && + weekday(end) === weekday(b) + ) { + pick = [start, end]; + } + } + if (pick === null) { + const start = shiftYears(a, k0, env, false, false); + const end = shiftYears(b, k0, env, false, false); + if (start !== null && end !== null) { + pick = [start, end]; + } + } + if ( + pick === null || + !surelyPositive(pick[0], env) || + !surelyPositive(pick[1], env) + ) { + return null; + } + const text = range(formatter, pick[0], pick[1]); + const runs = runsOf(text, env); + const yearIndexes = new Set(located.years.map((year) => year.index)); + return runs.length === located.runs.length && + skeleton(text, runs, yearIndexes, env) === + skeleton(located.text, located.runs, yearIndexes, env) + ? { text, runs } + : null; +} + +/** A run's sign: whether it is negative and how many characters the minus takes. */ +interface Sign { + readonly negative: boolean; + readonly length: number; +} + +/** The copies of the minus text before a run that belong to the pattern, not to the number. */ +function literalCount( + formatter: Intl.DateTimeFormat, + located: Located, + year: YearRun, + a: number, + b: number, + env: Env, + cache: { far?: Far | null }, +): number | null { + // 1. The matching year run of the other endpoint's half, when that endpoint is positive. + const mine = located.years + .filter((entry) => entry.owner === year.owner) + .map((entry) => entry.index); + const other = located.years + .filter((entry) => entry.owner !== year.owner) + .map((entry) => entry.index); + if ( + mine.length === other.length && + surelyPositive(year.owner === "a" ? b : a, env) + ) { + const run = located.runs[other[mine.indexOf(year.index)] ?? -1]; + return run === undefined + ? null + : zoneCount(located.text, run.start, env.minusSign); + } + // 2. The same range moved by whole years to where both endpoints are positive, when the pattern + // is unchanged. + if (cache.far === undefined) { + cache.far = farRange(formatter, located, a, b, env); + } + const run = cache.far?.runs[year.index]; + return cache.far === null || run === undefined + ? null + : zoneCount(cache.far.text, run.start, env.minusSign); +} + +function signOf( + formatter: Intl.DateTimeFormat, + located: Located, + year: YearRun, + a: number, + b: number, + env: Env, + cache: { far?: Far | null }, + digitsMatch: boolean, +): Sign | null { + const run = located.runs[year.index]; + if (run === undefined) { + return null; + } + const minus = env.minusSign; + const copies = zoneCount(located.text, run.start, minus); + if (copies === 0) { + return { negative: false, length: 0 }; + } + const ms = year.owner === "a" ? a : b; + const ref = refYear(ms, env); + // The calendar's own year is negative here and the run prints it: it is that year. + if (ref.negative && run.text === ref.digits) { + return { negative: true, length: minus.length }; + } + // Both years positive: neither y nor a week-year (within one of either) can be negative. + if (surelyPositive(ms, env)) { + return { negative: false, length: 0 }; + } + const literal = literalCount(formatter, located, year, a, b, env, cache); + if (literal !== null) { + if (copies - literal === 0) { + return { negative: false, length: 0 }; + } + return copies - literal === 1 + ? { negative: true, length: minus.length } + : null; + } + if (digitsMatch) { + return null; + } + // The digits are wrong either way; for the repair, read the sign from the week-year window: a + // week-year is within one year of the calendar's extended year or of the ISO year. + const window = weekYearWindow(ms, env); + const positive = window.has(run.value); + const negative = window.has(-run.value); + if (positive === negative) { + return null; + } + return negative + ? { negative: true, length: minus.length } + : { negative: false, length: 0 }; +} + +/** The values a week-year can take at `ms`: within one of the extended or the ISO year. */ +function weekYearWindow(ms: number, env: Env): Set { + const years = yearsOf(ms, env); + return new Set([ + years.calendar - 1, + years.calendar, + years.calendar + 1, + years.iso - 1, + years.iso, + years.iso + 1, + ]); +} + +// ---------- the expected year text ---------- + +/** The last two digits of a year's digits, padded. */ +function lastTwo(digits: string, env: Env): string { + const characters = [...digits]; + return characters.length >= 2 + ? characters.slice(-2).join("") + : env.zero + characters.join(""); +} + +/** + * Sexagenary position of ICU's related year (chinese, dangi): year 4 CE is jia-zi, position 1. + * Taken from ICU's own year, since ICU and Temporal can place a lunar new year a day apart. + */ +const cyclic = (ref: RefYear): number => + ((((ref.value - 4) % 60) + 60) % 60) + 1; + +/** Whether a year glued to another numeric field (brx `d/My`) shows `ref` in this run. */ +function gluedMatch( + run: Run, + ref: RefYear, + y: YearRun, + env: Env, + two: boolean, +): boolean { + const ref1 = refYear(y.shiftedMs, env); + const forms: [string, string][] = [ + [lastTwo(ref.digits, env), lastTwo(ref1.digits, env)], + ]; + if (!two) { + forms.unshift([ref.digits, ref1.digits]); + } + return forms.some(([digits, shifted]) => { + if (run.text.length <= digits.length) { + return false; + } + return ( + (run.text.endsWith(digits) && + y.shiftedText === + run.text.slice(0, run.text.length - digits.length) + shifted) || + (run.text.startsWith(digits) && + y.shiftedText === shifted + run.text.slice(digits.length)) + ); + }); +} + +/** + * Whether the run holds ICU's calendar year. `two`: the formatter asked for year "2-digit", whose + * output ECMA-402 FormatDateTimePattern cuts to two digits; an ICU week-year field keeps its own + * width there ("1617" for "17"), which is wrong as well. + */ +function digitsMatch( + run: Run, + ref: RefYear, + env: Env, + y: YearRun | undefined, + two: boolean, +): boolean { + // The whole year, never a glued form. Under "2-digit" more than two digits cannot come from a + // two-digit year field. + if (run.text === ref.digits) { + return !(two && run.count > 2); + } + if (run.count === 2 && run.text === lastTwo(ref.digits, env)) { + return true; + } + if (y !== undefined && gluedMatch(run, ref, y, env, two)) { + return true; + } + if (RELATED.has(env.calendar)) { + const position = cyclic(ref); + return ( + run.value === position || + (run.count === 2 && run.value === position % 100) + ); + } + return false; +} + +/** A run found wrong: it holds neither ICU's year nor its sign. */ +interface Wrong { + readonly run: Run; + readonly sign: Sign; + readonly ref: RefYear; + readonly ms: number; +} + +/** Check one range: the located year runs, and which of them do not hold the calendar year. */ +function checkRange( + formatter: Intl.DateTimeFormat, + a: number, + b: number, + options: Intl.DateTimeFormatOptions, + env: Env, +): { located: Located; wrong: Wrong[] } | null { + const located = locate(formatter, a, b, env); + if (located === null) { + return null; + } + const cache: { far?: Far | null } = {}; + const wrong: Wrong[] = []; + // ECMA-402 fixes "2-digit" at two digits for the year field only; in chinese and dangi the + // reference is the related year, which FormatNumeric prints in full whatever the option. + const two = options.year === "2-digit" && !RELATED.has(env.calendar); + for (const year of located.years) { + const ms = year.owner === "a" ? a : b; + const run = located.runs[year.index]; + if (run === undefined) { + return null; + } + const ref = refYear(ms, env); + const matches = digitsMatch(run, ref, env, year, two); + const sign = signOf(formatter, located, year, a, b, env, cache, matches); + if (sign === null) { + return null; + } + if (!(sign.negative === ref.negative && matches)) { + wrong.push({ run, sign, ref, ms }); + } + } + return { located, wrong }; +} + +// ---------- the verdict ---------- + +const atDate = (date: Temporal.PlainDate, env: Env, time = "12:00"): number => + date.toZonedDateTime({ timeZone: env.timeZone, plainTime: time }) + .epochMilliseconds; + +type Probe = [number, number]; + +/** The weekday offsets (1..6 from the first day of the week) of year starts, one date for each. */ +function yearStarts(env: Env, anchor: number): Map { + const byOffset = new Map(); + for ( + let year = anchor + 1; + year <= anchor + 80 && byOffset.size < 6; + year++ + ) { + let first = Temporal.PlainDate.from({ + calendar: env.temporalCalendar, + year, + monthCode: "M01", + day: 1, + }); + // Year boundaries as ICU's own calendar year sees them. + for ( + let steps = 0; + refYear(atDate(first, env), env).digits === + refYear(atDate(first.subtract({ days: 1 }), env), env).digits && + steps < 4; + steps++ + ) { + first = first.add({ days: 1 }); + } + const offset = (first.dayOfWeek - (env.firstDay ?? 1) + 7) % 7; + if (offset !== 0 && !byOffset.has(offset)) { + byOffset.set(offset, first); + } + } + return byOffset; +} + +/** Which year-start offsets to probe: two just after a week start (`L`) and two just before (`H`). */ +function pickedOffsets( + offsets: readonly number[], + hasFirstDay: boolean, +): string[] { + if (!hasFirstDay) { + return offsets.flatMap((o) => [`L${o}`, `H${o}`]); + } + const unique = (keys: string[]): string[] => [...new Set(keys)]; + const low = offsets.find((o) => o >= 1); + const lower = offsets.find((o) => o >= 2); + const high = [...offsets].reverse().find((o) => o <= 6); + const higher = [...offsets].reverse().find((o) => o <= 5); + return unique([ + ...[low, lower].flatMap((o) => (o === undefined ? [] : [`L${o}`])), + ...[high, higher].flatMap((o) => (o === undefined ? [] : [`H${o}`])), + ]); +} + +/** The day, month, year and time ranges on one side of a year boundary. */ +function sideProbes( + first: Temporal.PlainDate, + side: "L" | "H", + env: Env, +): Probe[] { + const last = first.subtract({ days: 1 }); + const at = (date: Temporal.PlainDate, time?: string): number => + atDate(date, env, time); + if (side === "L") { + return [ + [at(last.subtract({ days: 1 })), at(last)], + [at(last.subtract({ months: 1 })), at(last)], + [at(last), at(first)], + [at(last.subtract({ years: 1 })), at(last)], + [at(last, "10:00"), at(last, "15:00")], + [at(last, "10:00"), at(last, "10:30")], + ]; + } + return [ + [at(first), at(first.add({ days: 1 }))], + [at(first), at(first.add({ months: 1 }))], + [at(last), at(first)], + [at(first), at(first.add({ years: 1 }))], + [at(first, "10:00"), at(first, "15:00")], + [at(first, "10:00"), at(first, "10:30")], + ]; +} + +/** Probes in an earlier era (Temporal and ICU both see an era change), and across the era. */ +function earlierEraProbes( + anchor: number, + env: Env, + picked: readonly string[], + starts: ReadonlyMap, +): Probe[] { + const here = atDate( + Temporal.PlainDate.from({ + calendar: env.temporalCalendar, + year: anchor, + monthCode: "M06", + day: 1, + }), + env, + ); + for (const step of [ + 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, + ]) { + let earlier: Temporal.PlainDate; + try { + earlier = Temporal.PlainDate.from({ + calendar: env.temporalCalendar, + year: anchor - step, + monthCode: "M06", + day: 1, + }); + } catch { + continue; + } + const start = atDate(earlier, env); + if (maskEra(eraText(start, env)) === maskEra(eraText(here, env))) { + continue; + } + const across = picked.flatMap((key): Probe[] => { + const first = starts.get(Number(key.slice(1))); + return first === undefined + ? [] + : [ + [ + start, + atDate( + key.startsWith("L") ? first.subtract({ days: 1 }) : first, + env, + ), + ], + ]; + }); + return [ + [start, atDate(earlier.add({ days: 1 }), env)], + [start, atDate(earlier.add({ months: 1 }), env)], + [start, atDate(earlier.add({ years: 1 }), env)], + [atDate(earlier, env, "10:00"), atDate(earlier, env, "15:00")], + [atDate(earlier, env, "10:00"), atDate(earlier, env, "10:30")], + ...across, + ]; + } + return []; +} + +/** + * The probe ranges of a calendar: year boundaries from 2024 on at weekday offsets 1 to 6 from the + * locale's first day of the week, where `Y` and `y` differ, with day, month, year and time ranges + * on both sides; and day, month, year, time and cross-era ranges in an earlier era. + */ +function computeProbes(env: Env): Probe[] { + const anchor = Temporal.PlainDate.from("2024-07-01").withCalendar( + env.temporalCalendar, + ).year; + const starts = yearStarts(env, anchor); + const offsets = [...starts.keys()].sort((x, y) => x - y); + const picked = pickedOffsets(offsets, env.firstDay !== undefined); + const edges = picked.flatMap((key) => { + const first = starts.get(Number(key.slice(1))); + return first === undefined + ? [] + : sideProbes(first, key.startsWith("L") ? "L" : "H", env); + }); + return [...edges, ...earlierEraProbes(anchor, env, picked, starts)]; +} + +/** The probes of an environment, built once: they depend on its calendar, zone and locale only. */ +const probeCache = new WeakMap(); +function probes(env: Env): Probe[] { + let list = probeCache.get(env); + if (list === undefined) { + list = computeProbes(env); + probeCache.set(env, list); + } + return list; +} + +/** + * Whether the formatter's range pattern prints a week-based year where the calendar year is meant + * (defect D24 in ranges). A digit run is a year run when it moves exactly as a year under a shift + * of one or both endpoints by k years; each is compared with ICU's calendar year for its + * endpoint, signed with the locale's minus, and under `year: "2-digit"` only the last two digits + * (chinese and dangi print the related year at full width). A formatter whose range text holds no + * decimal year is not flagged. A probe whose year runs cannot be located counts as flagged. + * + * Computed once per formatter, on its first range call; only `format` and `formatRange` are called. + * + * @param formatter the formatter whose range text is read + * @param options the options it was built with + * @returns `true` when its range text needs `repairRangeYear` + * + * @example rangeYearVerdict(new Intl.DateTimeFormat("en", { year: "numeric", month: "short" }), { year: "numeric", month: "short" }) // false + * @example rangeYearVerdict(new Intl.DateTimeFormat("my-u-ca-buddhist", { year: "numeric", month: "short", day: "numeric" }), { year: "numeric", month: "short", day: "numeric" }) // true + */ +export function rangeYearVerdict( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, +): boolean { + const known = verdicts.get(formatter); + if (known !== undefined) { + return known; + } + let flagged: boolean; + try { + const env = envOf(formatter); + flagged = false; + for (const [a, b] of probes(env)) { + const checked = checkRange(formatter, a, b, options, env); + if (checked === null || checked.wrong.length > 0) { + flagged = true; + break; + } + } + } catch { + flagged = false; + } + verdicts.set(formatter, flagged); + return flagged; +} + +// ---------- the repair ---------- + +/** How a year run is written: full, or the last two digits. */ +function styleFor( + run: Run, + options: Intl.DateTimeFormatOptions, + env: Env, +): "two" | "full" { + if (RELATED.has(env.calendar)) { + return run.count === 2 ? "two" : "full"; + } + if (options.year === "2-digit") { + return "two"; + } + if (options.year === "numeric") { + return "full"; + } + return run.count === 2 ? "two" : "full"; +} + +/** Whether the run holds one whole week-year value (within one of the extended or ISO year). */ +function isWholeWeekYear(wrong: Wrong, env: Env): boolean { + const window = weekYearWindow(wrong.ms, env); + const value = wrong.sign.negative ? -wrong.run.value : wrong.run.value; + return ( + window.has(value) || + (wrong.run.count === 2 && + [...window].some( + (candidate) => + candidate < 0 === wrong.sign.negative && + Math.abs(candidate) % 100 === wrong.run.value, + )) + ); +} + +/** Whether the polyfill can project the instant onto the formatter's calendar. */ +const readable = (ms: number, env: Env): boolean => { + try { + return Number.isFinite(yearsOf(ms, env).calendar); + } catch { + return false; + } +}; + +/** + * The range text with each week-based year run replaced by the endpoint's calendar year: ICU's + * year, signed with the locale's minus, in the formatter's numbering system, ungrouped, at the + * width printed (full, or the last two digits). Only the runs found wrong change, and every other + * character is kept. + * + * @param formatter the formatter that prints the range + * @param options the options it was built with + * @param startMs the start of the range, in epoch milliseconds + * @param endMs the end of the range, in epoch milliseconds + * @returns the repaired text, or `null` when the year runs cannot be located or a run is not one + * whole week-year value + * + * @example repairRangeYear(new Intl.DateTimeFormat("kok-u-ca-japanese", { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }), { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }, Date.UTC(2018, 11, 27), Date.UTC(2019, 11, 27)) // the end year is 1 (Reiwa), not 2019 + */ +export function repairRangeYear( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, + startMs: number, + endMs: number, +): string | null { + try { + const env = envOf(formatter); + if (!readable(startMs, env) || !readable(endMs, env)) { + // The polyfill refuses a date the calendar cannot project (`indian` before ISO year 1, + // V8 bug 10529), so no week-year can be measured there: ICU's text stands. + return formatter.formatRange(startMs, endMs); + } + const checked = checkRange(formatter, startMs, endMs, options, env); + if (checked === null) { + return null; + } + if (!checked.wrong.every((wrong) => isWholeWeekYear(wrong, env))) { + return null; + } + let out = checked.located.text; + for (const wrong of checked.wrong.toSorted( + (x, y) => y.run.start - x.run.start, + )) { + const digits = + styleFor(wrong.run, options, env) === "two" + ? lastTwo(wrong.ref.digits, env) + : wrong.ref.digits; + const sign = wrong.ref.negative ? env.minusSign : ""; + out = + out.slice(0, wrong.run.start - wrong.sign.length) + + sign + + digits + + out.slice(wrong.run.end); + } + return out; + } catch { + return null; + } +} + +/** + * The formatter's range text with the calendar year where the engine prints the week-year: the + * one call every library `formatRange` goes through. The verdict is computed on the formatter's + * first call and kept; a formatter that is not flagged answers with the engine's own text, and a + * stand-in that repairs its own range is called as it is. + * + * @returns the text, or `null` when a flagged formatter's year runs cannot be repaired + */ +export function formatRangeChecked( + formatter: Intl.DateTimeFormat, + options: Intl.DateTimeFormatOptions, + startMs: number, + endMs: number, +): string | null { + if (handled.has(formatter) || !rangeYearVerdict(formatter, options)) { + return formatter.formatRange(startMs, endMs); + } + return repairRangeYear(formatter, options, startMs, endMs); +} diff --git a/packages/gmt/src/internal/weekYearRangeNull.test.ts b/packages/gmt/src/internal/weekYearRangeNull.test.ts new file mode 100644 index 000000000..dedeeccbe --- /dev/null +++ b/packages/gmt/src/internal/weekYearRangeNull.test.ts @@ -0,0 +1,51 @@ +import { formatDateRange } from "../plain/format/formatDateRange"; +import { formatDateTimeRange } from "../plain/format/formatDateTimeRange"; +import { formatZonedRange } from "../zoned/format/formatZonedRange"; + +vi.mock("./weekYearRange", async (importOriginal) => ({ + ...(await importOriginal()), + formatRangeChecked: () => null, +})); + +vi.mock("./temporalCompat", async (importOriginal) => ({ + ...(await importOriginal()), + isRangeZoneNameCompatNeeded: () => true, +})); + +/* + * CORE-112 (slice 3c): a flagged range whose year cannot be repaired is `null`, and every call + * site answers the invalid-input sentinel `""` for it (coding-standards, API contract), never the + * wrong-year text. The isolated mock makes `formatRangeChecked` answer `null`, so each of the four + * paths is reached: the two plain functions, and both zoned paths (plain, and zone-name repair). + */ +describe("a range whose year cannot be repaired", () => { + it("returns '' from formatDateRange", () => { + expect(formatDateRange("2024-07-10", "2024-07-12", "en", {})).toBe(""); + }); + + it("returns '' from formatDateTimeRange", () => { + expect( + formatDateTimeRange( + "2024-07-10T01:00:00", + "2024-07-12T01:00:00", + "en", + {}, + ), + ).toBe(""); + }); + + it.each` + label | options + ${"no zone name"} | ${{ year: "numeric" }} + ${"with a zone name"} | ${{ hour: "numeric", timeZoneName: "long" }} + `("returns '' from formatZonedRange, $label", ({ options }) => { + expect( + formatZonedRange( + "2024-07-10T01:00:00+00:00[UTC]", + "2024-07-12T01:00:00+00:00[UTC]", + "en", + options, + ), + ).toBe(""); + }); +}); diff --git a/packages/gmt/src/internal/weekYearRangeText.test.ts b/packages/gmt/src/internal/weekYearRangeText.test.ts new file mode 100644 index 000000000..f6f376b9f --- /dev/null +++ b/packages/gmt/src/internal/weekYearRangeText.test.ts @@ -0,0 +1,134 @@ +import { formatDateRange } from "../plain/format/formatDateRange"; +import { formatDateTimeRange } from "../plain/format/formatDateTimeRange"; +import { runInBoundedChild } from "../test/boundedChild"; +import { formatZonedRange } from "../zoned/format/formatZonedRange"; +import { normalizeDateTime } from "./normalizeDateTime"; + +/* + * CORE-112 (D24, slice 3c): a range prints the calendar year at each end, never the week-year. + * + * Every year below is the Temporal calendar year of that endpoint (`eraYear ?? year` where the + * pattern prints an era), written in the formatter's numbering system, not the engine's text: + * - kok japanese, 2018-12-27: Heisei 30 (Heisei ended 2019-04-30); 2019-12-27: Reiwa 1. + * - my buddhist, 2026-12-27: BE 2569 = 2026 + 543; 2027-01-03: BE 2570. Burmese digits. + * - kok roc, 2024-07-10 and 2024-07-12: ROC 113 = 2024 - 1911. + * - kok-Deva coptic, 2029-09-09 and 2029-09-10: Coptic 1745 AM (year 1745 runs from + * 2028-09-11 to 2029-09-10); month 13, so the polyfill cannot derive it (defect F). + * Layout, separators and era text stay as the locale data has them. The en dash is written as `-`, + * as GMT normalizes every formatted string. + */ +describe("range, week-year patterns", () => { + const numeric = { + year: "numeric", + month: "numeric", + day: "numeric", + } as const; + const weekdayShort = { ...numeric, weekday: "short" } as const; + const withEra = { era: "short", ...weekdayShort } as const; + + it.each` + locale | options | from | to | expected | label + ${"kok-u-ca-japanese"} | ${numeric} | ${"2018-12-27"} | ${"2019-12-27"} | ${"27-12-30 H – 27-12-1 R"} | ${"kok japanese, Heisei to Reiwa"} + ${"my-u-ca-buddhist"} | ${numeric} | ${"2026-12-27"} | ${"2027-01-03"} | ${"BE ၂၇/၁၂/၂၅၆၉ – BE ၀၃/၀၁/၂၅၇၀"} | ${"my buddhist, over New Year"} + ${"kok-u-ca-roc"} | ${weekdayShort} | ${"2024-07-10"} | ${"2024-07-12"} | ${"बुधवार, 10-7-113 ROC – शुक्रार-12-7-113"} | ${"kok roc, option set 12"} + ${"kok-u-ca-roc"} | ${withEra} | ${"2024-07-10"} | ${"2024-07-12"} | ${"बुधवार, 10-7-113 ROC – शुक्रार-12-7-113"} | ${"kok roc, option set 19"} + ${"kok-Deva-u-ca-coptic"} | ${numeric} | ${"2029-09-09"} | ${"2029-09-10"} | ${"4-13-1745 AM – 5-13-1745"} | ${"kok-Deva coptic, control"} + `( + "formatDateRange and formatDateTimeRange print the calendar year for $label ('$locale', $from to $to)", + ({ locale, options, from, to, expected }) => { + expect(formatDateRange(from, to, locale, options)).toBe( + normalizeDateTime(expected), + ); + expect( + formatDateTimeRange( + `${from}T00:00:00`, + `${to}T00:00:00`, + locale, + options, + ), + ).toBe(normalizeDateTime(expected)); + expect( + formatZonedRange( + `${from}T00:00:00+00:00[UTC]`, + `${to}T00:00:00+00:00[UTC]`, + locale, + options, + ), + ).toBe(normalizeDateTime(expected)); + }, + ); + + it("formatZonedRange prints the calendar year beside a zone name, in a child process", async () => { + const from = "2026-12-27T09:30:00+06:30[Asia/Yangon]"; + const to = "2027-01-03T09:30:00+06:30[Asia/Yangon]"; + const options = + '{ year: "numeric", month: "numeric", day: "numeric", timeZoneName: "short" }'; + const run = await runInBoundedChild([ + `gmt.formatZonedRange("${from}", "${to}", "my-u-ca-buddhist", ${options})`, + ]); + expect( + { timedOut: run.timedOut, crashed: run.crashed }, + run.stderr, + ).toEqual({ timedOut: false, crashed: false }); + const range = String(run.calls[0]?.value); + expect(range).toContain("၂၅၆၉"); + expect(range).toContain("၂၅၇၀"); + expect(range).not.toContain("၂၀၂"); + }); +}); + +/* + * Slice 3c before ISO year 1, in the calendars the polyfill cannot project directly (`TEMPORAL_STAND_IN` + * for coptic and ethiopic, `readable()` for indian). Each expected year is the Temporal year of + * the endpoint (native Temporal, which projects these calendars before ISO year 1), written as + * Intl prints it: ECMA-402 FormatDateTimePattern turns a year <= 0 into 1 - year, so coptic + * year -285 (ISO -0001-07-10) prints 286 and -283 prints 284; ethiopic prints the era year of the + * `aa` era (5491, 5493) because its years before AM 1 have that era; indian is one signed era, + * so -79 and -77 print as they are, with the locale's minus. The kok formatters print a week-year + * in their range pattern (kok-u-ca-coptic and kok-u-ca-ethiopic are flagged), so the repair + * must write these years; kok-u-ca-indian is not flagged and ICU's text stands. + */ +describe("range, calendar year before ISO year 1", () => { + const numeric = { + year: "numeric", + month: "numeric", + day: "numeric", + } as const; + + it.each` + locale | from | to | expected | label + ${"kok-u-ca-coptic"} | ${"-000001-07-10"} | ${"0001-07-10"} | ${"18-11-286 - 18-11-284"} | ${"coptic -285 to -283"} + ${"kok-Deva-u-ca-coptic"} | ${"-000001-07-10"} | ${"0001-07-10"} | ${"18-11-286 - 18-11-284"} | ${"kok-Deva coptic -285 to -283"} + ${"kok-u-ca-coptic"} | ${"-000002-07-10"} | ${"-000001-07-10"} | ${"18-11-287 - 18-11-286"} | ${"coptic -286 to -285"} + ${"kok-u-ca-coptic"} | ${"0001-01-01"} | ${"0001-12-31"} | ${"8-5-284 - 7-5-283"} | ${"coptic -283 to -282, across the coptic new year"} + ${"kok-u-ca-ethiopic"} | ${"-000001-07-10"} | ${"0001-07-10"} | ${"18-11-5491 - 18-11-5493 AA"} | ${"ethiopic aa 5491 to 5493"} + ${"kok-u-ca-ethiopic"} | ${"-000002-07-10"} | ${"-000001-07-10"} | ${"18-11-5490 - 18-11-5491 AA"} | ${"ethiopic aa 5490 to 5491"} + ${"kok-u-ca-ethiopic"} | ${"0001-01-01"} | ${"0001-12-31"} | ${"8-5-5493 - 7-5-5494 AA"} | ${"ethiopic aa 5493 to 5494"} + ${"kok-u-ca-indian"} | ${"-000001-07-10"} | ${"0001-07-10"} | ${"19-4--79 - 19-4--77 शक"} | ${"indian -79 to -77"} + ${"kok-u-ca-indian"} | ${"-000002-07-10"} | ${"-000001-07-10"} | ${"19-4--80 - 19-4--79 शक"} | ${"indian -80 to -79"} + ${"kok-u-ca-indian"} | ${"0001-01-01"} | ${"0001-12-31"} | ${"11-10--78 - 10-10--77 शक"} | ${"indian -78 to -77"} + `( + "the three range functions print the calendar year for $label ('$locale', $from to $to)", + ({ locale, from, to, expected }) => { + expect(formatDateRange(from, to, locale, numeric)).toBe( + normalizeDateTime(expected), + ); + expect( + formatDateTimeRange( + `${from}T00:00:00`, + `${to}T00:00:00`, + locale, + numeric, + ), + ).toBe(normalizeDateTime(expected)); + expect( + formatZonedRange( + `${from}T00:00:00+00:00[UTC]`, + `${to}T00:00:00+00:00[UTC]`, + locale, + numeric, + ), + ).toBe(normalizeDateTime(expected)); + }, + ); +}); diff --git a/packages/gmt/src/internal/weekYearSingle.test.ts b/packages/gmt/src/internal/weekYearSingle.test.ts new file mode 100644 index 000000000..4d4a3cc0f --- /dev/null +++ b/packages/gmt/src/internal/weekYearSingle.test.ts @@ -0,0 +1,121 @@ +import { formatDate } from "../plain/format/formatDate"; +import { formatDateTimeToParts } from "../plain/format/formatDateTimeToParts"; +import { formatDateToParts } from "../plain/format/formatDateToParts"; +import { Temporal } from "./temporal"; + +/* + * CORE-112 (D23, D24): a single date prints the calendar year, never the week-year. + * + * Every expected year is derived here from Temporal, not from the engine: the calendar year, or the + * era year where the pattern prints an era (ECMA-402 FormatDateTimePattern, `year` field), written + * in the formatter's numbering system. `numeric` is unpadded and ungrouped; `2-digit` is the last + * two digits, padded. CLDR 48 data prints the week-year in these patterns (UTS #35 Part 4 §8 + * defines `y` as the calendar year); the engine's own text is never asserted. Only the year + * changes: month, day, era and separators stay as the locale data has them. + */ +function expectedYear( + iso: string, + locale: string, + calendar: string, + width: "numeric" | "2-digit", + hasEra: boolean, +): string { + const date = Temporal.PlainDate.from(iso).withCalendar(calendar); + const year = hasEra ? (date.eraYear ?? date.year) : date.year; + const numberingSystem = new Intl.DateTimeFormat(locale).resolvedOptions() + .numberingSystem; + const digits = new Intl.NumberFormat(locale, { + numberingSystem, + useGrouping: false, + minimumIntegerDigits: width === "2-digit" ? 2 : 1, + }).format(year); + return width === "2-digit" ? [...digits].slice(-2).join("") : digits; +} + +describe("single date, week-year patterns", () => { + it.each` + locale | options | iso | calendar | width | hasEra | expected | label + ${"gd"} | ${{ year: "numeric", month: "short" }} | ${"2024-12-30"} | ${"gregory"} | ${"numeric"} | ${false} | ${"Dùbh 2024"} | ${"gd month short, year-end"} + ${"gd"} | ${{ year: "numeric", month: "short" }} | ${"2027-01-01"} | ${"gregory"} | ${"numeric"} | ${false} | ${"Faoi 2027"} | ${"gd month short, year-start"} + ${"gd"} | ${{ year: "numeric", month: "short" }} | ${"2025-07-01"} | ${"gregory"} | ${"numeric"} | ${false} | ${"Iuch 2025"} | ${"gd month short, mid-year control"} + ${"ksh"} | ${{ year: "numeric", month: "numeric" }} | ${"2024-12-30"} | ${"gregory"} | ${"numeric"} | ${false} | ${"2024-12"} | ${"ksh numeric, year-end"} + ${"ksh"} | ${{ year: "numeric", month: "numeric" }} | ${"2027-01-01"} | ${"gregory"} | ${"numeric"} | ${false} | ${"2027-01"} | ${"ksh numeric, year-start"} + ${"ksh"} | ${{ year: "2-digit", month: "2-digit" }} | ${"2024-12-30"} | ${"gregory"} | ${"2-digit"} | ${false} | ${"24-12"} | ${"ksh 2-digit, year-end"} + ${"sc"} | ${{ year: "numeric", month: "numeric" }} | ${"2024-12-30"} | ${"gregory"} | ${"numeric"} | ${false} | ${"12/2024"} | ${"sc numeric, year-end"} + ${"sc"} | ${{ year: "numeric", month: "numeric" }} | ${"2027-01-01"} | ${"gregory"} | ${"numeric"} | ${false} | ${"01/2027"} | ${"sc numeric, year-start"} + ${"te-u-ca-buddhist"} | ${{ year: "numeric", month: "long" }} | ${"2026-07-01"} | ${"buddhist"} | ${"numeric"} | ${false} | ${"జులై 2569"} | ${"te buddhist, mid-year"} + ${"te-u-ca-buddhist"} | ${{ year: "numeric", month: "long" }} | ${"2026-12-31"} | ${"buddhist"} | ${"numeric"} | ${false} | ${"డిసెంబర్ 2569"} | ${"te buddhist, year-end"} + ${"my-u-ca-japanese"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} | ${"2026-07-01"} | ${"japanese"} | ${"numeric"} | ${true} | ${"R ၀၁/၀၇/၈"} | ${"my japanese numeric"} + ${"my-u-ca-japanese"} | ${{ year: "2-digit", month: "2-digit", day: "2-digit" }} | ${"2026-07-01"} | ${"japanese"} | ${"2-digit"} | ${true} | ${"R ၀၁/၀၇/၀၈"} | ${"my japanese 2-digit"} + ${"my-u-ca-japanese"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} | ${"2024-12-30"} | ${"japanese"} | ${"numeric"} | ${true} | ${"R ၃၀/၁၂/၆"} | ${"my japanese year-end"} + ${"my-u-ca-buddhist"} | ${{ year: "numeric", month: "numeric", day: "numeric" }} | ${"2026-07-01"} | ${"buddhist"} | ${"numeric"} | ${true} | ${"BE ၀၁/၀၇/၂၅၆၉"} | ${"my buddhist numeric"} + ${"de-CH"} | ${{ era: "short", year: "numeric", month: "numeric", day: "numeric", weekday: "short" }} | ${"2024-12-30"} | ${"gregory"} | ${"numeric"} | ${true} | ${"Mo., 12.30.2024 n. Chr."} | ${"de-CH era short, month and day as CLDR orders them"} + ${"gl-u-ca-hebrew"} | ${{ dateStyle: "full" }} | ${"2026-09-12"} | ${"hebrew"} | ${"numeric"} | ${false} | ${"sábado, 1 de Tishri de 5787 AM"} | ${"gl hebrew dateStyle full, 1 Tishri"} + ${"gl-u-ca-hebrew"} | ${{ dateStyle: "full" }} | ${"2026-09-13"} | ${"hebrew"} | ${"numeric"} | ${false} | ${"domingo, 2 de Tishri de 5787 AM"} | ${"gl hebrew dateStyle full, 2 Tishri"} + ${"gl-u-ca-roc"} | ${{ dateStyle: "full" }} | ${"2026-07-01"} | ${"roc"} | ${"numeric"} | ${true} | ${"mércores, 1 de xullo de 115 ROC"} | ${"gl roc dateStyle full, unpadded"} + `( + "formatDate and formatDateToParts print the calendar year for $label ('$locale', $iso)", + ({ locale, options, iso, calendar, width, hasEra, expected }) => { + const year = expectedYear(iso, locale, calendar, width, hasEra); + expect(formatDate(iso, locale, options)).toBe(expected); + const parts = formatDateToParts(iso, locale, options); + expect(parts.map((part) => part.value).join("")).toBe(expected); + expect(parts.filter((part) => part.type === "year")).toEqual([ + { type: "year", value: year }, + ]); + expect(parts.some((part) => part.type === "unknown")).toBe(false); + }, + ); + + it("splits a gd month and year into month, literal and year parts", () => { + expect( + formatDateToParts("2024-12-30", "gd", { + year: "numeric", + month: "short", + }), + ).toEqual([ + { type: "month", value: "Dùbh" }, + { type: "literal", value: " " }, + { type: "year", value: "2024" }, + ]); + }); + + it("keeps the time fields next to a repaired gd year, in text and in parts", () => { + const options = { + year: "numeric", + month: "short", + hour: "numeric", + minute: "numeric", + } as const; + const parts = formatDateTimeToParts("2024-12-30T14:05:00", "gd", options); + expect(parts.map((part) => part.value).join("")).toBe("Dùbh 2024, 14:05"); + expect(parts.map((part) => part.type)).toEqual([ + "month", + "literal", + "year", + "literal", + "hour", + "literal", + "minute", + ]); + }); + + it.each` + locale | options + ${"en"} | ${{ year: "numeric", month: "long" }} + ${"de"} | ${{ year: "numeric", month: "long" }} + ${"fr"} | ${{ year: "numeric", month: "long" }} + ${"ja-u-ca-japanese"} | ${{ year: "numeric", month: "long" }} + ${"zh-u-ca-chinese"} | ${{ year: "numeric", month: "long" }} + ${"en"} | ${{ dateStyle: "full" }} + `( + "leaves '$locale' $options alone: the parts join to the text", + ({ locale, options }) => { + const parts = formatDateToParts("2024-12-30", locale, options); + expect(parts.map((part) => part.value).join("")).toBe( + formatDate("2024-12-30", locale, options), + ); + expect(parts.some((part) => part.type === "unknown")).toBe(false); + }, + ); +}); diff --git a/packages/gmt/src/internal/weekYearSynth.test.ts b/packages/gmt/src/internal/weekYearSynth.test.ts new file mode 100644 index 000000000..db435deb1 --- /dev/null +++ b/packages/gmt/src/internal/weekYearSynth.test.ts @@ -0,0 +1,93 @@ +import { createPartsSynth } from "./weekYearSynth"; +import type { WeekYearAnalysis } from "./weekYearText"; + +/* + * CORE-112 (D23): parts built without calling the engine's `formatToParts` on the formatter. The + * twins here are scripted stand-ins, so each row decides what the text fields are and the synth is + * shown to name them from data, never to guess. + */ +const FIRST = 1705314030456; +const SECOND = 1705357230456; + +const analysis: WeekYearAnalysis = { + calendar: "gregory", + timeZone: "UTC", + numberingSystem: "latn", + digits: new Set("0123456789"), + reference: undefined as never, + yearRuns: [], + styles: [], + labels: [], + count: 0, +}; + +const resolved = { + locale: "xx", + calendar: "gregory", + numberingSystem: "latn", + timeZone: "UTC", +} as Intl.ResolvedDateTimeFormatOptions; + +/** Twins whose month name equals the weekday name wherever `ties` says so. */ +function scriptTwins(ties: (ms: number) => boolean) { + vi.spyOn(Intl, "DateTimeFormat").mockImplementation(function ( + _locale: unknown, + options: Intl.DateTimeFormatOptions, + ) { + return { + resolvedOptions: () => ({}), + formatToParts: (ms: number): Intl.DateTimeFormatPart[] => { + if (options.weekday === "short" && options.month === undefined) { + return [{ type: "weekday", value: "Mon" }]; + } + if ( + options.month === "short" && + options.weekday === undefined && + options.day === undefined && + options.era === undefined + ) { + return [{ type: "month", value: ties(ms) ? "Mon" : "Jan" }]; + } + return []; + }, + }; + } as never); +} + +const synth = () => + createPartsSynth( + { weekday: "short", month: "short" }, + resolved, + analysis, + (ms) => ({ + text: ms === FIRST ? "Mon" : "Mon Jan", + edits: [], + runs: [], + }), + ); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("createPartsSynth", () => { + it("rejects a template date where two field types claim the same text and uses the next date", () => { + scriptTwins((ms) => ms === FIRST); + expect(synth()(SECOND)).toEqual([ + { type: "weekday", value: "Mon" }, + { type: "literal", value: " " }, + { type: "month", value: "Jan" }, + ]); + }); + + it("answers null when every template date has a tie", () => { + scriptTwins(() => true); + const answer = createPartsSynth( + { weekday: "short", month: "short" }, + resolved, + analysis, + () => ({ text: "Mon", edits: [], runs: [] }), + )(SECOND); + expect(answer).toBeNull(); + }); +}); diff --git a/packages/gmt/src/internal/weekYearSynth.ts b/packages/gmt/src/internal/weekYearSynth.ts new file mode 100644 index 000000000..35ad6a591 --- /dev/null +++ b/packages/gmt/src/internal/weekYearSynth.ts @@ -0,0 +1,508 @@ +import { Temporal } from "./temporal"; +import { + digitRuns, + type RepairedText, + type WeekYearAnalysis, +} from "./weekYearText"; + +/* + * CORE-112 (defect D23): `formatToParts` for a formatter whose parts must never reach the engine. + * + * On a V8 without commit 0426b0d1045d, `formatToParts` aborts the process (nodejs/node#67076, + * SIGTRAP, uncatchable) on a pattern with the week-year field `Y`. The parts are built here from + * the repaired `format` text: the numeric fields from the digit runs, every text field from the + * parts of year-free twin formatters (same locale, calendar, numbering system and zone), which + * hold no `Y`. Deleting this file retires the parts half of the workaround (the D23 canary says + * when). + */ + +/** Option names of the time fields. */ +const TIME_KEYS = [ + "hour", + "minute", + "second", + "fractionalSecondDigits", + "dayPeriod", + "timeZoneName", + "timeStyle", +] as const; + +const LETTER = /\p{L}|\p{M}/u; +/** Part types a twin supplies by digit run, not by text. */ +const NUMERIC_TYPES = new Set([ + "literal", + "day", + "hour", + "minute", + "second", + "fractionalSecond", + "year", + "relatedYear", + "yearName", +]); + +type Part = Intl.DateTimeFormatPart; +type Candidate = { + type: string; + key: string; + value: string; + numeric: boolean; +}; +type Twin = { + format: Intl.DateTimeFormat; + index: number; + numeric: boolean; +}; +type Field = { type: string; keys: string[] }; + +/** The widths a text field is printed in: the formatter's own, unless a style could print any. */ +function widthsOf( + options: Intl.DateTimeFormatOptions, + key: K, + all: NonNullable[], +): NonNullable[] { + const styled = + options.dateStyle !== undefined || options.timeStyle !== undefined; + const own = options[key]; + return !styled && own !== undefined ? [own] : all; +} + +/** Twins for the weekday, month and era fields, in every width the options can print. */ +function textTwinOptions( + options: Intl.DateTimeFormatOptions, +): Intl.DateTimeFormatOptions[] { + const out: Intl.DateTimeFormatOptions[] = []; + for (const weekday of widthsOf(options, "weekday", ["long", "short"])) { + out.push({ weekday }, { weekday, month: "long", day: "numeric" }); + } + for (const month of widthsOf(options, "month", ["long", "short"])) { + if (month !== "numeric" && month !== "2-digit") { + out.push({ month }, { month, day: "numeric" }); + } + } + for (const era of options.era === undefined + ? (["long", "short", "narrow"] as const) + : [options.era]) { + out.push({ era, month: "numeric", day: "numeric" }); + } + for (const width of ["long", "short"] as const) { + if (!out.some((o) => o.month === width && o.day !== undefined)) { + out.push({ month: width, day: "numeric" }); + } + if (!out.some((o) => o.weekday === width && o.month === undefined)) { + out.push({ weekday: width }); + } + } + out.push( + { month: "numeric", day: "numeric" }, + { month: "2-digit", day: "2-digit" }, + ); + return out; +} + +/** The twin for the time fields of a formatter, or `null` when it prints none. */ +function timeTwinOptions( + options: Intl.DateTimeFormatOptions, + hourCycle: string | undefined, +): Intl.DateTimeFormatOptions | null { + if (!TIME_KEYS.some((key) => options[key] !== undefined)) { + return null; + } + const time: Intl.DateTimeFormatOptions = {}; + for (const key of TIME_KEYS) { + if (options[key] !== undefined && key !== "timeStyle") { + Object.assign(time, { [key]: options[key] }); + } + } + if (options.timeStyle !== undefined) { + time.hour = "numeric"; + time.minute = "numeric"; + if (options.timeStyle === "long" || options.timeStyle === "full") { + time.timeZoneName = options.timeStyle === "full" ? "long" : "short"; + } + } + if (hourCycle !== undefined) { + time.hourCycle = hourCycle as Intl.DateTimeFormatOptions["hourCycle"]; + } + return time; +} + +/** The twin options for a formatter: its text fields, in every width its options can print. */ +function twinOptions( + options: Intl.DateTimeFormatOptions, + hourCycle: string | undefined, +): Intl.DateTimeFormatOptions[] { + const time = timeTwinOptions(options, hourCycle); + return time === null + ? textTwinOptions(options) + : [...textTwinOptions(options), time]; +} + +/** + * The twins of a formatter that print no year. A twin that prints a year could hold `Y`, so it is + * never asked for parts. + */ +function buildTwins( + options: Intl.DateTimeFormatOptions, + resolved: Intl.ResolvedDateTimeFormatOptions, +): Twin[] { + const twins: Twin[] = []; + const common = { + calendar: resolved.calendar, + numberingSystem: resolved.numberingSystem, + timeZone: resolved.timeZone, + }; + for (const [index, own] of twinOptions( + options, + resolved.hourCycle, + ).entries()) { + try { + const format = new Intl.DateTimeFormat(resolved.locale, { + ...common, + ...own, + }); + if (format.resolvedOptions().year === undefined) { + twins.push({ + format, + index, + numeric: + (own.month === "numeric" || own.month === "2-digit") && + own.era === undefined, + }); + } + } catch { + // A width this locale or calendar rejects supplies no candidates. + } + } + return twins; +} + +/** Every text and numeric value the twins print at `ms`, longest first. */ +function candidatesFrom(twins: readonly Twin[], ms: number): Candidate[] { + const out: Candidate[] = []; + for (const { format, index, numeric } of twins) { + for (const part of format.formatToParts(ms)) { + if (part.type === "literal" || part.value.trim() === "") { + continue; + } + const isNumber = + numeric && (part.type === "month" || part.type === "day"); + if (isNumber || !NUMERIC_TYPES.has(part.type)) { + out.push({ + type: part.type, + key: `${index}:${part.type}`, + value: part.value, + numeric: isNumber, + }); + } + } + } + return out.sort((a, b) => b.value.length - a.value.length); +} + +/** + * Whether `value` at `at` in `span` starts and ends on a field boundary: one or two characters may + * not begin or end inside a run of letters (the `d` of `de`). + */ +function fits(span: string, at: number, value: string): boolean { + if (!span.startsWith(value, at)) { + return false; + } + if (value.length > 2) { + return true; + } + const last = value.at(-1) ?? ""; + const first = value[0] ?? ""; + return !( + (LETTER.test(last) && LETTER.test(span[at + value.length] ?? "")) || + (LETTER.test(first) && LETTER.test(span[at - 1] ?? "")) + ); +} + +/** + * The template of a span: the text fields in order, found greedily from the candidates. `null` + * when two field types claim the same longest text at one place: a type chosen on a tie would be + * a guess, so a date where the names differ decides it (CORE-112 tie-break). + */ +function segment( + spans: readonly string[], + candidates: readonly Candidate[], +): Field[][] | null { + const plan: Field[][] = []; + for (const span of spans) { + const fields: Field[] = []; + for (let at = 0; at < span.length;) { + const hits = candidates.filter((c) => fits(span, at, c.value)); + const longest = hits[0]?.value.length; + if (longest === undefined) { + at++; + continue; + } + const best = hits.filter((c) => c.value.length === longest); + if (new Set(best.map((c) => c.type)).size > 1) { + return null; + } + fields.push({ + type: best[0]?.type ?? "literal", + keys: best.map((c) => c.key), + }); + at += longest; + } + plan.push(fields); + } + return plan; +} + +/** The text cut at the numeric runs, and the numeric parts between. */ +interface Spans { + readonly spans: string[]; + readonly numbers: Part[]; +} + +/** + * The extent of a numeric run widened to a twin's wider value for it (`1` printed as `01`), or + * `null` when no twin value covers it. + */ +function widenRun( + text: string, + run: { start: number; end: number; text: string }, + label: string, + candidates: readonly Candidate[], + position: number, +): { start: number; end: number } | null { + for (const c of candidates) { + if (!c.numeric || c.type !== label || c.value === run.text) { + continue; + } + const inside = c.value.indexOf(run.text); + const from = run.start - inside; + if ( + inside >= 0 && + from >= position && + text.slice(from, from + c.value.length) === c.value + ) { + return { start: from, end: from + c.value.length }; + } + } + return null; +} + +/** The repaired text cut at its numeric runs, and the numeric parts between. */ +function spansOf( + analysis: WeekYearAnalysis, + repaired: RepairedText, + candidates: readonly Candidate[], +): Spans | null { + const runs = digitRuns(repaired.text, analysis.digits); + if (runs.length !== analysis.count) { + return null; + } + const spans: string[] = []; + const numbers: Part[] = []; + let position = 0; + for (const [index, run] of runs.entries()) { + const label = analysis.labels[index]; + if (label === undefined || label === "literal" || label === "text") { + continue; + } + const year = analysis.yearRuns.indexOf(index); + const edit = year < 0 ? undefined : repaired.edits[year]; + const extent = + edit ?? widenRun(repaired.text, run, label, candidates, position) ?? run; + spans.push(repaired.text.slice(position, extent.start)); + numbers.push({ + type: label as Part["type"], + value: repaired.text.slice(extent.start, extent.end), + }); + position = extent.end; + } + spans.push(repaired.text.slice(position)); + return { spans, numbers }; +} + +/** The first dates the template is tried on: a month, a day and a time each. */ +const TEMPLATE_DATES = [ + [1, 15, "10:20:30.456"], + [1, 15, "22:20:30.456"], + [3, 9, "22:20:30.456"], + [5, 20, "03:20:30.456"], + [8, 3, "15:20:30.456"], +] as const; + +/** The time value of a template date in the formatter's calendar and zone. */ +function templateMs( + analysis: WeekYearAnalysis, + anchor: number, + [month, day, time]: (typeof TEMPLATE_DATES)[number], +): number { + return Temporal.PlainDate.from({ + calendar: analysis.calendar, + year: anchor, + month, + day, + } as Temporal.PlainDateLike).toZonedDateTime({ + timeZone: analysis.timeZone, + plainTime: time, + }).epochMilliseconds; +} + +/** + * Finds a field's value in a span at or after `position`: the earliest hit, the longer on a tie. + * `null` when none of its keys finds one. + */ +function placeField( + span: string, + position: number, + field: Field, + values: ReadonlyMap, +): { at: number; found: string } | null { + let best: { at: number; found: string } | null = null; + for (const key of field.keys) { + const value = values.get(key); + if (value === undefined) { + continue; + } + for ( + let i = span.indexOf(value, position); + i >= 0; + i = span.indexOf(value, i + 1) + ) { + if (fits(span, i, value)) { + if ( + best === null || + i < best.at || + (i === best.at && value.length > best.found.length) + ) { + best = { at: i, found: value }; + } + break; + } + } + } + return best; +} + +/** One span's parts: its template fields, the literals between, and the numeric part after. */ +function partsOfSpan( + span: string, + fields: readonly Field[], + values: ReadonlyMap, + number: Part | undefined, +): Part[] | null { + const parts: Part[] = []; + let position = 0; + for (const field of fields) { + const hit = placeField(span, position, field, values); + if (hit === null) { + return null; + } + if (hit.at > position) { + parts.push({ type: "literal", value: span.slice(position, hit.at) }); + } + parts.push({ type: field.type as Part["type"], value: hit.found }); + position = hit.at + hit.found.length; + } + if (position < span.length) { + parts.push({ type: "literal", value: span.slice(position) }); + } + if (number !== undefined) { + parts.push(number); + } + return parts; +} + +/** Adjacent literals joined into one. */ +function mergeLiterals(parts: readonly Part[]): Part[] { + const merged: Part[] = []; + for (const part of parts) { + const last = merged.at(-1); + if (last?.type === "literal" && part.type === "literal") { + last.value += part.value; + } else { + merged.push({ ...part }); + } + } + return merged; +} + +/** + * Parts of one flagged formatter, from its repaired `format` text and its twins. + * + * @param options the options the formatter was built with + * @param resolved its resolved options + * @param analysis what was read from its text + * @param repair the formatter's repaired text at a time value, or `null` + * @returns a function from a time value to its parts, or `null` where no answer is known + */ +export function createPartsSynth( + options: Intl.DateTimeFormatOptions, + resolved: Intl.ResolvedDateTimeFormatOptions, + analysis: WeekYearAnalysis, + repair: (ms: number) => RepairedText | null, +): (ms: number) => Part[] | null { + let twins: Twin[] | undefined; + let plan: Field[][] | null | undefined; + + const candidatesAt = (ms: number): Candidate[] => { + twins ??= buildTwins(options, resolved); + return candidatesFrom(twins, ms); + }; + + const spansAt = (ms: number, candidates: Candidate[]): Spans | null => { + const repaired = repair(ms); + return repaired === null ? null : spansOf(analysis, repaired, candidates); + }; + + const templateOf = (): Field[][] | null => { + if (plan !== undefined) { + return plan; + } + plan = null; + const anchor = Temporal.PlainDate.from("2024-07-01").withCalendar( + analysis.calendar, + ).year; + for (const date of TEMPLATE_DATES) { + const ms = templateMs(analysis, anchor, date); + const candidates = candidatesAt(ms); + const spans = spansAt(ms, candidates); + if (spans === null) { + continue; + } + plan = segment( + spans.spans, + candidates.filter((c) => !c.numeric), + ); + if (plan !== null) { + break; + } + } + return plan; + }; + + return (ms) => { + const template = templateOf(); + if (template === null) { + return null; + } + const candidates = candidatesAt(ms); + const spans = spansAt(ms, candidates); + if (spans === null) { + return null; + } + const values = new Map(candidates.map((c) => [c.key, c.value])); + const parts: Part[] = []; + for (const [n, span] of spans.spans.entries()) { + const next = partsOfSpan( + span, + template[n] ?? [], + values, + spans.numbers[n], + ); + if (next === null) { + return null; + } + parts.push(...next); + } + return mergeLiterals(parts); + }; +} diff --git a/packages/gmt/src/internal/weekYearText.ts b/packages/gmt/src/internal/weekYearText.ts new file mode 100644 index 000000000..de6241f41 --- /dev/null +++ b/packages/gmt/src/internal/weekYearText.ts @@ -0,0 +1,493 @@ +import { Temporal } from "./temporal"; + +/* + * CORE-112 (defect D24): the text half of the week-year workaround, read from `format` alone. + * + * Some CLDR 48 patterns use `Y`, the year of the week-of-year, where `y`, the calendar year, is + * meant (UTS #35 Part 4 §8, rows `y` and `Y`), so a date near a year end prints next year's number + * (Scottish Gaelic `Dùbh 2025` for 30 December 2024), and the Buddhist, Japanese and ROC calendars + * print the Gregorian week-year all year. `weekYearGuard.ts` decides which formatters do, using + * this module's reading of a formatter's digit runs; the year in each run is then written as + * ECMA-402 gives it: `numeric` unpadded and ungrouped, `2-digit` the last two digits padded + * (FormatDateTimePattern, the `year` steps), in the formatter's numbering system. + * + * Nothing here calls a parts method, so it never reaches the V8 abort of defect D23 + * (nodejs/node#67076). Only the year changes: every other choice CLDR made stays. + */ + +/** A maximal run of digits in a formatted text, as UTF-16 offsets. */ +export interface DigitRun { + readonly start: number; + readonly end: number; + readonly text: string; +} + +const ANY_DIGIT = /\p{Nd}/u; + +/** + * The digit runs of `text`, walked by code point: Adlam, Chakma and other digit sets lie outside + * the Basic Multilingual Plane. + */ +export function digitRuns( + text: string, + digits: ReadonlySet, +): DigitRun[] { + const runs: DigitRun[] = []; + let start = -1; + let index = 0; + for (const character of text) { + const isDigit = digits.has(character) || ANY_DIGIT.test(character); + if (isDigit && start < 0) { + start = index; + } else if (!isDigit && start >= 0) { + runs.push({ start, end: index, text: text.slice(start, index) }); + start = -1; + } + index += character.length; + } + if (start >= 0) { + runs.push({ start, end: index, text: text.slice(start, index) }); + } + return runs; +} + +/** The number of code points in `text`. */ +function codePointLength(text: string): number { + return [...text].length; +} + +/** The last two code points of `text`. */ +function lastTwo(text: string): string { + return [...text].slice(-2).join(""); +} + +const MAX_CACHED = 64; +const digitSets = new Map(); +const references = new Map(); + +/** Forget every digit set and reference formatter (a replaced `Intl`, a test seam). */ +export function forgetWeekYearText(): void { + digitSets.clear(); + references.clear(); +} + +/** The digits 0 to 9 of a numbering system, by value. */ +export function digitsOf(numberingSystem: string): readonly string[] { + let digits = digitSets.get(numberingSystem); + if (digits === undefined) { + digits = [ + ...new Intl.NumberFormat("und", { + numberingSystem, + useGrouping: false, + }).format(9876543210), + ].reverse(); + if (digitSets.size >= MAX_CACHED) { + digitSets.clear(); + } + digitSets.set(numberingSystem, digits); + } + return digits; +} + +/** The set of a numbering system's digit characters. */ +export function digitSetOf(numberingSystem: string): ReadonlySet { + return new Set(digitsOf(numberingSystem)); +} + +/** + * A root-locale formatter that prints the year alone in a calendar: its single digit run at a date + * is the calendar's year as ICU counts it, the same calendar arithmetic that prints the month and + * the day beside the year in the formatter under test. + */ +export interface Reference { + readonly format: Intl.DateTimeFormat; + readonly digits: ReadonlySet; +} + +/** The reference for a calendar, numbering system and time zone, built once. */ +export function referenceFor( + calendar: string, + numberingSystem: string, + timeZone: string, +): Reference { + const key = `${calendar}|${numberingSystem}|${timeZone}`; + let reference = references.get(key); + if (reference === undefined) { + reference = { + format: new Intl.DateTimeFormat("und", { + calendar, + numberingSystem, + year: "numeric", + timeZone, + }), + digits: digitSetOf(numberingSystem), + }; + if (references.size >= MAX_CACHED) { + references.clear(); + } + references.set(key, reference); + } + return reference; +} + +/** The calendar year the reference prints at `ms`, or `null` when it prints no single number. */ +export function referenceYear(reference: Reference, ms: number): string | null { + const runs = digitRuns(reference.format.format(ms), reference.digits); + return runs.length === 1 ? (runs[0]?.text ?? null) : null; +} + +/** The calendar year of a mid-year date, the anchor every probe date is counted from. */ +export function anchorYear(calendar: string): number { + return Temporal.PlainDate.from("2024-07-01").withCalendar(calendar).year; +} + +/** The date `month` / `day` of `year` in a calendar. */ +export function dateIn( + calendar: string, + year: number, + month: number, + day: number, +): Temporal.PlainDate { + return Temporal.PlainDate.from({ calendar, year, month, day }); +} + +/** + * The indexes of the digit runs that hold the year, or `null` when the run count changes between + * the three probe dates. + * + * A year run is equal a week apart in mid-January and different in the first following year whose + * 15 January falls on the same weekday: equal weekdays keep a weekday name with digits (luy `J4`) + * out of the set. + * + * @param runsAt the formatter's digit runs at a date + */ +export function yearRunIndexes( + calendar: string, + runsAt: (date: Temporal.PlainDate) => DigitRun[], +): number[] | null { + const first = anchorYear(calendar); + const january = dateIn(calendar, first, 1, 15); + let other = dateIn(calendar, first + 1, 1, 15); + for (let step = 1; step <= 14 && other.dayOfWeek !== january.dayOfWeek;) { + other = dateIn(calendar, first + step, 1, 15); + step++; + } + const base = runsAt(january); + const week = runsAt(january.add({ days: 7 })); + const year = runsAt(other); + if (base.length !== week.length || base.length !== year.length) { + return null; + } + return base.flatMap((run, index) => + run.text === week[index]?.text && run.text !== year[index]?.text + ? [index] + : [], + ); +} + +/** How a year run is written: `full` or the last `two` digits, and any number glued to it. */ +export interface YearStyle { + readonly kind: "full" | "two"; + /** Where the year sits in a run that also holds another number, else `undefined`. */ + readonly glued?: "start" | "end"; + /** The length of the other number in a glued run. */ + readonly rest?: number; +} + +/** The kind of field a digit run holds, found by moving one field at a time. */ +export type RunLabel = + | "year" + | "day" + | "month" + | "hour" + | "minute" + | "second" + | "fractionalSecond" + | "literal" + | "text"; + +/** What `analyse` reads from a formatter once, so a repair never re-reads it. */ +export interface WeekYearAnalysis { + readonly calendar: string; + readonly timeZone: string; + readonly numberingSystem: string; + readonly digits: ReadonlySet; + readonly reference: Reference; + /** Digit run indexes that hold the year. */ + readonly yearRuns: readonly number[]; + /** How each year run is written, in the order of `yearRuns`. */ + readonly styles: readonly YearStyle[]; + /** The field each digit run holds. */ + readonly labels: readonly RunLabel[]; + /** The digit run count of the formatter's text. */ + readonly count: number; +} + +/** The style of a year run read at mid-year, against the reference's year `year` there. */ +function styleOf(run: string, year: string | null): YearStyle { + return ( + (year === null ? null : styleAgainst(run, year)) ?? { + // The run is wrong even mid-year (Buddhist, Japanese and ROC print the Gregorian week-year): + // its own width decides, two digits meaning `2-digit`. + kind: codePointLength(run) === 2 ? "two" : "full", + } + ); +} + +/** The style of a run that matches the reference year in some form, or `null`. */ +function styleAgainst(run: string, year: string): YearStyle | null { + if (run === year) { + return { kind: "full" }; + } + if ( + codePointLength(run) === 2 && + (run === lastTwo(year) || [...run][1] === year) + ) { + return { kind: "two" }; + } + if (run.length > year.length && run.startsWith(year)) { + return { kind: "full", glued: "start", rest: run.length - year.length }; + } + if (run.length > year.length && run.endsWith(year)) { + return { kind: "full", glued: "end", rest: run.length - year.length }; + } + return null; +} + +const PERTURBED_FIELDS = [ + ["day", { days: 1 }], + ["month", { months: 1 }], + ["hour", { hours: 1 }], + ["minute", { minutes: 1 }], + ["second", { seconds: 1 }], + ["fractionalSecond", { milliseconds: 1 }], +] as const; + +/** + * Read a formatter's digit runs once: which hold the year, how each is written, and what field + * every other one holds. Only `format` is called, on the formatter itself, in its zone and with its + * time fields. `null` when the run count changes between probe dates. + */ +export function analyse( + format: (ms: number) => string, + resolved: Intl.ResolvedDateTimeFormatOptions, +): WeekYearAnalysis | null { + const calendar = resolved.calendar; + const timeZone = resolved.timeZone; + const numberingSystem = resolved.numberingSystem; + const digits = digitSetOf(numberingSystem); + const reference = referenceFor(calendar, numberingSystem, timeZone); + const zoned = (date: Temporal.PlainDate) => + date.toZonedDateTime({ timeZone, plainTime: "10:20:30.456" }); + const runsAt = (date: Temporal.PlainDate) => + digitRuns(format(zoned(date).epochMilliseconds), digits); + const yearRuns = yearRunIndexes(calendar, runsAt); + if (yearRuns === null) { + return null; + } + const first = anchorYear(calendar); + const midYear = zoned(dateIn(calendar, first, 6, 1)).epochMilliseconds; + const midRuns = digitRuns(format(midYear), digits); + const midYearText = referenceYear(reference, midYear); + const styles = yearRuns.map((index) => + styleOf(midRuns[index]?.text ?? "", midYearText), + ); + const start = zoned(dateIn(calendar, first, 1, 15)); + const base = digitRuns(format(start.epochMilliseconds), digits); + const moved = PERTURBED_FIELDS.map(([field, amount]) => ({ + field, + runs: digitRuns(format(start.add(amount).epochMilliseconds), digits), + })); + const labels = base.map((run, index): RunLabel => { + if (yearRuns.includes(index)) { + return "year"; + } + const changed = moved.filter( + (entry) => + entry.runs.length === base.length && + entry.runs[index]?.text !== run.text, + ); + // Several fields move it: digits inside a name (haw `P3`). None: a literal number. + const [only] = changed; + return changed.length === 1 && only !== undefined + ? only.field + : changed.length === 0 + ? "literal" + : "text"; + }); + return { + calendar, + timeZone, + numberingSystem, + digits, + reference, + yearRuns, + styles, + labels, + count: base.length, + }; +} + +/** The year as ECMA-402 writes it for a style: `numeric` is the reference's run, `2-digit` its last two digits, padded. */ +function yearText( + analysis: WeekYearAnalysis, + ms: number, + style: YearStyle, +): string | null { + const year = referenceYear(analysis.reference, ms); + if (year === null || style.kind === "full") { + return year; + } + return codePointLength(year) >= 2 + ? lastTwo(year) + : (digitsOf(analysis.numberingSystem)[0] ?? "0") + year; +} + +/** One year run replaced in a text. */ +export interface YearEdit { + /** The run in the native text. */ + readonly from: number; + readonly to: number; + /** The span of the year in the repaired text. */ + readonly start: number; + readonly end: number; + readonly value: string; +} + +/** A text with every year run holding the calendar year. */ +export interface RepairedText { + readonly text: string; + readonly edits: readonly YearEdit[]; + readonly runs: readonly DigitRun[]; +} + +/** + * `text` with every year run holding the calendar year, or `null` when the run count differs from + * the analysis (the text has a shape it did not read: the data canary fails on any such date, so a + * CLDR change that causes one is caught, not shipped). + */ +export function repairText( + analysis: WeekYearAnalysis, + text: string, + ms: number, +): RepairedText | null { + const runs = digitRuns(text, analysis.digits); + if (runs.length !== analysis.count) { + return null; + } + let out = ""; + let position = 0; + const edits: YearEdit[] = []; + for (const [n, index] of analysis.yearRuns.entries()) { + const style = analysis.styles[n]; + const run = runs[index]; + const value = style === undefined ? null : yearText(analysis, ms, style); + if (style === undefined || run === undefined || value === null) { + return null; + } + let from = run.start; + let to = run.end; + if (style.glued === "start") { + to = run.end - (style.rest ?? 0); + } else if (style.glued === "end") { + from = run.start + (style.rest ?? 0); + } + out += text.slice(position, from); + edits.push({ + from, + to, + start: out.length, + end: out.length + value.length, + value, + }); + out += value; + position = to; + } + return { text: out + text.slice(position), edits, runs }; +} + +/** + * Native parts with each year run written as the `year` part holding the calendar year. WebKit + * types the week-year `unknown`; a part that holds more than the run (a year glued to another + * number) keeps its type and has the run's slice replaced. + * + * @returns the patched parts, or `null` when a run is split across parts or the patched parts do + * not read as the repaired text + */ +export function patchYearParts( + parts: readonly Intl.DateTimeFormatPart[], + repaired: RepairedText, +): Intl.DateTimeFormatPart[] | null { + let offset = 0; + const out: Intl.DateTimeFormatPart[] = []; + for (const part of parts) { + const start = offset; + const end = start + part.value.length; + offset = end; + const inside = repaired.edits.filter( + (edit) => edit.from < end && edit.to > start, + ); + let value = part.value; + for (const edit of inside.toReversed()) { + if (edit.from < start || edit.to > end) { + return null; + } + value = + value.slice(0, edit.from - start) + + edit.value + + value.slice(edit.to - start); + } + const exact = + inside.length === 1 && inside[0]?.from === start && inside[0].to === end; + out.push({ + type: exact ? "year" : part.type, + value, + } as Intl.DateTimeFormatPart); + } + return out.map((part) => part.value).join("") === repaired.text ? out : null; +} + +/** The first of the three digit-run checks `weekYearGuard.ts` makes at a boundary. */ +export type BoundaryCheck = "ok" | "bad" | "shape"; + +/** + * Whether every year run at `date` still reads as it does at the inside date `mid`, where the + * calendar year is the same. + * + * A run printing the week-year differs at a year boundary; a run printing the calendar year does + * not. A year glued to another number is compared by the year inside it: the boundary run must hold + * the boundary date's calendar year in the same form (full or last two digits). + */ +export function checkYearRuns( + yearRuns: readonly number[], + at: readonly DigitRun[], + mid: readonly DigitRun[], + yearAt: string | null, + yearMid: string | null, +): boolean { + return yearRuns.every((index) => + runMoves(at[index]?.text ?? "", mid[index]?.text ?? "", yearAt, yearMid), + ); +} + +/** Whether one year run changes between the boundary and mid-year by exactly the year it holds. */ +function runMoves( + here: string, + inside: string, + yearAt: string | null, + yearMid: string | null, +): boolean { + if (here === inside) { + return true; + } + if (yearMid === null || yearAt === null) { + return false; + } + if (inside.includes(yearMid)) { + return inside.length > yearMid.length && here.includes(yearAt); + } + if (codePointLength(yearMid) > 2 && inside.includes(lastTwo(yearMid))) { + return codePointLength(inside) > 2 && here.includes(lastTwo(yearAt)); + } + return false; +} diff --git a/packages/gmt/src/internal/yearPrinting.test.ts b/packages/gmt/src/internal/yearPrinting.test.ts new file mode 100644 index 000000000..e41fc01b2 --- /dev/null +++ b/packages/gmt/src/internal/yearPrinting.test.ts @@ -0,0 +1,602 @@ +import { formatDate } from "../plain/format/formatDate"; +import { formatDateRange } from "../plain/format/formatDateRange"; +import { formatDateTime } from "../plain/format/formatDateTime"; +import { formatDateTimeRange } from "../plain/format/formatDateTimeRange"; +import { formatDateToParts } from "../plain/format/formatDateToParts"; +import { formatZonedDateTime } from "../zoned/format/formatZonedDateTime"; +import { formatZonedRange } from "../zoned/format/formatZonedRange"; +import { formatZonedToParts } from "../zoned/format/formatZonedToParts"; + +/* + * CORE-112 slice 7 (D25 to D28): the years an engine prints wrongly outside the week-year. + * + * Every expected value comes from a specification, never from the engine's text: + * - D25: Intl era/monthCode Table 2 as amended by tc39/proposal-intl-era-monthcode#86 (test262 + * tc39/test262#4877): the japanese calendar uses Gregorian eras up to and including 1872-12-31 + * and the solar Japanese eras from 1873-01-01. ISO -0001-07-10 is 2 BC, 1872-12-31 is 1872 AD, + * 1873-01-01 is Meiji 6 (Meiji 1 is 1868 as a year count). + * - D26: Table 2 and § 4.1.12 give `bh`; an engine with no `bh` name gives the house empty value. + * - D27: ECMA-402 FormatDateTimePattern, "2-digit": FormatNumeric with minimumIntegerDigits 2, so + * Reiwa 6 is 06; CLDR's ja data keeps 元年 for year 1 (owner decision). + * - D28: ECMA-402 FormatDateTimePattern, `relatedYear`: FormatNumeric at full width, no 2-digit + * form, so related year 5 is 5 and -1 is -1. + * Each value holds on an engine that has the defect and on one that does not. + */ + +const eraYear = { era: "short", year: "numeric" } as const; + +describe("D25: japanese dates before 1873-01-01 print Gregorian eras", () => { + it.each` + locale | iso | expected + ${"en-u-ca-japanese"} | ${"-000001-07-10"} | ${"2 BC"} + ${"ja-u-ca-japanese"} | ${"-000001-07-10"} | ${"紀元前2年"} + ${"en-u-ca-japanese"} | ${"1872-12-31"} | ${"1872 AD"} + ${"ja-u-ca-japanese"} | ${"1872-12-31"} | ${"西暦1872年"} + ${"en-u-ca-japanese"} | ${"1868-10-23"} | ${"1868 AD"} + ${"ja-u-ca-japanese"} | ${"1868-10-23"} | ${"西暦1868年"} + ${"en-u-ca-japanese"} | ${"1873-01-01"} | ${"6 Meiji"} + ${"ja-u-ca-japanese"} | ${"1873-01-01"} | ${"明治6年"} + `( + "formatDate prints '$expected' for '$locale' at $iso", + ({ locale, iso, expected }) => { + expect(formatDate(iso, locale, eraYear)).toBe(expected); + }, + ); + + it("splits the Gregorian era and year of a pre-1873 date into era and year parts", () => { + expect( + formatDateToParts("1872-12-31", "en-u-ca-japanese", eraYear), + ).toEqual([ + { type: "year", value: "1872" }, + { type: "literal", value: " " }, + { type: "era", value: "AD" }, + ]); + }); + + it("prints a zoned date before 1873 with the Gregorian era", () => { + expect( + formatZonedDateTime( + "-000001-07-10T12:00:00+00:00[UTC]", + "en-u-ca-japanese", + eraYear, + ), + ).toBe("2 BC"); + expect( + formatZonedToParts( + "-000001-07-10T12:00:00+00:00[UTC]", + "en-u-ca-japanese", + eraYear, + ) + .map((part) => part.value) + .join(""), + ).toBe("2 BC"); + }); + + it("prints a range inside the Gregorian eras and one inside the Meiji era", () => { + expect( + formatDateRange("1870-01-01", "1872-12-31", "en-u-ca-japanese", eraYear), + ).toMatch(/^1870\D+1872 AD$/); + expect( + formatDateRange("1873-01-01", "1875-06-01", "en-u-ca-japanese", eraYear), + ).toMatch(/^6\D+8 Meiji$/); + }); +}); + +describe("D25: more dates, locales and functions", () => { + it.each` + locale | iso | suffix + ${"en-u-ca-japanese-nu-arab"} | ${"-000001-07-10"} | ${"٢ BC"} + ${"en-u-ca-japanese-nu-arab"} | ${"1872-12-31"} | ${"١٨٧٢ AD"} + ${"en-u-ca-japanese-nu-arab"} | ${"1873-01-01"} | ${"٦ Meiji"} + ${"th-u-ca-japanese-nu-thai"} | ${"-000001-07-10"} | ${"๒"} + ${"th-u-ca-japanese-nu-thai"} | ${"1872-12-31"} | ${"๑๘๗๒"} + ${"th-u-ca-japanese-nu-thai"} | ${"1873-01-01"} | ${"๖"} + `( + "formatDate ends with '$suffix' for '$locale' at $iso (digits of the numbering system)", + ({ locale, iso, suffix }) => { + expect(formatDate(iso, locale, eraYear).endsWith(suffix)).toBe(true); + }, + ); + + it.each` + locale | iso | expected + ${"ja-u-ca-japanese"} | ${"-000001-07-10"} | ${[{ type: "era", value: "紀元前" }, { type: "year", value: "2" }, { type: "literal", value: "年" }]} + ${"ja-u-ca-japanese"} | ${"1873-01-01"} | ${[{ type: "era", value: "明治" }, { type: "year", value: "6" }, { type: "literal", value: "年" }]} + `( + "formatDateToParts splits '$locale' at $iso into era, year and literal", + ({ locale, iso, expected }) => { + expect(formatDateToParts(iso, locale, eraYear)).toEqual(expected); + }, + ); + + it("types the year part of a pre-1873 date in a non-Latin numbering system as year", () => { + expect( + formatDateToParts("1872-12-31", "en-u-ca-japanese-nu-arab", eraYear), + ).toEqual([ + { type: "year", value: "١٨٧٢" }, + { type: "literal", value: " " }, + { type: "era", value: "AD" }, + ]); + }); + + it("prints a plain date-time before 1873 with the Gregorian era", () => { + expect( + formatDateTime("1872-12-31T23:59:59", "en-u-ca-japanese", eraYear), + ).toBe("1872 AD"); + expect( + formatDateTime("1873-01-01T00:00:00", "en-u-ca-japanese", eraYear), + ).toBe("6 Meiji"); + }); + + // ISO -0100 is 101 BC and ISO -0001 is 2 BC (astronomical year numbering, year 0 is 1 BC). + it.each` + start | end | locale | expected + ${"-000100-01-01"} | ${"-000001-07-10"} | ${"en-u-ca-japanese"} | ${/^101\D+2 BC$/} + ${"-000100-01-01"} | ${"-000001-07-10"} | ${"ja-u-ca-japanese"} | ${/^紀元前101年\D+2年$/} + ${"1868-10-23"} | ${"1872-12-31"} | ${"en-u-ca-japanese"} | ${/^1868\D+1872 AD$/} + ${"1873-01-01"} | ${"1872-12-31"} | ${"en-u-ca-japanese"} | ${/^1873\D+1872 AD$/} + ${"1872-12-31"} | ${"1873-01-01"} | ${"en-u-ca-japanese"} | ${/^1872\D+1873 AD$/} + ${"1872-12-31"} | ${"1873-01-01"} | ${"ja-u-ca-japanese"} | ${/^西暦1872年\D+1873年$/} + `( + "the three range functions print '$locale' $start to $end in one calendar, the Gregorian one", + ({ start, end, locale, expected }) => { + expect(formatDateRange(start, end, locale, eraYear)).toMatch(expected); + expect( + formatDateTimeRange( + `${start}T00:00:00`, + `${end}T00:00:00`, + locale, + eraYear, + ), + ).toMatch(expected); + expect( + formatZonedRange( + `${start}T00:00:00+00:00[UTC]`, + `${end}T00:00:00+00:00[UTC]`, + locale, + eraYear, + ), + ).toMatch(expected); + }, + ); + + it("leaves a range inside the Meiji era in the japanese calendar, in every function", () => { + expect( + formatZonedRange( + "1873-01-01T00:00:00+00:00[UTC]", + "1875-06-01T00:00:00+00:00[UTC]", + "en-u-ca-japanese", + eraYear, + ), + ).toMatch(/^6\D+8 Meiji$/); + }); +}); + +/** Every `islamic*` calendar id the engine accepts (`islamicc` resolves to `islamic-civil`). */ +const islamicCalendars = [ + "islamic", + "islamic-civil", + "islamic-rgsa", + "islamic-tbla", + "islamic-umalqura", +] as const; + +describe("D26: islamic dates before the Hijra give the empty value", () => { + it.each(islamicCalendars.map((calendar) => ({ calendar })))( + "gives the empty value for '$calendar'", + ({ calendar }) => { + const locale = `en-u-ca-${calendar}`; + expect(formatDate("-000001-07-10", locale, eraYear)).toBe(""); + expect(formatDate("0600-07-10", locale, eraYear)).toBe(""); + expect(formatDateToParts("-000001-07-10", locale, eraYear)).toEqual([]); + expect(formatDateTime("0600-07-10T12:00:00", locale, eraYear)).toBe(""); + expect( + formatDateRange("-000001-07-10", "2025-07-10", locale, eraYear), + ).toBe(""); + expect(formatDateRange("2025-07-10", "0600-07-10", locale, eraYear)).toBe( + "", + ); + expect( + formatDateTimeRange( + "0600-07-10T00:00:00", + "2025-07-10T00:00:00", + locale, + eraYear, + ), + ).toBe(""); + expect( + formatZonedDateTime("0600-07-10T12:00:00+00:00[UTC]", locale, eraYear), + ).toBe(""); + expect( + formatZonedToParts("0600-07-10T12:00:00+00:00[UTC]", locale, eraYear), + ).toEqual([]); + expect( + formatZonedRange( + "0600-07-10T12:00:00+00:00[UTC]", + "2025-07-10T12:00:00+00:00[UTC]", + locale, + eraYear, + ), + ).toBe(""); + }, + ); + + // Last day before the Hijra and the first day of AH 1, as native Temporal computes them + // (`bh` era / year 0, then `ah` year 1). The `islamic` and `islamic-rgsa` calendars are not in + // Temporal, so the epoch cannot be derived there and only dates far before it are tested. + it.each` + calendar | lastBefore | firstDay + ${"islamic-civil"} | ${"0622-07-18"} | ${"0622-07-19"} + ${"islamic-tbla"} | ${"0622-07-17"} | ${"0622-07-18"} + ${"islamic-umalqura"} | ${"0622-07-18"} | ${"0622-07-19"} + `( + "'$calendar' gives the empty value for the last day before the Hijra and 1 AH for $firstDay", + ({ calendar, lastBefore, firstDay }) => { + const locale = `en-u-ca-${calendar}`; + expect(formatDate(lastBefore, locale, eraYear)).toBe(""); + expect(formatDateToParts(lastBefore, locale, eraYear)).toEqual([]); + expect(formatDate(firstDay, locale, eraYear)).toBe("1 AH"); + expect( + formatDateToParts(firstDay, locale, eraYear).find( + (part) => part.type === "year", + ), + ).toEqual({ type: "year", value: "1" }); + expect(formatDateRange(lastBefore, firstDay, locale, eraYear)).toBe(""); + expect(formatDateRange(firstDay, "0623-07-10", locale, eraYear)).toMatch( + /^1\D+2 AH$/, + ); + expect( + formatZonedRange( + `${lastBefore}T23:59:59+00:00[UTC]`, + `${firstDay}T12:00:00+00:00[UTC]`, + locale, + eraYear, + ), + ).toBe(""); + }, + ); + + it.each` + locale + ${"ja-u-ca-islamic-civil"} + ${"ar-u-ca-islamic-umalqura-nu-arab"} + ${"th-u-ca-islamic-tbla-nu-thai"} + `("gives the empty value before the Hijra for '$locale'", ({ locale }) => { + expect(formatDate("0600-07-10", locale, eraYear)).toBe(""); + expect(formatDateToParts("0600-07-10", locale, eraYear)).toEqual([]); + expect(formatDateRange("0600-07-10", "0601-07-10", locale, eraYear)).toBe( + "", + ); + }); + + it.each(islamicCalendars.map((calendar) => ({ calendar })))( + "leaves a date after the Hijra alone for '$calendar'", + ({ calendar }) => { + const locale = `en-u-ca-${calendar}`; + expect(formatDate("2025-07-10", locale, eraYear)).toBe("1447 AH"); + expect(formatDate("2026-07-10", locale, eraYear)).toBe("1448 AH"); + expect( + formatDateToParts("2025-07-10", locale, eraYear) + .map((part) => part.value) + .join(""), + ).toBe("1447 AH"); + expect( + formatDateRange("2025-07-10", "2026-07-10", locale, eraYear), + ).toMatch(/1447.*1448/); + }, + ); + + it("leaves a pre-Hijra date alone in a gregory formatter", () => { + expect(formatDate("0600-07-10", "en-u-ca-gregory", eraYear)).toBe("600 AD"); + }); + + it("leaves a pre-Hijra date alone when no era or year is printed", () => { + expect( + formatDate("0600-07-10", "en-u-ca-islamic-civil", { month: "long" }), + ).not.toBe(""); + }); +}); + +describe("D27: ja japanese with year 2-digit pads the era year", () => { + it.each` + iso | options | expected | label + ${"2024-07-10"} | ${{ year: "2-digit" }} | ${"令和06年"} | ${"Reiwa 6"} + ${"2019-05-01"} | ${{ year: "2-digit" }} | ${"令和元年"} | ${"Reiwa 1 keeps 元"} + ${"2019-05-01"} | ${{ year: "numeric" }} | ${"令和元年"} | ${"Reiwa 1 numeric"} + ${"2024-07-10"} | ${{ year: "numeric" }} | ${"令和6年"} | ${"numeric is unpadded"} + ${"2024-07-10"} | ${{ year: "2-digit", month: "numeric", day: "numeric" }} | ${"R06/7/10"} | ${"numeric-only pattern"} + ${"1990-06-10"} | ${{ year: "2-digit", month: "long", day: "numeric" }} | ${"平成02年6月10日"} | ${"Heisei 2, month 6 stays"} + ${"1989-01-08"} | ${{ year: "2-digit", month: "long", day: "numeric" }} | ${"平成元年1月8日"} | ${"Heisei 1, month 1 stays"} + ${"2018-06-10"} | ${{ year: "2-digit", month: "long", day: "numeric" }} | ${"平成30年6月10日"} | ${"two digits stay"} + `( + "formatDate prints '$expected' for $label ($iso)", + ({ iso, options, expected }) => { + expect(formatDate(iso, "ja-u-ca-japanese", options)).toBe(expected); + }, + ); + + it("pads in the year part and in the joined parts", () => { + const parts = formatDateToParts("2024-07-10", "ja-u-ca-japanese", { + year: "2-digit", + }); + expect(parts.find((part) => part.type === "year")).toEqual({ + type: "year", + value: "06", + }); + expect(parts.map((part) => part.value).join("")).toBe("令和06年"); + }); + + it("pads in a zoned date and keeps 元 there", () => { + expect( + formatZonedDateTime( + "2024-07-10T12:00:00+00:00[UTC]", + "ja-u-ca-japanese", + { + year: "2-digit", + }, + ), + ).toBe("令和06年"); + expect( + formatZonedDateTime( + "2019-05-01T12:00:00+00:00[UTC]", + "ja-u-ca-japanese", + { + year: "2-digit", + }, + ), + ).toBe("令和元年"); + }); +}); + +describe("D27: ranges across eras, ja japanese, year 2-digit", () => { + // Heisei 31 ends on 2019-04-30, Reiwa 1 starts on 2019-05-01, Showa 64 ends on 1989-01-07. + it.each` + start | end | first | second + ${"2019-04-30"} | ${"2020-05-01"} | ${"平成31年"} | ${"令和02年"} + ${"2019-05-01"} | ${"2020-05-01"} | ${"令和元年"} | ${"02年"} + ${"2019-04-30"} | ${"2019-05-01"} | ${"平成31年"} | ${"令和元年"} + ${"1989-01-07"} | ${"1990-01-07"} | ${"昭和64年"} | ${"平成02年"} + ${"1989-01-08"} | ${"1990-01-08"} | ${"平成元年"} | ${"02年"} + ${"2018-06-10"} | ${"2019-04-30"} | ${"平成30年"} | ${"31年"} + ${"2024-07-10"} | ${"2034-07-10"} | ${"令和06年"} | ${"16年"} + `( + "the three range functions print '$first' and '$second' for $start to $end", + ({ start, end, first, second }) => { + const expected = new RegExp(`^${first}\\D+${second}$`); + const options = { year: "2-digit" } as const; + expect(formatDateRange(start, end, "ja-u-ca-japanese", options)).toMatch( + expected, + ); + expect( + formatDateTimeRange( + `${start}T00:00:00`, + `${end}T00:00:00`, + "ja-u-ca-japanese", + options, + ), + ).toMatch(expected); + expect( + formatZonedRange( + `${start}T00:00:00+00:00[UTC]`, + `${end}T00:00:00+00:00[UTC]`, + "ja-u-ca-japanese", + options, + ), + ).toMatch(expected); + }, + ); + + it.each` + start | end | expected + ${"2019-04-30"} | ${"2020-05-01"} | ${/^平成31年\D+令和2年$/} + ${"2019-05-01"} | ${"2020-05-01"} | ${/^令和元年\D+2年$/} + ${"2024-07-10"} | ${"2034-07-10"} | ${/^令和6年\D+16年$/} + `( + "year numeric keeps the era year unpadded for $start to $end", + ({ start, end, expected }) => { + expect( + formatDateRange(start, end, "ja-u-ca-japanese", { year: "numeric" }), + ).toMatch(expected); + }, + ); + + it("pads a year of a range inside a numeric-only pattern as the engine does", () => { + expect( + formatDateRange("2024-07-10", "2025-07-10", "ja-u-ca-japanese", { + year: "2-digit", + month: "numeric", + day: "numeric", + }), + ).toMatch(/^R06\/\d+\/10\D+07\/\d+\/10$/); + }); + + it("pads the year parts of a plain date-time and a zoned date in the joined parts", () => { + expect( + formatDateTime("2024-07-10T12:00:00", "ja-u-ca-japanese", { + year: "2-digit", + }), + ).toBe("令和06年"); + expect( + formatZonedToParts("2024-07-10T12:00:00+00:00[UTC]", "ja-u-ca-japanese", { + year: "2-digit", + }).find((part) => part.type === "year"), + ).toEqual({ type: "year", value: "06" }); + }); + + it("leaves a locale other than ja alone", () => { + expect( + formatDate("2024-07-10", "en-u-ca-japanese", { + year: "2-digit", + era: "short", + }), + ).toBe("06 Reiwa"); + }); +}); + +describe("D28: chinese and dangi related year at full width under year 2-digit", () => { + // The related year is the Temporal `year` of the date in that calendar (native Temporal: + // ISO 0005-07-10 is 5, -0001-07-10 is -1, 0099 is 99, 0100 is 100, 2024-07-10 is 2024). + it.each` + calendar | iso | expected + ${"chinese"} | ${"0005-07-10"} | ${"5"} + ${"chinese"} | ${"-000001-07-10"} | ${"-1"} + ${"chinese"} | ${"0099-07-10"} | ${"99"} + ${"chinese"} | ${"0100-07-10"} | ${"100"} + ${"chinese"} | ${"2024-07-10"} | ${"2024"} + ${"dangi"} | ${"0005-07-10"} | ${"5"} + ${"dangi"} | ${"-000001-07-10"} | ${"-1"} + ${"dangi"} | ${"0099-07-10"} | ${"99"} + ${"dangi"} | ${"0100-07-10"} | ${"100"} + ${"dangi"} | ${"2024-07-10"} | ${"2024"} + `( + "prints related year '$expected' for '$calendar' at $iso, year 2-digit", + ({ calendar, iso, expected }) => { + const locale = `en-u-ca-${calendar}`; + const options = { year: "2-digit" } as const; + const text = formatDate(iso, locale, options); + const parts = formatDateToParts(iso, locale, options); + expect(parts.find((part) => part.type === "relatedYear")?.value).toBe( + expected, + ); + expect(text.startsWith(`${expected}(`)).toBe(true); + expect(parts.map((part) => part.value).join("")).toBe(text); + expect( + formatZonedDateTime(`${iso}T12:00:00+00:00[UTC]`, locale, options), + ).toBe(text); + expect(formatDateTime(`${iso}T12:00:00`, locale, options)).toBe(text); + expect( + formatDate(iso, locale, { year: "numeric" }).startsWith(`${expected}(`), + ).toBe(true); + }, + ); + + it.each` + calendar | iso | expected + ${"chinese"} | ${"-000001-07-10"} | ${"-1"} + ${"chinese"} | ${"0005-07-10"} | ${"5"} + ${"dangi"} | ${"-000001-07-10"} | ${"-1"} + ${"dangi"} | ${"0005-07-10"} | ${"5"} + `( + "keeps month 2-digit and prints related year '$expected' for '$calendar' at $iso", + ({ calendar, iso, expected }) => { + const locale = `en-u-ca-${calendar}`; + const options = { year: "2-digit", month: "2-digit" } as const; + const text = formatDate(iso, locale, options); + expect(text.endsWith(`/${expected}`)).toBe(true); + expect(text.startsWith("0")).toBe(true); + const parts = formatDateToParts(iso, locale, options); + expect(parts.map((part) => part.type)).toEqual([ + "month", + "literal", + "relatedYear", + ]); + expect(parts.map((part) => part.value).join("")).toBe(text); + }, + ); + + it.each` + locale | iso | expected + ${"en-u-ca-chinese-nu-arab"} | ${"0005-07-10"} | ${"٥"} + ${"en-u-ca-chinese-nu-arab"} | ${"-000001-07-10"} | ${"\u061C-١"} + ${"en-u-ca-chinese-nu-arab"} | ${"2024-07-10"} | ${"٢٠٢٤"} + ${"en-u-ca-dangi-nu-arab"} | ${"0005-07-10"} | ${"٥"} + ${"zh-u-ca-chinese-nu-hanidec"} | ${"0005-07-10"} | ${"五"} + ${"zh-u-ca-chinese-nu-hanidec"} | ${"-000001-07-10"} | ${"-一"} + `( + "prints related year '$expected' in the numbering system of '$locale' at $iso", + ({ locale, iso, expected }) => { + expect( + formatDateToParts(iso, locale, { year: "2-digit" }).find( + (part) => part.type === "relatedYear", + )?.value, + ).toBe(expected); + }, + ); + + it("leaves a gregory year 2-digit and a chinese year numeric untouched", () => { + expect( + formatDate("2024-07-10", "en-u-ca-gregory", { year: "2-digit" }), + ).toBe("24"); + expect( + formatDate("0005-07-10", "en-u-ca-chinese", { year: "numeric" }), + ).toMatch(/^5\(/); + }); + + it.each` + calendar + ${"chinese"} + ${"dangi"} + `( + "prints every related year of a '$calendar' range unpadded, in all three functions", + ({ calendar }) => { + const locale = `en-u-ca-${calendar}`; + const options = { year: "2-digit", month: "2-digit" } as const; + const related = (text: string): string[] => + [...text.matchAll(/\/(-?\d+)/g)].map((match) => match[1] ?? ""); + expect( + related(formatDateRange("0005-07-10", "0006-07-10", locale, options)), + ).toEqual(["5", "6"]); + expect( + related( + formatDateTimeRange( + "0005-07-10T00:00:00", + "0006-07-10T00:00:00", + locale, + options, + ), + ), + ).toEqual(["5", "6"]); + expect( + related( + formatZonedRange( + "0005-07-10T00:00:00+00:00[UTC]", + "0006-07-10T00:00:00+00:00[UTC]", + locale, + options, + ), + ), + ).toEqual(["5", "6"]); + expect( + related( + formatDateRange("-000001-07-10", "0005-07-10", locale, options), + ), + ).toEqual(["-1", "5"]); + expect( + related(formatDateRange("0005-07-10", "0005-08-10", locale, options)), + ).toEqual(["5", "5"]); + }, + ); + + it.each` + locale + ${"en-u-ca-chinese"} + ${"en-u-ca-dangi"} + `( + "leaves a 4-digit related year of a '$locale' range alone", + ({ locale }) => { + const text = formatDateRange("2024-07-10", "2025-07-10", locale, { + year: "2-digit", + month: "2-digit", + }); + expect([...text.matchAll(/\/(-?\d+)/g)].map((match) => match[1])).toEqual( + ["2024", "2025"], + ); + }, + ); + + it("prints a range that crosses from a 1-digit to a 3-digit related year at full width", () => { + const text = formatDateRange( + "0099-07-10", + "0100-07-10", + "en-u-ca-chinese", + { + year: "2-digit", + month: "2-digit", + }, + ); + expect([...text.matchAll(/\/(-?\d+)/g)].map((match) => match[1])).toEqual([ + "99", + "100", + ]); + }); +}); diff --git a/packages/gmt/src/internal/yearPrinting.ts b/packages/gmt/src/internal/yearPrinting.ts new file mode 100644 index 000000000..2cf612181 --- /dev/null +++ b/packages/gmt/src/internal/yearPrinting.ts @@ -0,0 +1,310 @@ +import { Temporal } from "./temporal"; +import { + isIslamicEraCompatNeeded, + isJapaneseEraCompatNeeded, + isJapaneseTwoDigitYearCompatNeeded, + isRelatedYearWidthCompatNeeded, +} from "./temporalCompat/capabilities"; +import { nowInstant } from "./temporalCompat/clock"; +import { formatRangeChecked, markRangeHandled } from "./weekYearRange"; +import { type DigitRun, digitRuns, digitSetOf, digitsOf } from "./weekYearText"; + +/* + * CORE-112 slice 7, defects D25 to D28: years an engine prints wrongly outside the week-year. + * + * Each repair is dormant behind one cached engine probe (`temporalCompat/capabilities.ts`), and a + * formatter is wrapped only when its probe fails and the formatter can show the defect, so a fixed + * engine runs no per-format work. One wrapper holds D25, D26 and D27 (each needs the date of the + * call, and a formatter has one calendar, so at most two apply); D28 is a change of the options a + * formatter is built with. Every replacement text comes from the engine's own formatters or + * `Intl.NumberFormat`: GMT owns no era name, digit or locale datum. Deleting this file, its hook in + * `formatterCache.ts` and the four probes retires the workaround. + * + * - D25 (ICU-23341, ICU-23619): the japanese calendar prints Japanese eras before 1873-01-01. Intl + * era/monthCode Table 2 as amended by tc39/proposal-intl-era-monthcode#86 (test262 + * tc39/test262#4877) uses the Gregorian eras up to and including 1872-12-31. Those dates format + * through a `calendar: "gregory"` twin. + * - D26 (ICU-23327): an islamic calendar prints a date before the Hijra as a negative year; the + * specification gives the era `bh`, which this engine cannot name, so the date has no printable + * year and the house empty value answers (`""`, or `[]` for parts). + * - D27 (ICU-23620): `year: "2-digit"` in `ja` japanese leaves the era year unpadded. + * ECMA-402 FormatDateTimePattern pads it to two digits; year 1 stays 元 (owner decision). + * - D28 (ICU-23621): `year: "2-digit"` in chinese and dangi pads the related year, which ECMA-402 prints at + * full width. The formatter is built with `year: "numeric"`, the same pattern at full width. + */ + +/** The options that give a formatter a date pattern when none of these is set. */ +const FIELD_KEYS = [ + "weekday", + "year", + "month", + "day", + "dayPeriod", + "hour", + "minute", + "second", + "fractionalSecondDigits", + "dateStyle", + "timeStyle", +] as const; + +/** Whether the formatter can print an era or a year (ECMA-402 CreateDateTimeFormat defaults). */ +function showsEraOrYear(options: Intl.DateTimeFormatOptions): boolean { + return ( + options.era !== undefined || + options.year !== undefined || + options.dateStyle !== undefined || + FIELD_KEYS.every((key) => options[key] === undefined) + ); +} + +/** A time value as `Intl` reads it: a number, a `Date`, or `undefined` for now. */ +function toMilliseconds(date: Date | number | undefined): number { + if (typeof date === "number") { + return date; + } + return date === undefined ? nowInstant().epochMilliseconds : Number(date); +} + +/** The first date the japanese calendar prints a Japanese era for: ISO 1873 (Meiji 6). */ +const FIRST_JAPANESE_ERA_YEAR = 1873; + +/** The year shifts D27 tries to find an endpoint the same day of the year, at the same time. */ +const SHIFTS = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40] as const; + +/** + * The options a chinese or dangi formatter is built with: `year: "2-digit"` becomes `"numeric"` + * when the engine pads the related year (D28), else the options as given. + * + * @param callerOptions the options the formatter was asked for + * @param calendar the calendar the formatter resolved + * @returns the options to build with + * + * @example widenRelatedYear({ year: "2-digit" }, "chinese") // { year: "numeric" } where the engine pads the related year + * @example widenRelatedYear({ year: "2-digit" }, "gregory") // { year: "2-digit" } + */ +export function widenRelatedYear( + callerOptions: Intl.DateTimeFormatOptions, + calendar: string, +): Intl.DateTimeFormatOptions { + if ( + callerOptions.year === "2-digit" && + (calendar === "chinese" || calendar === "dangi") && + isRelatedYearWidthCompatNeeded() + ) { + return { ...callerOptions, year: "numeric" }; + } + return callerOptions; +} + +/** + * The starts of the one-digit runs of `runs` whose text differs in `other`'s runs, when `other` has + * as many runs (else none: a year printed as 元 changed the count). + */ +function changedSingleDigits( + runs: readonly DigitRun[], + other: string | null, + digitSet: ReadonlySet, +): number[] { + const moved = other === null ? [] : digitRuns(other, digitSet); + if (moved.length !== runs.length) { + return []; + } + return runs + .filter( + (run, index) => run.text.length === 1 && run.text !== moved[index]?.text, + ) + .map((run) => run.start); +} + +/** The text with `zero` written before each run that starts at one of `starts`. */ +function insertZeros( + text: string, + runs: readonly DigitRun[], + starts: ReadonlySet, + zero: string, +): string { + return runs + .filter((run) => starts.has(run.start)) + .toReversed() + .reduce( + (out, run) => out.slice(0, run.start) + zero + out.slice(run.start), + text, + ); +} + +/** The ISO year (in the formatter's zone) and the Hijra check of an instant. */ +function zonedAt(ms: number, timeZone: string): Temporal.ZonedDateTime { + return Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO( + timeZone, + ); +} + +/** + * The formatter itself, or a wrapper that repairs the years of D25, D26 and D27 where the engine + * prints them wrongly. + * + * @param formatter the formatter the week-year guard returned + * @param callerOptions the options it was built with + * @param twinOf the cached formatter for other options and the same locale (a Gregorian twin) + * @returns the formatter, or its wrapper + * + * @example repairYearPrinting(new Intl.DateTimeFormat("en", { year: "numeric" }), { year: "numeric" }, () => new Intl.DateTimeFormat("en")) // the same formatter + * @example repairYearPrinting(new Intl.DateTimeFormat("ja-u-ca-japanese", { year: "2-digit", timeZone: "UTC" }), { year: "2-digit", timeZone: "UTC" }, () => new Intl.DateTimeFormat("ja")).format(Date.UTC(2024, 6, 10)) // "令和06年" where the engine prints 令和6年 + */ +export function repairYearPrinting( + formatter: Intl.DateTimeFormat, + callerOptions: Intl.DateTimeFormatOptions, + twinOf: (options: Intl.DateTimeFormatOptions) => Intl.DateTimeFormat, +): Intl.DateTimeFormat { + let resolved: Intl.ResolvedDateTimeFormatOptions; + try { + resolved = formatter.resolvedOptions(); + } catch { + return formatter; + } + const { calendar, timeZone, numberingSystem } = resolved; + const japanese = calendar === "japanese"; + const era = + japanese && showsEraOrYear(callerOptions) && isJapaneseEraCompatNeeded(); + const islamic = + calendar.startsWith("islamic") && + showsEraOrYear(callerOptions) && + isIslamicEraCompatNeeded(); + const pad = + japanese && + callerOptions.year === "2-digit" && + new Intl.Locale(resolved.locale).language === "ja" && + isJapaneseTwoDigitYearCompatNeeded(); + if (!era && !islamic && !pad) { + return formatter; + } + const zero = digitsOf(numberingSystem)[0] ?? "0"; + const digitSet = digitSetOf(numberingSystem); + let gregorian: Intl.DateTimeFormat | undefined; + const twin = (): Intl.DateTimeFormat => + (gregorian ??= twinOf({ ...callerOptions, calendar: "gregory" })); + + /** D25: the instant is before the first Japanese era (ISO year in the formatter's zone). */ + const beforeEras = (ms: number): boolean => + era && zonedAt(ms, timeZone).year < FIRST_JAPANESE_ERA_YEAR; + + /** D26: the instant is before the Hijra, decided by Temporal (era `bh`, or year 0 or less). */ + const beforeHijra = (ms: number): boolean => { + if (!islamic) { + return false; + } + try { + const date = zonedAt(ms, timeZone).withCalendar(calendar); + return date.era === "bh" || date.year <= 0; + } catch { + return false; + } + }; + + /** D27: an era year printed with one digit gains the formatter's own zero (never 元). */ + const padPart = (part: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart => + part.type === "year" && digitSet.has(part.value) && part.value.length === 1 + ? { ...part, value: zero + part.value } + : part; + + /** The instants shifted by whole years that keep date and time, or `null` when none does. */ + const shiftOf = (ms: number): number | null => { + const start = zonedAt(ms, timeZone); + for (const years of SHIFTS) { + const moved = start.add({ years }); + if ( + moved.month === start.month && + moved.day === start.day && + moved.toPlainTime().equals(start.toPlainTime()) + ) { + return moved.epochMilliseconds; + } + } + return null; + }; + + /** + * D27 in a range: the digit run that changes when an endpoint moves by whole years is an era + * year; one digit gains a zero. Each way of moving the endpoints (both, only the first, only the + * second) counts only when the number of digit runs is the same, so a year that prints as 元 is + * left alone. + */ + const paddedRange = (text: string, a: number, b: number): string => { + const shiftedA = shiftOf(a); + const shiftedB = shiftOf(b); + if (shiftedA === null || shiftedB === null) { + return text; + } + const runs = digitRuns(text, digitSet); + const starts = new Set(); + for (const [x, y] of [ + [shiftedA, shiftedB], + [shiftedA, b], + [a, shiftedB], + ] as const) { + const other = formatRangeChecked(formatter, callerOptions, x, y); + for (const start of changedSingleDigits(runs, other, digitSet)) { + starts.add(start); + } + } + return insertZeros(text, runs, starts, zero); + }; + + const standIn = { + format(date?: Date | number): string { + const ms = toMilliseconds(date); + if (beforeHijra(ms)) { + return ""; + } + if (beforeEras(ms)) { + return twin().format(ms); + } + return pad + ? formatter + .formatToParts(ms) + .map((part) => padPart(part).value) + .join("") + : formatter.format(ms); + }, + formatToParts(date?: Date | number): Intl.DateTimeFormatPart[] { + const ms = toMilliseconds(date); + if (beforeHijra(ms)) { + return []; + } + if (beforeEras(ms)) { + return twin().formatToParts(ms); + } + const parts = formatter.formatToParts(ms); + return pad ? parts.map(padPart) : parts; + }, + formatRange(start: Date | number, end: Date | number): string { + const a = toMilliseconds(start); + const b = toMilliseconds(end); + if (beforeHijra(a) || beforeHijra(b)) { + return ""; + } + // A range that starts or ends before 1873 prints in one calendar, the Gregorian one. + const text = + beforeEras(a) || beforeEras(b) + ? formatRangeChecked(twin(), callerOptions, a, b) + : formatRangeChecked(formatter, callerOptions, a, b); + if (text === null) { + return ""; + } + return pad && !(beforeEras(a) || beforeEras(b)) + ? paddedRange(text, a, b) + : text; + }, + formatRangeToParts(): never { + throw new TypeError( + "formatRangeToParts is not available on a formatter whose years are repaired (CORE-112)", + ); + }, + resolvedOptions(): Intl.ResolvedDateTimeFormatOptions { + return resolved; + }, + }; + markRangeHandled(standIn); + return standIn as Intl.DateTimeFormat; +} diff --git a/packages/gmt/src/internal/yearPrintingDormant.test.ts b/packages/gmt/src/internal/yearPrintingDormant.test.ts new file mode 100644 index 000000000..d36d4b3c8 --- /dev/null +++ b/packages/gmt/src/internal/yearPrintingDormant.test.ts @@ -0,0 +1,198 @@ +import { Temporal } from "./temporal"; + +/* + * CORE-112 slice 7: each repair is dormant behind one engine probe. With the four probes stubbed + * to pass (a fixed engine) no formatter is wrapped: the cache hands out the engine's own + * `Intl.DateTimeFormat`, so no per-format work runs. With them stubbed to fail, exactly the + * formatters that can show the defect are wrapped. (`vi.mock` makes this an isolated file; the + * setup file has already loaded the library, so each test loads the cache again after the mock.) + */ + +/** The formatter cache, loaded after the probe stub is in place. */ +async function freshCache(): Promise { + vi.resetModules(); + return import("./formatterCache"); +} + +const probes = vi.hoisted(() => ({ needed: true })); + +vi.mock("./temporalCompat/capabilities", async (importOriginal) => ({ + ...(await importOriginal()), + isJapaneseEraCompatNeeded: () => probes.needed, + isIslamicEraCompatNeeded: () => probes.needed, + isJapaneseTwoDigitYearCompatNeeded: () => probes.needed, + isRelatedYearWidthCompatNeeded: () => probes.needed, +})); + +const era = { era: "short", year: "numeric", timeZone: "UTC" } as const; +const twoDigit = { year: "2-digit", timeZone: "UTC" } as const; + +describe("year printing is dormant on a fixed engine", () => { + it.each` + locale | options | label + ${"en-u-ca-japanese"} | ${era} | ${"D25 japanese"} + ${"en-u-ca-islamic-civil"} | ${era} | ${"D26 islamic-civil"} + ${"en-u-ca-islamic-umalqura"} | ${era} | ${"D26 islamic-umalqura"} + ${"ja-u-ca-japanese"} | ${twoDigit} | ${"D27 ja japanese"} + ${"en-u-ca-chinese"} | ${twoDigit} | ${"D28 chinese"} + ${"en-u-ca-dangi"} | ${twoDigit} | ${"D28 dangi"} + `( + "returns the engine's own formatter for $label when its probe passes", + async ({ locale, options }) => { + probes.needed = false; + const { cachedFormatter } = await freshCache(); + const formatter = cachedFormatter("DateTimeFormat", locale, options); + expect(formatter).toBeInstanceOf(Intl.DateTimeFormat); + }, + ); + + it.each` + locale | options | label + ${"en-u-ca-japanese"} | ${era} | ${"D25 japanese"} + ${"en-u-ca-islamic-civil"} | ${era} | ${"D26 islamic-civil"} + ${"ja-u-ca-japanese"} | ${twoDigit} | ${"D27 ja japanese"} + `( + "wraps the formatter for $label when its probe fails", + async ({ locale, options }) => { + probes.needed = true; + const { cachedFormatter } = await freshCache(); + const formatter = cachedFormatter("DateTimeFormat", locale, options); + expect(formatter).not.toBeInstanceOf(Intl.DateTimeFormat); + }, + ); + + it.each` + locale | options | label + ${"en-u-ca-gregory"} | ${era} | ${"gregory with era"} + ${"en-u-ca-japanese"} | ${{ month: "long", timeZone: "UTC" }} | ${"japanese month only"} + ${"ja-u-ca-gregory"} | ${twoDigit} | ${"ja gregory 2-digit"} + `( + "wraps nothing for $label even when every probe fails", + async ({ locale, options }) => { + probes.needed = true; + const { cachedFormatter } = await freshCache(); + const formatter = cachedFormatter("DateTimeFormat", locale, options); + expect(formatter).toBeInstanceOf(Intl.DateTimeFormat); + }, + ); +}); + +describe("every public format function is the engine's own on a fixed engine", () => { + // Midnight UTC, as the library formats a plain date; the oracle is the engine's formatter built + // with the same locale and options, so a fixed engine gives the same text from the library. + const midnight = (iso: string): number => + Temporal.PlainDate.from(iso).toZonedDateTime("UTC").epochMilliseconds; + + it.each` + locale | options | start | end + ${"en-u-ca-japanese"} | ${{ era: "short", year: "numeric" }} | ${"-000001-07-10"} | ${"1872-12-31"} + ${"ja-u-ca-japanese"} | ${{ era: "short", year: "numeric" }} | ${"1868-10-23"} | ${"1873-01-01"} + ${"en-u-ca-islamic-civil"} | ${{ era: "short", year: "numeric" }} | ${"0600-07-10"} | ${"2025-07-10"} + ${"en-u-ca-islamic-umalqura"} | ${{ era: "short", year: "numeric" }} | ${"-000001-07-10"} | ${"0622-07-19"} + ${"ja-u-ca-japanese"} | ${{ year: "2-digit" }} | ${"2019-04-30"} | ${"2020-05-01"} + ${"en-u-ca-chinese"} | ${{ year: "2-digit", month: "2-digit" }} | ${"0005-07-10"} | ${"0006-07-10"} + ${"en-u-ca-dangi"} | ${{ year: "2-digit" }} | ${"-000001-07-10"} | ${"0005-07-10"} + `( + "formatDate, its parts and the three ranges equal the engine for '$locale' $options at $start to $end", + async ({ locale, options, start, end }) => { + probes.needed = false; + vi.resetModules(); + const [ + { formatDate }, + { formatDateToParts }, + { formatDateRange }, + { formatDateTimeRange }, + { formatZonedRange }, + { formatZonedDateTime }, + { normalizeDateTime }, + ] = await Promise.all([ + import("../plain/format/formatDate"), + import("../plain/format/formatDateToParts"), + import("../plain/format/formatDateRange"), + import("../plain/format/formatDateTimeRange"), + import("../zoned/format/formatZonedRange"), + import("../zoned/format/formatZonedDateTime"), + import("./normalizeDateTime"), + ]); + const engine = new Intl.DateTimeFormat(locale, { + ...options, + timeZone: "UTC", + }); + const a = midnight(start); + const b = midnight(end); + const zoned = (iso: string): string => `${iso}T00:00:00+00:00[UTC]`; + expect(formatDate(start, locale, options)).toBe( + normalizeDateTime(engine.format(a)), + ); + expect(formatDateToParts(start, locale, options)).toEqual( + engine.formatToParts(a), + ); + expect(formatZonedDateTime(zoned(start), locale, options)).toBe( + normalizeDateTime(engine.format(a)), + ); + const range = normalizeDateTime(engine.formatRange(a, b)); + expect(formatDateRange(start, end, locale, options)).toBe(range); + expect( + formatDateTimeRange( + `${start}T00:00:00`, + `${end}T00:00:00`, + locale, + options, + ), + ).toBe(range); + expect(formatZonedRange(zoned(start), zoned(end), locale, options)).toBe( + range, + ); + }, + ); +}); + +describe("widenRelatedYear", () => { + it.each` + needed | calendar | options | widened | label + ${true} | ${"chinese"} | ${{ year: "2-digit" }} | ${true} | ${"chinese, year 2-digit, probe fails"} + ${true} | ${"dangi"} | ${{ year: "2-digit", month: "2-digit" }} | ${true} | ${"dangi, year and month 2-digit, probe fails"} + ${false} | ${"chinese"} | ${{ year: "2-digit" }} | ${false} | ${"chinese, probe passes"} + ${true} | ${"chinese"} | ${{ year: "numeric" }} | ${false} | ${"chinese, year numeric"} + ${true} | ${"chinese"} | ${{ month: "2-digit" }} | ${false} | ${"chinese, no year"} + ${true} | ${"gregory"} | ${{ year: "2-digit" }} | ${false} | ${"gregory, year 2-digit"} + ${true} | ${"japanese"} | ${{ year: "2-digit" }} | ${false} | ${"japanese, year 2-digit"} + `("$widened for $label", async ({ needed, calendar, options, widened }) => { + probes.needed = needed; + vi.resetModules(); + const { widenRelatedYear } = await import("./yearPrinting"); + const out = widenRelatedYear(options, calendar); + if (widened) { + expect(out).toEqual({ ...options, year: "numeric" }); + expect(options.year).toBe("2-digit"); + } else { + expect(out).toBe(options); + } + }); +}); + +describe("the year repair wrapper", () => { + it("has no formatRangeToParts: a parts call on a wrapped formatter throws a TypeError", async () => { + probes.needed = true; + const { cachedFormatter } = await freshCache(); + const formatter = cachedFormatter( + "DateTimeFormat", + "en-u-ca-japanese", + era, + ); + expect(() => formatter.formatRangeToParts(0, 1)).toThrow(TypeError); + }); + + it("reports the options it resolved, not a stand-in's", async () => { + probes.needed = true; + const { cachedFormatter } = await freshCache(); + const formatter = cachedFormatter( + "DateTimeFormat", + "en-u-ca-japanese", + era, + ); + const resolved = formatter.resolvedOptions(); + expect(resolved.calendar).toBe("japanese"); + expect(resolved.timeZone).toBe("UTC"); + }); +}); diff --git a/packages/gmt/src/plain/format/formatDate.test.ts b/packages/gmt/src/plain/format/formatDate.test.ts index bda648a5c..22c31b501 100644 --- a/packages/gmt/src/plain/format/formatDate.test.ts +++ b/packages/gmt/src/plain/format/formatDate.test.ts @@ -386,7 +386,7 @@ describe("formatDate", () => { ${"ja-JP-u-ca-japanese"} | ${{ year: "numeric", month: "long" }} | ${"令和6年2月"} | ${"requested long month kept"} ${"ja-JP-u-ca-japanese"} | ${{ year: "numeric", month: "numeric" }} | ${"R6/2"} | ${"numeric fields give the pre-1.16.0 text"} ${"ja-JP"} | ${{ month: "long", day: "numeric" }} | ${"2月3日"} | ${"requested long month kept"} - ${"ja-JP-u-ca-japanese"} | ${{ year: "2-digit", month: "short", day: "numeric" }} | ${"令和6年2月3日"} | ${"requested short month kept"} + ${"ja-JP-u-ca-japanese"} | ${{ year: "2-digit", month: "short", day: "numeric" }} | ${"令和06年2月3日"} | ${"requested short month kept, 2-digit era year padded (D27)"} ${"en-US-u-ca-chinese"} | ${{ year: "numeric", month: "long" }} | ${"Twelfth Month 2023(gui-mao)"} | ${"year kept with long month"} ${"ko-KR-u-ca-hebrew"} | ${{ year: "numeric", month: "long" }} | ${"AM 5784년 5월"} | ${"requested long month kept"} ${"en-US"} | ${{ era: "long" }} | ${"2/3/2024 Anno Domini"} | ${"era alone gets the date defaults"} diff --git a/packages/gmt/src/plain/format/formatDateRange.ts b/packages/gmt/src/plain/format/formatDateRange.ts index 2f717b27c..4f2bb8791 100644 --- a/packages/gmt/src/plain/format/formatDateRange.ts +++ b/packages/gmt/src/plain/format/formatDateRange.ts @@ -1,3 +1,4 @@ +import { formatRangeChecked } from "../../internal/weekYearRange"; import { plainDateOf } from "../../internal/inputChecks"; import { normalizeDateTime } from "../../internal"; import { plainDateFormatOptions } from "../../internal/plainFormatOptions"; @@ -63,11 +64,13 @@ export function formatDateRange( if (resolved === null) { return ""; } - const out = cachedFormatter("DateTimeFormat", locale, resolved).formatRange( + const out = formatRangeChecked( + cachedFormatter("DateTimeFormat", locale, resolved), + resolved, startParsed.toZonedDateTime("UTC").epochMilliseconds, endParsed.toZonedDateTime("UTC").epochMilliseconds, ); - return normalizeDateTime(out); + return out === null ? "" : normalizeDateTime(out); } catch { return ""; } diff --git a/packages/gmt/src/plain/format/formatDateTimeRange.ts b/packages/gmt/src/plain/format/formatDateTimeRange.ts index 6d5fdbc01..703137d0c 100644 --- a/packages/gmt/src/plain/format/formatDateTimeRange.ts +++ b/packages/gmt/src/plain/format/formatDateTimeRange.ts @@ -1,3 +1,4 @@ +import { formatRangeChecked } from "../../internal/weekYearRange"; import { plainDateTimeOf } from "../../internal/inputChecks"; import { normalizeDateTime } from "../../internal"; import { plainDateTimeFormatOptions } from "../../internal/plainFormatOptions"; @@ -62,15 +63,14 @@ export function formatDateTimeRange( // Intl.DateTimeFormat raises for invalid ones. const read = readDateTimeFormatOptions(options); checkFormatterArguments("DateTimeFormat", locale, read); - const out = cachedFormatter( - "DateTimeFormat", - locale, - plainDateTimeFormatOptions(read), - ).formatRange( + const formatOptions = plainDateTimeFormatOptions(read); + const out = formatRangeChecked( + cachedFormatter("DateTimeFormat", locale, formatOptions), + formatOptions, startParsed.toZonedDateTime("UTC").epochMilliseconds, endParsed.toZonedDateTime("UTC").epochMilliseconds, ); - return normalizeDateTime(out); + return out === null ? "" : normalizeDateTime(out); } catch { return ""; } diff --git a/packages/gmt/src/test/optionsObject.test.ts b/packages/gmt/src/test/optionsObject.test.ts index d3e3018f7..a15e2f419 100644 --- a/packages/gmt/src/test/optionsObject.test.ts +++ b/packages/gmt/src/test/optionsObject.test.ts @@ -17,6 +17,23 @@ * exception both engines make: `"null"` is a well-formed subtag, so it is accepted and ignored. */ import { deepEqual } from "./deepEqual"; + +// This file asks whether an option given as an object is read like the same option given plainly, +// over thousands of distinct option sets. The range year check (D24) is a pure function of the +// formatter, so it answers the same for the wrapped and the plain call; it costs a few milliseconds +// per new formatter, which these thousands of formatters would turn into over 30 s. The range +// functions here call the engine's own `formatRange`, and weekYearRange.test.ts and +// weekYearRangeText.test.ts hold the repair itself. +vi.mock("../internal/weekYearRange", async (importOriginal) => ({ + ...(await importOriginal()), + formatRangeChecked: ( + formatter: Intl.DateTimeFormat, + _options: Intl.DateTimeFormatOptions, + startMs: number, + endMs: number, + ) => formatter.formatRange(startMs, endMs), +})); + import { formatCalendar, formatCalendarUnix, diff --git a/packages/gmt/src/zoned/format/formatZonedRange.ts b/packages/gmt/src/zoned/format/formatZonedRange.ts index 751d4d6fe..9fe16bac1 100644 --- a/packages/gmt/src/zoned/format/formatZonedRange.ts +++ b/packages/gmt/src/zoned/format/formatZonedRange.ts @@ -6,16 +6,27 @@ import type { DateTimeFormatOptions } from "../../types"; import { readDateTimeFormatOptions } from "../../internal/readDateTimeFormatOptions"; import { timeZoneEquals } from "../../internal/temporalCompat"; import { repairRangeParts } from "../../internal/repairRangeParts"; +import { formatRangeChecked } from "../../internal/weekYearRange"; +import { repairRangeText } from "../../internal/repairRangeText"; import { isRangeDayPeriodCompatNeeded, isRangeZoneNameCompatNeeded, } from "../../internal/temporalCompat"; +/** The `timeZoneName` part's value, or `undefined` when the parts carry none. */ +function zoneNameOf(parts: Intl.DateTimeFormatPart[]): string | undefined { + return parts.find((part) => part.type === "timeZoneName")?.value; +} + /** * The range with the parts a host gets wrong written in the requested form: the `timeZoneName` * width (defect D16, ICU-20548) and the flexible `dayPeriod` (defect D17). The part merge is * `repairRangeParts`. For D16 the carrier formatter uses a `short` zone name, which the engine * keeps; for D17 it is the requested formatter. + * + * `formatRangeToParts` is called only here, and a V8 that aborts on it (CORE-112, defect D23) never + * turns the D17 gate on: only SpiderMonkey does, which has no such abort. D16 alone takes + * `rangeWithRepairedZoneNames` and never calls a range parts method. */ function rangeWithRepairedParts( locale: string | string[] | undefined, @@ -45,6 +56,44 @@ function rangeWithRepairedParts( ); } +/** + * The range with the carrier's `short` zone names replaced by the requested ones (defect D16), + * read off the `formatRange` string by `repairRangeText`, with no range parts call. A range + * pattern is not visible through `resolvedOptions`, so a V8 that aborts on a week-of-year year + * field (CORE-112, defect D23) cannot be told which range parts call is safe: this one makes none. + * The zone names come from single-date parts, which `cachedFormatter` guards. + * + * @returns the repaired range, or `""` when a zone name cannot be given to an endpoint + */ +function rangeWithRepairedZoneNames( + locale: string | string[] | undefined, + formatOptions: Intl.DateTimeFormatOptions, + ms1: number, + ms2: number, +): string { + const want = cachedFormatter("DateTimeFormat", locale, formatOptions); + const carrierOptions = { ...formatOptions, timeZoneName: "short" as const }; + const carrier = cachedFormatter("DateTimeFormat", locale, carrierOptions); + // The year repair first (slice 3c), then the zone names: it changes digits only. + const text = formatRangeChecked(carrier, carrierOptions, ms1, ms2); + if (text === null) { + return ""; + } + return ( + repairRangeText( + text, + [ + zoneNameOf(carrier.formatToParts(ms1)), + zoneNameOf(carrier.formatToParts(ms2)), + ], + [ + zoneNameOf(want.formatToParts(ms1)), + zoneNameOf(want.formatToParts(ms2)), + ], + ) ?? "" + ); +} + /** * Format a zoned datetime range using the Temporal Intl.DateTimeFormat formatRange API. * @@ -137,17 +186,26 @@ export function formatZonedRange( style !== undefined && formatOptions.dayPeriod !== undefined && isRangeDayPeriodCompatNeeded(); - const out = - zoneNames || dayPeriods - ? rangeWithRepairedParts(locale, formatOptions, ms1, ms2, { - zoneNames, - dayPeriods, - }) - : cachedFormatter( - "DateTimeFormat", - locale, - formatOptions, - ).formatRange(ms1, ms2); + let out: string; + if (dayPeriods) { + out = rangeWithRepairedParts(locale, formatOptions, ms1, ms2, { + zoneNames, + dayPeriods, + }); + } else if (zoneNames) { + out = rangeWithRepairedZoneNames(locale, formatOptions, ms1, ms2); + } else { + const text = formatRangeChecked( + cachedFormatter("DateTimeFormat", locale, formatOptions), + formatOptions, + ms1, + ms2, + ); + if (text === null) { + return ""; + } + out = text; + } return normalizeDateTime(out); } catch { return ""; diff --git a/packages/gmt/src/zoned/format/formatZonedRangeBranches.test.ts b/packages/gmt/src/zoned/format/formatZonedRangeBranches.test.ts new file mode 100644 index 000000000..fe90b9175 --- /dev/null +++ b/packages/gmt/src/zoned/format/formatZonedRangeBranches.test.ts @@ -0,0 +1,98 @@ +import { normalizeDateTime } from "../../internal"; +import { formatZonedRange } from "./formatZonedRange"; + +const { zoneNameGate, dayPeriodGate } = vi.hoisted(() => ({ + zoneNameGate: vi.fn<(style: string) => boolean>(), + dayPeriodGate: vi.fn<() => boolean>(), +})); + +vi.mock("../../internal/temporalCompat", async (importOriginal) => ({ + ...(await importOriginal()), + isRangeZoneNameCompatNeeded: zoneNameGate, + isRangeDayPeriodCompatNeeded: dayPeriodGate, +})); + +/* + * CORE-112 slice 3: which repair `formatZonedRange` takes when the compat gates are forced. D16 + * alone repairs the `formatRange` string and makes no range parts call (a V8 that aborts on a + * week-of-year year field must never reach one); D17, reachable only on SpiderMonkey, keeps the + * parts merge, and with both gates on the parts merge handles both. The expected text is the + * requested form (ECMA-402 FormatDateTimeRange keeps the width the options ask for): each + * endpoint's `long` zone name, here Europe/London's standard and summer time across the 2026 change, + * and the flexible day periods "in the morning" and "noon" (not AM/PM). The range pattern's own + * punctuation is the engine's, so the day-period rows check the repaired fields, not the whole text. + */ +describe("formatZonedRange — D16 and D17 branch order", () => { + const from = "2026-03-28T12:00:00+00:00[Europe/London]"; + const to = "2026-03-30T13:00:00+01:00[Europe/London]"; + const options = { + hour: "numeric", + minute: "numeric", + timeZoneName: "long", + } as const; + const newYorkFrom = "2026-03-28T10:00:00-04:00[America/New_York]"; + const newYorkTo = "2026-03-28T12:00:00-04:00[America/New_York]"; + const dayPeriodOptions = { + hour: "numeric", + dayPeriod: "short", + timeZoneName: "short", + } as const; + const expected = normalizeDateTime( + "28/03/2026, 12:00 Greenwich Mean Time – 30/03/2026, 13:00 British Summer Time", + ); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + beforeEach(() => { + zoneNameGate.mockReturnValue(false); + dayPeriodGate.mockReturnValue(false); + }); + + it("D16 alone writes each endpoint's long zone name and calls no range parts method", () => { + zoneNameGate.mockReturnValue(true); + const partsCall = vi.spyOn( + Intl.DateTimeFormat.prototype, + "formatRangeToParts", + ); + expect(formatZonedRange(from, to, "en-GB", options)).toBe(expected); + expect(partsCall).not.toHaveBeenCalled(); + }); + + it("D17 alone merges the range parts", () => { + dayPeriodGate.mockReturnValue(true); + const partsCall = vi.spyOn( + Intl.DateTimeFormat.prototype, + "formatRangeToParts", + ); + const text = formatZonedRange( + newYorkFrom, + newYorkTo, + "en-US", + dayPeriodOptions, + ); + expect(text).toContain("10 in the morning"); + expect(text).toContain("12 noon"); + expect(text).toContain("EDT"); + expect(partsCall).toHaveBeenCalledTimes(1); + }); + + it("both gates on: the parts merge handles both repairs", () => { + zoneNameGate.mockReturnValue(true); + dayPeriodGate.mockReturnValue(true); + const partsCall = vi.spyOn( + Intl.DateTimeFormat.prototype, + "formatRangeToParts", + ); + const text = formatZonedRange(newYorkFrom, newYorkTo, "en-US", { + ...dayPeriodOptions, + timeZoneName: "long", + }); + expect(text).toContain("10 in the morning"); + expect(text).toContain("12 noon"); + expect(text).toContain("Eastern Daylight Time"); + expect(text).not.toContain("EDT"); + expect(partsCall).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/gmt/src/zoned/format/formatZonedRangeWeekYear.test.ts b/packages/gmt/src/zoned/format/formatZonedRangeWeekYear.test.ts new file mode 100644 index 000000000..6d1363060 --- /dev/null +++ b/packages/gmt/src/zoned/format/formatZonedRangeWeekYear.test.ts @@ -0,0 +1,35 @@ +import { runInBoundedChild } from "../../test/boundedChild"; + +/* + * CORE-112 (D23): V8 without commit 0426b0d1045d aborts the whole process (SIGTRAP, exit 133, + * nodejs/node#67076) on a `formatRangeToParts` call whose range pattern holds the week-of-year year + * field. The D16 zone-name repair used that call, so this range aborted Node. The call runs in a + * child process: the red state is the child crashing, never the Vitest worker. + * + * The expected zone names are the requested `long` ones from the single-date parts at each + * endpoint (ECMA-402 FormatDateTimePattern: the `timeZoneName` part), read from the same child. + */ +describe("formatZonedRange — no abort on a Burmese Buddhist-calendar range (D23)", () => { + const from = "2026-07-01T09:30:00+06:30[Asia/Yangon]"; + const to = "2026-07-04T09:30:00+06:30[Asia/Yangon]"; + const options = + '{ hour: "numeric", minute: "numeric", timeZoneName: "long" }'; + + it("returns a range holding the long zone name of each endpoint, in a child process", async () => { + const run = await runInBoundedChild([ + `gmt.formatZonedRange("${from}", "${to}", "my-u-ca-buddhist", ${options})`, + `gmt.formatZonedToParts("${from}", "my-u-ca-buddhist", ${options}).find((part) => part.type === "timeZoneName")?.value`, + `gmt.formatZonedToParts("${to}", "my-u-ca-buddhist", ${options}).find((part) => part.type === "timeZoneName")?.value`, + ]); + expect( + { timedOut: run.timedOut, crashed: run.crashed }, + run.stderr, + ).toEqual({ timedOut: false, crashed: false }); + const [range, startName, endName] = run.calls.map((call) => call.value); + expect(startName).toEqual(expect.any(String)); + expect(endName).toEqual(expect.any(String)); + expect(range).toEqual(expect.any(String)); + expect(range).toContain(startName); + expect(range).toContain(endName); + }); +}); diff --git a/scripts/canary/weekYear.mjs b/scripts/canary/weekYear.mjs new file mode 100644 index 000000000..78c1c0ca3 --- /dev/null +++ b/scripts/canary/weekYear.mjs @@ -0,0 +1,201 @@ +#!/usr/bin/env node +/** + * The weekly sweep for D23 and D24 (CORE-112): CLDR date patterns that print the week-of-year year + * where the calendar year is meant, and V8 without commit 0426b0d1045d aborting the process in + * `formatToParts` on them (nodejs/node#67076). + * + * The recorded repros in `temporalCompat/repros.ts` cannot see a new locale's `Y`. This sweep can: + * the locale list is the directory listing of the `cldr-dates-full` package for the CLDR version + * the engine reports, fetched at run time with `npm pack` into a temporary directory, never a + * dependency and never shipped, then filtered by `Intl.DateTimeFormat.supportedLocalesOf`. + * + * For every locale and calendar, over a set of option shapes: + * + * 1. In this process, `format` and the guard's parts only. A formatter the guard replaces must give + * non-empty parts that join to its own `format`, and a `format` that keeps its digit runs. + * 2. In one child process per locale: the engine's own `formatToParts` on every formatter the + * guard left alone. An exit of 133 is a guard false negative and fails the run. + * + * The D23 reading is confirmed on Node: `resolvedOptions().year` of a week-year pattern and a child + * process that calls `formatToParts` must agree (exit 133 with no year, exit 0 with one), else a + * signal GMT relies on has changed and the run fails. + * + * Needs `packages/gmt/dist` (run `pnpm build` first). Options: `--locales gd,ksh` for a quick run, + * `--calendars gregory,hebrew`. Exits 1 on any failure, 2 when it cannot run. + */ +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const ROOT = fileURLToPath(new URL("../..", import.meta.url)); +const DIST = join(ROOT, "packages/gmt/dist"); + +const OPTION_SETS = [ + { year: "numeric", month: "short" }, + { year: "numeric", month: "long" }, + { year: "numeric", month: "numeric" }, + { year: "2-digit", month: "2-digit" }, + { year: "numeric", month: "numeric", day: "numeric" }, + { year: "numeric", month: "short", day: "numeric", weekday: "short" }, + { + era: "short", + year: "numeric", + month: "numeric", + day: "numeric", + weekday: "short", + }, + { year: "numeric", month: "short", hour: "numeric", minute: "numeric" }, + { year: "numeric" }, + { era: "short" }, + { dateStyle: "full" }, + { dateStyle: "long" }, + { dateStyle: "medium" }, + { dateStyle: "short" }, + { dateStyle: "full", timeStyle: "short" }, +]; + +const DATES = [1735554000000, 1798798800000, 1782901200000, 1798755600000]; + +function argument(name) { + const at = process.argv.indexOf(`--${name}`); + return at < 0 ? null : (process.argv[at + 1] ?? "").split(","); +} + +/** The locales of `cldr-dates-full` for this engine's CLDR version, fetched into a temp directory. */ +function cldrLocales() { + const directory = mkdtempSync(join(tmpdir(), "gmt-cldr-")); + try { + const version = process.versions.cldr?.split(".")[0] ?? ""; + const pack = spawnSync( + "npm", + [ + "pack", + `cldr-dates-full@${version ? `${version}` : "latest"}`, + "--silent", + ], + { cwd: directory, encoding: "utf8" }, + ); + if (pack.status !== 0) { + return null; + } + const tarball = pack.stdout.trim().split("\n").at(-1) ?? ""; + spawnSync("tar", ["-xzf", tarball], { cwd: directory }); + const main = join(directory, "package", "main"); + return existsSync(main) ? readdirSync(main) : null; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +function localeList() { + const given = argument("locales"); + if (given !== null) { + return given; + } + const listed = cldrLocales(); + if (listed === null) { + console.error( + "cannot fetch cldr-dates-full (npm pack failed): pass --locales", + ); + process.exit(2); + } + return Intl.DateTimeFormat.supportedLocalesOf(listed); +} + +/** Exit status of a child process running `source`. */ +function exitOf(source) { + return spawnSync(process.execPath, ["--input-type=module", "-e", source], { + encoding: "utf8", + timeout: 60_000, + }); +} + +if (!existsSync(join(DIST, "internal/weekYearGuard.js"))) { + console.error("packages/gmt/dist is missing: run pnpm build first"); + process.exit(2); +} +const { guardDateTimeFormat } = await import( + pathToFileURL(join(DIST, "internal/weekYearGuard.js")).href +); + +const failures = []; +const counts = { formatters: 0, flagged: 0, unflagged: 0, crashed: 0 }; +const calendars = argument("calendars") ?? Intl.supportedValuesOf("calendar"); + +for (const locale of localeList()) { + const unflagged = []; + for (const calendar of calendars) { + for (const options of OPTION_SETS) { + const full = { ...options, calendar, timeZone: "UTC" }; + let native; + try { + native = new Intl.DateTimeFormat(locale, full); + } catch { + continue; + } + counts.formatters++; + const guarded = guardDateTimeFormat(native, full); + if (guarded === native) { + counts.unflagged++; + unflagged.push({ calendar, options: full }); + continue; + } + counts.flagged++; + for (const ms of DATES) { + const text = guarded.format(ms); + const parts = guarded.formatToParts(ms); + if ( + parts.length === 0 || + parts.map((part) => part.value).join("") !== text + ) { + failures.push({ + locale, + calendar, + options, + ms, + why: "parts do not join to the text", + text, + parts, + }); + } + } + } + } + if (unflagged.length > 0) { + const run = exitOf( + `for (const o of ${JSON.stringify(unflagged)}) for (const ms of ${JSON.stringify(DATES)})` + + ` new Intl.DateTimeFormat(${JSON.stringify(locale)}, { ...o.options }).formatToParts(ms);`, + ); + if (run.status !== 0) { + counts.crashed++; + failures.push({ + locale, + why: `unflagged formatter crashed (exit ${run.status}): a guard false negative`, + }); + } + } +} + +// The D23 reading and the abort must agree (Node only). +const gd = { year: "numeric", month: "short", timeZone: "UTC" }; +const resolvedYear = new Intl.DateTimeFormat("gd", gd).resolvedOptions().year; +const child = exitOf( + `new Intl.DateTimeFormat("gd", ${JSON.stringify(gd)}).formatToParts(0);`, +); +const aborts = child.status !== 0; +console.log( + `V8 ${process.versions.v8 ?? "none"}: resolvedOptions().year ${resolvedYear}, formatToParts exit ${child.status}`, +); +if ((resolvedYear === undefined) !== aborts) { + failures.push({ + why: "resolvedOptions().year and the abort disagree: the D23 crash signal no longer holds", + }); +} + +console.log(JSON.stringify(counts)); +for (const failure of failures) { + console.log(JSON.stringify(failure)); +} +process.exit(failures.length === 0 ? 0 : 1); diff --git a/scripts/lib/workarounds.mjs b/scripts/lib/workarounds.mjs index 8fdc2a01a..cc1856346 100644 --- a/scripts/lib/workarounds.mjs +++ b/scripts/lib/workarounds.mjs @@ -202,7 +202,7 @@ export const WORKAROUNDS = [ trigger: "an ICU release that fixes ICU-20548 is bundled by GMT's engines.node floor (>=22.16.0) and by every browser the native suite runs, so every D16 repro passes on every engine: this check reports Node, and the weekly run's compat check in each browser (the temporal-compat-chromium, -firefox, -webkit and -webkit-macos verdicts) reports the rest; D16 is removable only when all of them say so", steps: [ - "Delete the zoneNames branch of rangeWithRepairedParts and its gate in zoned/format/formatZonedRange.ts, isRangeZoneNameCompatNeeded in capabilities.ts and its export in index.ts, and the D16 repros.", + "Delete rangeWithRepairedZoneNames, the zoneNames branch of rangeWithRepairedParts and their gate in zoned/format/formatZonedRange.ts, internal/repairRangeText.ts and its test, isRangeZoneNameCompatNeeded in capabilities.ts and its export in index.ts, and the D16 repros.", "Keep every formatZonedRange row: their values are the field formats and hold either way.", `Full wording: ${COMPAT_README} § Removal steps 16.`, ], @@ -287,6 +287,79 @@ export const WORKAROUNDS = [ `Full wording: ${COMPAT_README} § Removal steps 22.`, ], }, + { + defects: ["D23"], + engines: ["v8"], + title: + "D23 — formatToParts and formatRangeToParts abort V8 on a week-of-year year field (nodejs/node#67076)", + trigger: + "every V8 the check reads (Node at the engines.node floor, and the temporal-compat-chromium verdict) passes the D23 repro: a gd formatter with year numeric and month short resolves a year, and the Node child-process confirmation of scripts/canary/weekYear.mjs exits 0 with a year part", + steps: [ + "Delete weekYearSynth.ts and its test, the crash signal and path B in weekYearGuard.ts (a flagged formatter takes native parts with the year patched everywhere), and the D23 repro in repros.ts.", + "Keep every expected-value row: the values are ECMA-402's and hold either way.", + `Full wording: ${COMPAT_README} § Removal steps 23.`, + ], + }, + { + defects: ["D24"], + title: + "D24 — CLDR date patterns print the week-of-year year where the calendar year is meant (internal/weekYearGuard.ts)", + trigger: + "every engine's compat verdict passes every D24 repro, and the weekly sweep of scripts/canary/weekYear.mjs flags no locale, calendar or option set", + steps: [ + "Delete weekYearGuard.ts, weekYearSynth.ts, weekYearText.ts, weekYearRange.ts and its tests, the formatRangeChecked calls in formatDateRange.ts, formatDateTimeRange.ts and formatZonedRange.ts, the construct hook and forgetWeekYearVerdicts call in formatterCache.ts, weekYearSource.test.ts and the D24 repros in repros.ts.", + "Keep every expected-value row (weekYearSingle.test.ts and the abort rows): the values are ECMA-402's and hold either way.", + `Full wording: ${COMPAT_README} § Removal steps 24.`, + ], + }, + { + defects: ["D25"], + title: + "D25 — the japanese calendar prints Japanese eras before 1873-01-01 (internal/yearPrinting.ts)", + trigger: + "every engine's compat verdict passes both D25 repros: en-u-ca-japanese prints 2 BC for ISO -0001-07-10 and 1872 AD for 1872-12-31 (tc39/proposal-intl-era-monthcode#86, tc39/test262#4877)", + steps: [ + "Delete the era branch of repairYearPrinting in yearPrinting.ts (beforeEras, the Gregorian twin, the era flag), isJapaneseEraCompatNeeded in capabilities.ts and the D25 repros in repros.ts.", + "Keep every D25 row in yearPrinting.test.ts: the values are the proposal's and hold either way.", + `Full wording: ${COMPAT_README} § Removal steps 25.`, + ], + }, + { + defects: ["D26"], + title: + "D26 — an islamic calendar prints a negative year before the Hijra (internal/yearPrinting.ts)", + trigger: + "every engine's compat verdict passes the D26 repro: en-u-ca-islamic-civil prints a different era text for ISO 600-07-10 and 2025-07-10", + steps: [ + "Delete the Hijra branch of repairYearPrinting in yearPrinting.ts (beforeHijra, the islamic flag), isIslamicEraCompatNeeded in capabilities.ts and the D26 repro in repros.ts. guardedDateTimeFormat in formatterCache.ts stays while D18 does.", + "Keep the D26 rows except those that assert the empty value, which a fixed engine replaces with the era's text.", + `Full wording: ${COMPAT_README} § Removal steps 26.`, + ], + }, + { + defects: ["D27"], + title: + "D27 — ja japanese year 2-digit leaves the era year unpadded (internal/yearPrinting.ts)", + trigger: + "every engine's compat verdict passes the D27 repro: ja-u-ca-japanese with year 2-digit prints 令和06年 for 2024-07-10", + steps: [ + "Delete the padding branch of repairYearPrinting in yearPrinting.ts (padPart, paddedRange, shiftOf, the pad flag), isJapaneseTwoDigitYearCompatNeeded in capabilities.ts and the D27 repro in repros.ts.", + "Keep every D27 row: 令和06年 and 元 are the values either way.", + `Full wording: ${COMPAT_README} § Removal steps 27.`, + ], + }, + { + defects: ["D28"], + title: + "D28 — chinese and dangi pad the related year under year 2-digit (internal/yearPrinting.ts)", + trigger: + "every engine's compat verdict passes the D28 repro: en-u-ca-chinese with year 2-digit prints the related year 5 for ISO 0005-07-10", + steps: [ + "Delete widenRelatedYear in yearPrinting.ts and its call in guardedDateTimeFormat (formatterCache.ts), isRelatedYearWidthCompatNeeded in capabilities.ts and the D28 repro in repros.ts; with D25 to D27 gone too, delete yearPrinting.ts and its hook in construct.", + "Keep every D28 row: the related year at full width is ECMA-402's value.", + `Full wording: ${COMPAT_README} § Removal steps 28.`, + ], + }, { defects: ["D9"], title: diff --git a/scripts/upstream.mjs b/scripts/upstream.mjs index b4425ec61..9e545443f 100644 --- a/scripts/upstream.mjs +++ b/scripts/upstream.mjs @@ -371,14 +371,14 @@ async function fetchSyncedAsync(repo, number, kind, timeout) { // ---------------------------------------------------------------- guard groups -/** Every `DefectId` / `ZonedDefectId` / `BoundedWorkDefectId` literal `probeRepros.ts` and `repros.ts` declare. */ +/** Every `DefectId` / `ZonedDefectId` / `BoundedWorkDefectId` / `CanaryDefectId` literal `probeRepros.ts` and `repros.ts` declare. */ function knownGuards() { const src = REPROS.map((path) => readFileSync(`${ROOT}${path}`, "utf8")).join( "\n", ); const guards = new Set(); for (const m of src.matchAll( - /export type (?:DefectId|ZonedDefectId|BoundedWorkDefectId) =([^;]+);/g, + /export type (?:DefectId|ZonedDefectId|BoundedWorkDefectId|CanaryDefectId) =([^;]+);/g, )) { for (const lit of m[1].matchAll(/"([^"]+)"/g)) guards.add(lit[1]); } From 44f0b717ca0fc22ef151553f1a352039df4d7a4c Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sat, 14 Nov 2026 09:04:14 +0200 Subject: [PATCH 04/12] perf(core): key the week-year verdict on the resolved pattern, not every raw option (CORE-112, #524) The verdict cache keyed on every option value, so values Intl ignores, such as `calendar: always`, each built a UTC twin and ran the week-year check, and thrashed the 256-entry cache. The key is now the resolved locale, calendar, numbering system and hour cycle plus the options that choose the pattern. The optionsObject formatYearMonth test drops from 6.8 s to 1.4 s on Node 22 and 26; it timed out at 30 s on the Node 22 TZ jobs. --- packages/gmt/src/internal/weekYearGuard.ts | 27 +++++++++++----------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/packages/gmt/src/internal/weekYearGuard.ts b/packages/gmt/src/internal/weekYearGuard.ts index e8ac41ef7..52752b447 100644 --- a/packages/gmt/src/internal/weekYearGuard.ts +++ b/packages/gmt/src/internal/weekYearGuard.ts @@ -204,22 +204,23 @@ function textSource( return new Intl.DateTimeFormat(resolved.locale, twin); } -/** The verdict-cache key: the pattern, never the zone (a zone moves the instant, not the pattern). */ +/** + * The verdict-cache key: the pattern, never the zone (a zone moves the instant, not the pattern). + * Only the options that choose the pattern are read; locale, calendar, numbering system and hour + * cycle come from what the formatter resolved, so a value `Intl` ignores or resolves to the same + * thing (`calendar: "always"`, `hour12` next to an `hourCycle`) shares one verdict. + */ function verdictKey( options: Intl.DateTimeFormatOptions, resolved: Intl.ResolvedDateTimeFormatOptions, -): string | null { - const entries = plainOptionEntries(options); - if (entries === null) { - return null; - } - const rest = entries.filter(([name]) => name !== "timeZone"); +): string { return JSON.stringify([ resolved.locale, resolved.calendar, resolved.numberingSystem, resolved.hourCycle ?? "", - rest, + options.formatMatcher ?? "", + [...DATE_KEYS, ...TIME_KEYS].map((key) => options[key] ?? ""), ]); } @@ -234,7 +235,7 @@ function isFlagged( verdictsBuiltWith = Intl.DateTimeFormat; } const key = verdictKey(options, resolved); - const known = key === null ? undefined : verdicts.get(key); + const known = verdicts.get(key); if (known !== undefined) { return known; } @@ -244,12 +245,10 @@ function isFlagged( resolved.calendar, resolved.numberingSystem, ); - if (key !== null) { - if (verdicts.size >= MAX_VERDICTS) { - verdicts.clear(); - } - verdicts.set(key, flagged); + if (verdicts.size >= MAX_VERDICTS) { + verdicts.clear(); } + verdicts.set(key, flagged); return flagged; } From 4cd85509b0aeb69934f27bd0f0bcfd9760bf19d5 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sat, 14 Nov 2026 10:18:02 +0200 Subject: [PATCH 05/12] test(canary): count D23 as out of scope on the WebKit leg D23 names only V8, so the native-suite check reports it out of scope on WebKit. The fake-browser test still expected one out-of-scope group; it now expects two and checks D23's state like D17's. --- apps/dox/scripts/canary/native-suite-compat.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/dox/scripts/canary/native-suite-compat.test.ts b/apps/dox/scripts/canary/native-suite-compat.test.ts index 9002af6c4..a41eb9247 100644 --- a/apps/dox/scripts/canary/native-suite-compat.test.ts +++ b/apps/dox/scripts/canary/native-suite-compat.test.ts @@ -333,14 +333,18 @@ describe("runBrowserCompat with a fake browser", () => { expect(verdict.counts).toEqual({ workarounds: WORKAROUNDS.length, stillNeeded: 0, - removable: WORKAROUNDS.length - 2, + removable: WORKAROUNDS.length - 3, guard: 1, - outOfScope: 1, + outOfScope: 2, }); expect(verdict.workarounds.find((w) => w.id === "D17")).toMatchObject({ state: "out-of-scope", engines: ["firefox"], }); + expect(verdict.workarounds.find((w) => w.id === "D23")).toMatchObject({ + state: "out-of-scope", + engines: ["v8"], + }); expect(verdict.workarounds.find((w) => w.id === "D19")).toMatchObject({ state: "removable", engines: ["webkit"], From 35767d13a7e99096cd261dcff8e6fe0a638547ac Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sun, 15 Nov 2026 09:18:51 +0200 Subject: [PATCH 06/12] feat(dox): Pulse page, and date ranges that print every field (DOX-G9, #522; CORE-112, #524) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Date ranges (CORE-112, D29): - `formatDateRange`, `formatDateTimeRange` and `formatZonedRange` check the range against the single dates field by field, as ECMA-402 Table 6 compares field values, and fall back to the two single dates only for a pattern class the engine prints wrong. - The gate covers 18 cases: a dropped, repeated or misplaced field, a missing era, the `ja` hour 12 under `hourCycle: h12` and the long day period printed short. - Islamic dates before the Hijra print an empty string; `ja` keeps 元年 and pads the rest. - A new weekly CLDR sweep runs the week-year and range-field detectors over every locale and calendar on Node 22, 24 and 26, and lists the locales that newly break or are fixed. - Upstream: CLDR-19912 (comment), CLDR-19913, ICU-23622, ICU-23623, ICU-23624 and ICU-23625. - Root bundle budget raised to 647000, and the four entry budgets that carry range formatting raised to match. Pulse (DOX-G9): - New `/pulse/` page in Start here: every scheduled check, what it watches, when it runs, its recent runs and the condition that retires it. The run history is read from GitHub at build only, best effort. - Badges, plates and cards across the site get bevelled corners, and the /upstream rows are reworked. Also refresh the compat snapshot (33 groups), the stats and the upstream filings, and add `postcss` as a Dox dev dependency for the bevel border test. --- .changeset/core-112-week-year.md | 9 + .fallowrc.jsonc | 37 + .github/workflows/ci.yml | 4 + .github/workflows/cldr-sweep-weekly.yml | 121 ++ .github/workflows/deploy-dox.yml | 4 +- .github/workflows/dox-gates-weekly.yml | 3 +- .github/workflows/leap-seconds.yml | 8 +- .github/workflows/temporal-oracle.yml | 8 +- .github/workflows/us-clock-watch.yml | 9 +- apps/dox/package.json | 3 +- apps/dox/scripts/build-pulse.mjs | 452 ++++++++ apps/dox/scripts/build-pulse.test.ts | 337 ++++++ apps/dox/scripts/llms.test.ts | 24 +- .../src/components/UpstreamDefectRow.astro | 5 +- .../src/components/UpstreamFilingRow.astro | 20 +- apps/dox/src/components/UpstreamTracker.astro | 12 +- .../components/UpstreamTrackerSummary.astro | 2 +- apps/dox/src/components/pulse/Pulse.astro | 37 + .../dox/src/components/pulse/PulseBeats.astro | 11 + apps/dox/src/components/pulse/PulseCard.astro | 11 + apps/dox/src/components/pulse/PulseLife.astro | 10 + .../src/components/pulse/PulseSummary.astro | 7 + apps/dox/src/content/docs/bundle-size.mdx | 2 +- apps/dox/src/content/docs/native-engines.mdx | 2 +- apps/dox/src/content/docs/pulse.mdx | 17 + apps/dox/src/content/docs/upstream.mdx | 6 +- apps/dox/src/data/gmt-stats.json | 6 +- apps/dox/src/data/pulse.ts | 179 +++ apps/dox/src/data/temporal-compat.json | 65 ++ apps/dox/src/data/temporal-compat.test.ts | 12 +- apps/dox/src/data/temporal-compat.ts | 10 +- apps/dox/src/data/upstream-filings.json | 409 ++++++- apps/dox/src/data/upstream-filings.test.ts | 274 ++++- apps/dox/src/data/upstream-filings.ts | 251 +++- apps/dox/src/data/upstream-trackers.test.ts | 337 ++++++ apps/dox/src/lib/bevel-border-widths.test.ts | 305 +++++ apps/dox/src/lib/mdx-jsx.ts | 80 +- apps/dox/src/lib/native-engines.test.ts | 8 +- apps/dox/src/lib/pulse-mount.test.ts | 97 ++ apps/dox/src/lib/pulse-mount.ts | 134 +++ apps/dox/src/lib/pulse-view.test.ts | 137 +++ apps/dox/src/lib/pulse-view.ts | 223 ++++ apps/dox/src/lib/runtime-tz-canary.test.ts | 2 + apps/dox/src/lib/section-order.ts | 5 +- apps/dox/src/lib/top-level-pages.test.ts | 16 +- apps/dox/src/lib/upstream-badges.test.ts | 68 +- apps/dox/src/lib/upstream-badges.ts | 48 +- .../dox/src/widgets/builders/badge.module.css | 29 +- .../widgets/builders/disclosure.module.css | 12 + .../src/widgets/builders/disclosure.test.ts | 27 + apps/dox/src/widgets/builders/disclosure.ts | 7 +- .../src/widgets/builders/plates.module.css | 8 +- .../src/widgets/builders/timeline.module.css | 49 + .../dox/src/widgets/builders/timeline.test.ts | 23 + apps/dox/src/widgets/builders/timeline.ts | 16 +- .../src/widgets/builders/verdict.module.css | 7 +- .../families/edi/edi-figure.module.css | 8 +- .../families/gnss/clock-ladder.module.css | 9 +- .../families/gnss/fuse-status.module.css | 7 +- .../families/holiday/rule-card.module.css | 7 +- .../families/holiday/signal-plates.module.css | 8 +- .../families/ids/format-card.module.css | 22 +- .../families/ids/instant-hero.module.css | 8 +- .../families/ledger/bl-plot.module.css | 9 +- .../families/pulse/pulse-template.test.ts | 85 ++ .../widgets/families/pulse/pulse-template.ts | 296 +++++ .../widgets/families/pulse/pulse.module.css | 207 ++++ .../punctuality/punct-board.module.css | 8 +- .../punctuality/punct-hero.module.css | 11 +- .../families/stored/stored-lanes.module.css | 7 +- .../families/timescale/drift-lanes.module.css | 8 +- .../families/timescale/scale-stack.module.css | 7 +- .../transport/journey-ribbons.module.css | 8 +- .../widgets/tools/departure-board.module.css | 7 +- .../tools/observance-comparator.module.css | 17 +- context/canary/overview.md | 35 +- context/domination/issues/CORE-112.md | 11 +- .../domination/js-temporal-polyfill-bugs.md | 96 +- .../specs/CORE-112/canary-and-docs.md | 11 + context/domination/specs/CORE-112/index.md | 58 +- .../specs/CORE-112/year-printing.md | 184 ++- context/dox/built.md | 16 +- context/dox/reference/visual-design.md | 4 + context/dox/specs/dox-g9/index.md | 152 +++ context/dox/tracker.md | 2 +- package.json | 2 + packages/gmt/src/internal/formatterCache.ts | 76 +- .../islamicCalendarResolution.test.ts | 136 +++ packages/gmt/src/internal/japaneseNumerals.ts | 86 ++ packages/gmt/src/internal/patternKey.ts | 45 + packages/gmt/src/internal/rangeBundle.test.ts | 110 ++ .../gmt/src/internal/rangeDetector.test.ts | 376 ++++++ packages/gmt/src/internal/rangeDetector.ts | 840 ++++++++++++++ .../gmt/src/internal/rangeFallback.test.ts | 71 ++ packages/gmt/src/internal/rangeFallback.ts | 171 +++ packages/gmt/src/internal/rangeFieldValues.ts | 218 ++++ packages/gmt/src/internal/rangeFields.test.ts | 386 +++++++ packages/gmt/src/internal/rangeFields.ts | 231 ++++ packages/gmt/src/internal/rangeHooks.ts | 98 ++ packages/gmt/src/internal/rangeRepairs.ts | 33 + .../gmt/src/internal/temporalCompat/README.md | 28 +- .../internal/temporalCompat/capabilities.ts | 55 + .../temporalCompat/rangeFieldRepros.ts | 302 +++++ .../gmt/src/internal/temporalCompat/repros.ts | 93 +- .../temporalCompat/weekYearSource.test.ts | 34 +- .../temporalCompat/yearPrintingProbes.test.ts | 29 +- packages/gmt/src/internal/weekYearGuard.ts | 62 +- .../gmt/src/internal/weekYearRange.test.ts | 2 +- packages/gmt/src/internal/weekYearRange.ts | 26 +- .../gmt/src/internal/yearPrinting.test.ts | 297 ++++- packages/gmt/src/internal/yearPrinting.ts | 223 ++-- .../src/internal/yearPrintingDormant.test.ts | 90 +- .../gmt/src/internal/yearPrintingRange.ts | 360 ++++++ .../src/plain/format/formatDateRange.test.ts | 22 + .../gmt/src/plain/format/formatDateRange.ts | 4 +- .../plain/format/formatDateTimeRange.test.ts | 19 + .../src/plain/format/formatDateTimeRange.ts | 4 +- .../gmt/src/zoned/format/formatZonedRange.ts | 156 ++- .../format/formatZonedRangeFields.test.ts | 97 ++ pnpm-lock.yaml | 3 + scripts/bundle-size.budgets.json | 10 +- scripts/canary/rangeFields.mjs | 1021 +++++++++++++++++ scripts/canary/weekYear.mjs | 50 +- scripts/lib/affected.mjs | 14 +- scripts/lib/cldr-locales.mjs | 61 + scripts/lib/pulse.mjs | 200 ++++ scripts/lib/upstream-trackers.mjs | 319 +++++ scripts/lib/workarounds.mjs | 36 +- scripts/upstream.mjs | 621 ++++++---- 129 files changed, 11574 insertions(+), 856 deletions(-) create mode 100644 .github/workflows/cldr-sweep-weekly.yml create mode 100644 apps/dox/scripts/build-pulse.mjs create mode 100644 apps/dox/scripts/build-pulse.test.ts create mode 100644 apps/dox/src/components/pulse/Pulse.astro create mode 100644 apps/dox/src/components/pulse/PulseBeats.astro create mode 100644 apps/dox/src/components/pulse/PulseCard.astro create mode 100644 apps/dox/src/components/pulse/PulseLife.astro create mode 100644 apps/dox/src/components/pulse/PulseSummary.astro create mode 100644 apps/dox/src/content/docs/pulse.mdx create mode 100644 apps/dox/src/data/pulse.ts create mode 100644 apps/dox/src/data/upstream-trackers.test.ts create mode 100644 apps/dox/src/lib/bevel-border-widths.test.ts create mode 100644 apps/dox/src/lib/pulse-mount.test.ts create mode 100644 apps/dox/src/lib/pulse-mount.ts create mode 100644 apps/dox/src/lib/pulse-view.test.ts create mode 100644 apps/dox/src/lib/pulse-view.ts create mode 100644 apps/dox/src/widgets/families/pulse/pulse-template.test.ts create mode 100644 apps/dox/src/widgets/families/pulse/pulse-template.ts create mode 100644 apps/dox/src/widgets/families/pulse/pulse.module.css create mode 100644 context/dox/specs/dox-g9/index.md create mode 100644 packages/gmt/src/internal/islamicCalendarResolution.test.ts create mode 100644 packages/gmt/src/internal/japaneseNumerals.ts create mode 100644 packages/gmt/src/internal/patternKey.ts create mode 100644 packages/gmt/src/internal/rangeBundle.test.ts create mode 100644 packages/gmt/src/internal/rangeDetector.test.ts create mode 100644 packages/gmt/src/internal/rangeDetector.ts create mode 100644 packages/gmt/src/internal/rangeFallback.test.ts create mode 100644 packages/gmt/src/internal/rangeFallback.ts create mode 100644 packages/gmt/src/internal/rangeFieldValues.ts create mode 100644 packages/gmt/src/internal/rangeFields.test.ts create mode 100644 packages/gmt/src/internal/rangeFields.ts create mode 100644 packages/gmt/src/internal/rangeHooks.ts create mode 100644 packages/gmt/src/internal/rangeRepairs.ts create mode 100644 packages/gmt/src/internal/temporalCompat/rangeFieldRepros.ts create mode 100644 packages/gmt/src/internal/yearPrintingRange.ts create mode 100644 packages/gmt/src/zoned/format/formatZonedRangeFields.test.ts create mode 100644 scripts/canary/rangeFields.mjs create mode 100644 scripts/lib/cldr-locales.mjs create mode 100644 scripts/lib/pulse.mjs create mode 100644 scripts/lib/upstream-trackers.mjs diff --git a/.changeset/core-112-week-year.md b/.changeset/core-112-week-year.md index 414fdcbfa..40bb7dc6c 100644 --- a/.changeset/core-112-week-year.md +++ b/.changeset/core-112-week-year.md @@ -3,3 +3,12 @@ --- Formatting no longer stops Node with a crash, and prints the right year, in languages whose date patterns print the year a week belongs to instead of the calendar year. `formatZonedRange`, `formatCalendar` and the `…ToParts` functions stopped Node 22, 24 and 26 with a crash for some languages and calendars, for example Burmese with the Buddhist calendar, and Galician with the Hebrew, Buddhist or ROC calendar and a full date style. Every format function also printed the wrong year near the start or end of a year, or all year in the Buddhist, Japanese and ROC calendars: Scottish Gaelic printed `Dùbh 2025` for 30 December 2024, and now prints `Dùbh 2024`. + +Some calendars and languages printed a year or a range that the specifications do not give, and now print the specifications' text: + +- The Japanese calendar before 1873, when Japan adopted it, printed an era year: `Dec 31, 5 Meiji` for 31 December 1872 is now `Dec 31, 1872 AD`. +- An Islamic date before the Hijra printed a negative year such as `-23 AH`, and is now the empty value. +- Japanese with the Japanese calendar and a two-digit year printed `令和6年`, and now prints `令和06年`. The first year of an era stays `元年`. With another numbering system the era year printed Latin digits, and now prints that system's digits: `ja-u-ca-japanese-nu-arab` printed `令和6年` and now prints `令和٦年`. +- The Chinese and Dangi calendars with a two-digit year padded the related year, which has no two-digit form: `05(yi-chou)` for the year 5 is now `5(yi-chou)`. +- A range whose language's interval pattern drops or repeats a field, such as the year of a Chinese-calendar range across two years, prints both dates in full, joined by the language's own range separator. +- A language with the `islamic` calendar printed the astronomical Hijri date (`Muh. 5, 1446 AH` for 10 July 2024). It now prints the tabular `islamic-tbla` date (`Muh. 4, 1446 AH`), and `islamic-rgsa` prints the language's default calendar. diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index 49fe5a583..19c6e99fc 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -8,6 +8,8 @@ "scripts/lib/native-suite-reporter.mjs", // The weekly D23/D24 locale sweep (CORE-112), run by hand or from a workflow. "scripts/canary/weekYear.mjs", + // The weekly D29 range sweep (CORE-112); it starts itself as a child process. + "scripts/canary/rangeFields.mjs", "packages/gmt/bench/*.bench.ts", "packages/gmt/src/test/*.browser.ts", "packages/gmt/src/test/boundedWorker.ts", @@ -56,6 +58,41 @@ "maxCrap": 70, "reason": "D24 range verdict: cyclomatic and cognitive are inside the limits; the CRAP figure is estimated from export references because these helpers are not exported, and weekYearRange.test.ts covers every branch through rangeYearVerdict", }, + { + "files": ["packages/gmt/src/internal/rangeDetector.ts"], + "functions": [ + "judge", + "rangeVerdict", + "isAbsent", + "probeKind", + "", + ], + "maxCyclomatic": 30, + "maxCognitive": 30, + "maxCrap": 150, + "reason": "D29 range detector kernel: judge and the per-probe check branch once per field class (year, month, day, day period, hour, minute, era); rangeDetector.test.ts covers each verdict and its broken field class, and the three-engine sweep exercises every branch, while fallow estimates CRAP from export references because the helpers are not exported", + }, + { + "files": ["packages/gmt/src/internal/rangeFieldValues.ts"], + "functions": ["rowsOf"], + "maxCrap": 40, + "reason": "D29 field-value rows (ECMA-402 Table 6): cyclomatic 11 and cognitive 8 are inside the limits, and the CRAP figure is estimated from export references because rowsOf is unexported; rangeFields.test.ts and yearPrinting.test.ts reach every row through rangeFieldsEqual", + }, + { + "files": ["packages/gmt/src/internal/weekYearSynth.ts"], + "functions": ["textTwinOptions", "timeTwinOptions", "fits"], + "maxCrap": 40, + "reason": "D23 week-year parts synthesis: cyclomatic 10 and cognitive at most 13 are inside the limits, and the CRAP figure is estimated from export references because each helper is unexported; weekYearSingle.test.ts covers each branch through guardedDateTimeFormat", + }, + { + "files": [ + "packages/gmt/src/internal/yearPrinting.ts", + "packages/gmt/src/zoned/format/formatZonedRange.ts", + ], + "functions": ["formatRange", "zonedRangeText", "twinParts"], + "maxCrap": 70, + "reason": "CORE-112 range repairs: cyclomatic (at most 11) and cognitive (at most 11) are inside the limits; the CRAP figure is estimated from export references because each is a closure or an unexported helper, and yearPrinting.test.ts, rangeFields.test.ts and formatZonedRange*.test.ts cover each branch through the public range functions", + }, { "files": ["packages/gmt/src/internal/patternToken.ts"], "functions": [ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5b9f7c1e..7d1244ab7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -243,6 +243,10 @@ jobs: if: contains(fromJSON(env.CHECKS), 'upstream') run: node scripts/upstream.mjs check + - name: Pulse checks match the workflows + if: contains(fromJSON(env.CHECKS), 'pulse') + run: node apps/dox/scripts/build-pulse.mjs --check + # Some content pages are generated, not committed: `guides/concepts/dst-disambiguation.md` # (copied from the canonical `docs/dst-disambiguation.md`), the `changelog/` pages (built # from each package's CHANGELOG.md), `scenarios/index.mdx`, `tools/index.mdx` and the diff --git a/.github/workflows/cldr-sweep-weekly.yml b/.github/workflows/cldr-sweep-weekly.yml new file mode 100644 index 000000000..8045552f7 --- /dev/null +++ b/.github/workflows/cldr-sweep-weekly.yml @@ -0,0 +1,121 @@ +name: CLDR sweep weekly + +# Pulse check: cldr-sweep +# +# The week-year and range-field defects (D23, D24, D29 in packages/gmt/src/internal/temporalCompat) +# depend on the locale data inside each Node release, so no unit test can cover them. Once a week +# this sweep runs both detectors over every `cldr-dates-full` locale and every calendar, on Node 22, +# 24 and 26: scripts/canary/weekYear.mjs for week-of-year years and V8 aborts, and +# scripts/canary/rangeFields.mjs for a range that drops, repeats or garbles a field of one date. +# It is far too slow for ci.yml (about 160 CPU-minutes per Node), so it never runs there. +# +# A run fails only when a detector misses a defect the engine's own range parts confirm, or reports +# one they do not. A locale that is still broken does not fail it. Each leg writes a report and +# uploads it; the next run reads the report of the same leg from the previous run and lists, in the +# job summary, the locales that newly break and the ones that are fixed. No issue is filed and no +# token can write. +# +# Legs: rangeFields.mjs --shard i/n deals the sorted locales out round-robin, so the shards of one +# Node share the work. weekYear.mjs runs once per Node, on shard 1. Adding or removing a shard +# means changing the matrix. + +on: + workflow_dispatch: + schedule: + - cron: "23 3 * * 6" + +concurrency: + group: cldr-sweep-weekly + cancel-in-progress: false + +permissions: + actions: read + contents: read + +env: + # The job runs the Node it names, not the devEngines.runtime pin. + pnpm_config_verify_deps_before_run: "false" + +jobs: + sweep: + name: Sweep (${{ matrix.leg }}) + runs-on: ubuntu-latest + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + include: + - { leg: node22-1, node: 22, shard: "1/2" } + - { leg: node22-2, node: 22, shard: "2/2" } + - { leg: node24-1, node: 24, shard: "1/2" } + - { leg: node24-2, node: 24, shard: "2/2" } + - { leg: node26-1, node: 26, shard: "1/2" } + - { leg: node26-2, node: 26, shard: "2/2" } + steps: + - uses: actions/checkout@v7 + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node }} + check-latest: true + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile --no-runtime + + - name: Build the library + run: pnpm --filter @northguild/gmt build + + # The week-year sweep covers every locale in one pass, so only the first shard of each Node + # runs it. + - name: Week-year sweep + if: ${{ startsWith(matrix.shard, '1/') }} + run: node scripts/canary/weekYear.mjs + + - name: Range-field sweep (shard ${{ matrix.shard }}) + if: ${{ !cancelled() }} + run: > + node scripts/canary/rangeFields.mjs --shard ${{ matrix.shard }} + --out "$RUNNER_TEMP/range-fields-${{ matrix.leg }}.json" + + - name: Upload the report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: cldr-sweep-${{ matrix.leg }}-${{ github.run_id }} + path: ${{ runner.temp }}/range-fields-${{ matrix.leg }}.json + if-no-files-found: ignore + retention-days: 35 + + # Finds the newest earlier run of this workflow that finished and kept a report for this leg, + # then lists what changed. No earlier report is a note, never a failure. + - name: Compare with the previous run + if: ${{ !cancelled() }} + env: + GH_TOKEN: ${{ github.token }} + LEG: ${{ matrix.leg }} + run: | + current="$RUNNER_TEMP/range-fields-$LEG.json" + { + echo "## Range fields, $LEG" + echo + } >> "$GITHUB_STEP_SUMMARY" + if [ ! -f "$current" ]; then + echo "This run wrote no report." >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + previous="" + for run in $(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/cldr-sweep-weekly.yml/runs?status=completed&per_page=10" \ + --jq ".workflow_runs[] | select(.id != $GITHUB_RUN_ID and .conclusion != \"cancelled\") | .id" 2>/dev/null); do + if gh run download "$run" --repo "$GITHUB_REPOSITORY" --name "cldr-sweep-$LEG-$run" --dir "$RUNNER_TEMP/previous" 2>/dev/null; then + previous="$RUNNER_TEMP/previous/range-fields-$LEG.json" + break + fi + done + if [ -z "$previous" ] || [ ! -f "$previous" ]; then + echo "No earlier report for this leg, so there is nothing to compare." >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + node scripts/canary/rangeFields.mjs --diff "$previous" "$current" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/deploy-dox.yml b/.github/workflows/deploy-dox.yml index 2d8b9ace6..3e514a91d 100644 --- a/.github/workflows/deploy-dox.yml +++ b/.github/workflows/deploy-dox.yml @@ -1,5 +1,7 @@ name: Deploy Dox +# Pulse check: deploy-dox +# on: # After Release, never alongside it. Release runs on every push to main, so this # still deploys every merge. A push that publishes pushes its @@ -9,7 +11,7 @@ on: # or failure. # # Failure mode: if Release ever stops running on pushes to main (renamed, - # disabled, or given a path filter), merges stop deploying the docs. The daily + # disabled, or given a path filter), merges stop deploying the docs. The # schedule and workflow_dispatch below still deploy. workflow_run: workflows: [Release] diff --git a/.github/workflows/dox-gates-weekly.yml b/.github/workflows/dox-gates-weekly.yml index b80b7e113..c55b3ac79 100644 --- a/.github/workflows/dox-gates-weekly.yml +++ b/.github/workflows/dox-gates-weekly.yml @@ -1,5 +1,7 @@ name: Dox gates weekly +# Pulse check: dox-gates +# # The PR job (ci.yml, `dox-gates`) checks the changed pages in Chromium. This sweep checks every page # in three browsers and both themes, once a week, and files what fails as a `dox-gate` issue, one # open issue per finding (apps/dox/scripts/gates/issue-plan.mjs). A failing gate fails its leg; the @@ -26,7 +28,6 @@ on: required: false default: false schedule: - # Sundays 04:41 UTC. - cron: "41 4 * * 0" concurrency: diff --git a/.github/workflows/leap-seconds.yml b/.github/workflows/leap-seconds.yml index 5deff6566..5ee2ac2a3 100644 --- a/.github/workflows/leap-seconds.yml +++ b/.github/workflows/leap-seconds.yml @@ -1,8 +1,10 @@ name: Leap-second canary +# Pulse check: leap-seconds +# # Compares GMT's built-in leap-second table (packages/gmt/src/internal/leapSeconds.ts) with the # IERS Leap_Second.dat file, or with IANA's leap-seconds.list (the same IERS table) when IERS cannot -# be reached and the IANA file has not expired. Manual and weekly only: never part of ci.yml or +# be reached and the IANA file has not expired. Manual and scheduled only: never part of ci.yml or # `pnpm run validate`, because those runs have no network. A difference (IERS lists a row GMT does # not, or a row differs) opens or updates one `canary` issue carrying the IERS header line # ("Updated through IERS Bulletin …"); a run that cannot read either file opens or updates one @@ -10,9 +12,6 @@ name: Leap-second canary # plus a `patch` changeset. The dispatch input is a dry run: it files a clearly marked [dry run] # issue and changes no comparison or exit code. Issues are filed only from main: a run on another # branch lists what it would have filed in the job summary and files nothing. -# -# The table is closed (CGPM 2026 Resolution 5: continuous UTC from 20 May 2027). Retire this -# workflow and scripts/leap-seconds.mjs once IERS publishes its file format for continuous UTC. on: workflow_dispatch: @@ -23,7 +22,6 @@ on: required: false default: false schedule: - # Mondays 06:43 UTC - cron: "43 6 * * 1" concurrency: diff --git a/.github/workflows/temporal-oracle.yml b/.github/workflows/temporal-oracle.yml index 67f271553..defa4ba21 100644 --- a/.github/workflows/temporal-oracle.yml +++ b/.github/workflows/temporal-oracle.yml @@ -1,8 +1,13 @@ name: Temporal oracle +# Pulse check: workaround-node +# Pulse check: native-oracle +# Pulse check: native-suite +# Pulse check: polyfill-swap +# # Compares GMT's calendar results against Chromium's native Temporal (test262 is the final # authority where they disagree) and reports which @js-temporal/polyfill workarounds are still -# needed. Manual and weekly only: never part of ci.yml, because "upstream still broken" must +# needed. Manual and scheduled only: never part of ci.yml, because "upstream still broken" must # never fail a build. A failing oracle job means a GMT result differs from native Temporal on a # row that the script's tag list does not explain — a GMT bug to fix. # @@ -59,7 +64,6 @@ on: required: false default: false schedule: - # Mondays 06:17 UTC - cron: "17 6 * * 1" concurrency: diff --git a/.github/workflows/us-clock-watch.yml b/.github/workflows/us-clock-watch.yml index 19a1a1272..8db8d4055 100644 --- a/.github/workflows/us-clock-watch.yml +++ b/.github/workflows/us-clock-watch.yml @@ -1,9 +1,11 @@ name: US clock-change watch +# Pulse check: us-clock-watch +# # Compares three sources with the committed snapshot (scripts/us-clock-watch.snapshot.json): the # Congress.gov API and the Open States API for bills on the clock-change subject (new, or a changed # latest action), and the IANA tz database for any change to the rules of a zone in -# apps/dox/src/lib/us-region-zones.json. Manual and weekly only: never part of ci.yml or +# apps/dox/src/lib/us-region-zones.json. Manual and scheduled only: never part of ci.yml or # `pnpm run validate`, because those runs have no network or keys. A difference opens or updates one # `canary` issue per kind (federal, state, tz-us-zone); a source that cannot run (a network or HTTP # error, a 429, a body that does not parse, a missing secret) opens or updates one could-not-run @@ -12,10 +14,6 @@ name: US clock-change watch # nothing. The dispatch input is a dry run: it files a clearly marked [dry run] issue and changes no # comparison or exit code. Issues are filed only from main: a run on another branch lists what it # would have filed in the job summary and files nothing. -# -# Retirement (context/domination/issues/CORE-90.md, Decisions): the tz part when the US clock-change -# checker (CORE-90 phase 2) ships; the federal and state parts when the Proposals view's data is -# removed or replaced. on: workflow_dispatch: @@ -26,7 +24,6 @@ on: required: false default: false schedule: - # Mondays 07:17 UTC - cron: "17 7 * * 1" concurrency: diff --git a/apps/dox/package.json b/apps/dox/package.json index daa9832bf..2a38ff1e6 100644 --- a/apps/dox/package.json +++ b/apps/dox/package.json @@ -6,7 +6,7 @@ "license": "UNLICENSED", "type": "module", "scripts": { - "generate": "node ../../scripts/upstream.mjs refresh && node ./scripts/generate-version-map.mjs && node ../../scripts/syntax-floor.mjs --ts src/generated/syntax-floor.ts && tsx ./scripts/build-reference.ts && node ./scripts/build-guides.mjs && node ./scripts/build-changelog.mjs && node ./scripts/build-scenario-index.mjs && tsx ./scripts/build-tool-index.ts && tsx ./scripts/build-industry-pages.ts && tsx ./scripts/build-industry-sidebars.ts && node ./scripts/ensure-sidebar-order.mjs && node ../../scripts/bundle-size.mjs report --json src/generated/bundle-size.json && tsx ./scripts/build-corpus-counts.ts", + "generate": "node ../../scripts/upstream.mjs refresh && node ./scripts/build-pulse.mjs && node ./scripts/generate-version-map.mjs && node ../../scripts/syntax-floor.mjs --ts src/generated/syntax-floor.ts && tsx ./scripts/build-reference.ts && node ./scripts/build-guides.mjs && node ./scripts/build-changelog.mjs && node ./scripts/build-scenario-index.mjs && tsx ./scripts/build-tool-index.ts && tsx ./scripts/build-industry-pages.ts && tsx ./scripts/build-industry-sidebars.ts && node ./scripts/ensure-sidebar-order.mjs && node ../../scripts/bundle-size.mjs report --json src/generated/bundle-size.json && tsx ./scripts/build-corpus-counts.ts", "predev": "pnpm --filter @northguild/gmt build:dev", "dev": "pnpm run generate && node ./scripts/dev-all.mjs", "predev:site": "pnpm --filter @northguild/gmt build:dev", @@ -109,6 +109,7 @@ "oxlint": "^1.78.0", "pixelmatch": "7.2.0", "pngjs": "7.0.0", + "postcss": "8.5.31", "postcss-html": "1.8.1", "stylelint": "17.16.0", "stylelint-config-standard": "40.0.0", diff --git a/apps/dox/scripts/build-pulse.mjs b/apps/dox/scripts/build-pulse.mjs new file mode 100644 index 000000000..39f6d5dc1 --- /dev/null +++ b/apps/dox/scripts/build-pulse.mjs @@ -0,0 +1,452 @@ +#!/usr/bin/env node +/** + * Builds the data behind `/pulse/` and keeps the repo's list of checks honest. + * + * node scripts/build-pulse.mjs write src/generated/pulse.json, then read run history + * node scripts/build-pulse.mjs --check report drift between the list and the repo (`pnpm pulse:check`) + * node scripts/build-pulse.mjs --sync rewrite the table in context/canary/overview.md (`pnpm pulse:sync`) + * + * The one hand-written source is `scripts/lib/pulse.mjs`. This script reads each workflow with + * `yaml` (its name, its schedules, its jobs) and joins them to the list, so no cadence or job name + * is typed twice. The run history of every scheduled workflow is read from GitHub at build only, + * best effort, the way `scripts/upstream.mjs refresh` reads the filings: ten seconds in all, a six + * hour freshness window, no token or a 404 leaves the history empty, and the page says so. The + * history goes to the gitignored `src/generated/pulse-runs.live.json`. + * + * Nothing runs on import: the functions below take their inputs, so the tests use fixtures and an + * injected `gh`, clock and stamp. The stamp uses GMT when `packages/gmt` is built, and a build + * without it reads no history. + */ +import { execFile } from "node:child_process"; +import { + existsSync, + readdirSync, + readFileSync, + statSync, + writeFileSync, + mkdirSync, +} from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { parseDocument } from "yaml"; +import { formatJson } from "../../../scripts/lib/format-json.mjs"; +import { tryLoadGmt } from "../../../scripts/lib/gmt.mjs"; +import { PULSE_AREAS, PULSE_CHECKS } from "../../../scripts/lib/pulse.mjs"; +import { WORKAROUNDS } from "../../../scripts/lib/workarounds.mjs"; + +const execFileAsync = promisify(execFile); + +const HERE = dirname(fileURLToPath(import.meta.url)); +export const REPO_ROOT = join(HERE, "../../.."); +const GENERATED = join(HERE, "../src/generated"); +export const PULSE_FILE = join(GENERATED, "pulse.json"); +export const RUNS_FILE = join(GENERATED, "pulse-runs.live.json"); + +export const OVERVIEW_PATH = "context/canary/overview.md"; +export const OVERVIEW_START = ""; +export const OVERVIEW_END = ""; + +const RUNS_BUDGET_MS = 10_000; +const RUNS_TTL_MS = 6 * 60 * 60 * 1000; +const RUNS_CALL_MS = 4_000; +const RUNS_PER_WORKFLOW = 12; + +/** The id a workaround group goes by: its defects joined, as the compat page labels it. */ +export const groupId = (group) => group.defects.join(" + "); + +/** Reads one workflow file: its name, every `schedule[].cron` and the id and name of every job. */ +export function readWorkflow(root, rel) { + const doc = parseDocument(readFileSync(join(root, rel), "utf8")); + if (doc.errors.length > 0) { + throw new Error(`${rel}: ${doc.errors[0].message}`); + } + const data = doc.toJS() ?? {}; + const on = data.on ?? {}; + const schedule = Array.isArray(on.schedule) ? on.schedule : []; + return { + name: typeof data.name === "string" ? data.name : rel, + crons: schedule.map((s) => s.cron).filter((c) => typeof c === "string"), + jobs: Object.entries(data.jobs ?? {}).map(([id, job]) => ({ + id, + name: typeof job?.name === "string" ? job.name : id, + })), + }; +} + +/** Every workflow file under `.github/workflows` that has an `on.schedule`, relative to the root. */ +export function scheduledWorkflows(root) { + const dir = join(root, ".github/workflows"); + if (!existsSync(dir)) return []; + return readdirSync(dir) + .filter((f) => /\.ya?ml$/.test(f)) + .sort() + .map((f) => `.github/workflows/${f}`) + .filter((rel) => readWorkflow(root, rel).crons.length > 0); +} + +const SKIP_DIRS = new Set(["node_modules", "dist", ".git", "generated"]); + +/** Files under `dir` (relative to `root`) whose name matches `test`, skipping dependency folders. */ +function findFiles(root, dir, test) { + const out = []; + const walk = (rel) => { + const abs = join(root, rel); + if (!existsSync(abs)) return; + for (const entry of readdirSync(abs, { withFileTypes: true })) { + if (entry.isDirectory()) { + if (!SKIP_DIRS.has(entry.name)) walk(`${rel}/${entry.name}`); + } else if (test(entry.name)) { + out.push(`${rel}/${entry.name}`); + } + } + }; + walk(dir); + return out.sort(); +} + +/** The workflow-or-test sources the list names, in list order, each once, with the checks it holds. */ +export function sourcesOf(checks) { + const map = new Map(); + for (const check of checks) { + if (!map.has(check.source)) map.set(check.source, []); + map.get(check.source).push(check); + } + return map; +} + +/** What `pulse.json` holds: the list joined with what the workflow files say. */ +export function buildPulse({ root = REPO_ROOT, checks = PULSE_CHECKS } = {}) { + const cards = []; + for (const [source, held] of sourcesOf(checks)) { + const isWorkflow = source.startsWith(".github/workflows/"); + const workflow = isWorkflow ? readWorkflow(root, source) : null; + cards.push({ + source, + file: source.split("/").at(-1), + kind: isWorkflow ? "workflow" : "test", + name: workflow?.name ?? held[0].name, + crons: workflow?.crons ?? [], + jobs: workflow?.jobs ?? [], + checkIds: held.map((c) => c.id), + }); + } + return { + areas: PULSE_AREAS, + checks: checks.map((c) => ({ ...c })), + cards, + workaroundGroups: WORKAROUNDS.map(groupId), + }; +} + +/** Whether a source file carries `Pulse check: ` in a comment. */ +const carriesTag = (text, id) => + new RegExp(`^\\s*(?:#|//|\\*)\\s*Pulse check:\\s*${id}\\s*$`, "m").test(text); + +/** A comment line that talks about retiring something: the list says it, not the source file. */ +const RETIRE_PROSE = + /^\s*(?:#|\/\/|\*)(?!\s*Pulse check:).*\bretire(?:s|d|ment)?\b/im; + +/** The plain-words cell for a check's life. */ +export function lifeText(life) { + switch (life.kind) { + case "permanent": + return `Stays. ${life.why}`; + case "workarounds": + return life.groups === "all" + ? "When the last workaround is gone." + : `When workarounds ${life.groups.join(", ")} are gone.`; + case "condition": + return `When ${life.until}.`; + } +} + +const cell = (text) => text.replaceAll("|", "\\|").replaceAll("\n", " "); + +const storyCell = (story) => + /^CORE-\d+$/.test(story) + ? `[${story}](../domination/issues/${story}.md)` + : `${story}: [../dox/built.md](../dox/built.md)`; + +/** The generated canary table, rows in list order. */ +export function overviewTable(checks = PULSE_CHECKS) { + const rows = checks.map((c) => { + const where = `\`${c.source.split("/").at(-1)}\`${c.job ? ` job \`${c.job}\`` : ""}`; + return `| ${[ + cell(c.name), + where, + cell(c.watches), + cell(c.finds), + cell(lifeText(c.life)), + c.story === "Dox epic" ? "Dox epic" : storyCell(c.story), + ].join(" | ")} |`; + }); + return [ + "| Canary | Where | Checks | Finds | Retires | Story |", + "| --- | --- | --- | --- | --- | --- |", + ...rows, + ].join("\n"); +} + +/** The overview text with the generated block replaced; `null` when the markers are missing. */ +export function syncedOverview(text, checks = PULSE_CHECKS) { + const start = text.indexOf(OVERVIEW_START); + const end = text.indexOf(OVERVIEW_END); + if (start === -1 || end === -1 || end < start) return null; + return `${text.slice(0, start + OVERVIEW_START.length)}\n\n${overviewTable(checks)}\n\n${text.slice(end)}`; +} + +/** Every way the list and the repo disagree, one sentence each. Empty means they agree. */ +export function checkDrift({ + root = REPO_ROOT, + checks = PULSE_CHECKS, + workarounds = WORKAROUNDS, +} = {}) { + const problems = []; + const ids = new Set(); + for (const c of checks) { + if (ids.has(c.id)) problems.push(`Two checks share the id ${c.id}.`); + ids.add(c.id); + } + + const scheduled = scheduledWorkflows(root); + const sources = new Set(checks.map((c) => c.source)); + for (const wf of scheduled) { + if (!sources.has(wf)) { + problems.push( + `${wf} runs on a schedule but no check in scripts/lib/pulse.mjs names it.`, + ); + } + } + + const canaryScripts = findFiles(root, "scripts/canary", (n) => + n.endsWith(".mjs"), + ); + const canaryTests = ["apps", "packages", "scripts"].flatMap((dir) => + findFiles(root, dir, (n) => n.endsWith("-canary.test.ts")), + ); + const namedScripts = new Set(checks.flatMap((c) => c.scripts ?? [])); + for (const s of canaryScripts) { + if (!namedScripts.has(s)) { + problems.push( + `${s} is a canary script but no check lists it under scripts.`, + ); + } + } + for (const t of canaryTests) { + if (!sources.has(t)) { + problems.push( + `${t} is a canary test but no check names it as its source.`, + ); + } + } + + const groupIds = new Set(workarounds.map(groupId)); + const claimed = new Set(); + for (const c of checks) { + const abs = join(root, c.source); + if (!existsSync(abs)) { + problems.push(`Check ${c.id}: ${c.source} does not exist.`); + continue; + } + const text = readFileSync(abs, "utf8"); + if (c.source.startsWith(".github/workflows/")) { + const wf = readWorkflow(root, c.source); + if (wf.crons.length === 0) { + problems.push(`Check ${c.id}: ${c.source} has no schedule.`); + } + if (c.job && !wf.jobs.some((j) => j.id === c.job)) { + problems.push(`Check ${c.id}: ${c.source} has no job ${c.job}.`); + } + } + for (const s of c.scripts ?? []) { + if (!existsSync(join(root, s))) { + problems.push(`Check ${c.id}: ${s} does not exist.`); + } + } + if (!carriesTag(text, c.id)) { + problems.push(`${c.source} has no "Pulse check: ${c.id}" line.`); + } + if (RETIRE_PROSE.test(text)) { + problems.push( + `${c.source} describes when it retires; that belongs in the check's life in scripts/lib/pulse.mjs.`, + ); + } + if (c.life.kind === "workarounds") { + const claims = c.life.groups === "all" ? [...groupIds] : c.life.groups; + for (const g of claims) { + if (!groupIds.has(g)) { + problems.push( + `Check ${c.id} claims workaround group ${g}, which does not exist.`, + ); + } + claimed.add(g); + } + } + } + for (const g of groupIds) { + if (!claimed.has(g)) { + problems.push(`Workaround group ${g} is claimed by no check's life.`); + } + } + + const overviewPath = join(root, OVERVIEW_PATH); + if (existsSync(overviewPath)) { + const text = readFileSync(overviewPath, "utf8"); + const next = syncedOverview(text, checks); + if (next === null) { + problems.push( + `${OVERVIEW_PATH} has no ${OVERVIEW_START} and ${OVERVIEW_END} markers.`, + ); + } else if (next !== text) { + problems.push( + `The table in ${OVERVIEW_PATH} is out of date: run pnpm pulse:sync.`, + ); + } + } + return problems; +} + +// --------------------------------------------------------------------------------------------- +// Run history + +/** What a workflow run is called on the page: only the fields it prints. */ +const RUN_JQ = `[.workflow_runs[] | select(.conclusion != null) | {startedAt: .run_started_at, conclusion: .conclusion, url: .html_url}]`; + +/** The default way to ask GitHub: the `gh` CLI, with a time limit. */ +export async function ghApi(path, timeoutMs) { + const { stdout } = await execFileAsync("gh", ["api", path, "--jq", RUN_JQ], { + timeout: Math.max(1, Math.floor(timeoutMs)), + maxBuffer: 4 * 1024 * 1024, + }); + return JSON.parse(stdout); +} + +/** + * Age in ms of the live file by its modified time; `Infinity` when there is none, or when + * `packages/gmt` is not built (the refresh then reads no history anyway). A test may answer + * synchronously. + * + * @param {string} file + * @returns {number | Promise} + */ +function liveFileAge(file) { + if (!existsSync(file)) return Infinity; + return tryLoadGmt().then((gmt) => + gmt === null + ? Infinity + : gmt.getUnixNow({ epochUnit: "milliseconds" }) - statSync(file).mtimeMs, + ); +} + +/** + * Reads the recent scheduled runs of every scheduled workflow and writes the live file. Returns + * what happened as a word for the log; never throws. Every input that touches the world is + * injectable. + */ +export async function refreshRuns({ + root = REPO_ROOT, + checks = PULSE_CHECKS, + file = RUNS_FILE, + env = process.env, + gh = ghApi, + stamp = async () => { + const gmt = await tryLoadGmt(); + return gmt === null ? null : gmt.getUtcNow(); + }, + ageOf = liveFileAge, + clock = () => performance.now(), + log = (line) => console.warn(line), +} = {}) { + if (env.CI === undefined && env.PULSE_REFRESH !== "force") { + if ((await ageOf(file)) < RUNS_TTL_MS) { + log( + `pulse: ${file} is under 6 h old, skipping (PULSE_REFRESH=force to refresh now)`, + ); + return "fresh"; + } + } + try { + const read = await stamp(); + if (read === null) { + log("pulse: packages/gmt is not built, so no run history was read"); + return "skipped"; + } + const sources = [...sourcesOf(checks).keys()].filter((s) => + scheduledWorkflows(root).includes(s), + ); + const deadline = clock() + RUNS_BUDGET_MS; + const workflows = {}; + for (const source of sources) { + const left = deadline - clock(); + if (left <= 0) throw new Error("the 10 s budget ran out"); + const name = source.split("/").at(-1); + try { + workflows[name] = await gh( + `repos/{owner}/{repo}/actions/workflows/${name}/runs?event=schedule&per_page=${RUNS_PER_WORKFLOW}`, + Math.min(left, RUNS_CALL_MS), + ); + } catch { + // A 404 (the workflow is not on main yet) or a failed call leaves this one without history. + workflows[name] = null; + } + } + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, formatJson({ runsRead: read, workflows })); + return "read"; + } catch (error) { + log( + `pulse: run history not read: ${error instanceof Error ? error.message : String(error)}`, + ); + return "failed"; + } +} + +// --------------------------------------------------------------------------------------------- + +async function main(argv) { + const mode = argv.includes("--check") + ? "check" + : argv.includes("--sync") + ? "sync" + : "build"; + if (mode === "sync") { + const path = join(REPO_ROOT, OVERVIEW_PATH); + const text = readFileSync(path, "utf8"); + const next = syncedOverview(text); + if (next === null) { + console.error( + `${OVERVIEW_PATH} has no ${OVERVIEW_START} and ${OVERVIEW_END} markers.`, + ); + process.exit(1); + } + if (next !== text) writeFileSync(path, next); + console.log( + next === text + ? "pulse: overview already current" + : "pulse: overview table rewritten", + ); + return; + } + const problems = checkDrift(); + if (problems.length > 0) { + console.error( + `pulse: the list of checks and the repo disagree:\n- ${problems.join("\n- ")}`, + ); + process.exit(1); + } + if (mode === "check") { + console.log(`pulse: ${PULSE_CHECKS.length} checks match the repo`); + return; + } + mkdirSync(GENERATED, { recursive: true }); + writeFileSync(PULSE_FILE, formatJson(buildPulse())); + await refreshRuns(); +} + +if ( + process.argv[1] && + relative(process.argv[1], fileURLToPath(import.meta.url)) === "" +) { + await main(process.argv.slice(2)); +} diff --git a/apps/dox/scripts/build-pulse.test.ts b/apps/dox/scripts/build-pulse.test.ts new file mode 100644 index 000000000..341982973 --- /dev/null +++ b/apps/dox/scripts/build-pulse.test.ts @@ -0,0 +1,337 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { + buildPulse, + checkDrift, + OVERVIEW_END, + OVERVIEW_PATH, + OVERVIEW_START, + overviewTable, + readWorkflow, + refreshRuns, + syncedOverview, +} from "./build-pulse.mjs"; + +type Check = Parameters[0] extends infer T + ? T extends readonly (infer C)[] + ? C + : never + : never; + +const WORKFLOW = `name: Fixture weekly + +# Pulse check: fixture + +on: + workflow_dispatch: + schedule: + - cron: "17 6 * * 1" + +jobs: + canary: + name: The canary + runs-on: ubuntu-latest +`; + +const CHECK = { + id: "fixture", + name: "Fixture", + area: "temporal", + source: ".github/workflows/fixture.yml", + job: "canary", + watches: "A thing.", + finds: "Opens an issue.", + life: { kind: "workarounds", groups: "all" }, + story: "CORE-1", +} as unknown as Check; + +const GROUPS = [{ defects: ["D1"] }, { defects: ["D2", "D3"] }]; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) + rmSync(dir, { recursive: true, force: true }); +}); + +/** A repo-shaped folder with one scheduled workflow and the overview table in sync. */ +function fixtureRoot( + files: Record = {}, + checks: readonly Check[] = [CHECK], +): string { + const root = mkdtempSync(join(tmpdir(), "pulse-")); + dirs.push(root); + const all: Record = { + ".github/workflows/fixture.yml": WORKFLOW, + [OVERVIEW_PATH]: `# Overview\n\n${OVERVIEW_START}\n${OVERVIEW_END}\n`, + ...files, + }; + for (const [rel, text] of Object.entries(all)) { + mkdirSync(dirname(join(root, rel)), { recursive: true }); + writeFileSync(join(root, rel), text); + } + const overview = join(root, OVERVIEW_PATH); + const synced = syncedOverview(readFileSync(overview, "utf8"), checks); + if (synced !== null) writeFileSync(overview, synced); + return root; +} + +describe("pulse: the real list matches the repo", () => { + it("reports no drift", () => { + expect(checkDrift()).toEqual([]); + }); + + it("joins every check to a card, with the cron and jobs the workflow file says", () => { + const data = buildPulse(); + const ids = data.cards.flatMap((c: { checkIds: string[] }) => c.checkIds); + expect(ids.sort()).toEqual( + data.checks.map((c: { id: string }) => c.id).sort(), + ); + const oracle = data.cards.find( + (c: { file: string }) => c.file === "temporal-oracle.yml", + ); + expect(oracle?.crons).toHaveLength(1); + expect(oracle?.jobs.map((j: { id: string }) => j.id)).toContain("oracle"); + }); +}); + +describe("pulse: the drift check", () => { + it("passes on a fixture where list, workflow, tag and groups agree", () => { + const root = fixtureRoot(); + expect( + checkDrift({ root, checks: [CHECK], workarounds: GROUPS as never }), + ).toEqual([]); + }); + + it("fails when a scheduled workflow has no entry", () => { + const root = fixtureRoot({ + ".github/workflows/other.yml": WORKFLOW.replace("fixture", "other"), + }); + const problems = checkDrift({ + root, + checks: [CHECK], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/other\.yml runs on a schedule/); + }); + + it("fails when an entry is deleted from the list", () => { + const root = fixtureRoot(); + const problems = checkDrift({ + root, + checks: [], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/fixture\.yml runs on a schedule/); + }); + + it("fails when the source loses its Pulse check line", () => { + const root = fixtureRoot({ + ".github/workflows/fixture.yml": WORKFLOW.replace( + "# Pulse check: fixture\n", + "", + ), + }); + const problems = checkDrift({ + root, + checks: [CHECK], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/no "Pulse check: fixture" line/); + }); + + it("fails when a workaround group is claimed by no check", () => { + const root = fixtureRoot(); + const partial = { + ...CHECK, + life: { kind: "workarounds", groups: ["D1"] }, + } as Check; + const problems = checkDrift({ + root, + checks: [partial], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch( + /group D2 \+ D3 is claimed by no check/, + ); + }); + + it("fails when a check claims a group that does not exist", () => { + const root = fixtureRoot(); + const wrong = { + ...CHECK, + life: { kind: "workarounds", groups: ["D9"] }, + } as Check; + const problems = checkDrift({ + root, + checks: [wrong], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/claims workaround group D9/); + }); + + it("fails when a job named by an entry is not in the workflow", () => { + const root = fixtureRoot(); + const wrong = { ...CHECK, job: "missing" } as Check; + const problems = checkDrift({ + root, + checks: [wrong], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/has no job missing/); + }); + + it("fails on retirement prose left in a source file", () => { + const root = fixtureRoot({ + ".github/workflows/fixture.yml": WORKFLOW.replace( + "# Pulse check: fixture\n", + "# Pulse check: fixture\n# Retire this workflow when it is done.\n", + ), + }); + const problems = checkDrift({ + root, + checks: [CHECK], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/describes when it retires/); + }); + + it("fails on a canary script and a canary test no entry names", () => { + const root = fixtureRoot({ + "scripts/canary/extra.mjs": "// a canary\n", + "apps/dox/src/lib/extra-canary.test.ts": "// a canary\n", + }); + const text = checkDrift({ + root, + checks: [CHECK], + workarounds: GROUPS as never, + }).join("\n"); + expect(text).toMatch(/scripts\/canary\/extra\.mjs is a canary script/); + expect(text).toMatch(/extra-canary\.test\.ts is a canary test/); + }); + + it("fails when the overview table is stale", () => { + const root = fixtureRoot(); + writeFileSync( + join(root, OVERVIEW_PATH), + `# Overview\n\n${OVERVIEW_START}\nold\n${OVERVIEW_END}\n`, + ); + const problems = checkDrift({ + root, + checks: [CHECK], + workarounds: GROUPS as never, + }); + expect(problems.join("\n")).toMatch(/out of date: run pnpm pulse:sync/); + }); +}); + +describe("pulse: the workflow reader", () => { + it("reads the name, the schedules and the jobs", () => { + const root = fixtureRoot(); + expect(readWorkflow(root, ".github/workflows/fixture.yml")).toEqual({ + name: "Fixture weekly", + crons: ["17 6 * * 1"], + jobs: [{ id: "canary", name: "The canary" }], + }); + }); +}); + +describe("pulse: the overview table", () => { + it("writes one row per check between the markers and is stable", () => { + const once = syncedOverview(`a\n${OVERVIEW_START}\n${OVERVIEW_END}\nb\n`, [ + CHECK, + ]); + expect(once).toContain("| Fixture | `fixture.yml` job `canary` |"); + expect(syncedOverview(once as string, [CHECK])).toBe(once); + }); + + it("returns null when the markers are missing", () => { + expect(syncedOverview("no markers", [CHECK])).toBeNull(); + }); +}); + +describe("pulse: run history", () => { + const RUN = { + conclusion: "success", + startedAt: "2026-11-09T06:20:00Z", + url: "u", + }; + + /** Reads the history into a fixture folder with everything injected: no network, no clock. */ + async function read( + options: Partial[0]> = {}, + ): Promise<{ result: string; file: string; logs: string[] }> { + const root = fixtureRoot(); + const file = join(root, "runs.json"); + const logs: string[] = []; + const result = await refreshRuns({ + root, + checks: [CHECK], + file, + env: {}, + stamp: async () => "2026-11-14T10:00:00Z", + ageOf: () => Infinity, + clock: () => 0, + log: (line: string) => logs.push(line), + gh: async () => [RUN], + ...options, + }); + return { result, file, logs }; + } + + it("writes the runs of each scheduled workflow with the time they were read", async () => { + const { result, file } = await read(); + expect(result).toBe("read"); + expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ + runsRead: "2026-11-14T10:00:00Z", + workflows: { "fixture.yml": [RUN] }, + }); + }); + + it("leaves a workflow's runs null when the call fails", async () => { + const { file } = await read({ + gh: async () => { + throw new Error("HTTP 404"); + }, + }); + expect( + JSON.parse(readFileSync(file, "utf8")).workflows["fixture.yml"], + ).toBeNull(); + }); + + it("skips while the file is under six hours old, unless forced", async () => { + expect((await read({ ageOf: () => 1000 })).result).toBe("fresh"); + expect( + (await read({ ageOf: () => 1000, env: { PULSE_REFRESH: "force" } })) + .result, + ).toBe("read"); + expect( + (await read({ ageOf: () => 1000, env: { CI: "true" } })).result, + ).toBe("read"); + }); + + it("reads nothing, and says so, when the library is not built", async () => { + const { result, logs } = await read({ stamp: async () => null }); + expect(result).toBe("skipped"); + expect(logs.join()).toMatch(/not built/); + }); + + it("gives up with a warning when the budget is spent", async () => { + let now = 0; + const { result, logs } = await read({ + clock: () => { + const t = now; + now += 20_000; + return t; + }, + }); + expect(result).toBe("failed"); + expect(logs.join()).toMatch(/budget/); + }); +}); diff --git a/apps/dox/scripts/llms.test.ts b/apps/dox/scripts/llms.test.ts index fdaa4980d..0beefa748 100644 --- a/apps/dox/scripts/llms.test.ts +++ b/apps/dox/scripts/llms.test.ts @@ -768,7 +768,7 @@ Body text here.`; expect(wrong).toEqual([]); }); - it("llms.txt lists Install first under Start here, and compare, bundle-size and upstream under Migrate", () => { + it("llms.txt lists Install first and upstream and pulse under Start here, and compare and bundle-size under Migrate", () => { const distDir = distDirOrSkip(); if (distDir === null) return; const llms = readFileSync(resolve(distDir, "llms.txt"), "utf8"); @@ -784,12 +784,18 @@ Body text here.`; const startHere = section("Start here"); expect(startHere[0]).toMatch(/\/install\.md\)/); const migrate = section("Migrate"); - for (const slug of [ - "compare", - "bundle-size", - "upstream", - "native-engines", - ]) { + for (const slug of ["upstream", "pulse"]) { + const link = new RegExp(`/${slug}\\.md\\)`); + expect( + startHere.some((line) => link.test(line)), + `${slug} is under Start here`, + ).toBe(true); + expect( + migrate.some((line) => link.test(line)), + `${slug} is not under Migrate`, + ).toBe(false); + } + for (const slug of ["compare", "bundle-size", "native-engines"]) { const link = new RegExp(`/${slug}\\.md\\)`); expect( migrate.some((line) => link.test(line)), @@ -809,7 +815,7 @@ Body text here.`; const urls = [...full.matchAll(/^> source: (\S+)$/gm)].map((m) => m[1]!); const path = (url: string) => url.replace(/^.*\/gmt\//, ""); expect(urls.length).toBeGreaterThan(0); - const lastStart = urls.findIndex((url) => path(url) === "why-gmt.md"); + const lastStart = urls.findIndex((url) => path(url) === "pulse.md"); expect(lastStart).toBeGreaterThanOrEqual(0); expect(path(urls[lastStart + 1]!)).toMatch(/^guides\//); const firstMigrate = urls.findIndex((url) => @@ -818,7 +824,7 @@ Body text here.`; expect(firstMigrate).toBeGreaterThan(lastStart); for (const url of urls.slice(firstMigrate)) { expect(path(url), url).toMatch( - /^(migrate\/|compare\/behaviour\.md$|compare\.md$|bundle-size\.md$|upstream\.md$|native-engines\.md$)/, + /^(migrate\/|compare\/behaviour\.md$|compare\.md$|bundle-size\.md$|native-engines\.md$)/, ); } }); diff --git a/apps/dox/src/components/UpstreamDefectRow.astro b/apps/dox/src/components/UpstreamDefectRow.astro index 5691449a0..7d439e1e8 100644 --- a/apps/dox/src/components/UpstreamDefectRow.astro +++ b/apps/dox/src/components/UpstreamDefectRow.astro @@ -14,10 +14,9 @@ import { groupLabel, groupWhatBreaks, reasonParts, - shortRef, stateLine, } from "../data/temporal-compat"; -import type { UpstreamFiling } from "../data/upstream-filings"; +import { filingRef, type UpstreamFiling } from "../data/upstream-filings"; import { chip, defectBadge } from "../lib/upstream-badges"; interface Props { @@ -55,7 +54,7 @@ const { count } = stateLine(group); diff --git a/apps/dox/src/components/UpstreamFilingRow.astro b/apps/dox/src/components/UpstreamFilingRow.astro index 891634c71..f974cc01e 100644 --- a/apps/dox/src/components/UpstreamFilingRow.astro +++ b/apps/dox/src/components/UpstreamFilingRow.astro @@ -8,8 +8,7 @@ * fields, so no status is typed by hand. The cells carry no `data-col`: the card is a header, a * body and a meta line, not label/value pairs. */ -import { shortRef } from "../data/temporal-compat"; -import type { UpstreamFiling } from "../data/upstream-filings"; +import { filingRef, type UpstreamFiling } from "../data/upstream-filings"; import { inlineCodeHtml } from "../lib/inline-code-html"; import { octicon } from "../lib/octicons"; import { @@ -52,9 +51,9 @@ const gmtNote = filing.gmtGuard ? null : filing.gmtNote; - {filing.kind === "pr" ? "Pull request:" : "Issue:"} + {filing.tracker === "github" && filing.kind === "pr" ? "Pull request:" : "Issue:"} - {shortRef(filing.repo, filing.number)} + {filingRef(filing)} @@ -74,8 +73,17 @@ const gmtNote = filing.gmtGuard ? null : filing.gmtNote; - {countLabel(filing.maintainerComments, "maintainer reply", "maintainer replies")} - + {filing.maintainerComments === null ? ( + <> + Maintainer replies are not tracked on this site + + + ) : ( + <> + {countLabel(filing.maintainerComments, "maintainer reply", "maintainer replies")} + + + )} diff --git a/apps/dox/src/components/UpstreamTracker.astro b/apps/dox/src/components/UpstreamTracker.astro index 41f0dafd7..b54d8d6f3 100644 --- a/apps/dox/src/components/UpstreamTracker.astro +++ b/apps/dox/src/components/UpstreamTracker.astro @@ -1,10 +1,10 @@ --- /** - * The /upstream/ tracker: one table per repository, built from `upstream-filings.ts` — the live + * The /upstream/ tracker: one table per repository or tracker, built from `upstream-filings.ts` — the live * refresh when GitHub is reachable, the committed snapshot otherwise. Nothing is fetched in the * browser. Sentences come from `lib/upstream-summary.ts`, styles in `gmt-content-tables.css`. */ -import { filingRepos, filingsForRepo } from "../data/upstream-filings"; +import { filingGroups, filingsForGroup } from "../data/upstream-filings"; import { UPSTREAM_COLUMNS as COLUMNS } from "../lib/upstream-status"; import { asDate } from "../lib/upstream-summary"; import UpstreamFilingRow from "./UpstreamFilingRow.astro"; @@ -16,18 +16,18 @@ import UpstreamTrackerSummary from "./UpstreamTrackerSummary.astro"; { - filingRepos.map((repo) => ( + filingGroups.map((group) => (

- {repo} + {group.name}

-
+
{COLUMNS.map((column) => )} - {filingsForRepo(repo).map((f) => ( + {filingsForGroup(group.id).map((f) => ( ))} diff --git a/apps/dox/src/components/UpstreamTrackerSummary.astro b/apps/dox/src/components/UpstreamTrackerSummary.astro index a26fcdf69..c4b41a8c6 100644 --- a/apps/dox/src/components/UpstreamTrackerSummary.astro +++ b/apps/dox/src/components/UpstreamTrackerSummary.astro @@ -17,7 +17,7 @@ import { contributionClause, coverageClause } from "../lib/upstream-summary";

- So far we have sent {filedByUs} reports and fixes to the Temporal projects, {filedPrs} of them as + So far we have sent {filedByUs} reports and fixes to Temporal and the projects it builds on, {filedPrs} of them as ready-to-merge code changes{contributionClause}. {coverageClause}: {handledInGmt} through its own built-in fix, and {unaffectingGmt} because the bug is in code GMT doesn't use. diff --git a/apps/dox/src/components/pulse/Pulse.astro b/apps/dox/src/components/pulse/Pulse.astro new file mode 100644 index 000000000..55112d403 --- /dev/null +++ b/apps/dox/src/components/pulse/Pulse.astro @@ -0,0 +1,37 @@ +--- +/** + * `/pulse/`: every scheduled check, what it watches, when it runs, its recent runs and what + * retires it. The markup is built in `widgets/families/pulse/pulse-template.ts`; the script below + * fills three reserved slots after first paint (`lib/pulse-mount.ts`). + */ +import { renderAreas, renderRead, renderRetire } from "../../widgets/families/pulse/pulse-template"; +import PulseSummary from "./PulseSummary.astro"; + +const areas = renderAreas().value; +const read = renderRead().value; +const retire = renderRetire().value; +--- + +

+ + +

GitHub may start a scheduled run hours late, so a run can sit well after its time.

+ +

How a check retires

+

+ A check watches until the fix it waits for ships upstream. Then its workaround is removed, and + the check goes with it. +

+ +
+ + diff --git a/apps/dox/src/components/pulse/PulseBeats.astro b/apps/dox/src/components/pulse/PulseBeats.astro new file mode 100644 index 000000000..39ae6bdc3 --- /dev/null +++ b/apps/dox/src/components/pulse/PulseBeats.astro @@ -0,0 +1,11 @@ +--- +/** The strip of a workflow'\''s last eight runs, or NO SIGNAL. The markup is built in `widgets/families/pulse/pulse-template.ts`. */ +import { cards } from "../../data/pulse"; +import { renderBeats } from "../../widgets/families/pulse/pulse-template"; +interface Props { file: string } +const card = cards.find((c) => c.file === Astro.props.file); +if (card === undefined) throw new Error(`pulse: no card for ${Astro.props.file}`); +const out = renderBeats(card, `pulse-${card.file.replace(/\.[^.]+$/, "")}`).value; +--- + + diff --git a/apps/dox/src/components/pulse/PulseCard.astro b/apps/dox/src/components/pulse/PulseCard.astro new file mode 100644 index 000000000..1828ca90f --- /dev/null +++ b/apps/dox/src/components/pulse/PulseCard.astro @@ -0,0 +1,11 @@ +--- +/** One workflow, or one unscheduled source, with its checks. The markup is built in `widgets/families/pulse/pulse-template.ts`. */ +import { cards } from "../../data/pulse"; +import { renderCard } from "../../widgets/families/pulse/pulse-template"; +interface Props { file: string } +const card = cards.find((c) => c.file === Astro.props.file); +if (card === undefined) throw new Error(`pulse: no card for ${Astro.props.file}`); +const out = renderCard(card).value; +--- + + diff --git a/apps/dox/src/components/pulse/PulseLife.astro b/apps/dox/src/components/pulse/PulseLife.astro new file mode 100644 index 000000000..f28be12b2 --- /dev/null +++ b/apps/dox/src/components/pulse/PulseLife.astro @@ -0,0 +1,10 @@ +--- +/** Watching, Fixed upstream, Retired, for one check. The markup is built in `widgets/families/pulse/pulse-template.ts`. */ +import { checkById } from "../../data/pulse"; +import { renderLife } from "../../widgets/families/pulse/pulse-template"; +interface Props { id: string } +const check = checkById(Astro.props.id); +const out = renderLife(check.life).value; +--- + + diff --git a/apps/dox/src/components/pulse/PulseSummary.astro b/apps/dox/src/components/pulse/PulseSummary.astro new file mode 100644 index 000000000..cdabb67e5 --- /dev/null +++ b/apps/dox/src/components/pulse/PulseSummary.astro @@ -0,0 +1,7 @@ +--- +/** The four readouts above the cards. The markup is built in `widgets/families/pulse/pulse-template.ts`. */ +import { renderSummary } from "../../widgets/families/pulse/pulse-template"; +const out = renderSummary().value; +--- + + diff --git a/apps/dox/src/content/docs/bundle-size.mdx b/apps/dox/src/content/docs/bundle-size.mdx index 1d0393cea..45a788a1a 100644 --- a/apps/dox/src/content/docs/bundle-size.mdx +++ b/apps/dox/src/content/docs/bundle-size.mdx @@ -15,4 +15,4 @@ The `@northguild/gmt` row is the whole package, all {formatCount(gmtStats.functi Sizes come from bundling `packages/gmt/src` with esbuild, minified, as ES modules for a neutral platform. 1 kB is 1,000 bytes. The minified size of each row is gated: the repository's check fails when it passes the budget in the last column, and a budget changes only by a reviewed edit. Gzipped sizes are reported and never gated, because they vary with the version of zlib. -The polyfill stays until a stable Safari ships `Temporal` and the weekly run against native `Temporal` passes on Node 26, Chromium, Firefox, WebKit on Linux and WebKit on macOS for 12 weeks running ([#316](https://github.com/northguild/gmt/issues/316)). +The polyfill stays until a stable Safari ships `Temporal` and the weekly run against native `Temporal` passes on Node 26, Chromium, Firefox, WebKit on Linux and WebKit on macOS for 12 weeks running ([#316](https://github.com/northguild/gmt/issues/316)). [Pulse](/pulse/) shows the checks that watch for it. diff --git a/apps/dox/src/content/docs/native-engines.mdx b/apps/dox/src/content/docs/native-engines.mdx index 1cf23d349..3e5d30095 100644 --- a/apps/dox/src/content/docs/native-engines.mdx +++ b/apps/dox/src/content/docs/native-engines.mdx @@ -64,4 +64,4 @@ tests their engine or data yet. If GMT gives a wrong answer on one, we want the ## Where the results are -The [weekly workflow](https://github.com/northguild/gmt/actions/workflows/temporal-oracle.yml) lists every run. Each run's summary names the engine version it tested and, for `webkit-macos`, the macOS version. +The [weekly workflow](https://github.com/northguild/gmt/actions/workflows/temporal-oracle.yml) lists every run. Each run's summary names the engine version it tested and, for `webkit-macos`, the macOS version. [Pulse](/pulse/) shows the recent results next to the other checks GMT runs. diff --git a/apps/dox/src/content/docs/pulse.mdx b/apps/dox/src/content/docs/pulse.mdx new file mode 100644 index 000000000..e1ce64d5f --- /dev/null +++ b/apps/dox/src/content/docs/pulse.mdx @@ -0,0 +1,17 @@ +--- +title: Pulse +description: > + Every scheduled check GMT runs against the engines, the polyfill, the world's clocks and this + site: what it watches, when it runs, its recent runs, and what retires it. +slug: pulse +industries: [core] +--- + +import Pulse from "../../components/pulse/Pulse.astro"; + +GMT is a living, breathing project, and its code is never finished. Every week these checks run +against the JavaScript engines, the polyfill, the world's clocks and this site. They spot a clock +rule that changes, an engine defect that is new, and the day a fix ships upstream, so its +workaround can go. + + diff --git a/apps/dox/src/content/docs/upstream.mdx b/apps/dox/src/content/docs/upstream.mdx index 055269cec..92ead5e39 100644 --- a/apps/dox/src/content/docs/upstream.mdx +++ b/apps/dox/src/content/docs/upstream.mdx @@ -65,7 +65,8 @@ Until that release, GMT's own code covers every bug in the table above. There are two Temporal polyfills: [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill), which GMT uses, and [`temporal-polyfill`](https://github.com/fullcalendar/temporal-polyfill) from FullCalendar, which is smaller and publishes releases more often. We ran GMT's whole test suite on -`temporal-polyfill` to see whether GMT should switch. +`temporal-polyfill` to see whether GMT should switch. The check that watches for a fix is on +[Pulse](/pulse/). Release 1.0.8 fixes most of the bugs in the table above, and the five bugs we reported in `temporal-polyfill` 1.0.6 and 1.0.7. Its UTC offsets match `Intl.DateTimeFormat` in every time @@ -137,7 +138,8 @@ found no differences. Every week, GMT runs its whole test suite on the Temporal built into Node 26, Chromium, Firefox, WebKit on Linux and WebKit on macOS, and expects the same answers it gets on the polyfill. A failure that no known bug explains opens an issue in GMT's repository. Each run lists the exact engine versions it used: -see the [weekly runs](https://github.com/northguild/gmt/actions/workflows/temporal-oracle.yml). +see the [weekly runs](https://github.com/northguild/gmt/actions/workflows/temporal-oracle.yml), +and [Pulse](/pulse/) for what each check watches and when it retires. The built-in engines have a few bugs of their own. We report each one we find. The list so far: diff --git a/apps/dox/src/data/gmt-stats.json b/apps/dox/src/data/gmt-stats.json index 8f2d32365..1bab358c6 100644 --- a/apps/dox/src/data/gmt-stats.json +++ b/apps/dox/src/data/gmt-stats.json @@ -1,8 +1,8 @@ { "suite": "packages/gmt", - "tests": 76128, - "files": 1015, - "executions": 2283840, + "tests": 76319, + "files": 1021, + "executions": 2289570, "nodes": ["22", "24", "26"], "timezones": 10, "timezoneList": [ diff --git a/apps/dox/src/data/pulse.ts b/apps/dox/src/data/pulse.ts new file mode 100644 index 000000000..f6ee4c3c8 --- /dev/null +++ b/apps/dox/src/data/pulse.ts @@ -0,0 +1,179 @@ +/** + * What `/pulse/` shows, joined from its sources. The one hand-written source is + * `scripts/lib/pulse.mjs`; `scripts/build-pulse.mjs` reads each workflow file (its name, its + * schedules, its jobs) and the recent runs, and writes `generated/pulse.json` and + * `generated/pulse-runs.live.json`. This module adds what the other pages already know: the + * workaround states from the compat snapshot and the filings. Counts come from those joins. + */ +import pulseData from "../generated/pulse.json"; +import { compatGroups, groupLabel, type CompatGroup } from "./temporal-compat"; +import { filingKey, filings, type UpstreamFiling } from "./upstream-filings"; + +export type PulseAreaId = "temporal" | "clocks" | "site"; + +export type PulseLife = + | { kind: "permanent"; why: string } + | { kind: "workarounds"; groups: "all" | readonly string[] } + | { + kind: "condition"; + until: string; + waitsOn?: readonly string[]; + waitsOnRepos?: readonly string[]; + }; + +export interface PulseCheck { + id: string; + name: string; + area: PulseAreaId; + source: string; + job?: string; + scripts?: readonly string[]; + watches: string; + finds: string; + life: PulseLife; + story: string; +} + +export interface PulseCard { + source: string; + file: string; + kind: "workflow" | "test"; + name: string; + crons: readonly string[]; + jobs: readonly { id: string; name: string }[]; + checkIds: readonly string[]; +} + +export interface PulseRun { + startedAt: string; + conclusion: string; + url: string; +} + +interface RunsFile { + runsRead: string; + workflows: Record; +} + +const isRunsFile = (value: unknown): value is RunsFile => + typeof value === "object" && + value !== null && + typeof (value as RunsFile).runsRead === "string" && + typeof (value as RunsFile).workflows === "object"; + +// The live file is optional and gitignored. Outside Vite `import.meta.glob` does not exist, and a +// missing file is the same as a failed read: every strip then says NO SIGNAL. +const liveModules = ( + typeof import.meta.glob === "function" + ? import.meta.glob("../generated/pulse-runs.live.json", { + eager: true, + import: "default", + }) + : {} +) as Record; +const live = Object.values(liveModules)[0]; +const runsFile: RunsFile | null = isRunsFile(live) ? live : null; + +export const areas = pulseData.areas as readonly { + id: PulseAreaId; + heading: string; + blurb: string; +}[]; +export const checks = pulseData.checks as readonly PulseCheck[]; +export const cards = pulseData.cards as readonly PulseCard[]; + +/** When the run history was read (UTC), or `null` when this build read none. */ +export const runsRead: string | null = runsFile?.runsRead ?? null; + +/** The recent scheduled runs of a card's workflow, newest first, or `null` when none were read. */ +export const runsFor = (card: PulseCard): readonly PulseRun[] | null => + runsFile?.workflows[card.file] ?? null; + +export const checkById = (id: string): PulseCheck => { + const found = checks.find((c) => c.id === id); + if (found === undefined) throw new Error(`pulse: no check ${id}`); + return found; +}; + +export const cardsIn = (area: PulseAreaId): readonly PulseCard[] => + cards.filter((card) => checkById(card.checkIds[0]!).area === area); + +/** The workaround groups a life claims, as the compat snapshot has them. */ +export function groupsClaimed(life: PulseLife): readonly CompatGroup[] { + if (life.kind !== "workarounds") return []; + return life.groups === "all" + ? compatGroups + : compatGroups.filter((g) => + (life.groups as readonly string[]).includes(groupLabel(g)), + ); +} + +/** The filings a `condition` life waits on: the keys it names, and every open one in its repos. */ +export function filingsWaitedOn(life: PulseLife): readonly UpstreamFiling[] { + if (life.kind !== "condition") return []; + const keys = life.waitsOn ?? []; + const repos = life.waitsOnRepos ?? []; + return filings.filter( + (f) => + keys.includes(filingKey(f)) || + (f.tracker === "github" && repos.includes(f.repo) && f.state === "open"), + ); +} + +export type LifeStep = "watching" | "fixed" | "retired" | "permanent"; + +/** + * Where a check is on its way out. `fixed` means the thing it waits on has been fixed upstream and + * the check is due to go; `retired` never shows, because a retired check is gone from the list. + */ +export function lifeStep(life: PulseLife): LifeStep { + switch (life.kind) { + case "permanent": + return "permanent"; + case "workarounds": { + const claimed = groupsClaimed(life); + return claimed.length > 0 && claimed.every((g) => g.state === "removable") + ? "fixed" + : "watching"; + } + case "condition": { + const waited = filingsWaitedOn(life); + return waited.length > 0 && waited.every((f) => f.state === "closed") + ? "fixed" + : "watching"; + } + } +} + +/** The counts the summary row and a workaround life line print. */ +export interface WorkaroundCounts { + total: number; + stillNeeded: number; + removable: number; + guards: number; + other: number; +} + +export function countWorkarounds( + groups: readonly CompatGroup[], +): WorkaroundCounts { + const count = (state: CompatGroup["state"]) => + groups.filter((g) => g.state === state).length; + const stillNeeded = count("still-needed"); + const removable = count("removable"); + const guards = count("guard"); + return { + total: groups.length, + stillNeeded, + removable, + guards, + other: groups.length - stillNeeded - removable - guards, + }; +} + +export const summary = { + checks: checks.length, + scheduled: cards.filter((c) => c.crons.length > 0).length, + workarounds: countWorkarounds(compatGroups), + filingsOpen: filings.filter((f) => f.state === "open").length, +}; diff --git a/apps/dox/src/data/temporal-compat.json b/apps/dox/src/data/temporal-compat.json index 913da2fd3..e8a212283 100644 --- a/apps/dox/src/data/temporal-compat.json +++ b/apps/dox/src/data/temporal-compat.json @@ -168,6 +168,71 @@ "failing": 6, "state": "still-needed" }, + { + "defects": ["D23"], + "title": "D23 — formatToParts and formatRangeToParts abort V8 on a week-of-year year field (nodejs/node#67076)", + "trigger": "every V8 the check reads (Node at the engines.node floor, and the temporal-compat-chromium verdict) passes the D23 repro: a gd formatter with year numeric and month short resolves a year, and the Node child-process confirmation of scripts/canary/weekYear.mjs exits 0 with a year part", + "probes": 1, + "failing": 1, + "state": "still-needed", + "engines": ["v8"] + }, + { + "defects": ["D24"], + "title": "D24 — CLDR date patterns print the week-of-year year where the calendar year is meant (internal/weekYearGuard.ts)", + "trigger": "every engine's compat verdict passes every D24 repro, and the weekly sweep of scripts/canary/weekYear.mjs flags no locale, calendar or option set", + "probes": 7, + "failing": 7, + "state": "still-needed" + }, + { + "defects": ["D25"], + "title": "D25 — the japanese calendar prints Japanese eras before 1873-01-01 (internal/yearPrinting.ts)", + "trigger": "every engine's compat verdict passes both D25 repros: en-u-ca-japanese prints 2 BC for ISO -0001-07-10 and 1872 AD for 1872-12-31 (tc39/proposal-intl-era-monthcode#86, tc39/test262#4877)", + "probes": 2, + "failing": 2, + "state": "still-needed" + }, + { + "defects": ["D26"], + "title": "D26 — an islamic calendar prints a negative year before the Hijra (internal/yearPrinting.ts)", + "trigger": "every engine's compat verdict passes the D26 repro: en-u-ca-islamic-civil prints a different era text for ISO 600-07-10 and 2025-07-10", + "probes": 1, + "failing": 1, + "state": "still-needed" + }, + { + "defects": ["D27"], + "title": "D27 — ja japanese leaves the era year unpadded under year 2-digit and in Latin digits under another numbering system (internal/yearPrinting.ts, internal/japaneseNumerals.ts)", + "trigger": "every engine's compat verdict passes both D27 repros: ja-u-ca-japanese with year 2-digit prints 令和06年 for 2024-07-10, and ja-u-ca-japanese-nu-arab with year numeric prints 令和٦年", + "probes": 2, + "failing": 2, + "state": "still-needed" + }, + { + "defects": ["D28"], + "title": "D28 — chinese and dangi pad the related year under year 2-digit (internal/yearPrinting.ts)", + "trigger": "every engine's compat verdict passes the D28 repro: en-u-ca-chinese with year 2-digit prints the related year 5 for ISO 0005-07-10", + "probes": 1, + "failing": 1, + "state": "still-needed" + }, + { + "defects": ["D29"], + "title": "D29 — a range drops, repeats or garbles a field of one date (internal/rangeFields.ts)", + "trigger": "every engine's compat verdict passes every D29 repro (rangeFieldRepros.ts, one range per upstream defect, so the gate stays on while any one fails), and the weekly sweep of scripts/canary/rangeFields.mjs flags no locale, calendar or option set", + "probes": 18, + "failing": 18, + "state": "still-needed" + }, + { + "defects": ["D30"], + "title": "D30 — islamic and islamic-rgsa resolve as written (internal/formatterCache.ts)", + "trigger": "every engine's compat verdict passes both D30 repros: en-u-ca-islamic resolves islamic-tbla and en-u-ca-islamic-rgsa resolves a calendar other than islamic-rgsa (tc39/proposal-intl-era-monthcode#99)", + "probes": 2, + "failing": 2, + "state": "still-needed" + }, { "defects": ["D9"], "title": "D9 — non-ISO months added and counted one month at a time (heap OOM for in-range amounts; temporalCompat/largeMonthSpan.ts)", diff --git a/apps/dox/src/data/temporal-compat.test.ts b/apps/dox/src/data/temporal-compat.test.ts index e525050b3..89f07657f 100644 --- a/apps/dox/src/data/temporal-compat.test.ts +++ b/apps/dox/src/data/temporal-compat.test.ts @@ -214,11 +214,13 @@ describe("temporal compat snapshot", () => { describe("shortRef", () => { it.each` - repo | number | label - ${"tc39/proposal-temporal"} | ${3292} | ${"tc39 #3292"} - ${"js-temporal/temporal-polyfill"} | ${369} | ${"polyfill #369"} - ${"fullcalendar/temporal-polyfill"} | ${126} | ${"fullcalendar #126"} - ${"whatwg/html"} | ${12} | ${"whatwg/html #12"} + repo | number | label + ${"tc39/proposal-temporal"} | ${3292} | ${"tc39 #3292"} + ${"js-temporal/temporal-polyfill"} | ${369} | ${"polyfill #369"} + ${"fullcalendar/temporal-polyfill"} | ${126} | ${"fullcalendar #126"} + ${"tc39/ecma402"} | ${1116} | ${"ecma402 #1116"} + ${"nodejs/node"} | ${67076} | ${"node #67076"} + ${"whatwg/html"} | ${12} | ${"whatwg/html #12"} `("labels $repo#$number as '$label'", ({ repo, number, label }) => { expect(shortRef(repo, number)).toBe(label); }); diff --git a/apps/dox/src/data/temporal-compat.ts b/apps/dox/src/data/temporal-compat.ts index 420f23e0f..7f74a2b0b 100644 --- a/apps/dox/src/data/temporal-compat.ts +++ b/apps/dox/src/data/temporal-compat.ts @@ -161,11 +161,13 @@ const KNOWN_REPOS: Readonly> = { "tc39/proposal-temporal": "tc39", "js-temporal/temporal-polyfill": "polyfill", "fullcalendar/temporal-polyfill": "fullcalendar", + "tc39/ecma402": "ecma402", + "nodejs/node": "node", }; /** * The short form the `/upstream/` tables print for a GitHub reference: `tc39 #3292`, - * `polyfill #369`, or `owner/repo #n` for any other repository. + * `polyfill #369`, `node #67076`, or `owner/repo #n` for any other repository. */ export const shortRef = (repo: string, number: number): string => `${KNOWN_REPOS[repo] ?? repo} #${number}`; @@ -267,10 +269,12 @@ const WHAT_BREAKS: Readonly> = { D22: "A length in days or larger measured from a repeated hour, which the polyfill can measure from the wrong pass or refuse, so it can be an hour too long or missing. Where the specification has no value, which also happens after a skipped hour, GMT returns its sentinel", D23: "Some languages and calendars, among them Scottish Gaelic, Galician, Burmese and Telugu, whose date patterns use the week-of-year year: asking Node or Chrome for the parts of such a date, or of a range, stopped the process with no error to catch", D24: "Dates in the same languages near the start or end of a year, which every browser prints with the year the week belongs to rather than the calendar year, and with some calendars, such as Buddhist in Telugu, on every day of the year", - D25: "Japanese calendar dates before 1873, which every browser prints in a Japanese era such as Meiji 5 or Taika, where the calendar uses the Gregorian era until the end of 1872", + D25: "Japanese calendar dates before 1873, which every browser prints in a Japanese era such as Meiji 5 or Taika, where the calendar uses the Gregorian era until the end of 1872. A range across 1873 prints each date in its own era", D26: "Islamic calendar dates before the Hijra (622 CE), which Node and Chrome print as a negative year. They have no name for the era before the Hijra, so GMT returns its empty value there", - D27: "Japanese calendar dates in Japanese with a two-digit year, which every browser prints as 令和6年 where 令和06年 is asked for. The first year of an era stays 元年", + D27: "Japanese calendar dates in Japanese with a two-digit year, which every browser prints as 令和6年 where 令和06年 is asked for, and with Arabic-Indic or other digits asked for, which Node, Chrome and Safari print in Latin digits. The first year of an era stays 元年", D28: "Chinese and Korean calendar dates with a two-digit year, where the Gregorian year shown beside the cycle year was padded, such as 05 for the year 5", + D29: "Date ranges in some languages and calendars that leave out, repeat or mix up a part of one date, such as a Chinese calendar range a year apart without the Gregorian year, or a Yoruba range with the weekday twice. GMT prints both dates in full, joined the language's own way", + D30: "Dates in the calendars named islamic and islamic-rgsa, which Node and Chrome print with an astronomical Islamic calendar the standard no longer offers. GMT uses islamic-tbla for islamic, and the language's default calendar for islamic-rgsa", "zoned.A": "Zoned times within a day of the earliest or latest instant Temporal supports", "zoned.B": diff --git a/apps/dox/src/data/upstream-filings.json b/apps/dox/src/data/upstream-filings.json index 9cbe74c65..82d9e6825 100644 --- a/apps/dox/src/data/upstream-filings.json +++ b/apps/dox/src/data/upstream-filings.json @@ -1,7 +1,8 @@ { - "checked": "2026-11-13T16:44:38.201248729Z", + "checked": "2026-11-15T06:33:13.36138981Z", "filings": [ { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 361, "kind": "pr", @@ -27,6 +28,7 @@ "mergedAt": "2026-09-21" }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 367, "kind": "pr", @@ -51,6 +53,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 368, "kind": "pr", @@ -75,6 +78,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 369, "kind": "pr", @@ -99,6 +103,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 370, "kind": "pr", @@ -123,6 +128,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 371, "kind": "pr", @@ -147,6 +153,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 372, "kind": "pr", @@ -171,6 +178,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "js-temporal/temporal-polyfill", "number": 373, "kind": "issue", @@ -197,6 +205,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3327, "kind": "issue", @@ -220,6 +229,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3328, "kind": "issue", @@ -243,6 +253,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3329, "kind": "issue", @@ -266,6 +277,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3330, "kind": "issue", @@ -289,6 +301,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3331, "kind": "issue", @@ -313,6 +326,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3332, "kind": "issue", @@ -336,6 +350,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3335, "kind": "issue", @@ -359,6 +374,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "tc39/proposal-temporal", "number": 3336, "kind": "issue", @@ -382,6 +398,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 119, "kind": "issue", @@ -406,6 +423,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 120, "kind": "issue", @@ -430,6 +448,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 121, "kind": "issue", @@ -454,6 +473,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 125, "kind": "issue", @@ -478,6 +498,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 126, "kind": "issue", @@ -502,6 +523,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 127, "kind": "issue", @@ -525,6 +547,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 128, "kind": "issue", @@ -548,6 +571,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 131, "kind": "pr", @@ -571,6 +595,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "fullcalendar/temporal-polyfill", "number": 132, "kind": "pr", @@ -592,10 +617,390 @@ "updatedAt": "2026-11-13", "closedAt": null, "mergedAt": null + }, + { + "tracker": "github", + "repo": "tc39/ecma402", + "number": 1116, + "kind": "issue", + "work": "report", + "title": "FormatDateTimePattern: \"value ≤ 0, set value to 1 − value\" is wrong for calendars with a single era", + "url": "https://github.com/tc39/ecma402/issues/1116", + "summary": "ECMA-402 turns a year of 0 or below into 1 minus the year for every calendar, but only a calendar with an inverse era needs that. The indian and persian calendars have one signed era, so `-79 Śaka` and `-622 AP` are right, and native Temporal already gives those years.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": null, + "gmtNote": "GMT prints the year the engine prints and keeps no year rule of its own, so this changes nothing in GMT.", + "state": "open", + "draft": false, + "reviewDecision": null, + "comments": 1, + "maintainerComments": 1, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null, + "mergedAt": null + }, + { + "tracker": "github", + "repo": "nodejs/node", + "number": 67076, + "kind": "issue", + "work": "report", + "title": "Intl.DateTimeFormat formatToParts aborts the process (unreachable code) when the locale pattern has Y: please cherry-pick V8 0426b0d1045d into v22.x, v24.x and v26.x", + "url": "https://github.com/nodejs/node/issues/67076", + "summary": "Node stops the whole process when `formatToParts` or `formatRangeToParts` formats a date with a pattern that holds the week-of-year year, which some languages' patterns do. It asks Node 22, 24 and 26 to take the V8 fix that Chromium 158 already has.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D23", + "gmtNote": null, + "state": "open", + "draft": false, + "reviewDecision": null, + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-10-28", + "updatedAt": "2026-10-28", + "closedAt": null, + "mergedAt": null + }, + { + "tracker": "github", + "repo": "nodejs/node", + "number": 67457, + "kind": "issue", + "work": "report", + "title": "Temporal on v26.x: until() and round() add one smallestUnit to a whole number of years, months or weeks (temporal_rs 0.2.3)", + "url": "https://github.com/nodejs/node/issues/67457", + "summary": "Node 26 adds one `smallestUnit` when it rounds a whole number of years, months or weeks. It asks Node 26 to move to `temporal_rs` 0.2.4 or later, or to take the one fix (boa-dev/temporal#723) on its own.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": null, + "gmtNote": "GMT makes no change: it already follows the spec text, and `@js-temporal/polyfill` 0.5.1 is right.", + "state": "open", + "draft": false, + "reviewDecision": null, + "comments": 2, + "maintainerComments": 2, + "createdAt": "2026-11-13", + "updatedAt": "2026-11-14", + "closedAt": null, + "mergedAt": null + }, + { + "tracker": "jira", + "key": "CLDR-19873", + "role": "contributor", + "work": "report", + "title": "Incorrect use of week-based year (Y) in gl and kek date patterns", + "url": "https://unicode-org.atlassian.net/browse/CLDR-19873", + "contributionUrl": "https://unicode-org.atlassian.net/browse/CLDR-19873?focusedCommentId=213171", + "summary": "Some languages' date patterns print the week-of-year year where the calendar year belongs. The ticket names gl and kek, and our comment adds the other patterns on `main`, the gd and te repros and the Node crash.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D24", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 1, + "maintainerComments": 0, + "createdAt": "2026-10-20", + "updatedAt": "2026-11-13", + "closedAt": null + }, + { + "tracker": "jira", + "key": "CLDR-19912", + "work": "report", + "title": "Interval formats that drop, repeat or misplace a field (yo, rw, sw, brx, dz, en_JP, kgp, yrl, ku, qu, rm, sv, th, wae, ta)", + "url": "https://unicode-org.atlassian.net/browse/CLDR-19912", + "summary": "Interval patterns in 15 languages drop, repeat or misplace a field when a range is formatted: yo, rw, sw, brx, dz, en-JP, kgp, yrl, ku, qu, rm, sv, th, wae and ta. It includes the rw `yMMMd` pattern that CLDR 49 adds and the ta `hmv` pattern.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D29", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 1, + "maintainerComments": 0, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-15", + "closedAt": null + }, + { + "tracker": "jira", + "key": "CLDR-19913", + "work": "report", + "title": "Interval formats that write a field in a different form from the single date, or run two fields together (fur, gsw, ksh, mn, brx, zh iso8601, root chinese)", + "url": "https://unicode-org.atlassian.net/browse/CLDR-19913", + "summary": "Interval patterns in fur, gsw, ksh and mn write the month in a different form from the single date. They also run two fields together in brx and in zh with the iso8601 calendar, and the root locale drops the chinese related year.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D29", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23609", + "work": "report", + "title": "PersianCalendar::isLeapYear returns true for every year before 0 since ICU4C 75", + "url": "https://unicode-org.atlassian.net/browse/ICU-23609", + "summary": "ICU4C 75 and later counts every Persian year before year 0 as a leap year, because a C++ `%` rounds toward zero. WebKit on macOS shows it.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": null, + "gmtNote": "Only GMT running on macOS WebKit's own `Temporal` sees it, where `addDate` and `subtractDate` return `\"\"` for the dates it breaks. GMT on the polyfill is right.", + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 2, + "maintainerComments": 0, + "createdAt": "2026-11-11", + "updatedAt": "2026-11-11", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23619", + "work": "report", + "title": "Japanese calendar: use the Gregorian era for 1868-10-23 to 1872-12-31 (Meiji 1–5)", + "url": "https://unicode-org.atlassian.net/browse/ICU-23619", + "summary": "The japanese calendar prints a date before 1873 in a Japanese era, where the standard asks for the Gregorian era up to the end of 1872. ICU 79 fixes most of it but still prints Meiji 1 to 5 for 1868-10-23 to 1872-12-31.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D25", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23620", + "work": "report", + "title": "ja@calendar=japanese: a two-digit year (yy) prints one digit when the pattern contains 年", + "url": "https://unicode-org.atlassian.net/browse/ICU-23620", + "summary": "A `ja` date in the japanese calendar with `year: \"2-digit\"` prints `令和6年` where the standard asks for `令和06年`, because ICU's Japanese year numbering ignores the minimum digit count.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D27", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 1, + "maintainerComments": 0, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23621", + "work": "report", + "title": "DateTimePatternGenerator turns a yy skeleton into a padded rr related year (Chinese, Dangi)", + "url": "https://unicode-org.atlassian.net/browse/ICU-23621", + "summary": "Under `year: \"2-digit\"` the chinese and dangi calendars print the related year padded to two digits, where ECMA-402 prints it at full width.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D28", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23622", + "work": "report", + "title": "DateIntervalFormat: a flexible day period (B) is printed once for two periods, and a chinese or dangi skeleton with U falls back to a pattern that loses fields", + "url": "https://unicode-org.atlassian.net/browse/ICU-23622", + "summary": "ICU prints the flexible day period B once for two different periods, and the chinese and dangi U skeletons fall back to patterns that lose fields.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D29", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23623", + "work": "report", + "title": "DateIntervalFormat: when only the era differs, the range uses the y entry and prints one era, so one date loses its era", + "url": "https://unicode-org.atlassian.net/browse/ICU-23623", + "summary": "When two dates differ only in their era, ICU takes the `y` interval pattern, which prints the era once, so one date loses its era: `scn` in the gregorian calendar, and ca, chr, fi, hr, it and ko in the ethiopic, japanese and roc calendars.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D29", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-15", + "updatedAt": "2026-11-15", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23624", + "work": "report", + "title": "DateIntervalFormat: an hour cycle set by the caller is not applied when the interval pattern comes from CLDR with a different hour letter (ja hm)", + "url": "https://unicode-org.atlassian.net/browse/ICU-23624", + "summary": "A `ja` range with `hourCycle: \"h12\"` keeps the `K` hour of the CLDR interval pattern and prints `0時` where the single date prints 12.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D29", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-15", + "updatedAt": "2026-11-15", + "closedAt": null + }, + { + "tracker": "jira", + "key": "ICU-23625", + "work": "report", + "title": "DateIntervalFormat: the long flexible day period width is not applied to B, so a range prints AM or PM where the single date prints the wide period", + "url": "https://unicode-org.atlassian.net/browse/ICU-23625", + "summary": "Under `dayPeriod: \"long\"` a range keeps the stored `B` width, so in 22 locales such as bgc, to, sd and gaa it prints AM or PM where the single date prints the wide period.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D29", + "gmtNote": null, + "state": "open", + "status": "New", + "resolution": null, + "fixVersions": [], + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-11-15", + "updatedAt": "2026-11-15", + "closedAt": null + }, + { + "tracker": "chromium", + "id": 585635918, + "work": "report", + "title": "Intl.DateTimeFormat keeps the \"islamic\" and \"islamic-rgsa\" calendars instead of the Intl era and monthCode fallbacks", + "url": "https://issues.chromium.org/issues/585635918", + "summary": "V8 keeps `islamic` and `islamic-rgsa` as the resolved calendar. ECMA-402 turns `islamic` into `islamic-tbla` and no longer has `islamic-rgsa`, and WebKit 26.6 does both.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D30", + "gmtNote": null, + "state": "open", + "comments": null, + "maintainerComments": null, + "createdAt": "2026-11-14", + "updatedAt": "2026-11-14", + "closedAt": null + }, + { + "tracker": "bugzilla", + "host": "bugs.webkit.org", + "id": 330688, + "work": "report", + "title": "Temporal and Intl reject the time zone ids CST6CDT, EST5EDT, MST7MDT and PST8PDT", + "url": "https://bugs.webkit.org/show_bug.cgi?id=330688", + "summary": "WebKit 26.6 rejects the time zone ids `CST6CDT`, `EST5EDT`, `MST7MDT` and `PST8PDT` in `Intl` and `Temporal`, although the time zone database defines all four as zones. Chromium, Firefox and Node accept them.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": null, + "gmtNote": "GMT has no workaround for this: it asks the engine about a time zone id, so these four read as invalid input on WebKit until the bug is fixed.", + "state": "open", + "status": "NEW", + "resolution": null, + "comments": 1, + "maintainerComments": 0, + "createdAt": "2026-11-09", + "updatedAt": "2026-11-10", + "closedAt": null + }, + { + "tracker": "bugzilla", + "host": "bugzilla.mozilla.org", + "id": 2085525, + "work": "report", + "title": "Intl.DateTimeFormat formatRange prints AM/PM instead of the dayPeriod when timeZoneName is set", + "url": "https://bugzilla.mozilla.org/show_bug.cgi?id=2085525", + "summary": "Firefox's `formatRange` prints AM/PM instead of the flexible day period when `timeZoneName` is set. A single `format` in Firefox, and `formatRange` in every other engine, print the day period.", + "pairsWith": [], + "closes": [], + "dependsOn": [], + "gmtGuard": "D17", + "gmtNote": null, + "state": "open", + "status": "UNCONFIRMED", + "resolution": null, + "comments": 0, + "maintainerComments": 0, + "createdAt": "2026-10-24", + "updatedAt": "2026-10-26", + "closedAt": null } ], "listings": [ { + "tracker": "github", "repo": "sindresorhus/awesome-nodejs", "number": 1402, "kind": "issue", @@ -613,6 +1018,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "sorrycc/awesome-javascript", "number": 1209, "kind": "pr", @@ -630,6 +1036,7 @@ "mergedAt": null }, { + "tracker": "github", "repo": "you-dont-need/You-Dont-Need-Momentjs", "number": 159, "kind": "pr", diff --git a/apps/dox/src/data/upstream-filings.test.ts b/apps/dox/src/data/upstream-filings.test.ts index d1102847c..14580e82d 100644 --- a/apps/dox/src/data/upstream-filings.test.ts +++ b/apps/dox/src/data/upstream-filings.test.ts @@ -5,6 +5,10 @@ import { resolve } from "node:path"; import { checked, contributions, + filingGroup, + filingGroups, + filingKey, + filingsForGroup, filedByUs, filedPrs, filings, @@ -19,14 +23,17 @@ import { listings, overlayLive, totalFilings, + TRACKERS, TRACKED_REPOS, unaffectingGmt, + type GitHubFiling, type UpstreamFiling, type UpstreamListing, } from "./upstream-filings"; +import { urlOf } from "../../../../scripts/lib/upstream-trackers.mjs"; import { getUtcNow, isAfterUtc, isValidUtc } from "@northguild/gmt"; -// The literal `DefectId` / `ZonedDefectId` / `BoundedWorkDefectId` union members +// The literal `DefectId` / `ZonedDefectId` / `BoundedWorkDefectId` / `CanaryDefectId` union members // `probeRepros.ts` and `repros.ts` declare — the same set `scripts/upstream.mjs check` parses out of // the same file, so a filing's `gmtGuard` can never name a group that doesn't exist. const reprosSrc = ["probeRepros.ts", "repros.ts"] @@ -43,7 +50,7 @@ const reprosSrc = ["probeRepros.ts", "repros.ts"] .join("\n"); const knownGuards = new Set(); for (const m of reprosSrc.matchAll( - /export type (?:DefectId|ZonedDefectId|BoundedWorkDefectId) =([^;]+);/g, + /export type (?:DefectId|ZonedDefectId|BoundedWorkDefectId|CanaryDefectId) =([^;]+);/g, )) { for (const lit of m[1].matchAll(/"([^"]+)"/g)) knownGuards.add(lit[1]); } @@ -59,18 +66,50 @@ describe("upstream filings", () => { expect(isAfterUtc(checked, getUtcNow())).toBe(false); }); - it("gives every filing a URL matching its own repo, kind and number", () => { + it("gives every filing a URL matching its own tracker and identity", () => { for (const f of filings) { - const expected = `https://github.com/${f.repo}/${f.kind === "pr" ? "pull" : "issues"}/${f.number}`; - expect(f.url).toBe(expected); + expect(f.url, filingKey(f)).toBe(urlOf(f)); } }); - it("has no duplicate repo+number", () => { - const keys = filings.map((f) => `${f.repo}#${f.number}`); + it("names a known tracker on every filing", () => { + for (const f of filings) + expect(TRACKERS, filingKey(f)).toContain(f.tracker); + }); + + it("has no duplicate identity", () => { + const keys = filings.map(filingKey); expect(new Set(keys).size).toBe(keys.length); }); + it("gives a filing only the members of its own tracker", () => { + // GitHub's `kind`, `draft`, `reviewDecision` and `mergedAt` mean nothing on the Jira, Chromium + // or Bugzilla trackers, so none of those carries them. + for (const f of filings) { + if (f.tracker === "github") continue; + for (const field of [ + "repo", + "number", + "kind", + "draft", + "reviewDecision", + "mergedAt", + ]) { + expect(f, `${filingKey(f)} ${field}`).not.toHaveProperty(field); + } + } + }); + + it("groups filings under one heading per repository or tracker", () => { + const grouped = filingGroups.reduce( + (n, g) => n + filingsForGroup(g.id).length, + 0, + ); + expect(grouped).toBe(totalFilings); + const headings = filingGroups.map((g) => g.name); + expect(new Set(headings).size).toBe(headings.length); + }); + it("sums repo counts to the total", () => { const sum = filingsByRepo.reduce((n, row) => n + row.count, 0); expect(sum).toBe(totalFilings); @@ -96,7 +135,7 @@ describe("upstream filings", () => { if (f.gmtGuard !== null) { expect( knownGuards.has(f.gmtGuard), - `${f.repo}#${f.number} gmtGuard "${f.gmtGuard}"`, + `${filingKey(f)} gmtGuard "${f.gmtGuard}"`, ).toBe(true); } } @@ -105,10 +144,9 @@ describe("upstream filings", () => { it("covers every filing in GMT: exactly one of gmtGuard or gmtNote", () => { // A filing with neither would be a defect GMT neither works around nor avoids. for (const f of filings) { - expect( - (f.gmtGuard === null) !== (f.gmtNote === null), - `${f.repo}#${f.number}`, - ).toBe(true); + expect((f.gmtGuard === null) !== (f.gmtNote === null), filingKey(f)).toBe( + true, + ); } expect(handledInGmt + unaffectingGmt).toBe(totalFilings); }); @@ -121,20 +159,18 @@ describe("upstream filings", () => { for (const f of filings) { if (f.role === undefined) continue; - expect(["author", "contributor"], `${f.repo}#${f.number}`).toContain( - f.role, - ); + expect(["author", "contributor"], filingKey(f)).toContain(f.role); } }); it("links our own comment on every filing we did not open", () => { // Without it the page would show a maintainer's PR with nothing saying what we did on it. - // `url` cannot carry the anchor: `scripts/upstream.mjs` rewrites it from repo, kind and number. + // `url` cannot carry the anchor: `scripts/upstream.mjs` rewrites it from the entry's identity. for (const f of filings) { - const label = `${f.repo}#${f.number}`; + const label = filingKey(f); if (f.role === "contributor") { expect(f.contributionUrl, label).toBeTruthy(); - expect(f.contributionUrl, label).toContain(`/${f.number}#`); + expect(f.contributionUrl, label).toContain(f.url); } else { expect(f.contributionUrl ?? null, label).toBeNull(); } @@ -169,9 +205,9 @@ describe("upstream filings", () => { }); it("pairs symmetrically: if A pairsWith B, B pairsWith A", () => { - const byKey = new Map(filings.map((f) => [`${f.repo}#${f.number}`, f])); + const byKey = new Map(filings.map((f) => [filingKey(f), f])); for (const f of filings) { - const key = `${f.repo}#${f.number}`; + const key = filingKey(f); for (const partnerKey of f.pairsWith) { const partner = byKey.get(partnerKey); expect( @@ -187,7 +223,7 @@ describe("upstream filings", () => { }); it("names only filings that exist in dependsOn and closes", () => { - const keys = new Set(filings.map((f) => `${f.repo}#${f.number}`)); + const keys = new Set(filings.map(filingKey)); for (const f of filings) { for (const dep of f.dependsOn) { // A dependency may be a filing tracked here, or an upstream number this @@ -218,8 +254,9 @@ describe("upstream filings", () => { describe("overlayLive", () => { const filing = ( number: number, - fields: Partial = {}, - ): UpstreamFiling => ({ + fields: Partial = {}, + ): GitHubFiling => ({ + tracker: "github", repo: "tc39/proposal-temporal", number, kind: "issue", @@ -251,7 +288,10 @@ describe("overlayLive", () => { { checked: committedAt, filings: [filing(3335), filing(3336)] }, { checked: liveAt, filings: [filing(3335)] }, ); - expect(result.filings.map((f) => f.number)).toEqual([3335, 3336]); + expect(result.filings.map(filingKey)).toEqual([ + "tc39/proposal-temporal#3335", + "tc39/proposal-temporal#3336", + ]); }); it("takes the hand-written fields from the committed file", () => { @@ -308,7 +348,7 @@ describe("overlayLive", () => { filings: [filing(3336), filing(3340, { new: true }), polyfill], }, ); - expect(result.filings.map((f) => `${f.repo}#${f.number}`)).toEqual([ + expect(result.filings.map(filingKey)).toEqual([ "js-temporal/temporal-polyfill#400", "tc39/proposal-temporal#3336", "tc39/proposal-temporal#3340", @@ -352,7 +392,8 @@ describe("overlayLive", () => { it("orders repositories as the tracker lists them, not alphabetically", () => { const at = "2026-11-02T10:00:00Z"; - const make = (repo: string, number: number): UpstreamFiling => ({ + const make = (repo: string, number: number): GitHubFiling => ({ + tracker: "github", repo, number, kind: "issue", @@ -387,7 +428,7 @@ describe("overlayLive", () => { ], }, ); - expect(result.filings.map((f) => `${f.repo}#${f.number}`)).toEqual([ + expect(result.filings.map(filingKey)).toEqual([ "js-temporal/temporal-polyfill#400", "tc39/proposal-temporal#3336", "fullcalendar/temporal-polyfill#130", @@ -397,9 +438,89 @@ describe("overlayLive", () => { it("names only tracked repositories in the committed data", () => { for (const f of filings) { - expect(TRACKED_REPOS).toContain(f.repo); + if (f.tracker === "github") expect(TRACKED_REPOS).toContain(f.repo); } }); + + it("orders every GitHub repository before the other trackers", () => { + const at = "2026-11-02T10:00:00Z"; + const jira = { + tracker: "jira", + key: "ICU-23619", + work: "report", + title: "t", + url: "https://unicode-org.atlassian.net/browse/ICU-23619", + summary: "s", + pairsWith: [], + closes: [], + dependsOn: [], + gmtGuard: "D25", + gmtNote: null, + state: "open", + status: "New", + resolution: null, + fixVersions: [], + comments: 0, + maintainerComments: 0, + createdAt: "2026-11-14", + updatedAt: "2026-11-14", + closedAt: null, + } satisfies UpstreamFiling; + const chromium = { + tracker: "chromium", + id: 585635918, + work: "report", + title: "t", + url: "https://issues.chromium.org/issues/585635918", + summary: "s", + pairsWith: [], + closes: [], + dependsOn: [], + gmtGuard: "D30", + gmtNote: null, + state: "open", + comments: null, + maintainerComments: null, + createdAt: "2026-11-14", + updatedAt: "2026-11-14", + closedAt: null, + } satisfies UpstreamFiling; + const github: GitHubFiling = { + tracker: "github", + repo: "nodejs/node", + number: 67076, + kind: "issue", + work: "report", + title: "t", + url: "https://github.com/nodejs/node/issues/67076", + summary: "s", + pairsWith: [], + closes: [], + dependsOn: [], + gmtGuard: "D23", + gmtNote: null, + state: "open", + draft: false, + reviewDecision: null, + comments: 0, + maintainerComments: 0, + createdAt: "2026-10-28", + updatedAt: "2026-10-28", + closedAt: null, + mergedAt: null, + }; + const result = overlayLive( + { checked: at, filings: [chromium, jira, github] }, + { checked: "2026-11-02T11:00:00Z", filings: [chromium, jira, github] }, + ); + expect(result.filings.map(filingKey)).toEqual([ + "nodejs/node#67076", + "ICU-23619", + "chromium#585635918", + ]); + expect(filingGroup(jira).name).toBe("Unicode Jira (ICU and CLDR)"); + expect(filingGroup(chromium).name).toBe("Chromium issue tracker"); + }); }); const TEMPORAL_REPOS = [ @@ -412,6 +533,7 @@ const listing = ( number: number, fields: Partial = {}, ): UpstreamListing => ({ + tracker: "github", repo: "example/comparison-list", number, kind: "issue", @@ -451,10 +573,10 @@ describe("upstream listings", () => { }); it("is on a project outside Temporal, and shares no key with a filing", () => { - const filingKeys = new Set(filings.map((f) => `${f.repo}#${f.number}`)); + const filingKeys = new Set(filings.map(filingKey)); for (const l of listings) { - expect(TEMPORAL_REPOS, `${l.repo}#${l.number}`).not.toContain(l.repo); - expect(filingKeys.has(`${l.repo}#${l.number}`)).toBe(false); + expect(TEMPORAL_REPOS, filingKey(l)).not.toContain(l.repo); + expect(filingKeys.has(filingKey(l))).toBe(false); } }); @@ -603,4 +725,94 @@ describe("scripts/upstream.mjs check", () => { expect(result.ok).toBe(false); expect(result.output).toContain("duplicate"); }); + + // Each tracker has its own members, and `check` rejects any that belongs to another. + const entry = (tracker: string, id?: Record) => { + const found = (committed.filings as Record[]).find( + (f) => + f.tracker === tracker && + (id === undefined || Object.entries(id).every(([k, v]) => f[k] === v)), + ); + expect(found, tracker).toBeDefined(); + return found!; + }; + const withFilings = (...changed: Record[]) => { + const keys = new Set( + changed.map((c) => + JSON.stringify([c.tracker, c.key, c.id, c.repo, c.number]), + ), + ); + return { + ...committed, + filings: [ + ...(committed.filings as Record[]).filter( + (f) => + !keys.has( + JSON.stringify([f.tracker, f.key, f.id, f.repo, f.number]), + ), + ), + ...changed, + ], + }; + }; + + it("fails on a Jira filing that carries a GitHub member", () => { + const bad = { ...entry("jira"), reviewDecision: null }; + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("does not belong to a jira filing"); + }); + + it("fails on a Chromium filing that carries a Bugzilla status", () => { + const bad = { ...entry("chromium"), status: "NEW" }; + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("does not belong to a chromium filing"); + }); + + it("fails on a GitHub filing without a kind", () => { + const { kind: _kind, ...bad } = entry("github"); + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("kind"); + }); + + it("fails on a Jira key outside ICU and CLDR", () => { + const bad = { + ...entry("jira"), + key: "ABC-1", + url: "https://unicode-org.atlassian.net/browse/ABC-1", + }; + const result = run(withFilings(entry("jira"), bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("not an ICU or CLDR issue key"); + }); + + it("fails on a Chromium filing with comment counts", () => { + const bad = { ...entry("chromium"), comments: 2, maintainerComments: 1 }; + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("null on a Chromium filing"); + }); + + it("fails on a Bugzilla filing on another host", () => { + const bad = { ...entry("bugzilla"), host: "bugzilla.example.test" }; + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("host"); + }); + + it("fails on an unknown tracker", () => { + const bad = { ...entry("jira"), tracker: "linear" }; + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("tracker"); + }); + + it("fails on an open Jira filing that has a resolution", () => { + const bad = { ...entry("jira"), state: "open", resolution: "Fixed" }; + const result = run(withFilings(bad)); + expect(result.ok).toBe(false); + expect(result.output).toContain("resolved as"); + }); }); diff --git a/apps/dox/src/data/upstream-filings.ts b/apps/dox/src/data/upstream-filings.ts index db72750d5..05bea1f01 100644 --- a/apps/dox/src/data/upstream-filings.ts +++ b/apps/dox/src/data/upstream-filings.ts @@ -1,6 +1,9 @@ /** * The upstream filings GMT has reported against `@js-temporal/polyfill`, - * `tc39/proposal-temporal` and `fullcalendar/temporal-polyfill`. `/upstream/` and its `UpstreamTracker.astro` + * `tc39/proposal-temporal`, `fullcalendar/temporal-polyfill`, `tc39/ecma402` and `nodejs/node` on + * GitHub, and on the Unicode Jira, the Chromium issue tracker and two Bugzilla servers. Every entry + * names its tracker (`tracker`), and each tracker has its own identity fields, so no entry carries a + * member that belongs to another tracker. `/upstream/` and its `UpstreamTracker.astro` * import every figure from here, the same way `gmt-stats.ts` is the one place * a GMT number is typed. * @@ -23,6 +26,7 @@ * error, but a glob that matches nothing is just an empty object. */ import { isAfterUtc } from "@northguild/gmt"; +import { shortRef } from "./temporal-compat"; import committedData from "./upstream-filings.json"; /** `port` mirrors an already-merged upstream commit; `fix` and `report` are a @@ -30,10 +34,8 @@ import committedData from "./upstream-filings.json"; * publish of commits already on `main`. */ export type FilingWork = "port" | "fix" | "report" | "release"; -export interface UpstreamFiling { - repo: string; - number: number; - kind: "pr" | "issue"; +/** What every tracker's filing carries: our judgement, then what the tracker reports. */ +interface FilingBase { /** `null` only for a filing `sync` just discovered and nobody has classified yet. */ work: FilingWork | null; title: string; @@ -69,24 +71,79 @@ export interface UpstreamFiling { */ outcome?: string | null; /** A `"contributor"` row's link to our own comment. `url` cannot hold it: `sync` rewrites `url` - * from the repo, kind and number every run. */ + * from the tracker's own identity every run. */ contributionUrl?: string | null; state: "open" | "closed"; + createdAt: string; + updatedAt: string; + closedAt: string | null; + /** Live file only: discovery found this filing but the committed file doesn't have it + * yet, so its hand-written fields (`summary`, `gmtGuard`, ...) are still empty. */ + new?: boolean; +} + +/** A GitHub issue or pull request. */ +export interface GitHubFiling extends FilingBase { + tracker: "github"; + repo: string; + number: number; + kind: "pr" | "issue"; draft: boolean; reviewDecision: "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED" | null; comments: number; /** Comments by anyone outside GMT (`AUTHORS` in `scripts/upstream.mjs`), so a * cross-link one of us posts never counts as a maintainer response. */ maintainerComments: number; - createdAt: string; - updatedAt: string; - closedAt: string | null; mergedAt: string | null; - /** Live file only: `gh` found this filing but the committed file doesn't have it - * yet, so its hand-written fields (`summary`, `gmtGuard`, ...) are still empty. */ - new?: boolean; } +/** An issue in the Unicode Jira (`ICU-…` or `CLDR-…`). */ +export interface JiraFiling extends FilingBase { + tracker: "jira"; + /** The Jira key, such as `"ICU-23619"`. */ + key: string; + /** Jira's own status name, such as `"Accepted"` or `"Done"`. */ + status: string; + /** Jira's resolution name once resolved, such as `"Fixed"`; `null` while unresolved. */ + resolution: string | null; + fixVersions: readonly string[]; + comments: number; + maintainerComments: number; +} + +/** + * An issue on the Chromium issue tracker. The tracker has no public API, so what is read is the + * state and the dates; the comment counts are `null` because the endpoint we can call without + * signing in does not return comments. + */ +export interface ChromiumFiling extends FilingBase { + tracker: "chromium"; + /** The numeric issue id. */ + id: number; + comments: null; + maintainerComments: null; +} + +/** A bug on a Bugzilla server (`bugzilla.mozilla.org` or `bugs.webkit.org`). */ +export interface BugzillaFiling extends FilingBase { + tracker: "bugzilla"; + host: string; + /** The numeric bug id. */ + id: number; + /** Bugzilla's status, such as `"NEW"` or `"RESOLVED"`. */ + status: string; + /** Bugzilla's resolution once resolved, such as `"FIXED"`; `null` while open. */ + resolution: string | null; + comments: number; + maintainerComments: number; +} + +export type UpstreamFiling = + | GitHubFiling + | JiraFiling + | ChromiumFiling + | BugzillaFiling; + /** * A pull request or an issue GMT opened on a project outside Temporal, such as a comparison list * that should include GMT. It fixes no Temporal defect, so it is not a filing: it has no `work`, @@ -94,6 +151,7 @@ export interface UpstreamFiling { * synced. */ export interface UpstreamListing { + tracker: "github"; repo: string; number: number; kind: "pr" | "issue"; @@ -140,8 +198,22 @@ export const HAND_WRITTEN_FIELDS = [ * `scripts/upstream.mjs`, which a test holds equal. */ export const LISTING_HAND_WRITTEN_FIELDS = ["summary"] as const; -const keyOf = (f: { repo: string; number: number }): string => - `${f.repo}#${f.number}`; +/** The stable identity of an entry: `owner/repo#n`, `ICU-23619`, `chromium#n`, `host#n`. */ +export const filingKey = (f: UpstreamFiling | UpstreamListing): string => { + switch (f.tracker) { + case "github": + return `${f.repo}#${f.number}`; + case "jira": + return f.key; + case "chromium": + return `chromium#${f.id}`; + case "bugzilla": + return `${f.host}#${f.id}`; + } +}; + +/** The trackers, in page order. Mirrors `TRACKERS` in `scripts/upstream.mjs`. */ +export const TRACKERS = ["github", "jira", "chromium", "bugzilla"] as const; /** * The repositories the tracker follows, in page order. Mirrors `REPOS` in `scripts/upstream.mjs`, @@ -151,20 +223,98 @@ export const TRACKED_REPOS = [ "js-temporal/temporal-polyfill", "tc39/proposal-temporal", "fullcalendar/temporal-polyfill", + "tc39/ecma402", + "nodejs/node", ] as const; -const repoRank = (repo: string): number => { - const i = (TRACKED_REPOS as readonly string[]).indexOf(repo); - return i === -1 ? TRACKED_REPOS.length : i; +/** A heading on the page: one GitHub repository, or one other tracker. */ +export interface FilingGroup { + /** Stable id, the page's grouping key. */ + id: string; + /** What the heading says. */ + name: string; + /** Where the heading links. */ + href: string; +} + +const JIRA_HOST = "unicode-org.atlassian.net"; + +/** Which heading a filing sits under. */ +export function filingGroup(f: UpstreamFiling): FilingGroup { + switch (f.tracker) { + case "github": + return { + id: f.repo, + name: f.repo, + href: `https://github.com/${f.repo}`, + }; + case "jira": + return { + id: JIRA_HOST, + name: "Unicode Jira (ICU and CLDR)", + href: `https://${JIRA_HOST}`, + }; + case "chromium": + return { + id: "issues.chromium.org", + name: "Chromium issue tracker", + href: "https://issues.chromium.org", + }; + case "bugzilla": + return { + id: f.host, + name: + f.host === "bugs.webkit.org" ? "WebKit Bugzilla" : "Mozilla Bugzilla", + href: `https://${f.host}`, + }; + } +} + +/** The short label a table prints for one filing: `tc39 #3292`, `ICU-23619`, `Chromium 585635918`. */ +export function filingRef(f: UpstreamFiling | UpstreamListing): string { + switch (f.tracker) { + case "github": + return shortRef(f.repo, f.number); + case "jira": + return f.key; + case "chromium": + return `Chromium ${f.id}`; + case "bugzilla": + return `${f.host === "bugs.webkit.org" ? "WebKit" : "Mozilla"} ${f.id}`; + } +} + +/** The page order of two entries: tracker, then repository or host, then number. */ +const orderKey = ( + f: UpstreamFiling | UpstreamListing, +): [number, string, number] => { + const rank = TRACKERS.indexOf(f.tracker); + switch (f.tracker) { + case "github": { + const i = (TRACKED_REPOS as readonly string[]).indexOf(f.repo); + return [ + rank, + String(i === -1 ? TRACKED_REPOS.length : i).padStart(3, "0") + f.repo, + f.number, + ]; + } + case "jira": + return [rank, f.key.split("-")[0], Number(f.key.split("-")[1])]; + case "chromium": + return [rank, "", f.id]; + case "bugzilla": + return [rank, f.host, f.id]; + } }; -const byRepoThenNumber = ( - a: { repo: string; number: number }, - b: { repo: string; number: number }, -): number => - repoRank(a.repo) - repoRank(b.repo) || - a.repo.localeCompare(b.repo) || - a.number - b.number; +const byPageOrder = ( + a: UpstreamFiling | UpstreamListing, + b: UpstreamFiling | UpstreamListing, +): number => { + const [ra, sa, na] = orderKey(a); + const [rb, sb, nb] = orderKey(b); + return ra - rb || sa.localeCompare(sb) || na - nb; +}; /** * The live file laid over the committed one. @@ -183,9 +333,9 @@ export function overlayLive( live: UpstreamFilings, ): UpstreamFilings { if (!isAfterUtc(live.checked, committed.checked)) return committed; - const liveByKey = new Map(live.filings.map((f) => [keyOf(f), f])); + const liveByKey = new Map(live.filings.map((f) => [filingKey(f), f])); const fromCommitted = committed.filings.map((own) => { - const fresh = liveByKey.get(keyOf(own)); + const fresh = liveByKey.get(filingKey(own)); if (fresh === undefined) return own; const merged: Record = { ...fresh }; for (const field of HAND_WRITTEN_FIELDS) { @@ -194,11 +344,11 @@ export function overlayLive( } return merged as unknown as UpstreamFiling; }); - const committedKeys = new Set(committed.filings.map(keyOf)); - const onlyLive = live.filings.filter((f) => !committedKeys.has(keyOf(f))); + const committedKeys = new Set(committed.filings.map(filingKey)); + const onlyLive = live.filings.filter((f) => !committedKeys.has(filingKey(f))); return { checked: live.checked, - filings: [...fromCommitted, ...onlyLive].sort(byRepoThenNumber), + filings: [...fromCommitted, ...onlyLive].sort(byPageOrder), listings: overlayListings(committed.listings ?? [], live.listings), }; } @@ -208,17 +358,17 @@ function overlayListings( live: readonly UpstreamListing[] | undefined, ): readonly UpstreamListing[] { if (live === undefined) return committed; - const liveByKey = new Map(live.map((l) => [keyOf(l), l])); + const liveByKey = new Map(live.map((l) => [filingKey(l), l])); return committed .map((own) => { - const fresh = liveByKey.get(keyOf(own)); + const fresh = liveByKey.get(filingKey(own)); if (fresh === undefined) return own; const merged: Record = { ...fresh }; for (const field of LISTING_HAND_WRITTEN_FIELDS) merged[field] = own[field]; return merged as unknown as UpstreamListing; }) - .sort(byRepoThenNumber); + .sort(byPageOrder); } function isUpstreamFilings(value: unknown): value is UpstreamFilings { @@ -226,7 +376,12 @@ function isUpstreamFilings(value: unknown): value is UpstreamFilings { typeof value === "object" && value !== null && typeof (value as UpstreamFilings).checked === "string" && - Array.isArray((value as UpstreamFilings).filings) + Array.isArray((value as UpstreamFilings).filings) && + // A live file written before the trackers were named holds GitHub entries without a + // `tracker`; it is ignored and the committed file stands. + (value as UpstreamFilings).filings.every((f) => + (TRACKERS as readonly string[]).includes(f?.tracker), + ) ); } @@ -269,14 +424,14 @@ export const checked: string = upstreamFilings.checked; export const listings: readonly UpstreamListing[] = upstreamFilings.listings ?? []; -/** Every distinct repository a filing names, in first-seen (JSON) order. */ -export const filingRepos: readonly string[] = [ - ...new Set(filings.map((f) => f.repo)), +/** Every distinct heading a filing sits under, in first-seen (JSON) order. */ +export const filingGroups: readonly FilingGroup[] = [ + ...new Map(filings.map((f) => [filingGroup(f).id, filingGroup(f)])).values(), ]; -/** Filings for one repository, in the order the JSON lists them (repo, then number). */ -export function filingsForRepo(repo: string): readonly UpstreamFiling[] { - return filings.filter((f) => f.repo === repo); +/** Filings under one heading, in the order the JSON lists them. */ +export function filingsForGroup(id: string): readonly UpstreamFiling[] { + return filings.filter((f) => filingGroup(f).id === id); } export interface CountRow { @@ -284,18 +439,20 @@ export interface CountRow { count: number; } -/** How many filings name each repository. */ -export const filingsByRepo: readonly CountRow[] = filingRepos.map((repo) => ({ - label: repo, - count: filingsForRepo(repo).length, +/** How many filings sit under each heading. */ +export const filingsByRepo: readonly CountRow[] = filingGroups.map((g) => ({ + label: g.id, + count: filingsForGroup(g.id).length, })); -/** How many filings are a PR versus an issue. */ +/** How many filings are a GitHub PR versus a GitHub issue; other trackers have issues only. */ export const filingsByKind: readonly CountRow[] = ( ["pr", "issue"] as const ).map((kind) => ({ label: kind, - count: filings.filter((f) => f.kind === kind).length, + count: filings.filter( + (f) => (f.tracker === "github" ? f.kind : "issue") === kind, + ).length, })); /** How many filings are open versus closed. */ @@ -308,7 +465,7 @@ export const filingsByState: readonly CountRow[] = ( /** Filings with at least one comment from someone other than the author. */ export const filingsWithMaintainerResponse: number = filings.filter( - (f) => f.maintainerComments > 0, + (f) => (f.maintainerComments ?? 0) > 0, ).length; /** Every distinct non-null `gmtGuard` a filing names — the GMT canary groups @@ -344,5 +501,5 @@ export const contributions: number = filings.filter((f) => !isOurs(f)).length; /** Our own pull requests — the filings that carry a ready-to-merge patch. A maintainer's PR we * only commented on is not one of these, which is why the page cannot count `kind === "pr"`. */ export const filedPrs: number = filings.filter( - (f) => isOurs(f) && f.kind === "pr", + (f) => isOurs(f) && f.tracker === "github" && f.kind === "pr", ).length; diff --git a/apps/dox/src/data/upstream-trackers.test.ts b/apps/dox/src/data/upstream-trackers.test.ts new file mode 100644 index 000000000..df3b3ac3a --- /dev/null +++ b/apps/dox/src/data/upstream-trackers.test.ts @@ -0,0 +1,337 @@ +import * as gmt from "@northguild/gmt"; +import { + bugzillaBugUrl, + bugzillaCommentsUrl, + chromiumIssueUrl, + identityOf, + isJiraKey, + jiraDiscoveryUrl, + jiraIssueUrl, + keyOf, + makeDays, + parseBugzilla, + parseChromium, + parseJira, + parseJiraDiscovery, + SYNCED_FIELDS, + urlOf, +} from "../../../../scripts/lib/upstream-trackers.mjs"; + +// The readers take a recorded response as text and know nothing of the network, so each test +// feeds one a trimmed copy of what the tracker returned (Jira on 2026-11-14, Chromium's page +// JSON, Bugzilla's REST API) and never calls out. +const days = makeDays(gmt); +const OURS = "712020:edbd7a30-b6e5-42d7-b938-06b19b5d87a9"; + +describe("makeDays", () => { + it("reads a time in the reporter's offset as the UTC day", () => { + // 21:53 in California on the 13th is the 14th in UTC; slicing the text would say the 13th. + expect(days.fromIso("2026-11-13T21:53:32.451-0800")).toBe("2026-11-14"); + expect(days.fromIso("2026-11-13T21:53:32.451-08:00")).toBe("2026-11-14"); + expect(days.fromIso("2026-11-14T01:00:00Z")).toBe("2026-11-14"); + }); + + it("answers null for anything that is not a time", () => { + expect(days.fromIso("")).toBeNull(); + expect(days.fromIso(undefined)).toBeNull(); + expect(days.fromEpochSeconds("x")).toBeNull(); + }); + + it("reads epoch seconds as a UTC day", () => { + expect(days.fromEpochSeconds(1794679042)).toBe("2026-11-14"); + }); +}); + +describe("tracker identities", () => { + it("names and links each tracker's entries", () => { + const refs = [ + { tracker: "github", repo: "nodejs/node", number: 67076, kind: "issue" }, + { tracker: "jira", key: "ICU-23619" }, + { tracker: "chromium", id: 585635918 }, + { tracker: "bugzilla", host: "bugs.webkit.org", id: 330688 }, + ]; + expect(refs.map(keyOf)).toEqual([ + "nodejs/node#67076", + "ICU-23619", + "chromium#585635918", + "bugs.webkit.org#330688", + ]); + expect(refs.map(urlOf)).toEqual([ + "https://github.com/nodejs/node/issues/67076", + "https://unicode-org.atlassian.net/browse/ICU-23619", + "https://issues.chromium.org/issues/585635918", + "https://bugs.webkit.org/show_bug.cgi?id=330688", + ]); + }); + + it("keeps only the identity members of an entry", () => { + expect( + identityOf({ tracker: "jira", key: "ICU-23619", status: "New" }), + ).toEqual({ key: "ICU-23619" }); + }); + + it("accepts keys of the projects we file in and no others", () => { + expect(isJiraKey("ICU-23619")).toBe(true); + expect(isJiraKey("CLDR-19912")).toBe(true); + expect(isJiraKey("ABC-1")).toBe(false); + expect(isJiraKey("ICU-0")).toBe(false); + }); + + it("gives GitHub-only fields to GitHub alone", () => { + for (const tracker of ["jira", "chromium", "bugzilla"] as const) { + for (const field of ["draft", "reviewDecision", "mergedAt"]) { + expect(SYNCED_FIELDS[tracker]).not.toContain(field); + } + } + expect(SYNCED_FIELDS.github).toContain("mergedAt"); + }); +}); + +const jiraIssue = (over: Record = {}) => + JSON.stringify({ + key: "ICU-23609", + fields: { + summary: "PersianCalendar::isLeapYear returns true for every year < 0", + status: { + name: "New", + statusCategory: { key: "new", name: "To Do" }, + }, + resolution: null, + resolutiondate: null, + fixVersions: [], + created: "2026-11-10T16:41:07.000-0800", + updated: "2026-11-10T17:02:44.118-0800", + comment: { + total: 3, + comments: [ + { author: { accountId: OURS }, body: "Adding the support thread." }, + { author: { accountId: OURS }, body: "More detail." }, + { author: { accountId: "557058:someone-else" }, body: "Thanks." }, + ], + }, + ...over, + }, + }); + +describe("Jira", () => { + it("searches by our reporter id in ICU and CLDR", () => { + const url = decodeURIComponent(jiraDiscoveryUrl()); + expect(url).toContain("/rest/api/3/search/jql?"); + expect(url).toContain(OURS); + expect(url).toContain("project in (ICU, CLDR)"); + expect(jiraIssueUrl("ICU-23609")).toContain("/rest/api/2/issue/ICU-23609?"); + }); + + it("lists the keys a search found and says whether the list is complete", () => { + const raw = JSON.stringify({ + issues: [{ key: "ICU-23609" }, { key: "CLDR-19912" }, { key: "XYZ-1" }], + isLast: true, + }); + expect(parseJiraDiscovery(raw)).toEqual({ + keys: ["ICU-23609", "CLDR-19912"], + complete: true, + }); + expect( + parseJiraDiscovery(JSON.stringify({ issues: [], isLast: false })) + .complete, + ).toBe(false); + }); + + it("refuses a search response without an issues list", () => { + expect(() => parseJiraDiscovery("{}")).toThrow(/no issues array/); + }); + + it("reads an open issue and counts only replies from others", () => { + expect(parseJira(jiraIssue(), "ICU-23609", days)).toEqual({ + title: "PersianCalendar::isLeapYear returns true for every year < 0", + url: "https://unicode-org.atlassian.net/browse/ICU-23609", + state: "open", + status: "New", + resolution: null, + fixVersions: [], + comments: 3, + maintainerComments: 1, + createdAt: "2026-11-11", + updatedAt: "2026-11-11", + closedAt: null, + }); + }); + + it("reads a resolved issue as closed, with its fix versions and day", () => { + const parsed = parseJira( + jiraIssue({ + status: { name: "Done", statusCategory: { key: "done" } }, + resolution: { name: "Fixed" }, + resolutiondate: "2026-11-20T09:00:00.000-0800", + fixVersions: [{ name: "79.1" }], + }), + "ICU-23609", + days, + ); + expect(parsed).toMatchObject({ + state: "closed", + status: "Done", + resolution: "Fixed", + fixVersions: ["79.1"], + closedAt: "2026-11-20", + }); + }); + + it("refuses a response for another issue or of another shape", () => { + expect(() => parseJira(jiraIssue(), "ICU-1", days)).toThrow(/unexpected/); + expect(() => parseJira("{}", "ICU-23609", days)).toThrow(/unexpected/); + }); +}); + +// A trimmed copy of the page JSON for an open issue: `)]}'`, then positional arrays, with the +// issue at response[0][1][22] as `[null, id, core, null, created, modified, resolved?, …]`. +const chromiumPage = (id: number, { resolved }: { resolved?: number } = {}) => { + const issue: unknown[] = [ + null, + id, + [1456516, 1, 2, 3, 3, "Intl.DateTimeFormat keeps the islamic calendar"], + null, + [1794679042, 304000000], + [1794679086, 219000000], + ]; + if (resolved !== undefined) issue[6] = [resolved]; + const slots: unknown[] = Array.from({ length: 22 }, () => null); + return `)]}'\n\n${JSON.stringify([["b.IssueFetchResponse", [...slots, issue]]])}`; +}; + +describe("Chromium", () => { + it("asks the tracker's own page endpoint", () => { + expect(chromiumIssueUrl(585635918)).toBe( + "https://issues.chromium.org/action/issues/585635918", + ); + }); + + it("reads an open issue, with comment counts it cannot know left null", () => { + expect(parseChromium(chromiumPage(585635918), 585635918, days)).toEqual({ + title: "Intl.DateTimeFormat keeps the islamic calendar", + url: "https://issues.chromium.org/issues/585635918", + state: "open", + comments: null, + maintainerComments: null, + createdAt: "2026-11-14", + updatedAt: "2026-11-14", + closedAt: null, + }); + }); + + it("reads an issue with a resolved time as closed", () => { + expect( + parseChromium( + chromiumPage(585635918, { resolved: 1794765442 }), + 585635918, + days, + ), + ).toMatchObject({ state: "closed", closedAt: "2026-11-15" }); + }); + + it("throws on a shape it does not recognise, so the caller keeps the last state", () => { + expect(() => parseChromium(")]}'\n[]", 585635918, days)).toThrow( + /unexpected response shape/, + ); + expect(() => parseChromium(chromiumPage(1), 585635918, days)).toThrow( + /unexpected response shape/, + ); + expect(() => + parseChromium("blocked", 585635918, days), + ).toThrow(); + }); +}); + +const bugzillaBug = (over: Record = {}) => + JSON.stringify({ + bugs: [ + { + id: 330688, + summary: "Temporal and Intl reject the time zone ids CST6CDT", + status: "NEW", + resolution: "", + is_open: true, + creator: "owner@example.test", + creation_time: "2026-11-09T20:15:00Z", + last_change_time: "2026-11-10T08:00:00Z", + ...over, + }, + ], + }); +const bugzillaComments = (creators: string[]) => + JSON.stringify({ + bugs: { + "330688": { + comments: creators.map((creator, count) => ({ count, creator })), + }, + }, + }); + +describe("Bugzilla", () => { + it("asks the host's REST API for the bug and its comments", () => { + expect(bugzillaBugUrl("bugs.webkit.org", 330688)).toContain( + "https://bugs.webkit.org/rest/bug/330688?include_fields=", + ); + expect(bugzillaCommentsUrl("bugzilla.mozilla.org", 2085525)).toBe( + "https://bugzilla.mozilla.org/rest/bug/2085525/comment", + ); + }); + + it("does not count the description, and counts replies by others as maintainers'", () => { + const parsed = parseBugzilla( + bugzillaBug(), + bugzillaComments([ + "owner@example.test", + "owner@example.test", + "triager@example.test", + ]), + "bugs.webkit.org", + 330688, + days, + ); + expect(parsed).toMatchObject({ + url: "https://bugs.webkit.org/show_bug.cgi?id=330688", + state: "open", + status: "NEW", + resolution: null, + comments: 2, + maintainerComments: 1, + createdAt: "2026-11-09", + updatedAt: "2026-11-10", + closedAt: null, + }); + }); + + it("reads a resolved bug as closed on the day it was resolved", () => { + const parsed = parseBugzilla( + bugzillaBug({ + status: "RESOLVED", + resolution: "FIXED", + is_open: false, + cf_last_resolved: "2026-11-12T10:00:00Z", + }), + bugzillaComments(["owner@example.test"]), + "bugs.webkit.org", + 330688, + days, + ); + expect(parsed).toMatchObject({ + state: "closed", + resolution: "FIXED", + closedAt: "2026-11-12", + comments: 0, + }); + }); + + it("refuses a response for another bug", () => { + expect(() => + parseBugzilla( + bugzillaBug({ id: 1 }), + bugzillaComments([]), + "bugs.webkit.org", + 330688, + days, + ), + ).toThrow(/unexpected response shape/); + }); +}); diff --git a/apps/dox/src/lib/bevel-border-widths.test.ts b/apps/dox/src/lib/bevel-border-widths.test.ts new file mode 100644 index 000000000..7c55f47be --- /dev/null +++ b/apps/dox/src/lib/bevel-border-widths.test.ts @@ -0,0 +1,305 @@ +/** + * Guard: a bevelled box never has border sides of different widths. + * + * Chromium paints `corner-shape: bevel` wrongly when the sides differ: the colour of the thick + * side runs along part of the opposite edge (a 3px series-coloured bottom bar showed as a + * partial line along the top). The house fix is one width on every side, the accent colour on + * the one side, and the extra thickness drawn as an inset `box-shadow` (with the same amount + * added to padding where the old border took layout room). + * + * A side of width 0 is ignored: it paints nothing, and a band with only side edges draws cleanly. + * + * The scan parses every stylesheet and every `"; + expect(findUnequalBevelBorders(css, "x.astro")).toHaveLength(1); + }); + + it("leaves an even border, and an uneven one with no bevel, alone", () => { + expect( + findUnequalBevelBorders( + ".a { border: 1px solid red; border-block-end-color: blue; corner-shape: bevel; }", + "x.css", + ), + ).toEqual([]); + expect( + findUnequalBevelBorders( + ".a { border: 1px solid red; border-block-end: 3px solid blue; }", + "x.css", + ), + ).toEqual([]); + }); + + it("has no bevelled rule with unequal border side widths", () => { + const report: string[] = []; + for (const file of files) { + const css = readFileSync(path.join(DOX, file), "utf8"); + for (const f of findUnequalBevelBorders(css, file)) { + report.push(`${file}:${f.line} ${f.selector} (${f.detail})`); + } + } + expect(report).toEqual([]); + }); +}); diff --git a/apps/dox/src/lib/mdx-jsx.ts b/apps/dox/src/lib/mdx-jsx.ts index 155ecea9a..9eae0de4a 100644 --- a/apps/dox/src/lib/mdx-jsx.ts +++ b/apps/dox/src/lib/mdx-jsx.ts @@ -9,6 +9,24 @@ * * Kept free of Astro globals so vitest can import it directly. */ +import { + areas as pulseAreas, + cardsIn as pulseCardsIn, + checkById as pulseCheck, + countWorkarounds, + filingsWaitedOn, + groupsClaimed, + runsFor as pulseRuns, + runsRead as pulseRunsRead, + type PulseLife, +} from "../data/pulse"; +import { filingRef as pulseFilingRef } from "../data/upstream-filings"; +import { + beats as pulseBeats, + beatsCaption, + cadenceText, + noSignal, +} from "./pulse-view"; import { BUNDLE_COLUMNS, bundleCells, bundleRows } from "./bundle-size"; import { KEY_POINTS } from "../data/canada-key-points"; import { keyPointsMarkdown } from "../data/clock-change-text"; @@ -24,12 +42,12 @@ import { compatGroups, groupLabel, groupWhatBreaks, - shortRef, stateLine, } from "../data/temporal-compat"; import { filedByUs, filedPrs, + filingRef, filings, handledInGmt, listings, @@ -337,9 +355,7 @@ function renderUpstreamDefects(): string { const rows = compatGroups.map((group) => { const sent = filings .filter((f) => f.gmtGuard && group.defects.includes(f.gmtGuard)) - .map( - (f) => `[${shortRef(f.repo, f.number)}](${f.contributionUrl ?? f.url})`, - ) + .map((f) => `[${filingRef(f)}](${f.contributionUrl ?? f.url})`) .join(", "); const { badge, count } = stateLine(group); // A guard row continues with why it is kept. The reason is free text, so it is escaped: a `|` @@ -464,7 +480,7 @@ function renderBehaviourMatrix(): string { * with it (CORE-8 review, #253). */ function renderUpstreamTracker(): string { - return `\n**So far we have sent ${filedByUs} reports and fixes to the Temporal projects, ${filedPrs} of them as ready-to-merge code changes${contributionClause}. ${coverageClause}: ${handledInGmt} through its own built-in fix, and ${unaffectingGmt} because the bug is in code GMT doesn't use.**\n`; + return `\n**So far we have sent ${filedByUs} reports and fixes to Temporal and the projects it builds on, ${filedPrs} of them as ready-to-merge code changes${contributionClause}. ${coverageClause}: ${handledInGmt} through its own built-in fix, and ${unaffectingGmt} because the bug is in code GMT doesn't use.**\n`; } /** @@ -484,6 +500,59 @@ function renderUpstreamListings(): string { ].join("\n"); } +/** A check's retirement, in words, for the text twin of `/pulse/`. */ +function pulseLife(life: PulseLife): string { + if (life.kind === "permanent") return `Stays. ${life.why}`; + if (life.kind === "condition") { + const waited = filingsWaitedOn(life).map( + (f) => `[${pulseFilingRef(f)}](${f.url})`, + ); + return `Retires when ${life.until}.${waited.length > 0 ? ` Waiting on ${waited.join(", ")}.` : ""}`; + } + const claimed = groupsClaimed(life); + if (claimed.length === 0) { + return "Retires with its workarounds, which are not in the compatibility snapshot yet."; + } + const c = countWorkarounds(claimed); + return `Retires with its workarounds: ${c.stillNeeded} still needed, ${c.removable} removable, ${c.guards} guards.`; +} + +/** + * `` as Markdown: each check's cadence, what it watches, its last results as words and + * what retires it. There is no next run: that is a live value the text cannot hold. + */ +function renderPulse(): string { + const out: string[] = [""]; + for (const area of pulseAreas) { + out.push(`## ${area.heading}`, "", area.blurb, ""); + for (const card of pulseCardsIn(area.id)) { + out.push(`### ${card.name}`, ""); + const cron = card.crons[0]; + if (cron === undefined) { + out.push("Runs with the Dox tests, never on a schedule.", ""); + } else { + out.push(card.crons.map(cadenceText).join(" and ") + ".", ""); + const runs = pulseRuns(card); + const lost = noSignal(runs, pulseRunsRead); + out.push( + lost !== null || runs === null || pulseRunsRead === null + ? `No signal: ${lost?.text ?? "Run history not read in this build"}.` + : beatsCaption(pulseBeats(cron, runs, pulseRunsRead)) + ".", + "", + ); + } + for (const id of card.checkIds) { + const check = pulseCheck(id); + out.push( + `- **${check.name}.** ${check.watches} ${check.finds} ${pulseLife(check.life)}`, + ); + } + out.push(""); + } + } + return out.join("\n"); +} + /** * Render the components that carry prose, and unwrap the ones that don't. * @@ -537,6 +606,7 @@ export function renderMdxComponents(body: string): string { out = replaceElements(out, "LibraryCompare", renderLibraryCompare); out = replaceElements(out, "UpstreamDefects", renderUpstreamDefects); out = replaceElements(out, "UpstreamTracker", renderUpstreamTracker); + out = replaceElements(out, "Pulse", renderPulse); out = replaceElements(out, "UpstreamListings", renderUpstreamListings); out = replaceElements(out, "BundleSize", renderBundleSize); out = replaceElements(out, "MigrationMap", renderMigrationMap); diff --git a/apps/dox/src/lib/native-engines.test.ts b/apps/dox/src/lib/native-engines.test.ts index f287c3dfb..9932b8b58 100644 --- a/apps/dox/src/lib/native-engines.test.ts +++ b/apps/dox/src/lib/native-engines.test.ts @@ -94,11 +94,15 @@ describe("the sidebar", () => { "install", "core-rules", "why-gmt", + "upstream", + "pulse", ]); }); - it("puts the engine page right after Helping fix Temporal", () => { + it("puts the engine page right after the bundle-size page", () => { const slugs = MIGRATE.map((p) => p.slug); - expect(slugs.indexOf("native-engines")).toBe(slugs.indexOf("upstream") + 1); + expect(slugs.indexOf("native-engines")).toBe( + slugs.indexOf("bundle-size") + 1, + ); }); }); diff --git a/apps/dox/src/lib/pulse-mount.test.ts b/apps/dox/src/lib/pulse-mount.test.ts new file mode 100644 index 000000000..27bf18d63 --- /dev/null +++ b/apps/dox/src/lib/pulse-mount.test.ts @@ -0,0 +1,97 @@ +/** + * @vitest-environment jsdom + */ +import { afterEach, describe, expect, it } from "vitest"; +import { screen } from "@testing-library/dom"; +import { setHtml, raw } from "~/widgets/builders"; +import { mountPulse, type PulseLib } from "./pulse-mount"; + +const lib: PulseLib = { + getUtcNow: () => "2026-11-14T09:00:00Z", + parseCronExpression: (c) => (c === "bad" ? null : { c }), + cronRuns: (_e, _z, r) => [{ instant: r.after.replace("09:00", "21:00") }], + formatRelativeUtc: (v, _l, o) => (v === o.reference ? "now" : "in 12 hours"), + diffUtc: (a, b) => (a === "old" ? 9 : 0.1 + (b === "" ? 0 : 0)), +}; + +const aborts: AbortController[] = []; +afterEach(() => { + for (const a of aborts.splice(0)) a.abort(); + document.body.replaceChildren(); +}); + +function setup(read = "2026-11-14T06:00:00Z"): HTMLElement { + const root = document.createElement("div"); + setHtml( + root, + raw(`
+

Next run

+

read

+
+
strip
+ +
`), + ); + document.body.append(root); + return root; +} + +async function run(root: HTMLElement, now = lib.getUtcNow) { + const c = new AbortController(); + aborts.push(c); + await mountPulse(root, c.signal, { + lib: () => Promise.resolve({ ...lib, getUtcNow: now }), + }); + return c; +} + +describe("mountPulse", () => { + it("fills the next-run and read-ago slots", async () => { + await run(setup()); + expect(screen.getByLabelText("next run")).toHaveTextContent("in 12 hours"); + expect(screen.getByLabelText("read ago")).toHaveTextContent("in 12 hours"); + }); + + it("switches an old strip to NO SIGNAL with the days", async () => { + await run(setup("old")); + expect(screen.getByText(/NO SIGNAL/)).toBeVisible(); + expect(screen.getByText("Run history is 9 days old")).toBeInTheDocument(); + expect(screen.queryByText("strip")).not.toBeVisible(); + }); + + it("leaves a recent strip alone", async () => { + await run(setup()); + expect(screen.getByText("strip")).toBeVisible(); + expect(screen.getByText(/NO SIGNAL/)).not.toBeVisible(); + }); + + it("recomputes when the tab becomes visible, and stops after abort", async () => { + const root = setup(); + let at = "2026-11-14T09:00:00Z"; + const c = new AbortController(); + aborts.push(c); + await mountPulse(root, c.signal, { + now: () => at, + lib: () => Promise.resolve(lib), + }); + const slot = screen.getByLabelText("next run"); + expect(slot).toHaveTextContent("in 12 hours"); + at = "2026-11-14T21:00:00Z"; + // oxlint-disable-next-line dox-test/no-dispatch-event -- no user action changes visibility; the event is the input + document.dispatchEvent(new Event("visibilitychange")); + expect(slot).toHaveTextContent("now"); + c.abort(); + at = "2026-11-14T09:00:00Z"; + // oxlint-disable-next-line dox-test/no-dispatch-event -- no user action changes visibility; the event is the input + document.dispatchEvent(new Event("visibilitychange")); + expect(slot).toHaveTextContent("now"); + }); + + it("does nothing when already aborted", async () => { + const c = new AbortController(); + c.abort(); + const root = setup(); + await mountPulse(root, c.signal, { lib: () => Promise.resolve(lib) }); + expect(screen.getByLabelText("next run")).toBeEmptyDOMElement(); + }); +}); diff --git a/apps/dox/src/lib/pulse-mount.ts b/apps/dox/src/lib/pulse-mount.ts new file mode 100644 index 000000000..d6a994041 --- /dev/null +++ b/apps/dox/src/lib/pulse-mount.ts @@ -0,0 +1,134 @@ +/** + * The wiring of `/pulse/`. The server renders every card; this fills three reserved slots after + * first paint and changes nothing else: each card's "Next run", the "read … ago" line, and a + * strip whose run history has grown too old (it switches to NO SIGNAL). + * + * Time is gmt's, loaded from subpaths after first paint, with a `deps.now` seam for tests. There + * is no timer and no polling: the slots are recomputed when the tab becomes visible again. + * Aborting the signal removes that listener. + */ +import { INERT_HANDLE, type WidgetHandle } from "./widget-mount"; + +/** A read older than this many days is too old to call "recent" (`pulse-view.ts`). */ +const STALE_AFTER_DAYS = 8; + +/** The gmt functions the mount uses, so a test supplies its own. */ +export interface PulseLib { + getUtcNow(): string; + parseCronExpression(cron: string): unknown; + cronRuns( + expr: never, + zone: string, + range: { after: string; count: number }, + mode: "crontabMatch", + ): readonly { instant: string }[]; + formatRelativeUtc( + value: string, + locale: string, + options: { reference: string }, + ): string; + diffUtc(from: string, to: string, unit: "days"): number; +} + +export interface PulseDeps { + /** The current instant. Defaults to gmt's `getUtcNow`. */ + now: () => string; + /** The gmt functions. Defaults to the subpath imports. */ + lib: () => Promise; +} + +async function loadLib(): Promise { + const [get, parse, calc, format, utcCalc] = await Promise.all([ + import("@northguild/gmt/utc/get"), + import("@northguild/gmt/recurrence/parse"), + import("@northguild/gmt/recurrence/calculate"), + import("@northguild/gmt/utc/format"), + import("@northguild/gmt/utc/calculate"), + ]); + return { + getUtcNow: get.getUtcNow, + parseCronExpression: parse.parseCronExpression, + cronRuns: calc.cronRuns as PulseLib["cronRuns"], + formatRelativeUtc: format.formatRelativeUtc, + diffUtc: utcCalc.diffUtc as PulseLib["diffUtc"], + }; +} + +export function mountPulse( + root: HTMLElement, + signal: AbortSignal, + deps: Partial = {}, +): Promise { + if (signal.aborted) return Promise.resolve(INERT_HANDLE); + const own = new AbortController(); + signal.addEventListener("abort", () => own.abort(), { once: true }); + const life = own.signal; + const doc = root.ownerDocument; + + return (deps.lib ?? loadLib)().then((lib) => { + if (life.aborted) return INERT_HANDLE; + const now = (): string => deps.now?.() ?? lib.getUtcNow(); + + const fill = (): void => { + if (life.aborted) return; + const at = now(); + for (const el of root.querySelectorAll( + "[data-pulse-next]", + )) { + const cron = el.getAttribute("data-pulse-next") ?? ""; + const expr = lib.parseCronExpression(cron); + if (expr === null) continue; + const next = lib.cronRuns( + expr as never, + "UTC", + { after: at, count: 1 }, + "crontabMatch", + )[0]; + if (next === undefined) continue; + el.textContent = lib.formatRelativeUtc(next.instant, "en", { + reference: at, + }); + el.closest("[data-pulse-card]")?.setAttribute("data-pulse-ready", ""); + } + for (const el of root.querySelectorAll( + "[data-pulse-read]", + )) { + const read = el.getAttribute("data-pulse-read") ?? ""; + const out = el.querySelector("[data-pulse-read-ago]"); + if (out !== null) + out.textContent = lib.formatRelativeUtc(read, "en", { + reference: at, + }); + } + for (const strip of root.querySelectorAll( + "[data-pulse-strip-read]", + )) { + const read = strip.getAttribute("data-pulse-strip-read") ?? ""; + const days = Math.floor(lib.diffUtc(read, at, "days")); + if (days <= STALE_AFTER_DAYS) continue; + strip.setAttribute("data-signal", "lost"); + const text = strip.querySelector( + "[data-pulse-signal-text]", + ); + if (text !== null) text.textContent = `Run history is ${days} days old`; + strip + .querySelector("[data-pulse-signal]") + ?.removeAttribute("hidden"); + strip + .querySelector("[data-pulse-beats]") + ?.setAttribute("hidden", ""); + } + }; + + const onVisible = (): void => { + if (doc.visibilityState === "visible") fill(); + }; + fill(); + doc.addEventListener("visibilitychange", onVisible, { signal: life }); + + return { + destroy: () => own.abort(), + getPermalinkState: () => null, + }; + }); +} diff --git a/apps/dox/src/lib/pulse-view.test.ts b/apps/dox/src/lib/pulse-view.test.ts new file mode 100644 index 000000000..d1ec27947 --- /dev/null +++ b/apps/dox/src/lib/pulse-view.test.ts @@ -0,0 +1,137 @@ +import { + beatLabel, + beats, + beatsCaption, + cadenceText, + nextRun, + noSignal, + resultOf, + type Run, +} from "./pulse-view"; + +const run = (startedAt: string, conclusion = "success"): Run => ({ + startedAt, + conclusion, + url: `https://example.test/${startedAt}`, +}); + +// A Saturday at 14:00 UTC; the Monday 06:17 runs before it are 2, 9, 16, 23 Nov ... counting back. +const READ = "2026-11-14T14:00:00Z"; + +describe("cadenceText", () => { + it.each([ + ["17 6 * * 1", "Every Monday at 06:17 UTC"], + ["23 3 * * 6", "Every Saturday at 03:23 UTC"], + ["43 6 * * 1", "Every Monday at 06:43 UTC"], + ["17 7 * * 1", "Every Monday at 07:17 UTC"], + ["41 4 * * 0", "Every Sunday at 04:41 UTC"], + ["0 6 * * *", "Every day at 06:00 UTC"], + ])("reads %s as %s", (cron, words) => { + expect(cadenceText(cron)).toBe(words); + }); + + it("throws on a schedule it cannot say in words", () => { + expect(() => cadenceText("*/5 * * * *")).toThrow(/cannot read/); + expect(() => cadenceText("0 6 * * 1,3")).toThrow(/cannot read/); + expect(() => cadenceText("0 6 1 * *")).toThrow(/cannot read/); + expect(() => cadenceText("nonsense")).toThrow(/cannot read/); + }); +}); + +describe("nextRun", () => { + it("is the first schedule time after the given instant", () => { + expect(nextRun("17 6 * * 1", READ)).toBe("2026-11-16T06:17:00Z"); + }); +}); + +describe("beats", () => { + it("answers each expected time with the run that started after it", () => { + const list = beats( + "17 6 * * 1", + [run("2026-11-09T06:30:00Z"), run("2026-11-02T06:25:00Z", "failure")], + READ, + ); + expect(list).toHaveLength(8); + expect(list.at(-1)).toMatchObject({ + expected: "2026-11-09T06:17:00Z", + result: "passed", + }); + expect(list.at(-2)).toMatchObject({ + expected: "2026-11-02T06:17:00Z", + result: "failed", + }); + }); + + it("marks a week with no run as No run", () => { + const list = beats("17 6 * * 1", [run("2026-11-09T06:30:00Z")], READ); + expect(list.at(-2)?.result).toBe("none"); + expect(list.at(-2)?.run).toBeNull(); + expect(beatLabel(list.at(-2)!)).toBe("No run, expected 2 November"); + }); + + it("counts a 13:00 start as the 06:17 run, because GitHub may start a run hours late", () => { + const list = beats("17 6 * * 1", [run("2026-11-09T13:00:00Z")], READ); + expect(list.at(-1)?.result).toBe("passed"); + }); + + it("does not give one run to the next week's expected time", () => { + const list = beats("17 6 * * 1", [run("2026-11-02T06:20:00Z")], READ); + expect(list.at(-2)?.result).toBe("passed"); + expect(list.at(-1)?.result).toBe("none"); + }); + + it("calls a cancelled run Did not finish", () => { + const list = beats( + "17 6 * * 1", + [run("2026-11-09T06:20:00Z", "cancelled")], + READ, + ); + expect(list.at(-1)?.result).toBe("unfinished"); + expect(beatsCaption(list)).toBe( + "Last 8 · latest Did not finish, 9 November", + ); + }); + + it("with no runs at all, every beat is No run", () => { + expect( + beats("17 6 * * 1", [], READ).every((b) => b.result === "none"), + ).toBe(true); + }); +}); + +describe("resultOf", () => { + it.each([ + ["success", "passed"], + ["failure", "failed"], + ["startup_failure", "failed"], + ["cancelled", "unfinished"], + ["timed_out", "unfinished"], + ["skipped", "unfinished"], + ])("%s is %s", (conclusion, result) => { + expect(resultOf(conclusion)).toBe(result); + }); +}); + +describe("noSignal", () => { + it("is no signal when no history was read", () => { + expect(noSignal(null, null)?.text).toBe( + "Run history not read in this build", + ); + expect(noSignal(null, READ)?.reason).toBe("not-read"); + }); + + it("trusts a read of a few days", () => { + expect(noSignal([], READ, "2026-11-20T14:00:00Z")).toBeNull(); + }); + + it("does not trust a 9-day-old read", () => { + expect(noSignal([], READ, "2026-11-23T14:00:00Z")).toEqual({ + reason: "stale", + text: "Run history is 9 days old", + }); + }); + + it("at build, with no now, only a missing history is no signal", () => { + expect(noSignal([], READ)).toBeNull(); + }); +}); diff --git a/apps/dox/src/lib/pulse-view.ts b/apps/dox/src/lib/pulse-view.ts new file mode 100644 index 000000000..3f2114879 --- /dev/null +++ b/apps/dox/src/lib/pulse-view.ts @@ -0,0 +1,223 @@ +/** + * The rules `/pulse/` applies to a schedule and its run history: how a cron reads in words, which + * of the last expected runs happened and how each ended, and when the history is too old to trust. + * + * Time is GMT's (`parseCronExpression`, `cronRuns`, `formatUtc`), never `Date`. Nothing here reads + * a clock: every function takes the instants it needs, so the same inputs give the same page at + * build and the same answer in a test. + */ +// The package root, not a subpath: see `upstream-summary.ts` for the dev-server alias trap. +import { + addUtc, + cronRuns, + diffUtc, + formatUtc, + isBeforeUtc, + parseCronExpression, +} from "@northguild/gmt"; + +/** How many expected runs a strip shows. */ +export const BEAT_COUNT = 8; + +/** A read older than this many days is not trusted: the strip says NO SIGNAL. */ +export const STALE_AFTER_DAYS = 8; + +/** How far back the expected runs are searched; wide enough for eight of any daily or weekly run. */ +const LOOKBACK_DAYS = 70; + +/** Any instant before the first run; the weekday of the next run after it names the weekday. */ +const ANCHOR = "2000-01-01T00:00:00Z"; + +const pad2 = (n: number): string => String(n).padStart(2, "0"); + +/** + * "Every Monday at 06:17 UTC" or "Every day at 06:00 UTC". Accepts a fixed minute and hour with the + * day of the week `*` or one weekday, and throws on anything else, so a new kind of schedule is a + * decision here and not a silently wrong sentence. + */ +export function cadenceText(cron: string): string { + const e = parseCronExpression(cron); + if ( + e === null || + e.minute.values.length !== 1 || + e.hour.values.length !== 1 || + !e.dayOfMonth.star || + !e.month.star + ) { + throw new Error(`pulse: cannot read the schedule "${cron}" in words`); + } + const time = `${pad2(e.hour.values[0]!)}:${pad2(e.minute.values[0]!)} UTC`; + if (e.dayOfWeek.star && e.dayOfWeek.values.length === 7) { + return `Every day at ${time}`; + } + if (e.dayOfWeek.values.length !== 1) { + throw new Error(`pulse: cannot read the schedule "${cron}" in words`); + } + const next = cronRuns( + e, + "UTC", + { after: ANCHOR, count: 1 }, + "crontabMatch", + )[0]; + if (next === undefined) { + throw new Error(`pulse: the schedule "${cron}" never runs`); + } + const weekday = formatUtc(next.instant, "en", { + timeZone: "UTC", + weekday: "long", + }); + return `Every ${weekday} at ${time}`; +} + +/** The first run after `after`, as an instant, or `null` when the schedule never fires again. */ +export function nextRun(cron: string, after: string): string | null { + const e = parseCronExpression(cron); + if (e === null) return null; + return ( + cronRuns(e, "UTC", { after, count: 1 }, "crontabMatch")[0]?.instant ?? null + ); +} + +/** A run as the run history file holds it. */ +export interface Run { + startedAt: string; + conclusion: string; + url: string; +} + +export type BeatResult = "passed" | "failed" | "unfinished" | "none"; + +/** The words a result is called, and how it is drawn. Never a colour word. */ +export const RESULT_WORD: Readonly> = { + passed: "Passed", + failed: "Failed", + unfinished: "Did not finish", + none: "No run", +}; + +export const RESULT_PATTERN: Readonly< + Record +> = { + passed: "solid", + failed: "cross", + unfinished: "outline", + none: "dotted", +}; + +export interface Beat { + /** The time the schedule said the run would start (UTC). */ + expected: string; + result: BeatResult; + /** The run that answered it, when there was one. */ + run: Run | null; +} + +/** How GitHub's conclusion reads as one of the four results. */ +export function resultOf(conclusion: string): BeatResult { + switch (conclusion) { + case "success": + case "neutral": + return "passed"; + case "failure": + case "startup_failure": + return "failed"; + default: + return "unfinished"; + } +} + +/** + * The last `BEAT_COUNT` expected runs up to `runsRead`, oldest first, each with the run that + * answered it. A run answers the expected time it started after and before the next one: GitHub may + * start a scheduled run hours late, so a 13:00 start answers a 06:17 schedule. An expected time + * with no run is `none`; a second run in the same gap is ignored in favour of the newest. + * `runs` is newest first, as the history file holds it. + */ +export function beats( + cron: string, + runs: readonly Run[], + runsRead: string, +): Beat[] { + const e = parseCronExpression(cron); + if (e === null) throw new Error(`pulse: cannot read the schedule "${cron}"`); + const expected = cronRuns( + e, + "UTC", + { start: addUtc(runsRead, { days: -LOOKBACK_DAYS }), end: runsRead }, + "crontabMatch", + ) + .map((r) => r.instant) + .slice(-BEAT_COUNT); + return expected.map((time, i) => { + const next = expected[i + 1]; + const answer = + runs.find( + (r) => + !isBeforeUtc(r.startedAt, time) && + (next === undefined || isBeforeUtc(r.startedAt, next)), + ) ?? null; + return { + expected: time, + result: answer === null ? "none" : resultOf(answer.conclusion), + run: answer, + }; + }); +} + +/** Why a strip cannot be read, in words, or `null` when it can. */ +export type NoSignal = + | { reason: "not-read"; text: string } + | { reason: "stale"; text: string }; + +/** + * Whether the strip can be shown. `runs: null` (no history was read in this build) is always no + * signal. With `now` given, a read more than `STALE_AFTER_DAYS` old is too: the page was built long + * ago and what it says about "recent" runs is not recent. Build time passes no `now`. + */ +export function noSignal( + runs: readonly Run[] | null, + runsRead: string | null, + now?: string, +): NoSignal | null { + if (runs === null || runsRead === null) { + return { reason: "not-read", text: "Run history not read in this build" }; + } + if (now !== undefined) { + const gap = diffUtc(runsRead, now, "days"); + const days = typeof gap === "number" ? Math.floor(gap) : 0; + if (days > STALE_AFTER_DAYS) { + return { reason: "stale", text: `Run history is ${days} days old` }; + } + } + return null; +} + +/** "9 November": the day of a run, in UTC. */ +export const dayOf = (instant: string): string => + formatUtc(instant, "en-GB", { + timeZone: "UTC", + day: "numeric", + month: "long", + }); + +/** "06:17 UTC". */ +export const timeOf = (instant: string): string => + `${formatUtc(instant, "en-GB", { timeZone: "UTC", hour: "2-digit", minute: "2-digit", hourCycle: "h23" })} UTC`; + +/** "14 November 2026, 06:02 UTC". */ +export const stampOf = (instant: string): string => + `${formatUtc(instant, "en-GB", { timeZone: "UTC", day: "numeric", month: "long", year: "numeric" })}, ${timeOf(instant)}`; + +/** What a beat says to a screen reader and in the text twin. */ +export const beatLabel = (b: Beat): string => + b.result === "none" + ? `${RESULT_WORD.none}, expected ${dayOf(b.expected)}` + : `${RESULT_WORD[b.result]}, ${dayOf(b.expected)}`; + +/** "Last 8 · latest Passed, 9 November". */ +export function beatsCaption(list: readonly Beat[]): string { + const latest = list.at(-1); + return latest === undefined + ? "No scheduled run is due yet" + : `Last ${list.length} · latest ${beatLabel(latest)}`; +} diff --git a/apps/dox/src/lib/runtime-tz-canary.test.ts b/apps/dox/src/lib/runtime-tz-canary.test.ts index 7d2974617..b35c1bcd5 100644 --- a/apps/dox/src/lib/runtime-tz-canary.test.ts +++ b/apps/dox/src/lib/runtime-tz-canary.test.ts @@ -2,6 +2,8 @@ import { getTimeZoneOffset } from "@northguild/gmt/zoned/get"; import { PROBE_INSTANT, PROBE_ZONES } from "./canada-clock-change"; import { MOROCCO_FACTS, MOROCCO_PROBE } from "./morocco-clock-change"; +// Pulse check: runtime-tz + /** * A canary for the machine running the tests. The page states what tzdb 2026e gives for each * probe zone; a runtime with older time zone data gives another offset, and the Canada checker's diff --git a/apps/dox/src/lib/section-order.ts b/apps/dox/src/lib/section-order.ts index 346e56b0f..cc972b41b 100644 --- a/apps/dox/src/lib/section-order.ts +++ b/apps/dox/src/lib/section-order.ts @@ -7,11 +7,13 @@ * `migrate/index`. A `label` is the short text the sidebar shows; the page title stays in full. */ -/** What a reader needs first, in reading order. */ +/** What a reader needs first, in reading order, then the proof that GMT is kept up: the fixes it sends back to Temporal, and the checks that keep running. */ export const START_HERE = [ { slug: "install" }, { slug: "core-rules" }, { slug: "why-gmt" }, + { slug: "upstream" }, + { slug: "pulse" }, ] as const satisfies readonly { slug: string; label?: string }[]; /** The Migrate group: the overview, the pages that weigh GMT against the others, the weekly engine runs, one page per library, then the behaviour matrix. */ @@ -19,7 +21,6 @@ export const MIGRATE = [ { slug: "migrate", label: "Overview" }, { slug: "compare", label: "GMT vs. the others" }, { slug: "bundle-size" }, - { slug: "upstream" }, { slug: "native-engines" }, { slug: "migrate/date-fns", label: "From date-fns" }, { slug: "migrate/luxon", label: "From Luxon" }, diff --git a/apps/dox/src/lib/top-level-pages.test.ts b/apps/dox/src/lib/top-level-pages.test.ts index 865ccacef..b2c8c84b9 100644 --- a/apps/dox/src/lib/top-level-pages.test.ts +++ b/apps/dox/src/lib/top-level-pages.test.ts @@ -27,6 +27,7 @@ describe("topLevelPages", () => { "../content/docs/guides/intro.mdx": "g", "../content/docs/alpha.mdx": "a", "../content/docs/upstream.mdx": "u", + "../content/docs/pulse.mdx": "p", "../content/docs/index.mdx": "x", "../content/docs/why-gmt.mdx": "w", "../content/docs/core-rules.mdx": "c", @@ -36,6 +37,8 @@ describe("topLevelPages", () => { { slug: "install", source: "i" }, { slug: "core-rules", source: "c" }, { slug: "why-gmt", source: "w" }, + { slug: "upstream", source: "u" }, + { slug: "pulse", source: "p" }, { slug: "alpha", source: "a" }, { slug: "zebra", source: "z" }, ]); @@ -45,7 +48,7 @@ describe("topLevelPages", () => { const raw = { "../content/docs/compare.mdx": "c", "../content/docs/bundle-size.mdx": "b", - "../content/docs/upstream.mdx": "u", + "../content/docs/native-engines.mdx": "n", "../content/docs/install.mdx": "i", }; const slugs = topLevelPages(raw).map((p) => p.slug); @@ -113,17 +116,16 @@ describe("migratePages", () => { ).toEqual([{ slug: "migrate/index", source: "index" }]); }); - it("names twelve pages, the overview keyed as a folder index", () => { - expect(MIGRATE_ORDER).toHaveLength(12); + it("names eleven pages, the overview keyed as a folder index", () => { + expect(MIGRATE_ORDER).toHaveLength(11); expect(MIGRATE_ORDER[0]).toBe("migrate/index"); }); - it("lists compare, bundle-size, upstream and native-engines after the overview", () => { - expect(MIGRATE_ORDER.slice(0, 5)).toEqual([ + it("lists compare, bundle-size and native-engines after the overview", () => { + expect(MIGRATE_ORDER.slice(0, 4)).toEqual([ "migrate/index", "compare", "bundle-size", - "upstream", "native-engines", ]); }); @@ -142,6 +144,8 @@ describe("the sidebar config", () => { "install", "core-rules", "why-gmt", + "upstream", + "pulse", ]) { expect(config, `the config writes out ${slug}`).not.toContain( `slug: "${slug}"`, diff --git a/apps/dox/src/lib/upstream-badges.test.ts b/apps/dox/src/lib/upstream-badges.test.ts index 9f5fafdda..164e9db2a 100644 --- a/apps/dox/src/lib/upstream-badges.test.ts +++ b/apps/dox/src/lib/upstream-badges.test.ts @@ -7,6 +7,7 @@ import { stateNote, workBadge, } from "./upstream-badges"; +import type { UpstreamFiling } from "../data/upstream-filings"; describe("stateBadge", () => { it.each` @@ -20,7 +21,16 @@ describe("stateBadge", () => { `( "$kind $state draft=$draft merged=$mergedAt is $text", ({ kind, state, draft, mergedAt, text, tone, icon }) => { - expect(stateBadge({ kind, state, draft, mergedAt })).toEqual({ + expect( + stateBadge({ + tracker: "github", + kind, + state, + draft, + mergedAt, + reviewDecision: null, + }), + ).toEqual({ text, tone, icon, @@ -31,6 +41,7 @@ describe("stateBadge", () => { describe("a listing that is an issue", () => { const issue = { + tracker: "github", kind: "issue", state: "open", draft: false, @@ -50,10 +61,48 @@ describe("a listing that is an issue", () => { describe("stateNote", () => { it("keeps what 'Merged' alone loses", () => { - expect(stateNote({ mergedAt: "2026-05-01" })).toBe( + const github = (mergedAt: string | null) => + ({ tracker: "github", mergedAt }) as UpstreamFiling; + expect(stateNote(github("2026-05-01"))).toBe( "Merged, not yet in a published release", ); - expect(stateNote({ mergedAt: null })).toBeNull(); + expect(stateNote(github(null))).toBeNull(); + }); + + it("gives a Jira or Bugzilla filing the tracker's own words", () => { + const jira = { + tracker: "jira", + status: "Done", + resolution: "Fixed", + fixVersions: ["79.1"], + } as unknown as UpstreamFiling; + expect(stateNote(jira)).toBe( + "Status Done, resolution Fixed, fix version 79.1", + ); + const open = { + tracker: "bugzilla", + status: "UNCONFIRMED", + resolution: null, + } as UpstreamFiling; + expect(stateNote(open)).toBe("Status UNCONFIRMED"); + }); + + it("has nothing to add for a Chromium filing", () => { + expect(stateNote({ tracker: "chromium" } as UpstreamFiling)).toBeNull(); + }); +}); + +describe("a filing on another tracker", () => { + it("reads as an issue with no review chip", () => { + for (const tracker of ["jira", "chromium", "bugzilla"] as const) { + const f = { tracker, state: "closed", closedAt: "2026-11-20" } as const; + expect(stateBadge(f)).toEqual({ + text: "Closed", + tone: "purple", + icon: "issue-closed", + }); + expect(reviewBadge(f)).toBeNull(); + } }); }); @@ -72,9 +121,16 @@ describe("reviewBadge", () => { `( "$kind $state draft=$draft $reviewDecision shows $text", ({ kind, state, draft, reviewDecision, text }) => { - expect(reviewBadge({ kind, state, draft, reviewDecision })?.text).toBe( - text, - ); + expect( + reviewBadge({ + tracker: "github", + kind, + state, + draft, + mergedAt: null, + reviewDecision, + })?.text, + ).toBe(text); }, ); }); diff --git a/apps/dox/src/lib/upstream-badges.ts b/apps/dox/src/lib/upstream-badges.ts index 80a67f29e..0408379e7 100644 --- a/apps/dox/src/lib/upstream-badges.ts +++ b/apps/dox/src/lib/upstream-badges.ts @@ -10,7 +10,7 @@ * `upstream-badges.test.ts`. */ import { stateLine, type CompatGroup } from "~/data/temporal-compat"; -import type { UpstreamFiling } from "~/data/upstream-filings"; +import type { GitHubFiling, UpstreamFiling } from "~/data/upstream-filings"; import { badge } from "../widgets/builders/badge"; import type { SafeHtml } from "../widgets/builders/html"; import type { OcticonName } from "./octicons"; @@ -25,22 +25,28 @@ export interface BadgeSpec { dim?: boolean; } -type StateFields = Pick< - UpstreamFiling, - "kind" | "state" | "draft" | "mergedAt" ->; -type ReviewFields = Pick< - UpstreamFiling, - "kind" | "state" | "draft" | "reviewDecision" +type GitHubFields = Pick< + GitHubFiling, + "tracker" | "kind" | "state" | "draft" | "mergedAt" | "reviewDecision" >; +/** The state fields every tracker has; the GitHub ones are read only when `tracker` is `"github"`. */ +type StateFields = + | GitHubFields + | Pick< + Exclude, + "tracker" | "state" | "closedAt" + >; +type ReviewFields = StateFields; type InGmtFields = Pick< UpstreamFiling, - "gmtGuard" | "gmtNote" | "kind" | "pairsWith" ->; + "gmtGuard" | "gmtNote" | "pairsWith" +> & { + kind?: "pr" | "issue"; +}; /** Where a filing stands on GitHub, with the icon GitHub draws for that state. */ export function stateBadge(f: StateFields): BadgeSpec & { icon: OcticonName } { - if (f.kind === "issue") { + if (f.tracker !== "github" || f.kind === "issue") { return f.state === "closed" ? { text: "Closed", tone: "purple", icon: "issue-closed" } : { text: "Open", tone: "spring", icon: "issue-opened" }; @@ -59,8 +65,22 @@ export function stateBadge(f: StateFields): BadgeSpec & { icon: OcticonName } { * The part of a filing's state that GitHub's one word loses. A merged pull request is not yet * in a published polyfill release, which is the fact that decides whether a user has the fix. */ -export function stateNote(f: Pick): string | null { - return f.mergedAt ? "Merged, not yet in a published release" : null; +export function stateNote(f: UpstreamFiling): string | null { + switch (f.tracker) { + case "github": + return f.mergedAt ? "Merged, not yet in a published release" : null; + case "jira": + case "bugzilla": { + const resolution = f.resolution ? `, resolution ${f.resolution}` : ""; + const fixed = + f.tracker === "jira" && f.fixVersions.length > 0 + ? `, fix version ${f.fixVersions.join(", ")}` + : ""; + return `Status ${f.status}${resolution}${fixed}`; + } + case "chromium": + return null; + } } /** @@ -69,6 +89,8 @@ export function stateNote(f: Pick): string | null { * GitHub leaves `reviewDecision` empty until somebody reviews. */ export function reviewBadge(f: ReviewFields): BadgeSpec | null { + // Reviews are a GitHub pull request's: no other tracker has a review verdict. + if (f.tracker !== "github") return null; if (f.reviewDecision === "APPROVED") { return { text: "Approved", tone: "spring", icon: "check", dim: true }; } diff --git a/apps/dox/src/widgets/builders/badge.module.css b/apps/dox/src/widgets/builders/badge.module.css index 6e0f7bd0f..5f82836df 100644 --- a/apps/dox/src/widgets/builders/badge.module.css +++ b/apps/dox/src/widgets/builders/badge.module.css @@ -7,7 +7,7 @@ box-sizing: border-box; padding: 0.125rem 0.5rem; border: 1px solid var(--gmt-badge-edge); - border-radius: var(--gmt-radius-sm); + border-radius: var(--gmt-bevel-sm); corner-shape: bevel; background: var(--gmt-surface-widget); color: var(--gmt-badge-ink); @@ -76,22 +76,25 @@ } } -/* A solid state pill, as GitHub draws Open, Merged and Closed: the tone fills the whole badge and - the page's void colour is the ink, so the word and icon stay readable on it. The fill is the - tone's `-ink` token, which is dark enough on the light page and light enough on the dark one for - the void ink to hold 4.5:1 either way. It is larger than the outline chips around it. */ +/* A solid state chip, as GitHub draws Open, Merged and Closed: the same bevelled box as the + outline chips beside it, filled with its tone, with the page's void colour as the ink. A + cyan chip is the selected one, filled ice as `--gmt-selected-fill`. Each fill is the tone's + `-ink` token, dark enough on the light page and light enough on the dark one for the void ink + to hold 4.5:1 either way. */ .fill { - --gmt-badge-solid: var(--gmt-ice-dim); + --gmt-badge-solid: var(--gmt-ice); - padding: 0.25rem 0.75rem; - border-color: transparent; - border-radius: 999px; - corner-shape: round; + border-color: var(--gmt-badge-solid); background: var(--gmt-badge-solid); color: var(--gmt-void); - font-size: var(--gmt-text-sm); font-weight: 600; + &[data-tone="cyan"] { + --gmt-badge-solid: var(--gmt-selected-fill); + + color: var(--gmt-selected-ink); + } + &[data-tone="spring"] { --gmt-badge-solid: var(--gmt-spring-ink); } @@ -99,4 +102,8 @@ &[data-tone="purple"] { --gmt-badge-solid: var(--gmt-purple-ink); } + + &[data-tone="danger"] { + --gmt-badge-solid: var(--gmt-danger-ink); + } } diff --git a/apps/dox/src/widgets/builders/disclosure.module.css b/apps/dox/src/widgets/builders/disclosure.module.css index 23d13b4a7..dfd2dd7d2 100644 --- a/apps/dox/src/widgets/builders/disclosure.module.css +++ b/apps/dox/src/widgets/builders/disclosure.module.css @@ -66,6 +66,18 @@ } } +/* A flow disclosure: the panel is a block under the button, as wide as the root, and takes its + room in the page. */ +.root[data-flow="true"] { + display: block; + + & > .panel { + position: static; + inline-size: auto; + max-inline-size: none; + } +} + @media (forced-colors: active) { .button, .panel { diff --git a/apps/dox/src/widgets/builders/disclosure.test.ts b/apps/dox/src/widgets/builders/disclosure.test.ts index a30b03bca..37dbf3f92 100644 --- a/apps/dox/src/widgets/builders/disclosure.test.ts +++ b/apps/dox/src/widgets/builders/disclosure.test.ts @@ -89,6 +89,33 @@ describe("disclosure", () => { }); }); +describe("disclosure flow", () => { + it("opens and shuts the same way, and keeps its name and panel", async () => { + const abort = new AbortController(); + const r = renderHtml( + disclosure({ + id: "f", + label: "31 workarounds", + flow: true, + children: html`

The list

`, + }), + ); + try { + wireDisclosure(r.first(), { + signal: abort.signal, + }); + const button = screen.getByRole("button", { name: "31 workarounds" }); + expect(button).toHaveAttribute("aria-expanded", "false"); + await userEvent.click(button); + expect(button).toHaveAttribute("aria-expanded", "true"); + expect(screen.getByText("The list")).toBeVisible(); + await expectNoAxeViolations(r.host); + } finally { + abort.abort(); + } + }); +}); + describe("disclosure panel width", () => { /* jsdom has no layout, so the rule that keeps the panel inside a clipping drawer is read from the stylesheet; the browser run measures the rectangle. */ diff --git a/apps/dox/src/widgets/builders/disclosure.ts b/apps/dox/src/widgets/builders/disclosure.ts index 1f226aa7b..186d9f14e 100644 --- a/apps/dox/src/widgets/builders/disclosure.ts +++ b/apps/dox/src/widgets/builders/disclosure.ts @@ -32,11 +32,16 @@ export interface DisclosureOptions extends GateOption { className?: string; /** Extra class on the button, from the caller's own module. */ buttonClassName?: string; + /** + * Open the panel in the page's flow, below the button and as wide as its container, so a long + * list pushes what follows down instead of floating over it. The behaviour is the same. + */ + flow?: boolean; } export function disclosure(o: DisclosureOptions): SafeHtml { const open = o.open === true; - return html`
{column}