From b50a60dca46e968509f1ba65eca0f17e893167d3 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 6 Nov 2026 10:54:38 +0200 Subject: [PATCH 01/40] fix(dox): put the Changelog group last in the sidebar Release notes are reference, not a place to start, so the Changelog group moves below Check. llms.txt lists its Changelog section last to match. --- apps/dox/astro.config.mjs | 18 +++++++++--------- apps/dox/src/pages/llms.txt.ts | 10 +++++----- context/dox/built.md | 7 ++++--- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/apps/dox/astro.config.mjs b/apps/dox/astro.config.mjs index fef724f9f..7adc1711e 100644 --- a/apps/dox/astro.config.mjs +++ b/apps/dox/astro.config.mjs @@ -253,15 +253,6 @@ export default defineConfig({ { slug: "bundle-size" }, ], }, - { - label: "Changelog", - items: [ - { slug: "changelog", label: "@northguild/gmt" }, - { slug: "changelog/gmt-eslint", label: "gmt-eslint" }, - { slug: "changelog/gmt-oxlint", label: "gmt-oxlint" }, - { slug: "changelog/gmt-biome", label: "gmt-biome" }, - ], - }, { label: "Migrate", collapsed: true, @@ -303,6 +294,15 @@ export default defineConfig({ collapsed: false, items: [{ autogenerate: { directory: "check" } }], }, + { + label: "Changelog", + items: [ + { slug: "changelog", label: "@northguild/gmt" }, + { slug: "changelog/gmt-eslint", label: "gmt-eslint" }, + { slug: "changelog/gmt-oxlint", label: "gmt-oxlint" }, + { slug: "changelog/gmt-biome", label: "gmt-biome" }, + ], + }, ], components: { Head: "./src/components/Head.astro", diff --git a/apps/dox/src/pages/llms.txt.ts b/apps/dox/src/pages/llms.txt.ts index 496f3611a..331d26e6e 100644 --- a/apps/dox/src/pages/llms.txt.ts +++ b/apps/dox/src/pages/llms.txt.ts @@ -98,11 +98,6 @@ export const GET: APIRoute = () => { links: directoryLinks(base, "check", { indexFirst: true }), }, { heading: "Start here", links: startHere.map(({ link }) => link) }, - // The release record: linked here so an agent can fetch it, left out of llms-full.txt. - { - heading: "Changelog", - links: directoryLinks(base, "changelog", { indexFirst: true }), - }, { heading: "Migrate", links: migrateLinks }, // The guides index is a list of the guides below it. { @@ -120,6 +115,11 @@ export const GET: APIRoute = () => { heading: "Mistakes", links: directoryLinks(base, "mistakes", { indexFirst: false }), }, + // The release record, last as in the sidebar: linked here so an agent can fetch it, left out of llms-full.txt. + { + heading: "Changelog", + links: directoryLinks(base, "changelog", { indexFirst: true }), + }, ]; return new Response( diff --git a/context/dox/built.md b/context/dox/built.md index 099023806..38905f3a4 100644 --- a/context/dox/built.md +++ b/context/dox/built.md @@ -597,10 +597,11 @@ that bind future changes, the traps, and the runbooks. Every story is done; stat printed `tru` / `e`. `table-fit` passes on all four pages at 1440 px; at 375 px the box scrolls as every table does. Astro caches rendered Markdown in `node_modules/.astro/data-store.json` keyed by the file, so delete it after changing a rehype plugin. - - **Sidebar.** A top-level "Changelog" group with four links: `@northguild/gmt`, `gmt-eslint`, - `gmt-oxlint`, `gmt-biome`. `guides/integration/linting.mdx` links the three plugin pages. + - **Sidebar.** The last top-level group, "Changelog", with four links: `@northguild/gmt`, + `gmt-eslint`, `gmt-oxlint`, `gmt-biome`. `guides/integration/linting.mdx` links the three + plugin pages. - **Text surfaces.** The HTML pages and Pagefind carry them; each page's `.md` twin exists as for - every page; `llms.txt` has a "Changelog" section with four links; `llms-full.txt` and the + every page; `llms.txt` ends with a "Changelog" section of four links; `llms-full.txt` and the retrieval chunks leave them out (`topLevelPages` takes only slugs without `/`, and `guide-sources.ts` globs `guides/` and the top level), asserted in `llms.test.ts` and `guide-sources.test.ts`. Old signatures would ground answers in removed APIs. From adec4dee9b008580992e2528a131399f69280f5a Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 6 Nov 2026 10:54:46 +0200 Subject: [PATCH 02/40] fix(dox): slide the sidebar in and out on the way to and from the landing The landing has no sidebar, so a navigation to or from it used to cut the sidebar away in one frame or pop it in. It now slides off to the left, or in from the left, on the zone drawer's duration and sweep curve, with the same band of ice light crossing it. The band moves to one shared token, --gmt-sheen, that the drawer and the sidebar both read. The sidebar's group also drops the backdrop-filter it took from the capture, which left a sidebar-shaped blur over the hero after the sidebar had gone. Reduced motion keeps the one-frame swap. --- apps/dox/src/styles/gmt-tokens.css | 15 ++++- apps/dox/src/styles/gmt-view-transitions.css | 64 ++++++++++++++++++- .../src/widgets/builders/drawer.module.css | 14 +--- 3 files changed, 77 insertions(+), 16 deletions(-) diff --git a/apps/dox/src/styles/gmt-tokens.css b/apps/dox/src/styles/gmt-tokens.css index 281fe9c95..76058dabe 100644 --- a/apps/dox/src/styles/gmt-tokens.css +++ b/apps/dox/src/styles/gmt-tokens.css @@ -109,13 +109,22 @@ --gmt-motion-sonar-loop-duration: 2s; /* ---- Ice and the sweep ---- - * The pale top of the ice scale, the cyan-tinted frost between it and the cyan, and the - * one easing curve for a sweep (a panel or tab gliding into place). Used by the edge - * control and the zone drawer. + * The pale top of the ice scale, the cyan-tinted frost between it and the cyan, the + * one easing curve for a sweep (a panel or tab gliding into place), and the sheen: one + * band of ice light at 105°, sized to cross a pane when drawn at 250% of its width. Used + * by the edge control, the zone drawer and the sidebar's view transition. */ --gmt-ice-bright: #e6f6ff; --gmt-frost: color-mix(in oklab, var(--gmt-ice-bright) 70%, var(--gmt-cyan)); --gmt-ease-sweep: cubic-bezier(0.25, 0.6, 0.2, 1); + --gmt-sheen: linear-gradient( + 105deg, + transparent 38%, + color-mix(in oklab, var(--gmt-ice-bright) 10%, transparent) 45%, + color-mix(in oklab, var(--gmt-ice-bright) 24%, transparent) 50%, + color-mix(in oklab, var(--gmt-ice-bright) 10%, transparent) 55%, + transparent 62% + ); /* ---- Glass blur (DOX-D1) ---- * Every `backdrop-filter` reads one of these, so reduced transparency is a diff --git a/apps/dox/src/styles/gmt-view-transitions.css b/apps/dox/src/styles/gmt-view-transitions.css index efd791bfd..f003bf2ac 100644 --- a/apps/dox/src/styles/gmt-view-transitions.css +++ b/apps/dox/src/styles/gmt-view-transitions.css @@ -9,7 +9,9 @@ * * The header and sidebar are the same on every page, so they get their own * names and no animation: they swap in place and never visibly move. Only the - * rest of the page (the content column and "On this page") cross-fades. + * rest of the page (the content column and "On this page") cross-fades. The + * landing has no sidebar, so to and from it the sidebar slides out or in under + * the zone drawer's sheen. * * northguild.dev and this site are one origin, so the same transition also runs * between them. Three names are shared with that site's header: `ng-header`, @@ -81,6 +83,66 @@ display: none; } +/* The group takes the pane's backdrop-filter from the capture, and it stays in the pane's place + for the whole transition. On the way to the landing that blurred the hero under where the sidebar + had been, a sidebar-shaped smear left behind after the sidebar had gone. The snapshots are drawn + without it. Behind the sidebar on every other page is only the page's background, so nothing + is lost there. https://drafts.csswg.org/css-view-transitions-1/#update-pseudo-element-styles */ +::view-transition-group(gmt-sidebar) { + backdrop-filter: none; +} + +/* A page without a sidebar (the landing) on one side of the navigation. The snapshot is then alone + in its group, so the rules above would cut it away in one frame or pop it in. Instead it moves + like the home page's zone drawer, on the same duration and sweep curve: it slides off to the + left and fades as it leaves, and in from the left as it arrives. The drawer's sheen, one band + of ice light, crosses it from the content side as it moves. The band is the snapshot's own + background, behind the translucent glass, so it slides and fades with the sidebar. Under + reduced motion the duration is 0s, so the sidebar goes or comes in one frame. */ +::view-transition-old(gmt-sidebar):only-child { + display: block; + animation: + gmt-sidebar-out var(--gmt-duration-med) var(--gmt-ease-sweep) both, + gmt-sidebar-sheen var(--gmt-duration-med) ease-in-out both; +} + +::view-transition-new(gmt-sidebar):only-child { + animation: + gmt-sidebar-in var(--gmt-duration-med) var(--gmt-ease-sweep) both, + gmt-sidebar-sheen var(--gmt-duration-med) ease-in-out both; +} + +::view-transition-old(gmt-sidebar):only-child, +::view-transition-new(gmt-sidebar):only-child { + background-image: var(--gmt-sheen); + background-repeat: no-repeat; + background-size: 250% 100%; +} + +@keyframes gmt-sidebar-sheen { + from { + background-position: -10% 0; + } + + to { + background-position: 110% 0; + } +} + +@keyframes gmt-sidebar-out { + to { + opacity: 0; + translate: -100% 0; + } +} + +@keyframes gmt-sidebar-in { + from { + opacity: 0; + translate: -100% 0; + } +} + ::view-transition-old(root), ::view-transition-new(root) { animation-duration: var(--gmt-duration-fast); diff --git a/apps/dox/src/widgets/builders/drawer.module.css b/apps/dox/src/widgets/builders/drawer.module.css index 94f3fefc1..5fed2ec53 100644 --- a/apps/dox/src/widgets/builders/drawer.module.css +++ b/apps/dox/src/widgets/builders/drawer.module.css @@ -16,16 +16,6 @@ padding: var(--gmt-space-4); border-radius: var(--gmt-radius-md); corner-shape: bevel; - - --drawer-sheen: linear-gradient( - 105deg, - transparent 38%, - color-mix(in oklab, var(--gmt-ice-bright) 10%, transparent) 45%, - color-mix(in oklab, var(--gmt-ice-bright) 24%, transparent) 50%, - color-mix(in oklab, var(--gmt-ice-bright) 10%, transparent) 55%, - transparent 62% - ); - background: var(--drawer-glass); backdrop-filter: var(--gmt-header-blur); color: var(--gmt-ice); @@ -106,14 +96,14 @@ dropping the layer when the animation ends shows no jump. */ @keyframes sheen { from { - background-image: var(--drawer-sheen); + background-image: var(--gmt-sheen); background-position: -10% 0; background-size: 250% 100%; background-repeat: no-repeat; } to { - background-image: var(--drawer-sheen); + background-image: var(--gmt-sheen); background-position: 110% 0; background-size: 250% 100%; background-repeat: no-repeat; From bab0a14bb0f73424ec81443dcfb85df7e373a248 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 6 Nov 2026 10:54:54 +0200 Subject: [PATCH 03/40] feat(dox): give /why-gmt the sidebars and a row of headline figures /why-gmt was the one Start here page on the splash template, so it had no sidebar and no On this page list. It is now a normal doc page. The section grid goes, the sections read top to bottom, and the Date bug section moves up to follow the intro. Its heading is now a plain ## line in the page, so it lists in On this page; WhyDateBug no longer draws one, and its card grid answers to its own container instead of the grid cell. Under the intro, a row of tiles gives the headline figures (tests, CI runs, public functions, time zones, locales), each linked to its section. The figures come from gmt-stats.json through why-gmt-figures.ts, which the page and the Markdown twin both render. --- apps/dox/src/components/GridSection.astro | 8 +- apps/dox/src/components/WhyDateBug.astro | 21 ++--- apps/dox/src/components/WhyGmtFigures.astro | 93 +++++++++++++++++++++ apps/dox/src/content/docs/why-gmt.mdx | 41 ++------- apps/dox/src/lib/mdx-jsx.test.ts | 16 +++- apps/dox/src/lib/mdx-jsx.ts | 15 +++- apps/dox/src/lib/why-gmt-figures.ts | 45 ++++++++++ apps/dox/src/styles/dox.css | 20 +---- context/dox/built.md | 7 +- context/dox/reference/visual-design.md | 3 +- 10 files changed, 194 insertions(+), 75 deletions(-) create mode 100644 apps/dox/src/components/WhyGmtFigures.astro create mode 100644 apps/dox/src/lib/why-gmt-figures.ts diff --git a/apps/dox/src/components/GridSection.astro b/apps/dox/src/components/GridSection.astro index 86ee2cdf8..51561ba19 100644 --- a/apps/dox/src/components/GridSection.astro +++ b/apps/dox/src/components/GridSection.astro @@ -1,8 +1,8 @@ --- -/** Trivial grid-cell wrapper for /why-gmt's responsive 3/2/1 section grid - * (see .gmt-why-grid in dox.css). Also carries the HUD bracket-corner - * treatment so each panel reads as a targeting reticle. On the landing each - * section is one page of the hero's carousel: `page` is that page's name. */ +/** Grid-cell wrapper for the landing's below-hero section grid (see + * .gmt-home-grid in dox.css). Also carries the HUD bracket-corner treatment + * so each panel reads as a targeting reticle. Each section is one page of + * the hero's carousel: `page` is that page's name. */ interface Props { page?: string; } diff --git a/apps/dox/src/components/WhyDateBug.astro b/apps/dox/src/components/WhyDateBug.astro index d7fde6de8..0321fbf03 100644 --- a/apps/dox/src/components/WhyDateBug.astro +++ b/apps/dox/src/components/WhyDateBug.astro @@ -1,6 +1,5 @@ --- import { dateFaults } from "../data/date-faults"; -import SectionHeading from "./SectionHeading.astro"; /** * Homepage grid section: why `new Date` / `Date` objects are the root cause @@ -14,7 +13,8 @@ import SectionHeading from "./SectionHeading.astro"; */ interface Props { - /** `home`: the short list the landing page shows. `full`: every fault with its reason. */ + /** `home`: the short list the landing page shows. `full`: every fault with its reason, under + * the heading the page writes (so it lists in the page's table of contents). */ variant: "home" | "full"; } @@ -37,7 +37,6 @@ const shown = variant === "home" ? dateFaults.filter((f) => f.home) : dateFaults ) : (
- The bug is the Date object

Almost every date/time bug in a JavaScript codebase traces back to one type. Date conflates an instant with a wall-clock reading, @@ -70,10 +69,9 @@ const shown = variant === "home" ? dateFaults.filter((f) => f.home) : dateFaults display: flex; flex-direction: column; gap: var(--gmt-space-4); + container: why-date-block / inline-size; } - - .why-date-lede { margin: 0; max-inline-size: 68ch; @@ -101,13 +99,12 @@ const shown = variant === "home" ? dateFaults.filter((f) => f.home) : dateFaults grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); } - /* Container query (not @media): this section can be squeezed into one of - several columns in the homepage's GridSection grid, at any viewport - width — a viewport media query here would force 3 fixed-width columns - even when the section itself has no room for them, cramming each fault - card below the 14rem minimum the auto-fit rule above already protects. - .gmt-grid-section (dox.css) is the named container. */ - @container gmt-grid-section (min-width: 45rem) { + /* Container query (not @media): the block sits in /why-gmt's content column, + whose width depends on the sidebars as well as the viewport — a viewport + media query would force 3 columns even when the column has no room for + them, cramming each fault card below the 14rem minimum the auto-fit rule + above already protects. */ + @container why-date-block (min-width: 45rem) { .why-date-grid { grid-template-columns: repeat(3, 1fr); } diff --git a/apps/dox/src/components/WhyGmtFigures.astro b/apps/dox/src/components/WhyGmtFigures.astro new file mode 100644 index 000000000..47d069936 --- /dev/null +++ b/apps/dox/src/components/WhyGmtFigures.astro @@ -0,0 +1,93 @@ +--- +import { whyGmtFigures } from "../lib/why-gmt-figures"; + +/** + * The row of headline figures under the /why-gmt intro. Each figure links to the section that + * explains it. A list, so screen readers and agents read it as one; static, no hydration. + * The text surfaces render the same list as Markdown (`mdx-jsx.ts`). + */ +--- + +

+ + diff --git a/apps/dox/src/content/docs/why-gmt.mdx b/apps/dox/src/content/docs/why-gmt.mdx index 41bedd862..7575656d1 100644 --- a/apps/dox/src/content/docs/why-gmt.mdx +++ b/apps/dox/src/content/docs/why-gmt.mdx @@ -1,7 +1,6 @@ --- title: "Why GMT?" description: "Data-driven comparison of GMT against legacy date libraries — test volume, API surface, locale coverage, and testing rigor." -template: splash --- import { @@ -14,9 +13,9 @@ import { testExecutionSvg, } from "../../../scripts/render-charts"; import ChartContainer from "../../components/ChartContainer.astro"; -import GridSection from "../../components/GridSection.astro"; import TimezoneMap from "../../components/TimezoneMap.astro"; import WhyDateBug from "../../components/WhyDateBug.astro"; +import WhyGmtFigures from "../../components/WhyGmtFigures.astro"; import { coreFunctions, coreNamespaces, @@ -64,11 +63,13 @@ export const plainAndZoned = coreNamespaces `@northguild/gmt` is not the latest entry in a crowded field — it is a fundamentally different bet about what a date/time library should guarantee. -The pages below make that concrete with data drawn from the library itself. +The sections below make that concrete with data drawn from the library itself. -
+ - +## The bug is the `Date` object + + ## CI test execution volume @@ -104,10 +105,6 @@ outnumber the largest alternative's ({largestSuite.displayName}, {formatCount(la is what turns that into {formatCount(gmtStats.executions)} executions: about {executionRatio(executionRange.max)}× the most-executed alternative and about {formatCount(executionRatio(executionRange.min))}× the least, against a surface area that is itself larger. - - - - ## API surface GMT exposes {formatCount(gmtStats.functions)} public functions across {gmtStats.byNamespace.length} namespaces, plus {gmtStats.patterns} @@ -159,10 +156,6 @@ UN/EDIFACT `DTM`, ANSI X12 dates and time codes, and GS1 EPCIS 2.0 event times. - - - - ## Timezone coverage GMT tests against {gmtStats.timezones} timezones chosen not for geographic spread but for offset coverage — from {formatOffset(zoneOffsets.min.minutes)} ({zoneOffsets.min.zoneId}) to {formatOffset(zoneOffsets.max.minutes)} ({zoneOffsets.max.zoneId}). That {offsetWindowHours}-hour window means that at any given moment, at least one zone is already living in tomorrow while another is still stuck in yesterday. Date-boundary bugs — off-by-one day, wrong month rollover, DST gaps — only surface when the suite runs across this full offset range. A test that passes at UTC can fail at UTC+14 simply because the calendar date is different. @@ -172,10 +165,6 @@ GMT tests against {gmtStats.timezones} timezones chosen not for geographic sprea caption={`${gmtStats.timezones} timezones spanning ${formatOffset(zoneOffsets.min.minutes)} to ${formatOffset(zoneOffsets.max.minutes)}. Hover a dot for the current local time in ISO 8601. Times refresh every second via Temporal.`} /> - - - - ## Locale matrix GMT does not test every locale — there are hundreds, and most differ only in formatting minutiae. Instead it tests a curated matrix of {gmtStats.locales} locales chosen to stress the dimensions that actually break date libraries: script direction (LTR/RTL Arabic and Hebrew), character sets (CJK, Cyrillic, Latin), pluralization rules, and ICU data variants. The goal is not exhaustive locale coverage — it is representative coverage of every class of bug that locale-aware code can produce. @@ -186,10 +175,6 @@ GMT does not test every locale — there are hundreds, and most differ only in f caption={`${gmtStats.locales} locales across ${localeFamilyCounts.length} script families. ${formatFamilyCounts(localeFamilyCounts)}. Each cell shows the locale code and English name.`} /> - - - - ## Correct at the edges Most date bugs hide at the extremes, where ordinary tests never look. GMT tests them directly: @@ -208,16 +193,6 @@ Most date bugs hide at the extremes, where ordinary tests never look. GMT tests [See the evidence behind each of these →](/guides/concepts/correct-at-the-edges/) · Where the Temporal polyfill gets one of these wrong, GMT returns the spec's answer and reports the defect upstream: [Helping fix Temporal →](/upstream/) - - - - - - - - - - ## What this means | Dimension | GMT | Legacy libraries | @@ -256,7 +231,3 @@ That is what {formatCount(gmtStats.executions)} CI executions verify. The full table, how each figure was measured, and what each library covers are on [GMT and the other libraries](/compare/). - - - -
diff --git a/apps/dox/src/lib/mdx-jsx.test.ts b/apps/dox/src/lib/mdx-jsx.test.ts index 4f2d92fd5..d20003b42 100644 --- a/apps/dox/src/lib/mdx-jsx.test.ts +++ b/apps/dox/src/lib/mdx-jsx.test.ts @@ -2,6 +2,7 @@ import { alternativesStack } from "../data/date-alternatives"; import { dateFaults } from "../data/date-faults"; import { competitorComparisons } from "../data/library-comparison"; import { renderMdxComponents } from "./mdx-jsx"; +import { whyGmtFigures } from "./why-gmt-figures"; const rowsOf = (md: string): string[] => md.split("\n").filter((line) => line.startsWith("|")); @@ -15,9 +16,9 @@ describe("the Date-bug table in the text surfaces", () => { for (const f of shown) expect(rows.join("\n")).toContain(f.output); }); - it("shows every fault with its reason, under its heading, on the full variant", () => { + it("shows every fault with its reason on the full variant, leaving the heading to the page", () => { const md = renderMdxComponents(''); - expect(md).toContain("## The bug is the `Date` object"); + expect(md).not.toMatch(/^#/m); const rows = rowsOf(md); expect(rows[0]).toBe("| You write | You get | Why |"); expect(rows).toHaveLength(2 + dateFaults.length); @@ -32,6 +33,17 @@ describe("the Date-bug table in the text surfaces", () => { }); }); +describe("the /why-gmt headline figures in the text surfaces", () => { + it("lists every figure with its label", () => { + const md = renderMdxComponents(""); + expect(md).not.toMatch(/<[A-Z]/); + const items = md.split("\n").filter((line) => line.startsWith("- ")); + expect(items).toHaveLength(whyGmtFigures.length); + for (const f of whyGmtFigures) + expect(md).toContain(`- **${f.value}** ${f.label}`); + }); +}); + describe("the library table in the text surfaces", () => { it("shows name and foundation on the landing's variant", () => { const rows = rowsOf( diff --git a/apps/dox/src/lib/mdx-jsx.ts b/apps/dox/src/lib/mdx-jsx.ts index fda82952b..4685acb7a 100644 --- a/apps/dox/src/lib/mdx-jsx.ts +++ b/apps/dox/src/lib/mdx-jsx.ts @@ -16,6 +16,7 @@ import { MOROCCO_KEY_POINTS } from "../data/morocco-key-points"; import { serversMarkdown } from "./canada-clock-change"; import { serversMarkdown as moroccoServersMarkdown } from "./morocco-clock-change"; import { dateFaults } from "../data/date-faults"; +import { whyGmtFigures } from "./why-gmt-figures"; import { alternativesStack } from "../data/date-alternatives"; import { compatGroups, @@ -244,9 +245,8 @@ function renderWhyDateBug(props: Record): string { const rows = dateFaults.map( (f) => `| \`${f.input}\` | ${f.output} | ${f.why} |`, ); + // The heading is the page's own `##` line, so it is not repeated here. return [ - "", - "## The bug is the `Date` object", "", "Almost every date/time bug in a JavaScript codebase traces back to one type. `Date` conflates an instant with a wall-clock reading, parses two ways depending on the string, and mutates in place.", "", @@ -257,6 +257,15 @@ function renderWhyDateBug(props: Record): string { ].join("\n"); } +/** `` as a Markdown list: each headline figure with what it counts. */ +function renderWhyGmtFigures(): string { + return [ + "", + ...whyGmtFigures.map((f) => `- **${f.value}** ${f.label}`), + "", + ].join("\n"); +} + /** * `` as a Markdown table: the landing page's name and * foundation per library, or the full list with what each one is. @@ -517,6 +526,8 @@ export function renderMdxComponents(body: string): string { // The home page's two argument cards hold real prose — the `Date` faults and the library // stack — so they render rather than drop. They were invisible to the old nine-name gate. out = replaceElements(out, "WhyDateBug", renderWhyDateBug); + // The headline figures under the /why-gmt intro, as a list. + out = replaceElements(out, "WhyGmtFigures", renderWhyGmtFigures); // Key points first, then the servers card and what the library does; the live parts have no text. out = replaceElements( out, diff --git a/apps/dox/src/lib/why-gmt-figures.ts b/apps/dox/src/lib/why-gmt-figures.ts new file mode 100644 index 000000000..66191ae4e --- /dev/null +++ b/apps/dox/src/lib/why-gmt-figures.ts @@ -0,0 +1,45 @@ +import { formatCount, gmtStats } from "../data/gmt-stats"; +import { formatOffset, zoneOffsetRange } from "./timezone-offset-range"; + +const zoneOffsets = zoneOffsetRange(gmtStats.timezoneList); + +/** One headline figure at the top of /why-gmt, linking to the section that explains it. */ +export interface WhyGmtFigure { + value: string; + label: string; + /** The heading anchor of the section on /why-gmt that gives the detail. */ + href: string; +} + +/** + * The headline figures under the /why-gmt intro, all read from `gmt-stats.json`. The page + * (`WhyGmtFigures.astro`) and the text surfaces (`mdx-jsx.ts`) both render this list, so the + * two cannot disagree. + */ +export const whyGmtFigures: readonly WhyGmtFigure[] = [ + { + value: formatCount(gmtStats.tests), + label: "tests in one run", + href: "#ci-test-execution-volume", + }, + { + value: formatCount(gmtStats.executions), + label: "test runs in CI on every pull request", + href: "#ci-test-execution-volume", + }, + { + value: formatCount(gmtStats.functions), + label: "public functions", + href: "#api-surface", + }, + { + value: String(gmtStats.timezones), + label: `time zones, from ${formatOffset(zoneOffsets.min.minutes)} to ${formatOffset(zoneOffsets.max.minutes)}`, + href: "#timezone-coverage", + }, + { + value: String(gmtStats.locales), + label: "locales in every test", + href: "#locale-matrix", + }, +]; diff --git a/apps/dox/src/styles/dox.css b/apps/dox/src/styles/dox.css index b2e81b1d2..b640fda8c 100644 --- a/apps/dox/src/styles/dox.css +++ b/apps/dox/src/styles/dox.css @@ -1,6 +1,6 @@ /* Misc page-level layout for live components */ -/* HUD dashboard layout for sidebar-less pages (/, /why-gmt, and any future +/* HUD dashboard layout for sidebar-less pages (/ and any future * splash-template page). Starlight caps * sidebar-less pages at --sl-content-width: 67.5rem and centers them, which * reads as too much dead margin at wide viewports for a dashboard feel. @@ -208,9 +208,9 @@ html:not([data-has-sidebar]) .sl-container { max-inline-size: 90ch; } -/* Section grid — see GridSection.astro. Shared by the homepage's below-hero +/* Section grid — see GridSection.astro. The homepage's below-hero * sections (Key features / the bug is Date / the alternatives, wrapped in - * index.mdx as .gmt-home-grid) and /why-gmt's chart sections + * index.mdx as .gmt-home-grid). * * Natural auto-flow columns (repeat(auto-fit, minmax(...))) rather than * fixed 1/2/3-column breakpoints: the browser fits as many columns as the @@ -233,20 +233,6 @@ html:not([data-has-sidebar]) .sl-container { margin: 0; } -.gmt-why-grid { - display: grid; - grid-template-columns: 1fr; - gap: var(--gmt-space-8, 3rem); - padding: var(--gmt-space-8, 3rem); - inline-size: 100%; -} - -@media (width >= 48rem) { - .gmt-why-grid { - grid-template-columns: repeat(auto-fit, minmax(30vw, 1fr)); - } -} - /* A list of guarantees, one per line, each marked with a spring-green check. * Plain markdown underneath (a
    ), so screen readers and agents read it as * a normal list; the check is decorative. Used on /why-gmt instead of cards, diff --git a/context/dox/built.md b/context/dox/built.md index 38905f3a4..cbec51937 100644 --- a/context/dox/built.md +++ b/context/dox/built.md @@ -612,6 +612,11 @@ that bind future changes, the traps, and the runbooks. Every story is done; stat - **`api-surface.mjs` skips `content/docs/changelog/`**: release notes record past APIs (`@northguild/gmt/duty`, `isLeapSecond` from `timescale`) that today's surface must not check. A `packages/*/CHANGELOG.md` change runs the Dox content checks (`affected.mjs`). +- **`/why-gmt/` is a normal doc page**, with both sidebars like the rest of "Start here"; only + the landing uses the splash template. Its headings are plain `##` lines in `why-gmt.mdx`, + so each lists in "On this page" (`WhyDateBug variant="full"` draws no heading of its own). + The figure tiles under the intro are `WhyGmtFigures.astro`, from the list in + `src/lib/why-gmt-figures.ts` that `mdx-jsx.ts` also renders for the text surfaces. - **`/compare/` is a top-level page**, in "Start here" after `why-gmt` (`astro.config.mjs` for the sidebar, `START_ORDER` in `src/lib/top-level-pages.ts` for `llms.txt` and `llms-full.txt`). `` renders each of its tables and the notes list @@ -2628,7 +2633,7 @@ Shared hooks come first, then the globe, then the clock-change pages. override, `menu-button.ts`, the test and the `components` entry are deleted. - **Corner brackets:** two L-shaped corners, top left and bottom right, on a few frames only (when one is right: [visual-design.md § Panels](reference/visual-design.md#panels)). - `.gmt-brackets` (`gmt-primitives.css`, cyan) is on each `GridSection.astro` panel of the home page and `/why-gmt`. The hero has no frame. The transport tools draw the same + `.gmt-brackets` (`gmt-primitives.css`, cyan) is on each `GridSection.astro` panel of the home page. The hero has no frame. The transport tools draw the same frame in the frame's own colour (`--leg-color`, else `--series`) from `families/transport/leg-fieldset.module.css` (the Delivery Scheduler's legs and the Timetable Reader's rows). diff --git a/context/dox/reference/visual-design.md b/context/dox/reference/visual-design.md index 7c8336558..aa5b6c94b 100644 --- a/context/dox/reference/visual-design.md +++ b/context/dox/reference/visual-design.md @@ -67,8 +67,7 @@ Cool blue→green on a blue-tinted near-black. Everything is a token. - **Corner brackets mark a frame. They do not decorate a panel.** A bracket frame carries two L-shaped corners, top left and bottom right. The site has them in two places: - **Landmark sections**, in cyan (`.gmt-brackets`): the home page's hero stage, where they sit - inside the hero's edges, and each `GridSection` cell of the section grids on the home page - and `/why-gmt`. + inside the hero's edges, and each `GridSection` cell of the home page's section grid. - **A framed group of controls that the reader repeats or compares**: each leg of the Delivery Scheduler and each row of the Timetable Reader. Every frame in the set holds the same fields for one numbered item, and its brackets take that item's series colour, so the From bc21e1765aba409c7bb4c441bf4bac2a571a4597 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 6 Nov 2026 10:55:11 +0200 Subject: [PATCH 04/40] feat(dox): colour code blocks from the site's palette The code blocks used Starlight's default Expressive Code themes, whose blues blended into pages that are already mostly cyan. They now use a dark and a light theme that code-themes.ts builds from the --gmt-syntax-* tokens when the site builds: keywords purple, function names gold, strings green, numbers and literals rose, types cyan, comments and punctuation dim ice. These are the series colours the tools already use, through their -ink tokens. Every token is held to the 7:1 code-frame floor in both themes. Starlight still draws the frames, tabs and buttons. The widget call lines read the same tokens, so they change colour with the code blocks. --- apps/dox/astro.config.mjs | 13 +- apps/dox/src/lib/code-themes.ts | 195 +++++++++++++++++++++++ apps/dox/src/styles/gmt-tokens.css | 38 ++--- apps/dox/src/styles/gmt-widget-reset.css | 2 +- 4 files changed, 227 insertions(+), 21 deletions(-) create mode 100644 apps/dox/src/lib/code-themes.ts diff --git a/apps/dox/astro.config.mjs b/apps/dox/astro.config.mjs index 7adc1711e..f5832efe7 100644 --- a/apps/dox/astro.config.mjs +++ b/apps/dox/astro.config.mjs @@ -21,6 +21,7 @@ import { pruneWidgetCss } from "./src/lib/prune-widget-css.ts"; import { gmtReferenceWatch } from "./src/lib/gmt-reference-watch.ts"; import { devWorkerProxy } from "./src/lib/dev-worker-proxy.ts"; import { SITE_BASE, SITE_ORIGIN, withBase } from "./src/lib/site.ts"; +import { codeThemes } from "./src/lib/code-themes.ts"; // `site` + `base` make every Starlight link, the canonical tag, the sitemap // and Pagefind resolve under /gmt/. One module holds both, for the Worker and @@ -171,7 +172,17 @@ export default defineConfig({ // stylesheet until it has loaded — so on each route change the page // painted with an empty gap below the first heading for a frame. An // inline diff --git a/apps/dox/src/components/UpstreamDefectRow.astro b/apps/dox/src/components/UpstreamDefectRow.astro index 562b88ff2..a6c78c211 100644 --- a/apps/dox/src/components/UpstreamDefectRow.astro +++ b/apps/dox/src/components/UpstreamDefectRow.astro @@ -6,14 +6,12 @@ * The "still needed" column is the canary's `state`, which `pnpm compat:snapshot` writes into * `temporal-compat.json` from the same probes `pnpm compat` runs. The row reads it and never works * it out again from the probe counts, so the column is a measurement rather than a sentence - * anyone typed. A `guard` row passes its probes by design, so it says "Kept on purpose" and - * prints the reason the snapshot recorded, with each GitHub reference as a short link. + * anyone typed. */ import type { CompatGroup } from "../data/temporal-compat"; import { groupLabel, groupWhatBreaks, - reasonParts, shortRef, stateLine, } from "../data/temporal-compat"; @@ -42,19 +40,11 @@ const { badge, count } = stateLine(group); "gmt-defects-badge", (group.state === "still-needed" || group.state === "out-of-scope") && "gmt-defects-badge--ok", - group.state === "guard" && "gmt-defects-badge--guard", ]} > {badge}

    {count}

    - {group.state === "guard" && group.guard && ( -

    - {reasonParts(group.guard.reason).map((part) => - "href" in part ? {part.text} : part.text, - )} -

    - )} {filings.length === 0 ? ( diff --git a/apps/dox/src/components/UpstreamDefects.astro b/apps/dox/src/components/UpstreamDefects.astro index 54dbfe8f6..c49f18aaf 100644 --- a/apps/dox/src/components/UpstreamDefects.astro +++ b/apps/dox/src/components/UpstreamDefects.astro @@ -72,8 +72,8 @@ const filingsFor = (defects: readonly string[]) => /* * `--gmt-ice-dim` is the muted text tier that holds the 7:1 floor. `--sl-color-gray-3` measured - * 4.39:1 on the dark page and 2.49:1 in the light cell, so every line here (the description, the - * check count and a guard row's reason) used to sit under it. + * 4.39:1 on the dark page and 2.49:1 in the light cell, so every line here (the description and the + * check count) used to sit under it. */ .sl-markdown-content .gmt-defects td p { margin-block-start: 0.25rem; @@ -96,36 +96,6 @@ const filingsFor = (defects: readonly string[]) => color: var(--gmt-cyan-ink); } -/* - * "Kept on purpose": every check passes only because the installed polyfill cannot show the bug - * yet, so the badge claims neither "needed" (green) nor "fixed". It is a full bevelled border on - * all four sides with ice text, never a one-sided accent. - * - * The label is wider than the state cell's content box at the table's 34rem minimum, so it wraps - * between words inside its own border. The column widths come from `table-layout: fixed` and the - * percentages above, so a taller row never moves a column. - * - * Border: `--gmt-border-strong` measures 2.19:1 on the dark page and 1.54:1 on the light one, - * short of the 3:1 non-text bar (WCAG 2.2 SC 1.4.11). `--gmt-ice-dim-fill` is the first token that - * clears it in both themes (6.80:1 dark, 5.74:1 light). - */ -.gmt-defects-badge--guard { - display: inline-block; - max-inline-size: 100%; - box-sizing: border-box; - padding: 0 var(--gmt-space-1); - border: 1px solid var(--gmt-ice-dim-fill); - border-radius: var(--gmt-radius-sm); - corner-shape: bevel; - color: var(--gmt-ice); - white-space: normal; -} - -/* A short reference such as `tc39 #3292` reads as one token, so it never splits at its space. */ -.gmt-defects-reason a { - white-space: nowrap; -} - .sl-markdown-content .gmt-defects-refs { margin: 0; padding: 0; diff --git a/apps/dox/src/components/polyfill-tokens.test.ts b/apps/dox/src/components/polyfill-tokens.test.ts new file mode 100644 index 000000000..e93e6bd24 --- /dev/null +++ b/apps/dox/src/components/polyfill-tokens.test.ts @@ -0,0 +1,71 @@ +import { + hexOf, + ratio, + css, + darkBlock, + lightBlock, +} from "~/test/token-contrast"; + +// Token names are built from the prefix: the house-class rule bans a `gmt-` string in a test. +const P = "gmt"; +const TOKENS = [`--${P}-polyfill-shipped`, `--${P}-polyfill-previous`] as const; +const THEMES = ["dark", "light"] as const; + +/** `--gmt-glass-tint`'s alpha in a theme, read from the token file as a fraction. */ +function glassAlpha(theme: (typeof THEMES)[number]): number { + const block = theme === "light" ? lightBlock : darkBlock; + const found = [ + ...block.matchAll( + /--gmt-glass-tint:\s*color\(from var\(--gmt-teal\)[^/]*\/\s*([\d.]+)%\)/g, + ), + ].at(-1); + if (!found) throw new Error(`no --${P}-glass-tint in the ${theme} block`); + return Number(found[1]) / 100; +} + +/** The glass panel: `--gmt-teal` at the theme's tint alpha over `--gmt-void`. */ +function glass(theme: (typeof THEMES)[number]): string { + const alpha = glassAlpha(theme); + const teal = hexOf(`--${P}-teal`, theme); + const void_ = hexOf(`--${P}-void`, theme); + const channel = (hex: string, i: number) => + Number.parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16); + const mixed = [0, 1, 2].map((i) => + Math.round(channel(teal, i) * alpha + channel(void_, i) * (1 - alpha)), + ); + return `#${mixed.map((c) => c.toString(16).padStart(2, "0")).join("")}`; +} + +describe("the polyfill series tokens", () => { + it("resolve to the same hex in both themes", () => { + for (const token of TOKENS) { + expect(hexOf(token, "light"), token).toBe(hexOf(token, "dark")); + } + }); + + it("are declared once, with no override in the light block", () => { + for (const token of TOKENS) { + expect(css.match(new RegExp(`${token}:`, "g")), token).toHaveLength(1); + expect(lightBlock, token).not.toContain(`${token}:`); + } + }); + + for (const theme of THEMES) { + it(`reach 3:1 against every chart surface in the ${theme} theme`, () => { + const surfaces = { + [`--${P}-void`]: hexOf(`--${P}-void`, theme), + [`--${P}-surface`]: hexOf(`--${P}-surface`, theme), + [`--${P}-surface-2`]: hexOf(`--${P}-surface-2`, theme), + glass: glass(theme), + }; + for (const token of TOKENS) { + for (const [name, surface] of Object.entries(surfaces)) { + expect( + ratio(hexOf(token, theme), surface), + `${token} on ${name} (${surface})`, + ).toBeGreaterThanOrEqual(3); + } + } + }); + } +}); diff --git a/apps/dox/src/content/docs/bundle-size.mdx b/apps/dox/src/content/docs/bundle-size.mdx index f802f1b5c..d2fbd7acf 100644 --- a/apps/dox/src/content/docs/bundle-size.mdx +++ b/apps/dox/src/content/docs/bundle-size.mdx @@ -3,15 +3,114 @@ title: Bundle size description: Minified and gzipped bytes of the whole package and of single functions, measured from the source on every build, with the budget each is held to. --- +import { Aside } from "@astrojs/starlight/components"; import BundleSize from "~/components/BundleSize.astro"; +import ChartContainer from "~/components/ChartContainer.astro"; +import PolyfillCompare from "~/components/PolyfillCompare.astro"; +import { + bundleSizeSvgs, + polyfillLegends, + polyfillSummaries, +} from "../../../scripts/render-charts"; import { gmtStats, formatCount } from "~/data/gmt-stats"; +import { nativeFailures } from "~/data/native-engine-failures"; +import { polyfillFigures } from "~/lib/bundle-size-figures"; -Every import of `@northguild/gmt` carries `@js-temporal/polyfill`, so the polyfill row is the floor under every other row: no import is smaller than it. The last four columns of the other rows show what is left once the floor is taken away. + + + + +Every import of `@northguild/gmt` carries the `temporal-polyfill` polyfill, {polyfillFigures.floorGzipped} gzipped ({polyfillFigures.floorMinified} minified). That is the polyfill row: no import is smaller than it. GMT's own code is what a row adds above that floor. {polyfillFigures.smallestName} adds {polyfillFigures.smallestCodeMinified} minified, {polyfillFigures.smallestCodeGzipped} gzipped. The two "over the polyfill" columns show that part for every row. The `@northguild/gmt` row is the whole package, all {formatCount(gmtStats.functions)} public functions, which is the figure a package-size service such as Bundlephobia reports. A single function from a module costs far less than that row. -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. +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 comparison below also bundles the last release on `@js-temporal/polyfill`, `@northguild/gmt` {polyfillFigures.previousGmt}, with the same esbuild settings. + +## Why GMT uses temporal-polyfill + +GMT reads and returns ISO 8601 strings and does its date arithmetic with `Temporal`. Every bundle includes a polyfill for it until a stable Safari ships `Temporal` (see the end of this page). The polyfill is the largest part of almost every import, so its size sets how large GMT is to install. + +`temporal-polyfill` {polyfillFigures.shippedVersion} is {polyfillFigures.floorGzipped} gzipped. `@js-temporal/polyfill` {polyfillFigures.previousVersion}, the polyfill of GMT releases up to {polyfillFigures.previousGmt}, is {polyfillFigures.previousFloorGzipped}: a difference of {polyfillFigures.floorDifferenceGzipped} on every import. + + + +Each pair of bars below is one import: the solid part is the polyfill, the hatched part is GMT's code. Across the functions measured, GMT's code is {polyfillFigures.smallestCodeGzipped} to {polyfillFigures.largestCodeGzipped} gzipped. The whole package is {polyfillFigures.rootGzipped} gzipped on `temporal-polyfill` and {polyfillFigures.previousRootGzipped} on `@js-temporal/polyfill`. + + + + + +Size is one reason. The others, bounded month arithmetic and a maintained release line, are on [Helping fix Temporal](/upstream/#why-this-polyfill). + +## Why there is no build without the polyfill + +A build on the `Temporal` built into each runtime would leave out the polyfill and carry only GMT's code, {polyfillFigures.smallestCodeGzipped} to {polyfillFigures.largestCodeGzipped} gzipped for each function measured. GMT does not publish one, because the built-in engines give wrong answers, and different wrong answers from each other. + +Every week, GMT runs its whole test suite on the `Temporal` built into Node 26, Chromium, Firefox and WebKit, the engine in Safari. {nativeFailures.total} of GMT's tests get a wrong answer from at least one of them and the right answer from `temporal-polyfill` in the same runtime: + +| Built-in `Temporal` | GMT tests it fails | +| --- | --- | +| Node 26 | {nativeFailures.node} | +| Chromium | {nativeFailures.chromium} | +| Firefox | {nativeFailures.firefox} | +| WebKit | {nativeFailures.webkit} | + +Each engine fails its own tests, for its own bugs: Node and Chromium share one engine, and Firefox and WebKit each have another. On a build without the polyfill, one call could give a different answer in each browser, and on a runtime that has no `Temporal` it would not run at all. The bugs behind them are listed under [Native engines](/upstream/#native-engines), with the report for each one filed so far. + +GMT does not ship code that it knows gives a wrong answer. A bug it finds is fixed before the release that would carry it, never shipped and written up as a known issue ([Zero known bugs](/guides/concepts/correct-at-the-edges/#zero-known-bugs)). A build without the polyfill would ship every one of these failures, so there is none. On `temporal-polyfill`, GMT gives the standard's answer in each case. The polyfill stays until a stable Safari ships `Temporal` and the weekly run against native `Temporal` passes on Node 26, Chromium, Firefox and WebKit for 12 weeks running ([#316](https://github.com/northguild/gmt/issues/316)). diff --git a/apps/dox/src/content/docs/install.mdx b/apps/dox/src/content/docs/install.mdx index 311db556c..e4e3a8d93 100644 --- a/apps/dox/src/content/docs/install.mdx +++ b/apps/dox/src/content/docs/install.mdx @@ -6,6 +6,7 @@ description: Add @northguild/gmt to your project, and what the package exports. import { TabItem, Tabs } from "@astrojs/starlight/components"; import { gmtVersion } from "~/generated/versions"; +import { polyfillFigures } from "~/lib/bundle-size-figures"; Latest release: **v{gmtVersion}** @@ -65,8 +66,8 @@ Check for `""`, `null`, `false` or `[]` where you would otherwise catch an error ## What you get Every public function, type and regex is a flat named export of the package root, and -`Temporal`, `Intl` and `toTemporalInstant` are re-exported from `@js-temporal/polyfill` beside -them. There are no namespace objects to import — a namespace is a subpath: +`Temporal`, `Intl` and `toTemporalInstant` are re-exported beside them, from `temporal-polyfill` +in {polyfillFigures.firstShippedGmt} and later, and from `@js-temporal/polyfill` up to {polyfillFigures.previousGmt}. There are no namespace objects to import — a namespace is a subpath: ```typescript // Everything is available from the package root diff --git a/apps/dox/src/content/docs/upstream.mdx b/apps/dox/src/content/docs/upstream.mdx index c5e3f7160..462d5d2b2 100644 --- a/apps/dox/src/content/docs/upstream.mdx +++ b/apps/dox/src/content/docs/upstream.mdx @@ -11,11 +11,12 @@ import UpstreamDefects from "../../components/UpstreamDefects.astro"; import UpstreamListings from "../../components/UpstreamListings.astro"; import UpstreamTracker from "../../components/UpstreamTracker.astro"; import { gmtVersion } from "../../generated/versions"; +import { polyfillFigures } from "../../lib/bundle-size-figures"; GMT is built on [Temporal](https://tc39.es/proposal-temporal/), the new JavaScript date and time standard. Node and some browsers now have Temporal built in, but GMT runs on the community -[`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill) everywhere, so it gives -the same answer on every runtime. Every week, GMT's whole test suite also runs on the built-in +[`temporal-polyfill`](https://github.com/fullcalendar/temporal-polyfill) {polyfillFigures.shippedVersion} +everywhere, so it gives the same answer on every runtime. Every week, GMT's whole test suite also runs on the built-in engines. **If you use GMT, there is nothing on this page for you to do.** The polyfill has a handful of bugs @@ -46,52 +47,22 @@ that bug yet. GMT keeps its fix until someone has checked a newer release. ## How a fix reaches you -The polyfill is being brought back in line with the current version of the standard, one change at a -time. It is a long job, and it decides where each fix has to go: +`temporal-polyfill` publishes fixes in its regular patch releases. Every week, GMT's upgrade check +(the polyfill-swap leg of the [weekly runs](https://github.com/northguild/gmt/actions/workflows/temporal-oracle.yml)) +runs the test for every bug in the table above, and GMT's whole test suite, against each new +release. When every test for a bug passes, GMT marks that workaround as removable and takes it out in +a GMT release. Until then, GMT's own code covers the bug. -- **The standard first.** Its maintainers asked us to send fixes to the Temporal standard rather - than straight to the polyfill, so that the catching-up work stays manageable. -- **The polyfill next.** Fixes arrive there as that work moves forward. This is why several of the - pull requests below were closed with thanks instead of merged. None was turned down; each was sent - where it would do more good. -- **A release last.** The maintainers would rather publish one release once the polyfill has caught - up than a release for each fix. - -Until that release, GMT's own code covers every bug in the table above. +The maintainers of `@js-temporal/polyfill`, which GMT ran on before, asked us to send fixes to the +Temporal standard first, because they were bringing that polyfill back in line with the standard one +change at a time. That is why several of the pull requests below were closed with thanks instead of +merged. None was turned down; each was sent where it would do more good. ## Why this polyfill -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. - -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 -zone, on every day from 1970 to ten years ahead. On Node, GMT's whole test suite passes on it -with no test failing that passes on `@js-temporal/polyfill`. Release 1.0.7 had two bugs that -1.0.8 fixes: - -- **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. -- **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 - `@js-temporal/polyfill`. - -One bug is left, and the maintainers closed its report as a known limitation: - -- **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`. - -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, and checks every zone's offsets against -`Intl.DateTimeFormat`. A release that passes both opens an issue in GMT's repository, and that -issue starts the switch. See the -[weekly runs](https://github.com/northguild/gmt/actions/workflows/temporal-oracle.yml). The full -comparison is in GMT's repository: +From {polyfillFigures.firstShippedGmt}, GMT runs on [`temporal-polyfill`](https://github.com/fullcalendar/temporal-polyfill) {polyfillFigures.shippedVersion} from FullCalendar, imported from `temporal-polyfill/full/implementation`. GMT releases up to {polyfillFigures.previousGmt} ran on [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill) {polyfillFigures.previousVersion}. There are three reasons. Month arithmetic takes bounded time on `temporal-polyfill` for any amount inside Temporal's range, where `@js-temporal/polyfill` steps through months in a loop that can run for a long time on a very large amount. `temporal-polyfill` has a maintained release line: it fixed every bug we reported to it, in its 1.0.6 and 1.0.7 releases. And it is smaller, {polyfillFigures.floorGzipped} gzipped against {polyfillFigures.previousFloorGzipped}, which is {polyfillFigures.floorDifferenceGzipped} less on every import. The [bundle size](/bundle-size/#why-gmt-uses-temporal-polyfill) page has the figures for each function. + +On Node, GMT's whole test suite passes on `temporal-polyfill` with no test failing that passes on `@js-temporal/polyfill`, and its UTC offsets match `Intl.DateTimeFormat` in every time zone, on every day from 1970 to ten years ahead. Three limits remain, and GMT works around each one. An amount of months outside Temporal's range still makes the polyfill do work that grows with the amount before it throws, so GMT refuses those amounts first. A length measured from a time in an hour that happens twice gets an answer in two cases where the standard has none, so GMT returns its empty value there. The third, which its maintainers closed as a known limitation (FullCalendar #118, not our report), is that it can treat a link name such as `Asia/Calcutta` as a different zone from `Asia/Kolkata`. GMT's own probe sees it in WebKit, as `Etc/UTC` not equal to `UTC`, and GMT corrects that comparison there. The full comparison is in GMT's repository: [`temporal-polyfill-swap.md`](https://github.com/northguild/gmt/blob/main/context/domination/research/temporal-polyfill-swap.md). ## What we sent, and what happened to it @@ -111,7 +82,7 @@ GMT also opens pull requests on other projects, when a list or comparison should ## What this means for you **You don't need to do anything.** Where the polyfill has one of these bugs, GMT uses its own -correct code instead. It checks once, as it loads, whether the installed polyfill still has each +correct code instead. The first time it needs a fix, it checks whether the installed polyfill still has that bug; where the bug is gone, GMT uses the polyfill directly. You get the same correct answer either way. @@ -153,7 +124,7 @@ GMT gives the standard's answer in every case. ## What kind of bugs are these? -They're rare edge cases. Most only show up: +These are the bugs we found. They are rare edge cases. Most only show up: - near the very first or very last date Temporal can represent (around the year 275,000); - in non-Gregorian calendars, such as Hebrew, Persian, Islamic or Japanese; @@ -164,10 +135,12 @@ Temporal is a large, carefully designed standard, and the polyfill is a big piec Finding bugs like these is normal. We found them because GMT tests the unusual corners that most code never reaches. -We sent them to two places: +We sent them to three places: -- **The polyfill** ([`js-temporal/temporal-polyfill`](https://github.com/js-temporal/temporal-polyfill)), - the package GMT and many other projects install. Some of its fixes are already written but +- **The runtime GMT is on** ([`fullcalendar/temporal-polyfill`](https://github.com/fullcalendar/temporal-polyfill)). + Every bug we reported there is fixed. +- **The polyfill GMT ran on before** ([`js-temporal/temporal-polyfill`](https://github.com/js-temporal/temporal-polyfill)), + the package that many other projects install. Some of its fixes are already written but not yet in a published release, so we've asked for a new release. That would also fix two bugs other users had already reported. - **The Temporal proposal** ([`tc39/proposal-temporal`](https://github.com/tc39/proposal-temporal)), @@ -185,7 +158,10 @@ We sent them to two places: - We also check that the fix doesn't change any answer that was already right. Every example and fix is written up in full in GMT's repository: -[`js-temporal-polyfill-bugs.md`](https://github.com/northguild/gmt/blob/main/context/domination/js-temporal-polyfill-bugs.md). +[`js-temporal-polyfill-bugs.md`](https://github.com/northguild/gmt/blob/main/context/domination/js-temporal-polyfill-bugs.md) +for the `@js-temporal/polyfill` reports, and +[`temporal-polyfill-swap.md`](https://github.com/northguild/gmt/blob/main/context/domination/research/temporal-polyfill-swap.md) +for the `temporal-polyfill` reports and the comparison. See also: [Why GMT?](/why-gmt/) · [Correct at the edges](/guides/concepts/correct-at-the-edges/) · [Standards](/guides/concepts/standards/) diff --git a/apps/dox/src/data/bundle-size.test.ts b/apps/dox/src/data/bundle-size.test.ts index 93b54baa8..91f9d5a12 100644 --- a/apps/dox/src/data/bundle-size.test.ts +++ b/apps/dox/src/data/bundle-size.test.ts @@ -1,6 +1,14 @@ -import { readFileSync } from "node:fs"; +import { readdirSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import report from "../generated/bundle-size.json"; +import { bundleCells, bundleRows } from "../lib/bundle-size"; +import { + formatBytes, + polyfillFigures, + polyfillSets, +} from "../lib/bundle-size-figures"; +import { pageExpressionValues } from "../lib/page-expression-values"; +import { stripMdx } from "../lib/page-markdown"; const budgets = JSON.parse( readFileSync( @@ -47,3 +55,188 @@ describe("the bundle-size figures", () => { } }); }); + +describe("the polyfill sets", () => { + it("list the shipped set first and the previous set second", () => { + const flags = ( + report as { polyfills: { shipped: boolean }[] } + ).polyfills.map((p) => p.shipped); + expect(flags).toEqual([true, false]); + }); + + it("repeat the top-level entries in the shipped set, without the budget", () => { + const shipped = ( + report as { + polyfills: { + entries: Record; + }[]; + } + ).polyfills[0].entries; + const top = Object.fromEntries( + Object.entries(entries).map(([name, { minified, gzipped }]) => [ + name, + { minified, gzipped }, + ]), + ); + expect(shipped).toEqual(top); + }); +}); + +describe("the first GMT release on the shipped polyfill", () => { + // The pages name it before it is published, so it is worked out from the last release on the + // previous polyfill. Until the release, the pending changesets must make it a minor one; after + // it, the changelog must hold it. + const root = resolve(import.meta.dirname, "..", "..", "..", ".."); + const gmtDir = resolve(root, "packages", "gmt"); + const { previous } = polyfillSets(); + const current = ( + JSON.parse(readFileSync(resolve(gmtDir, "package.json"), "utf8")) as { + version: string; + } + ).version; + + it("is the minor release after the last one on the previous polyfill", () => { + const [major, minor] = previous.gmt.split(".").map(Number); + expect(polyfillFigures.firstShippedGmt).toBe(`${major}.${minor + 1}.0`); + }); + + it("is the release the pending changesets make, or one the changelog holds", () => { + if (current === previous.gmt) { + const changesets = resolve(root, ".changeset"); + const bumps = readdirSync(changesets) + .filter((name) => name.endsWith(".md") && name !== "README.md") + .flatMap((name) => { + const text = readFileSync(resolve(changesets, name), "utf8"); + const head = /^---\n([\s\S]*?)\n?---/.exec(text)?.[1] ?? ""; + const bump = /^"@northguild\/gmt":\s*(major|minor|patch)\s*$/m.exec( + head, + ); + return bump ? [bump[1]] : []; + }); + expect(bumps).toContain("minor"); + expect(bumps).not.toContain("major"); + } else { + const changelog = readFileSync(resolve(gmtDir, "CHANGELOG.md"), "utf8"); + expect(changelog).toMatch( + new RegExp( + `^## ${polyfillFigures.firstShippedGmt.replaceAll(".", "\\.")}$`, + "m", + ), + ); + } + }); +}); + +describe("the floor row's import line", () => { + it("names the shipped polyfill's import", () => { + const shipped = ( + report as { polyfills: { shipped: boolean; import: string }[] } + ).polyfills.find((p) => p.shipped); + const floorRow = bundleRows().find((r) => r.name === report.floor); + expect(floorRow?.importLine).toBe( + `import { Temporal } from "${shipped?.import}"`, + ); + }); +}); + +describe("the over-the-polyfill columns", () => { + it("use the one byte format, so a small amount is not rounded to 0.4 kB", () => { + for (const row of bundleRows()) { + if (row.overMin === null || row.overGz === null) continue; + const cells = bundleCells(row); + expect(cells[3]).toBe(formatBytes(row.overMin)); + expect(cells[4]).toBe(formatBytes(row.overGz)); + } + }); +}); + +describe("the /bundle-size page", () => { + const source = readFileSync( + resolve(import.meta.dirname, "..", "content", "docs", "bundle-size.mdx"), + "utf8", + ); + const text = stripMdx(source, { values: pageExpressionValues() }); + const { shipped, previous } = polyfillSets(); + + it("names both polyfill packages as literals", () => { + expect(source).toContain(`\`${shipped.package}\``); + expect(source).toContain(`\`${previous.package}\``); + }); + + it("states the figures in its lead, from the data", () => { + expect(text).toContain(polyfillFigures.floorGzipped); + expect(text).toContain(polyfillFigures.floorMinified); + expect(text).toContain(`\`${polyfillFigures.smallestName}\``); + expect(text).toContain(polyfillFigures.previousFloorGzipped); + expect(text).toContain(polyfillFigures.floorDifferenceGzipped); + }); + + it("types no version of its own", () => { + expect(source).not.toContain(shipped.version); + expect(source).not.toContain(previous.version); + expect(source).not.toContain(previous.gmt); + }); + + it("states the previous release by the published GMT it was measured on", () => { + expect(text).toContain(`\`@northguild/gmt\` ${previous.gmt}`); + }); + + it("holds the captions of both charts in the text surfaces", () => { + expect(text).toMatch(/Gzipped size of each polyfill on its own/); + expect(text).toMatch(/Minified size of each polyfill on its own/); + expect(text).toMatch(/Gzipped size of each single-function import/); + expect(text).toMatch(/Minified size of each single-function import/); + }); + + it("leaves no expression, component tag or total-across-entries figure in the text", () => { + expect(text).not.toMatch(/\{[A-Za-z]/); + expect(text).not.toMatch(/<[A-Z][A-Za-z]*[\s/>]/); + expect(text).not.toMatch(/total across/i); + }); + + it("avoids words that age or sell", () => { + expect(text).not.toMatch( + /\b(now|new|old|recently|used to|switched|lean|tiny|huge|just)\b/i, + ); + }); + + it("links the other reasons on the upstream page", () => { + expect(text).toContain("/upstream/#why-this-polyfill"); + }); + + it("lists the comparison table with both packages in its header", () => { + expect(text).toContain(shipped.package); + expect(text).toContain(previous.package); + }); +}); + +describe("the /upstream page's reasons for the polyfill", () => { + const source = readFileSync( + resolve(import.meta.dirname, "..", "content", "docs", "upstream.mdx"), + "utf8", + ); + const text = stripMdx(source, { values: pageExpressionValues() }); + const section = text.slice( + text.indexOf("## Why this polyfill"), + text.indexOf("## What we sent"), + ); + + it("states the three reasons, with the size figures from the data", () => { + expect(section).toContain("bounded time"); + expect(section).toContain("maintained release line"); + expect(section).toContain(polyfillFigures.floorGzipped); + expect(section).toContain(polyfillFigures.previousFloorGzipped); + expect(section).toContain(polyfillFigures.floorDifferenceGzipped); + }); + + it("types no size and no version of its own", () => { + const { shipped, previous } = polyfillSets(); + const own = source.slice( + source.indexOf("## Why this polyfill"), + source.indexOf("## What we sent"), + ); + expect(own).not.toContain(shipped.version); + expect(own).not.toContain(previous.version); + expect(own).not.toMatch(/\d+(\.\d+)?\s?kB/); + }); +}); diff --git a/apps/dox/src/data/gmt-stats.json b/apps/dox/src/data/gmt-stats.json index b0ff62c75..7248f8b63 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": 71340, - "files": 944, - "executions": 2140200, + "tests": 71051, + "files": 937, + "executions": 2131530, "nodes": ["22", "24", "26"], "timezones": 10, "timezoneList": [ diff --git a/apps/dox/src/data/native-engine-failures.test.ts b/apps/dox/src/data/native-engine-failures.test.ts new file mode 100644 index 000000000..8711b7d4e --- /dev/null +++ b/apps/dox/src/data/native-engine-failures.test.ts @@ -0,0 +1,26 @@ +import { KNOWN_NATIVE_FAILURES } from "../../../../scripts/lib/native-suite-tags.mjs"; +import { nativeFailures } from "./native-engine-failures"; + +describe("nativeFailures", () => { + it("counts each test once in the total, however many runtimes it fails on", () => { + expect(nativeFailures.total).toBe(String(KNOWN_NATIVE_FAILURES.length)); + expect( + new Set(KNOWN_NATIVE_FAILURES.map((row) => `${row.file} ${row.test}`)) + .size, + ).toBe(KNOWN_NATIVE_FAILURES.length); + }); + + it("counts a test on every runtime it fails on", () => { + for (const leg of ["node", "chromium", "firefox", "webkit"] as const) { + expect(nativeFailures[leg]).toBe( + String( + KNOWN_NATIVE_FAILURES.filter((row) => row.legs.includes(leg)).length, + ), + ); + } + }); + + it("names a reason for every failure the page counts", () => { + for (const row of KNOWN_NATIVE_FAILURES) expect(row.defect).not.toBe(""); + }); +}); diff --git a/apps/dox/src/data/native-engine-failures.ts b/apps/dox/src/data/native-engine-failures.ts new file mode 100644 index 000000000..5026570f4 --- /dev/null +++ b/apps/dox/src/data/native-engine-failures.ts @@ -0,0 +1,21 @@ +/** + * How many GMT tests give a wrong answer on each runtime's built-in `Temporal` and the right one on + * the polyfill, counted from the weekly native run's list of known failures. /bundle-size states + * these to say why GMT ships no build without the polyfill; the bugs behind them are listed on + * /upstream under "Native engines". + */ +import { KNOWN_NATIVE_FAILURES } from "../../../../scripts/lib/native-suite-tags.mjs"; + +type Leg = "node" | "chromium" | "firefox" | "webkit"; + +const onLeg = (leg: Leg) => + String(KNOWN_NATIVE_FAILURES.filter((row) => row.legs.includes(leg)).length); + +/** Counts as strings, ready for the page and its Markdown twin. One row is one test. */ +export const nativeFailures = { + total: String(KNOWN_NATIVE_FAILURES.length), + node: onLeg("node"), + chromium: onLeg("chromium"), + firefox: onLeg("firefox"), + webkit: onLeg("webkit"), +} as const; diff --git a/apps/dox/src/data/temporal-compat.json b/apps/dox/src/data/temporal-compat.json index 3eb004d59..9cc66defe 100644 --- a/apps/dox/src/data/temporal-compat.json +++ b/apps/dox/src/data/temporal-compat.json @@ -1,114 +1,5 @@ { "groups": [ - { - "defects": ["D1"], - "title": "D1 — calendar fields → ISO, add, until and Duration relativeTo near the limits (temporalCompat)", - "trigger": "a js-temporal release ports proposal-temporal a41eb67 (+ af0cb4b) and becomes GMT's @js-temporal/polyfill floor (upstream-issue draft C)", - "probes": 27, - "failing": 23, - "state": "still-needed" - }, - { - "defects": ["D2"], - "title": "D2 — buddhist read through ICU4C's Julian/Gregorian hybrid", - "trigger": "a js-temporal release contains 2bb6ba1 (already on main)", - "probes": 2, - "failing": 2, - "state": "still-needed" - }, - { - "defects": ["D3", "D4"], - "title": "D3 + D4 — Hebrew years <= 0 (polyfill leap-year %, ICU4C one day off)", - "trigger": "BOTH a js-temporal release ports proposal-temporal 0df570c AND GMT's engines.node floor bundles an ICU containing 5267bb5778 (ICU-23007)", - "probes": 3, - "failing": 3, - "state": "still-needed" - }, - { - "defects": ["D5"], - "title": "D5 — Indian before ISO year 1 (stale V8 bug 10529 detector)", - "trigger": "a js-temporal release ports proposal-temporal 314b112", - "probes": 1, - "failing": 1, - "state": "still-needed" - }, - { - "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, - "failing": 11, - "state": "still-needed" - }, - { - "defects": ["D7"], - "title": "D7 — Hebrew until by years throws mixed-sign (tc39/proposal-temporal#3159)", - "trigger": "a js-temporal release ports proposal-temporal 0e32ee0", - "probes": 2, - "failing": 2, - "state": "still-needed" - }, - { - "defects": ["D8"], - "title": "D8 — japanese pre-proposal era codes", - "trigger": "a js-temporal release contains 2bb6ba1", - "probes": 3, - "failing": 3, - "state": "still-needed" - }, - { - "defects": ["D10"], - "title": "D10 — fields → ISO skips a 5–6-day month 13 in far years (tc39/proposal-temporal#3329; ethioaa, so coptic and ethiopic)", - "trigger": "js-temporal ports tc39 #3292 together with the #3329 fix (0.5.1 predates #3292, so this group passes today: it guards against a port of #3292 alone)", - "probes": 2, - "failing": 0, - "state": "guard", - "guard": { - "package": "@js-temporal/polyfill", - "through": "0.5.1", - "reason": "Polyfill 0.5.1 is older than the change that exposes this bug (tc39/proposal-temporal#3292), so these checks cannot fail on it yet." - } - }, - { - "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", - "probes": 6, - "failing": 6, - "state": "still-needed" - }, - { - "defects": ["D12"], - "title": "D12 — a zoned string's offset written with seconds is matched by minutes instead of exactly (zonedWallClock.ts defect 4)", - "trigger": "a js-temporal release contains 23d1275 (\"Normative: Require strict matching with a precise ZonedDateTime offset\", on main)", - "probes": 2, - "failing": 2, - "state": "still-needed" - }, - { - "defects": ["D13"], - "title": "D13 — two offset changes inside one 14-day transition search step are skipped, or stall the search for ever (zonedWallClock.ts defect 5)", - "trigger": "a js-temporal release on which EVERY D13 probe returns the spec value, the stall.* probes within 20,000 offset reads. a79c6a1 (per-zone search windows, on main, in no release) alone is not enough: its 17-day window for Africa/El_Aaiun holds three offsets in April 1976, so stall.nextElAaiun fails there (not filed)", - "probes": 8, - "failing": 6, - "state": "still-needed" - }, - { - "defects": ["D14"], - "title": "D14 — ZonedDateTime#round to the day does not clamp an instant in the second piece of a date that starts twice (zonedWallClockOperations.ts roundZonedDateTime)", - "trigger": "a js-temporal release that ports the day-round clamp of tc39/ecma262#3966 (commit 5f44331e0a11) (tc39/proposal-temporal#3312; reference polyfill commit 59a51ea9d4); Node 26's V8 throws RangeError on the probe. Expected value: test262 intl402/Temporal/ZonedDateTime/prototype/round/same-date-starts-twice.js", - "probes": 1, - "failing": 1, - "state": "still-needed" - }, - { - "defects": ["D15"], - "title": "D15 — `Z` string read by wall clock under offset: \"ignore\" instead of as an exact instant (zonedWallClock.ts defect 6)", - "trigger": "a js-temporal release (and Node floor) whose ToTemporalZonedDateTime keeps a Z string's own instant under offset: \"ignore\", as InterpretISODateTimeOffset requires. Native V8 (Node 24.21 with --harmony-temporal) shares the defect; not filed upstream yet, and js-temporal main c55b211 and tc39 main e8cc03f both still have it (bug doc § O). The expected value is the specification's", - "probes": 1, - "failing": 1, - "state": "still-needed" - }, { "defects": ["D16"], "title": "D16 — formatRange drops O and long zone-name widths (ICU-20548)", @@ -126,86 +17,29 @@ "state": "out-of-scope", "engines": ["firefox"] }, - { - "defects": ["D18"], - "title": "D18 — Islamic calendar dates before the Hijra read as positive years in a second era (WebKit)", - "trigger": "the weekly run's compat check in WebKit (the temporal-compat-webkit verdict) reports D18 removable: every D18 repro passes in the WebKit the native suite runs, once a js-temporal release reads the Islamic eras or WebKit prints the year as V8 does. WebKit is the only engine in D18's scope; this check runs on Node, where D18 is out of scope and never removable", - "probes": 6, - "failing": 0, - "state": "out-of-scope", - "engines": ["webkit"] - }, { "defects": ["D19"], "title": "D19 — ZonedDateTime#equals answers false for two identifiers of one zone where resolvedOptions keeps the identifier (JavaScriptCore)", - "trigger": "a js-temporal release whose TimeZoneEquals finds the primary identifier on a host whose Intl.DateTimeFormat#resolvedOptions returns the identifier as written, so the D19 probe (Etc/UTC equals UTC, ECMA-402 §6.5) passes in the WebKit the native suite runs: the weekly run's compat check in WebKit (the temporal-compat-webkit verdict) reports it. WebKit is the only engine in D19's scope; this check runs on Node, where D19 is out of scope and never removable", + "trigger": "a temporal-polyfill release whose TimeZoneEquals finds the primary identifier on a host whose Intl.DateTimeFormat#resolvedOptions returns the identifier as written, so the D19 probe (Etc/UTC equals UTC, ECMA-402 §6.5) passes in the WebKit the native suite runs: the weekly run's compat check in WebKit (the temporal-compat-webkit verdict) reports it. WebKit is the only engine in D19's scope; this check runs on Node, where D19 is out of scope and never removable", "probes": 1, "failing": 0, "state": "out-of-scope", "engines": ["webkit"] }, - { - "defects": ["D20"], - "title": "D20 — PlainYearMonth.from and PlainMonthDay.from reject an upper-case iso8601 calendar annotation", - "trigger": "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", - "probes": 2, - "failing": 2, - "state": "still-needed" - }, - { - "defects": ["D21"], - "title": "D21 — Temporal.Now reads one millisecond early after a clock before 1970 (temporalCompat/clock.ts)", - "trigger": "a js-temporal release whose SystemUTCEpochNanoSeconds adds a floored modulo (or no tail) so the D21 repro (the second Temporal.Now.instant() with the system clock at 1960-01-01T00:00:00Z reads 1960) passes on Node; filed as tc39/proposal-temporal#3335. The expected value is the specification's and test262's built-ins/Temporal/Now/instant/return-value-value.js", - "probes": 1, - "failing": 1, - "state": "still-needed" - }, { "defects": ["D22"], "title": "D22 — a zoned relativeTo or start in a repeated hour is measured from the wrong instant, so total, round and until in a date unit answer wrongly from the later pass, and wrongly or not at all from the earlier pass when the end falls in the later pass at a lower wall clock; where a TC39 Assert fails no value exists (tc39/proposal-temporal#3336), including after a skipped hour, and GMT returns its sentinel where the polyfill extrapolates", - "trigger": "a js-temporal release contains 3c403686d39 (\"fix for issues #3141, #3148 and #3149\", on main) and tc39/proposal-temporal#3319, so every D22 repro passes, P7D with largestUnit \"week\" giving P1W among them, and the release gives no value in totalsWithNoValue, noDayCorrection and emptyDaySpan, where TC39 Asserts (tc39/proposal-temporal#3336) and the source on main strips three of them from production builds (read, not run); if #3336 gives these lengths a value instead, the rows, the throws and the repros change together", + "trigger": "a temporal-polyfill release on which every D22 repro passes, P7D with largestUnit \"week\" giving P1W among them, and which gives no value in totalsWithNoValue, noDayCorrection and emptyDaySpan, where TC39 Asserts (tc39/proposal-temporal#3336); if #3336 gives these lengths a value instead, the rows, the throws and the repros change together", "probes": 8, - "failing": 6, + "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)", - "trigger": "a js-temporal release adds and differences non-ISO months in bounded work: each D9 probe reads at most 100 Intl dates for 1,200 months", - "probes": 4, - "failing": 4, - "state": "still-needed" - }, - { - "defects": ["zoned.A"], - "title": "zoned.A — wall clock → exact time at the range limits (zonedWallClock.ts defect 1, zonedWallClockDifference.ts defect 1)", - "trigger": "a js-temporal release contains 05ce7a3 (the max.* probes) and 95237e0 (the min.* probes); both are on main", - "probes": 10, - "failing": 10, - "state": "still-needed" - }, - { - "defects": ["zoned.B"], - "title": "zoned.B — next transition missed near the maximum (zonedWallClock.ts defect 2)", - "trigger": "a js-temporal release fixes GetNamedTimeZoneNextTransition near the maximum (upstream-issue draft B; not fixed on main)", - "probes": 3, - "failing": 3, - "state": "still-needed" - }, - { - "defects": ["zoned.E"], - "title": "zoned.E — transition search floored at 1847-01-01 (zonedWallClock.ts defect 3)", - "trigger": "a js-temporal release containing js-temporal/temporal-polyfill#372 (tc39/proposal-temporal#3330)", - "probes": 5, - "failing": 5, - "state": "still-needed" - }, - { - "defects": ["zoned.D"], - "title": "zoned.D — UTC fast path skips IsValidEpochNanoseconds (zonedWallClockDifference.ts defect 2)", - "trigger": "a js-temporal release validates the UTC fast path of GetPossibleEpochNanoseconds (upstream-issue draft D; not fixed on main)", - "probes": 2, - "failing": 2, + "title": "D9 — an out-of-range non-ISO month amount throws only after work linear in the amount (temporalCompat/monthRange.ts throws first)", + "trigger": "a temporal-polyfill release throws for an out-of-range month amount in bounded time: hebrew 2024-01-15 + 40,000,000 months throws in at most 5,000 ms (an absolute ceiling that fails the repro at once), and + 400,000,000 months throws in under 3 × the time of + 40,000,000 months + 10 ms", + "probes": 1, + "failing": 1, "state": "still-needed" } ] diff --git a/apps/dox/src/data/temporal-compat.test.ts b/apps/dox/src/data/temporal-compat.test.ts index e525050b3..ee4e7086e 100644 --- a/apps/dox/src/data/temporal-compat.test.ts +++ b/apps/dox/src/data/temporal-compat.test.ts @@ -1,8 +1,3 @@ -import { readFileSync } from "node:fs"; -import { createRequire } from "node:module"; -import { dirname, join } from "node:path"; - -import { workaroundState } from "../../../../scripts/lib/workaround-state.mjs"; import { WORKAROUNDS } from "../../../../scripts/lib/workarounds.mjs"; import { COMPAT_STATES, @@ -12,7 +7,6 @@ import { groupsMissingDescription, groupsStillNeeded, probeTotals, - reasonParts, shortRef, stateLine, toCompatGroup, @@ -88,26 +82,6 @@ describe("temporal compat snapshot", () => { } }); - it("gives every guard row a complete guard", () => { - for (const group of compatGroups.filter((g) => g.state === "guard")) { - const label = groupLabel(group); - expect(group.guard, label).toBeDefined(); - expect(group.guard!.package.length, label).toBeGreaterThan(0); - expect(group.guard!.through.length, label).toBeGreaterThan(0); - expect(group.guard!.reason.length, label).toBeGreaterThan(0); - } - }); - - it("words every guard reason without the canary's term 'probe'", () => { - // The page prints the reason as written and never says "probe", so a reader would meet a word - // the rest of the page does not use. - for (const group of compatGroups.filter((g) => g.guard)) { - expect(group.guard!.reason, groupLabel(group)).not.toMatch( - /\bprobes?\b/i, - ); - } - }); - describe("toCompatGroup", () => { const row = { defects: ["X1"], @@ -117,15 +91,9 @@ describe("temporal compat snapshot", () => { failing: 0, state: "removable", }; - const guard = { package: "pkg", through: "1.2.3", reason: "Because." }; it("keeps a well-formed row's values unchanged", () => { expect(toCompatGroup(row)).toEqual(row); - expect(toCompatGroup({ ...row, state: "guard", guard })).toEqual({ - ...row, - state: "guard", - guard, - }); }); it("throws on an unknown state, naming the group and the value", () => { @@ -144,25 +112,6 @@ describe("temporal compat snapshot", () => { /group X1 has state "out-of-scope" but no engines/, ); }); - - it("throws on a guard row with no guard", () => { - expect(() => toCompatGroup({ ...row, state: "guard" })).toThrow( - /group X1 has state "guard" but no complete guard/, - ); - }); - - it.each(["package", "through", "reason"] as const)( - "throws on a guard row whose %s is empty", - (field) => { - expect(() => - toCompatGroup({ - ...row, - state: "guard", - guard: { ...guard, [field]: "" }, - }), - ).toThrow(/no complete guard/); - }, - ); }); describe("stateLine", () => { @@ -180,7 +129,6 @@ describe("temporal compat snapshot", () => { state | badge | count ${"still-needed"} | ${"✓ Yes"} | ${"3 of 4 checks fail"} ${"removable"} | ${"No"} | ${"4 of 4 checks pass"} - ${"guard"} | ${"Kept on purpose"} | ${"4 of 4 checks pass"} ${"out-of-scope"} | ${"✓ Yes, on Firefox"} | ${"4 of 4 checks pass on Node, which does not show this defect"} `( "gives $state the badge '$badge' and '$count'", @@ -203,9 +151,7 @@ describe("temporal compat snapshot", () => { }); it("chooses by state alone, not by the probe counts", () => { - expect(stateLine({ ...group("guard"), failing: 2 }).badge).toBe( - "Kept on purpose", - ); + expect(stateLine({ ...group("removable"), failing: 2 }).badge).toBe("No"); expect(stateLine({ ...group("still-needed"), failing: 0 }).badge).toBe( "✓ Yes", ); @@ -230,165 +176,4 @@ describe("temporal compat snapshot", () => { }, ); }); - - describe("reasonParts", () => { - it("turns an owner/repo#number reference into a short link", () => { - expect( - reasonParts( - "Older than the change that exposes this bug (tc39/proposal-temporal#3292), so it passes.", - ), - ).toEqual([ - { text: "Older than the change that exposes this bug (" }, - { - text: "tc39 #3292", - href: "https://github.com/tc39/proposal-temporal/issues/3292", - }, - { text: "), so it passes." }, - ]); - }); - - const hrefs = (parts: ReturnType) => - parts.flatMap((p) => ("href" in p ? [p.href] : [])); - const TC39 = "tc39/proposal-temporal"; - const POLYFILL = "js-temporal/temporal-polyfill"; - - it("links every reference and keeps text between them", () => { - expect( - reasonParts(`${TC39}#1 and ${POLYFILL}#2`).map((p) => - "href" in p ? p.href : p.text, - ), - ).toEqual([ - `https://github.com/${TC39}/issues/1`, - " and ", - `https://github.com/${POLYFILL}/issues/2`, - ]); - }); - - it("links a reference at the end of a sentence and one in parentheses", () => { - expect(hrefs(reasonParts(`Tracked in ${TC39}#3292.`))).toEqual([ - `https://github.com/${TC39}/issues/3292`, - ]); - expect(reasonParts(`Tracked in ${TC39}#3292.`).at(-1)).toEqual({ - text: ".", - }); - expect(hrefs(reasonParts(`(${TC39}#7)`))).toEqual([ - `https://github.com/${TC39}/issues/7`, - ]); - }); - - it("links only the repositories the site knows, so `and/or#1` stays text", () => { - expect(reasonParts("pass and/or#1 here")).toEqual([ - { text: "pass and/or#1 here" }, - ]); - expect(reasonParts("a/b#1")).toEqual([{ text: "a/b#1" }]); - }); - - it("does not link a reference that is part of a URL or a longer name", () => { - for (const text of [ - `https://github.com/${TC39}/issues/3292#3`, - `https://github.com/${TC39}#3`, - `x-${TC39}#3`, - `${TC39}#3abc`, - ]) { - expect(reasonParts(text), text).toEqual([{ text }]); - } - }); - - it("links nothing when no repository is known", () => { - expect(reasonParts(`${TC39}#1`, [])).toEqual([{ text: `${TC39}#1` }]); - }); - - it("matches a repository name with dots when the site knows it", () => { - expect( - hrefs(reasonParts("fixed in a.b/c.d#1 and not axb/cxd#2", ["a.b/c.d"])), - ).toEqual(["https://github.com/a.b/c.d/issues/1"]); - }); - - it("leaves a reason with no reference as one text part", () => { - expect(reasonParts("No upstream change yet.")).toEqual([ - { text: "No upstream change yet." }, - ]); - }); - - it("does not link a bare #number or an owner/repo with no number", () => { - expect(reasonParts(`see #12 in ${TC39}`)).toEqual([ - { text: `see #12 in ${TC39}` }, - ]); - }); - - it("joins back to the reason it was given", () => { - for (const g of compatGroups) { - if (!g.guard) continue; - const joined = reasonParts(g.guard.reason) - .map((p) => - "href" in p - ? p.href.replace( - /^https:\/\/github\.com\/(.+)\/issues\/(\d+)$/, - "$1#$2", - ) - : p.text, - ) - .join(""); - expect(joined).toBe(g.guard.reason); - } - }); - }); - - describe("guards", () => { - const declared = WORKAROUNDS.filter((w) => w.guard !== undefined).map( - (w) => ({ label: w.defects.join(" + "), through: w.guard!.through }), - ); - - it("carries a guard on exactly the rows whose script entry declares one, with the same through", () => { - const recorded = compatGroups - .filter((g) => g.guard !== undefined) - .map((g) => ({ label: groupLabel(g), through: g.guard!.through })); - expect(recorded.sort((a, b) => a.label.localeCompare(b.label))).toEqual( - declared.sort((a, b) => a.label.localeCompare(b.label)), - ); - expect(declared.length).toBeGreaterThan(0); - }); - - it("records each guard with its package, through and reason, in that order", () => { - for (const group of compatGroups.filter((g) => g.guard)) { - expect(Object.keys(group.guard!), groupLabel(group)).toEqual([ - "package", - "through", - "reason", - ]); - expect(group.guard!.reason.length).toBeGreaterThan(10); - } - }); - - it("gives each guarded row the state workaroundState derives from the installed polyfill", () => { - // Derived, not a pinned "D10 is a guard": a reviewed lockfile bump moves the answer, and - // `snapshot --check` already forces the regeneration. - const manifest = createRequire( - join(import.meta.dirname, "../../../../packages/gmt/package.json"), - ).resolve("@js-temporal/polyfill"); - let installed = "unknown"; - for ( - let dir = dirname(manifest); - dir !== dirname(dir); - dir = dirname(dir) - ) { - try { - const { name, version } = JSON.parse( - readFileSync(join(dir, "package.json"), "utf8"), - ); - if (name === "@js-temporal/polyfill") { - installed = version; - break; - } - } catch { - // no manifest at this level: keep walking up - } - } - for (const group of compatGroups.filter((g) => g.guard)) { - expect(group.state, groupLabel(group)).toBe( - workaroundState(group, installed).state, - ); - } - }); - }); }); diff --git a/apps/dox/src/data/temporal-compat.ts b/apps/dox/src/data/temporal-compat.ts index 1cb210e1f..57fffd96a 100644 --- a/apps/dox/src/data/temporal-compat.ts +++ b/apps/dox/src/data/temporal-compat.ts @@ -20,24 +20,10 @@ import snapshot from "./temporal-compat.json"; export const COMPAT_STATES = [ "still-needed", "removable", - "guard", "out-of-scope", ] as const; export type CompatState = (typeof COMPAT_STATES)[number]; -/** - * Why a group whose probes all pass is still kept, and until which release of which package. - * Written by `workaroundState` in `pnpm compat:snapshot`, from the guard the script declares. - */ -export interface CompatGuard { - /** The package whose version decides the guard. */ - package: string; - /** The last version on which the passing probes prove nothing. */ - through: string; - /** Plain-English reason the probes pass without proving the defect is gone. Shown on the page as written. */ - reason: string; -} - export interface CompatGroup { /** The canary ids this group covers, e.g. `["D3", "D4"]`. */ defects: readonly string[]; @@ -59,18 +45,12 @@ export interface CompatGroup { * rather than `removable`: its probes pass there because the defect does not show there. */ engines?: readonly string[]; - /** - * Present when the group declares a guard, from `workaroundState` in `pnpm compat:snapshot`. - * With `state: "removable"` the guard has lapsed and the page shows no reason. - */ - guard?: CompatGuard; } type SnapshotRow = (typeof snapshot.groups)[number]; /** - * A JSON import types `state` as `string`, so each row is narrowed here, and a guarded row must say - * why. Only the script writes the file and `snapshot --check` guards it, so a throw can fire only + * A JSON import types `state` as `string`, so each row is narrowed here. Only the script writes the file and `snapshot --check` guards it, so a throw can fire only * on a hand-edited copy; it fails the build rather than rendering a wrong or empty column. The * row's values pass through unchanged: nothing is computed or corrected here. */ @@ -82,19 +62,6 @@ export const toCompatGroup = (row: SnapshotRow): CompatGroup => { `temporal-compat.json: group ${label} has unknown state "${row.state}" — run pnpm compat:snapshot`, ); } - if (state === "guard") { - const { guard } = row; - if ( - guard === undefined || - !guard.package || - !guard.through || - !guard.reason - ) { - throw new Error( - `temporal-compat.json: group ${label} has state "guard" but no complete guard (package, through, reason) — run pnpm compat:snapshot`, - ); - } - } if ( state === "out-of-scope" && !(row as { engines?: string[] }).engines?.length @@ -139,11 +106,6 @@ export const stateLine = (g: CompatGroup): { badge: string; count: string } => { }; case "removable": return { badge: "No", count: `${g.probes} of ${g.probes} checks pass` }; - case "guard": - return { - badge: "Kept on purpose", - count: `${g.probes} of ${g.probes} checks pass`, - }; case "out-of-scope": return { badge: `✓ Yes, on ${(g.engines ?? []).map(engineLabel).join(" and ")}`, @@ -170,49 +132,6 @@ const KNOWN_REPOS: Readonly> = { export const shortRef = (repo: string, number: number): string => `${KNOWN_REPOS[repo] ?? repo} #${number}`; -/** A run of plain text in a guard reason, or a reference the page prints as a link. */ -export type ReasonPart = { text: string } | { text: string; href: string }; - -const escapeRegExp = (text: string): string => - text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - -/** - * A guard reason split for the page. Each `owner/repo#n` becomes a short link, so the narrow - * state column never has to break a 27-character token mid-word. The snapshot, the Markdown twin - * and the canary issue keep the full reference. - * - * A reference links only when its repository is one the site knows (`repos`, by default the two - * repositories `shortRef` names). Syntax alone cannot tell `tc39/proposal-temporal#3292` from - * `and/or#1`: both are a legal owner and repository, and a link to a repository nobody chose to - * track is a wrong guess presented as a fact. A name that is not listed stays text. The match - * must also start at a boundary, not after a word, `.`, `/`, `:` or `-` character, so a number - * anchor on a URL (`…/issues/3292#3`) or a longer name (`x-owner/repo#1`) is never read as a - * reference, and it must end at the digits, so `#3abc` is not one either. - */ -export const reasonParts = ( - reason: string, - repos: readonly string[] = Object.keys(KNOWN_REPOS), -): readonly ReasonPart[] => { - if (repos.length === 0) return reason ? [{ text: reason }] : []; - const ref = new RegExp( - `(? last) parts.push({ text: reason.slice(last, m.index) }); - parts.push({ - text: shortRef(repo, Number(number)), - href: `https://github.com/${repo}/issues/${number}`, - }); - last = m.index + whole.length; - } - if (last < reason.length) parts.push({ text: reason.slice(last) }); - return parts; -}; - /** Every probe across every group, and how many still fail. */ export const probeTotals: { probes: number; failing: number } = compatGroups.reduce( @@ -244,35 +163,11 @@ export const groupSummary = (g: CompatGroup): string => { * otherwise silently fall back to the maintainer wording. */ const WHAT_BREAKS: Readonly> = { - D1: "Dates within about a year of the earliest or latest date Temporal can represent, in the non-ISO calendars", - D2: "Buddhist calendar dates before 1582, read through an old Julian/Gregorian switch", - "D3 + D4": "Hebrew calendar years at or before year 0", - D5: "Indian national calendar dates before ISO year 1", - D6: "Counting months between two dates in a non-ISO calendar, at the end of a month", - D7: "Counting years from a leap-month date in the Hebrew calendar", - D8: "Japanese era codes, and the date the Meiji era starts", - D9: "Adding or counting very large numbers of months in a non-ISO calendar", - D10: "Coptic and Ethiopic dates in far years, where a short thirteenth month can be skipped", - D11: "Rounding or measuring a span in months from the 29th, 30th or 31st", - D12: "Zoned strings whose offset is written with seconds, in a zone whose offset was not a whole number of minutes", - D13: "Finding a zone's clock changes, and the start or length of a day, where two changes fall less than 14 days apart", - D14: "Rounding a zoned time to the day on a date that starts twice, because the clocks went back across midnight", - D15: "Zoned strings that end in Z, read with the offset option set to ignore, where the time was taken as local clock time rather than UTC", + D9: "Adding a very large number of months in a non-ISO calendar, where the polyfill takes a long time to refuse an amount that is out of range", D16: "Time ranges that name the time zone in a long or offset form, such as Eastern Standard Time or GMT-5, which Chrome, Node and Safari cut to a short name or drop", D17: "Time ranges that show a flexible day period and a time zone, such as 10 in the morning GMT-5, which Firefox writes as 10 AM", - D18: "Islamic calendar dates before the Hijra (622 CE), which Safari reads as positive years in a second era, so a count of months across them never finished", D19: "Two names for one zone, such as UTC and Etc/UTC or Asia/Kolkata and Asia/Calcutta, which the polyfill treats as different zones in Safari and WebKit", - 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", - "zoned.A": - "Zoned times within a day of the earliest or latest instant Temporal supports", - "zoned.B": - "Finding the next time zone transition within about two months of the latest instant", - "zoned.D": - "A calculation in UTC near the range limit that should be rejected, but quietly returned a value", - "zoned.E": - "Time zone transitions before 1847, including the 1844 date-line move in Asia/Manila and four Pacific zones", }; /** The plain-language line for a group, falling back to the canary's own wording. */ diff --git a/apps/dox/src/data/upstream-filings.json b/apps/dox/src/data/upstream-filings.json index c06bec7b4..45bc820c9 100644 --- a/apps/dox/src/data/upstream-filings.json +++ b/apps/dox/src/data/upstream-filings.json @@ -14,8 +14,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "D11", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "closed", "draft": false, "reviewDecision": "APPROVED", @@ -37,8 +37,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "zoned.D", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "outcome": "Closed, not rejected: the maintainer is applying the upstream changes in order and asked to keep it that way, so this one arrives in its turn rather than ahead of it.", "state": "closed", "draft": false, @@ -61,8 +61,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "D8", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "outcome": "Closed, not rejected: the maintainer is applying the upstream changes in order and asked to keep it that way, so this one arrives in its turn rather than ahead of it.", "state": "closed", "draft": false, @@ -85,8 +85,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "D1", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "outcome": "Closed, not rejected: the maintainer is applying the upstream changes in order and asked to keep it that way, so this one arrives in its turn rather than ahead of it.", "state": "closed", "draft": false, @@ -109,8 +109,8 @@ "pairsWith": ["tc39/proposal-temporal#3327"], "closes": [], "dependsOn": ["js-temporal/temporal-polyfill#369"], - "gmtGuard": "D1", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "outcome": "Closed, not rejected: the maintainer will apply the fix to the Temporal standard first, and it reaches the polyfill from there.", "state": "closed", "draft": false, @@ -133,8 +133,8 @@ "pairsWith": ["tc39/proposal-temporal#3328"], "closes": [], "dependsOn": [], - "gmtGuard": "zoned.B", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "outcome": "Closed, not rejected: the maintainer will apply the fix to the Temporal standard first, and it reaches the polyfill from there.", "state": "closed", "draft": false, @@ -157,8 +157,8 @@ "pairsWith": ["tc39/proposal-temporal#3330"], "closes": [], "dependsOn": [], - "gmtGuard": "zoned.E", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "outcome": "Closed, not rejected: the maintainer will apply the fix to the Temporal standard first, and it reaches the polyfill from there.", "state": "closed", "draft": false, @@ -184,8 +184,8 @@ "js-temporal/temporal-polyfill#347" ], "dependsOn": [], - "gmtGuard": "zoned.A", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -207,8 +207,8 @@ "pairsWith": ["js-temporal/temporal-polyfill#370"], "closes": [], "dependsOn": [], - "gmtGuard": "D1", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -230,8 +230,8 @@ "pairsWith": ["js-temporal/temporal-polyfill#371"], "closes": [], "dependsOn": [], - "gmtGuard": "zoned.B", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -254,7 +254,7 @@ "closes": [], "dependsOn": [], "gmtGuard": null, - "gmtNote": "GMT computes coptic and ethiopic dates through ethioaa and finds a date from its calendar fields by bisection, so this search-step bug can't affect it. A canary check (D10) watches for it in every polyfill release.", + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -276,8 +276,8 @@ "pairsWith": ["js-temporal/temporal-polyfill#372"], "closes": [], "dependsOn": [], - "gmtGuard": "zoned.E", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -323,8 +323,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "D13", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -346,8 +346,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "D21", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT no longer runs on `@js-temporal/polyfill`, where this defect is, so it can't affect GMT.", "state": "open", "draft": false, "reviewDecision": null, @@ -488,8 +488,8 @@ "pairsWith": [], "closes": [], "dependsOn": [], - "gmtGuard": "zoned.E", - "gmtNote": null, + "gmtGuard": null, + "gmtNote": "GMT's workaround for this is gone because every one of its checks passes on temporal-polyfill 1.0.8, which GMT now runs on.", "outcome": "Closed as fixed: released in temporal-polyfill 1.0.8.", "state": "closed", "draft": false, diff --git a/apps/dox/src/lib/bar-chart-kit.ts b/apps/dox/src/lib/bar-chart-kit.ts new file mode 100644 index 000000000..21e972992 --- /dev/null +++ b/apps/dox/src/lib/bar-chart-kit.ts @@ -0,0 +1,114 @@ +/** + * The parts every bar-chart registry shares: the hues, the page-level gradients and hatches + * `ChartContainer` declares, the tooltip wrapper and the `BarChart` shape. `why-gmt-charts.ts` and + * `bundle-size-charts.ts` each build a registry from these, and `bar-charts.ts` joins the two, so + * neither page's charts import the other's module. + * + * Kept free of the stats and the report: a chart module in the client graph imports this file. + */ +import type { ChartDefinition, ChartPoint } from "@tanstack/charts"; +import { defineChart } from "@tanstack/charts"; +import type { + ChartTooltipContent, + ChartTooltipExtension, +} from "@tanstack/charts/tooltip"; +import { chartTooltipMotion } from "./chart-motion"; + +type TooltipOption = Parameters[0]["tooltip"]; + +// --------------------------------------------------------------------------- +// Gradients +// --------------------------------------------------------------------------- + +/** A series hue: the name after `--gmt-` of the token that paints it. */ +export type BarHue = + | "spring" + | "signal" + | "cyan" + | "polyfill-shipped" + | "polyfill-previous"; + +export interface BarGradient { + id: string; + hue: BarHue; + top: number; + bottom: number; +} + +// Same recipe as the locale matrix tiles: the bottom stop sits 0.09 under the top. +const BAR_OPACITY = { top: 0.32, bottom: 0.23 }; + +export function barGradientId(hue: BarHue): string { + return `gmt-bar-${hue}`; +} + +export function barGradient(hue: BarHue): BarGradient { + return { id: barGradientId(hue), hue, ...BAR_OPACITY }; +} + +/** + * A hatch: a tint of the hue with diagonal lines over it, declared once as a page-level SVG + * pattern (`ChartContainer.astro`). The tint and the lines are both the hue's token at reduced + * strength, so the difference from a solid bar never rests on colour alone. + */ +export interface BarPattern { + id: string; + hue: BarHue; + /** The fill strength of the tint under the lines. */ + tint: number; + /** The strength of the lines. */ + line: number; + /** The side of the repeating tile, in user units. */ + size: number; + lineWidth: number; +} + +export function barHatchId(hue: BarHue): string { + return `gmt-bar-${hue}-hatch`; +} + +export function barHatch( + hue: BarHue, + overrides: Partial> = {}, +): BarPattern { + return { + id: barHatchId(hue), + hue, + tint: 0.12, + line: 0.6, + size: 7, + lineWidth: 2, + ...overrides, + }; +} + +export function withTooltip( + extension: ChartTooltipExtension | undefined, + content: (datum: unknown) => ChartTooltipContent, +): { tooltip?: TooltipOption } { + if (!extension) return {}; + return { + tooltip: { + use: extension, + ...chartTooltipMotion(), + content: (points: readonly ChartPoint[]) => + content(points[0]?.datum), + } as TooltipOption, + }; +} + +// --------------------------------------------------------------------------- +// The shape of a registered chart +// --------------------------------------------------------------------------- + +export interface BarChart { + ariaLabel: string; + idPrefix: string; + width: number; + height: number; + gradients: readonly BarGradient[]; + /** Hatches the chart's shaded marks refer to, declared as page-level patterns. */ + patterns: readonly BarPattern[]; + /** Widened to the runtime's untyped definition so every chart shares a caller. */ + definition: (tooltip?: ChartTooltipExtension) => ChartDefinition; +} diff --git a/apps/dox/src/lib/bar-charts.test.ts b/apps/dox/src/lib/bar-charts.test.ts new file mode 100644 index 000000000..592ea5447 --- /dev/null +++ b/apps/dox/src/lib/bar-charts.test.ts @@ -0,0 +1,56 @@ +import { BAR_CHARTS, isBarChartId, type BarChartId } from "./bar-charts"; +import { BUNDLE_SIZE_CHARTS } from "./bundle-size-charts"; +import { WHY_GMT_CHARTS } from "./why-gmt-charts"; + +describe("the joined bar-chart registry", () => { + it("holds every /why-gmt chart and every /bundle-size chart, each once", () => { + const ids = Object.keys(BAR_CHARTS).sort(); + expect(ids).toEqual( + [ + ...Object.keys(WHY_GMT_CHARTS), + ...Object.keys(BUNDLE_SIZE_CHARTS), + ].sort(), + ); + expect(new Set(ids).size).toBe(ids.length); + }); + + it("gives every chart its own SVG id prefix", () => { + const prefixes = Object.values(BAR_CHARTS).map((chart) => chart.idPrefix); + expect(new Set(prefixes).size).toBe(prefixes.length); + }); + + it("accepts each registered id and rejects everything else", () => { + for (const id of Object.keys(BAR_CHARTS)) + expect(isBarChartId(id)).toBe(true); + expect(isBarChartId("locale-matrix")).toBe(false); + expect(isBarChartId(undefined)).toBe(false); + }); + + it("types an id as one of the registry's keys", () => { + const id: BarChartId = "industries"; + expect(BAR_CHARTS[id].patterns.length).toBeGreaterThan(0); + }); +}); + +describe("what the registry pulls into a browser", () => { + it("never reaches the reference corpus or the page's server-side table module", async () => { + const path = await import("node:path"); + const { importsOf, resolveLocal, SRC } = + await import("~/test/import-graph"); + const seen = new Set(); + const queue = [path.join(SRC, "lib/bar-charts.ts")]; + while (queue.length > 0) { + const file = queue.pop() as string; + if (seen.has(file)) continue; + seen.add(file); + for (const { specifier } of importsOf(file)) { + const resolved = resolveLocal(file, specifier); + if (resolved) queue.push(resolved); + } + } + const reached = [...seen].map((file) => path.relative(SRC, file)); + expect( + reached.filter((file) => /gmt-corpus|lib\/bundle-size\.ts$/.test(file)), + ).toEqual([]); + }); +}); diff --git a/apps/dox/src/lib/bar-charts.ts b/apps/dox/src/lib/bar-charts.ts new file mode 100644 index 000000000..0f921963f --- /dev/null +++ b/apps/dox/src/lib/bar-charts.ts @@ -0,0 +1,24 @@ +/** + * Every bar chart the site draws, joined from the per-page registries. `ChartContainer.astro` and + * `scripts/render-charts.ts` read this one registry; each page's charts live in their own module, + * so neither page's chart code imports the other's. + */ +import type { BarChart } from "./bar-chart-kit"; +import { + BUNDLE_SIZE_CHARTS, + type BundleSizeChartId, +} from "./bundle-size-charts"; +import { WHY_GMT_CHARTS, type WhyGmtChartId } from "./why-gmt-charts"; + +export type { BarGradient, BarPattern } from "./bar-chart-kit"; + +export type BarChartId = WhyGmtChartId | BundleSizeChartId; + +export const BAR_CHARTS: Record = { + ...WHY_GMT_CHARTS, + ...BUNDLE_SIZE_CHARTS, +}; + +export function isBarChartId(id: string | undefined): id is BarChartId { + return id !== undefined && Object.hasOwn(BAR_CHARTS, id); +} diff --git a/apps/dox/src/lib/bundle-size-charts.test.ts b/apps/dox/src/lib/bundle-size-charts.test.ts new file mode 100644 index 000000000..770172213 --- /dev/null +++ b/apps/dox/src/lib/bundle-size-charts.test.ts @@ -0,0 +1,251 @@ +// @vitest-environment jsdom +import { createChartRuntime, renderChartSvg } from "@tanstack/charts"; +import { screen, within } from "@testing-library/dom"; +import { renderHtml } from "~/widgets/test-fixture"; +import { raw } from "~/widgets/builders/html"; +import { barHatchId } from "./bar-chart-kit"; +import { + bundleSizeCharts, + polyfillLegendHtml, + polyfillSummaryHtml, + polyfillTooltips, + type BundleSizeChartId, +} from "./bundle-size-charts"; +import { chartRows, formatBytes, polyfillSets } from "./bundle-size-figures"; +import { fixtureReport } from "./bundle-size-figures.fixture"; + +const IDS: readonly BundleSizeChartId[] = [ + "polyfill-floor-gzipped", + "polyfill-floor-minified", + "polyfill-split-gzipped", + "polyfill-split-minified", +]; + +/** Render one chart of the fixture to a document, tearing the runtime down as it goes. */ +function render(id: BundleSizeChartId, report = fixtureReport()): Document { + const chart = bundleSizeCharts(report)[id]; + const runtime = createChartRuntime(); + try { + const scene = runtime.render(chart.definition(), { + width: chart.width, + height: chart.height, + }); + const svg = renderChartSvg(scene, { + ariaLabel: chart.ariaLabel, + idPrefix: chart.idPrefix, + }); + return new DOMParser().parseFromString(svg, "image/svg+xml"); + } finally { + runtime.destroy(); + } +} + +interface Rect { + fill: string; + x: number; + y: number; + width: number; + height: number; +} + +/** The bar rects of a render: those whose fill is a polyfill token or a polyfill hatch. */ +function bars(doc: Document): Rect[] { + return [...doc.querySelectorAll("rect")] + .map((rect) => ({ + fill: rect.getAttribute("fill") ?? "", + x: Number(rect.getAttribute("x")), + y: Number(rect.getAttribute("y")), + width: Number(rect.getAttribute("width")), + height: Number(rect.getAttribute("height")), + })) + .filter((rect) => rect.fill.includes("polyfill-")); +} + +const solid = (rects: Rect[]) => + rects.filter((r) => !r.fill.startsWith("url(")); +const hatched = (rects: Rect[]) => + rects.filter((r) => r.fill.startsWith("url(")); + +describe("the bundle-size charts", () => { + it("render a scene for every id without throwing", () => { + for (const id of IDS) expect(() => render(id), id).not.toThrow(); + }); + + it("draw one bar per set in the floor chart", () => { + for (const id of [ + "polyfill-floor-gzipped", + "polyfill-floor-minified", + ] as const) { + expect(bars(render(id)), id).toHaveLength(2); + } + }); + + it("colour the bars by the shipped flag, not by the order of the sets", () => { + const report = fixtureReport(); + const reversed = { + ...report, + polyfills: [...(report.polyfills ?? [])].reverse(), + }; + for (const r of [report, reversed]) { + const rects = bars(render("polyfill-floor-gzipped", r)); + expect(rects.map((x) => x.fill)).toEqual([ + `var(--${"gmt"}-polyfill-shipped)`, + `var(--${"gmt"}-polyfill-previous)`, + ]); + } + }); + + it("puts the shipped bar above the previous bar in the floor chart", () => { + const [first, second] = bars(render("polyfill-floor-gzipped")); + expect(first.fill).toContain("shipped"); + expect(first.y).toBeLessThan(second.y); + }); + + it("draws a floor rect and a code rect for each package of each chart row", () => { + const rows = chartRows(fixtureReport()).length; + for (const id of [ + "polyfill-split-gzipped", + "polyfill-split-minified", + ] as const) { + const rects = bars(render(id)); + expect(solid(rects), id).toHaveLength(2 * rows); + expect(hatched(rects), id).toHaveLength(2 * rows); + } + }); + + it("starts each code rect where its floor rect ends, on the same row", () => { + const rects = bars(render("polyfill-split-gzipped")); + for (const floor of solid(rects)) { + const hue = floor.fill.replace("var(--gmt-", "").replace(")", ""); + const code = hatched(rects).find( + (r) => + r.fill === `url(#${barHatchId(hue as "polyfill-shipped")})` && + Math.abs(r.y - floor.y) < 0.5, + ); + expect( + code, + `a code rect beside ${floor.fill} at y=${floor.y}`, + ).toBeDefined(); + expect( + Math.abs((code?.x ?? 0) - (floor.x + floor.width)), + ).toBeLessThanOrEqual(0.5); + expect(code?.height).toBeCloseTo(floor.height, 1); + } + }); + + it("puts the shipped bar above the previous bar in every band", () => { + const rects = bars(render("polyfill-split-gzipped")); + const shipped = solid(rects).filter((r) => r.fill.includes("shipped")); + const previous = solid(rects).filter((r) => r.fill.includes("previous")); + expect(shipped).toHaveLength(previous.length); + for (const [i, rect] of shipped.entries()) { + expect(rect.y).toBeLessThan(previous[i].y); + // Each pair shares its band: the previous bar starts within one band below. + expect(previous[i].y - rect.y).toBeLessThan(2 * rect.height + 4); + } + }); + + it("sizes the split chart from its row count", () => { + const report = fixtureReport(); + const rows = chartRows(report).length; + const chart = bundleSizeCharts(report)["polyfill-split-gzipped"]; + expect(chart.height).toBe(rows * 64 + 80); + expect(bundleSizeCharts(report)["polyfill-floor-gzipped"].height).toBe(200); + }); + + it("declares the gradients and hatches its marks use", () => { + const chart = bundleSizeCharts(fixtureReport())["polyfill-split-gzipped"]; + expect(chart.patterns.map((p) => p.hue).sort()).toEqual([ + "polyfill-previous", + "polyfill-shipped", + ]); + }); +}); + +describe("the key and summary", () => { + it("lists two items for the floor chart, named by package and version", () => { + renderHtml(raw(polyfillLegendHtml("floor", fixtureReport()))); + const items = within( + screen.getByRole("list", { name: "Key" }), + ).getAllByRole("listitem"); + expect(items.map((i) => i.textContent)).toEqual([ + "alpha-poly 2.0.0", + "beta-poly 0.5.1", + ]); + }); + + it("lists four items for the split chart, each naming the polyfill or the GMT code above it", () => { + renderHtml(raw(polyfillLegendHtml("split", fixtureReport()))); + const items = within( + screen.getByRole("list", { name: "Key" }), + ).getAllByRole("listitem"); + expect(items.map((i) => i.textContent)).toEqual([ + "alpha-poly polyfill", + "GMT code above alpha-poly", + "beta-poly polyfill", + "GMT code above beta-poly", + ]); + }); + + it("gives the floor chart one summary line per bar", () => { + renderHtml(raw(polyfillSummaryHtml("floor", "gzipped", fixtureReport()))); + expect(screen.getAllByRole("listitem").map((i) => i.textContent)).toEqual([ + `alpha-poly 2.0.0: ${formatBytes(2000)}.`, + `beta-poly 0.5.1: ${formatBytes(4800)}.`, + ]); + }); + + it("gives the split chart one line per bar, from the figures", () => { + renderHtml(raw(polyfillSummaryHtml("split", "gzipped", fixtureReport()))); + const lines = screen.getAllByRole("listitem").map((i) => i.textContent); + expect(lines).toHaveLength(2 * chartRows(fixtureReport()).length); + expect(lines[0]).toBe( + `fnSmall, alpha-poly: polyfill ${formatBytes(2000)}, GMT code ${formatBytes(300)}, total ${formatBytes(2300)}.`, + ); + }); + + it("reads the minified measure in the minified summary", () => { + renderHtml(raw(polyfillSummaryHtml("floor", "minified", fixtureReport()))); + expect(screen.getAllByRole("listitem").map((i) => i.textContent)).toEqual([ + `alpha-poly 2.0.0: ${formatBytes(5000)}.`, + `beta-poly 0.5.1: ${formatBytes(12000)}.`, + ]); + }); +}); + +describe("the tooltips", () => { + const { floor, split } = polyfillTooltips(fixtureReport()); + + it("name the package and version, then the polyfill, in the floor chart", () => { + const { shipped } = polyfillSets(fixtureReport()); + const content = floor({ + set: "shipped", + package: shipped.package, + version: shipped.version, + value: 2000, + }); + expect(content.title).toBe("alpha-poly 2.0.0"); + expect(content.rows).toEqual([ + { label: "Polyfill", value: formatBytes(2000) }, + ]); + }); + + it("give polyfill, GMT code and total in the split chart", () => { + const content = split({ + name: "fnBig", + set: "previous", + package: "beta-poly", + version: "0.5.1", + floor: 4800, + code: 1400, + total: 6200, + }); + expect(content.title).toBe("fnBig"); + expect(content.rows).toEqual([ + { label: "Package", value: "beta-poly 0.5.1" }, + { label: "Polyfill", value: formatBytes(4800) }, + { label: "GMT code", value: formatBytes(1400) }, + { label: "Total", value: formatBytes(6200) }, + ]); + }); +}); diff --git a/apps/dox/src/lib/bundle-size-charts.ts b/apps/dox/src/lib/bundle-size-charts.ts new file mode 100644 index 000000000..46b0d7b74 --- /dev/null +++ b/apps/dox/src/lib/bundle-size-charts.ts @@ -0,0 +1,353 @@ +/** + * The two charts on /bundle-size, drawn from `bundle-size-figures.ts` and nothing else: the floor + * of each polyfill, and each function's size split into the polyfill and GMT's code above it. + * Every chart is built by `bundleSizeCharts(report)` so a test can hand it a fixture; the + * registry at the bottom is the live one. Same render path as /why-gmt: the build-time SVG + * (`scripts/render-charts.ts`) and the live mount in `ChartContainer.astro`. + * + * Package names, versions and entry names are read from the report, never typed here. The shipped + * and previous sets are told apart by the `shipped` flag. Client graph: this module imports the + * figures module and the kit, and neither reaches the corpus. + */ +import { barX, defineChart, group } from "@tanstack/charts"; +import { scaleBand } from "@tanstack/charts/scales/band"; +import { scaleLinear } from "@tanstack/charts/scales/linear"; +import type { + ChartTooltipContent, + ChartTooltipExtension, +} from "@tanstack/charts/tooltip"; +import { chartKey, chartSummary } from "~/widgets/builders"; +import type { ChartKeyHue } from "~/widgets/builders/chart-key"; +import { + barHatch, + barHatchId, + withTooltip, + type BarChart, + type BarHue, +} from "./bar-chart-kit"; +import { + chartRows, + formatBytes, + polyfillSets, + type BundleReport, + type Measure, + type PolyfillSet, +} from "./bundle-size-figures"; +import live from "../generated/bundle-size.json"; + +const liveReport = live as unknown as BundleReport; + +type Side = "shipped" | "previous"; + +const SIDES: readonly Side[] = ["shipped", "previous"]; + +const HUE: Record = { + shipped: "polyfill-shipped", + previous: "polyfill-previous", +}; + +const hueVar = (side: Side) => `var(--gmt-${HUE[side]})`; + +export type BundleSizeChartId = + | "polyfill-floor-gzipped" + | "polyfill-floor-minified" + | "polyfill-split-gzipped" + | "polyfill-split-minified"; + +export type PolyfillChartKind = "floor" | "split"; + +const label = (set: PolyfillSet) => `${set.package} ${set.version}`; + +// --------------------------------------------------------------------------- +// Rows +// --------------------------------------------------------------------------- + +/** One bar of the floor chart: a polyfill alone. */ +export interface FloorDatum { + set: Side; + package: string; + version: string; + value: number; +} + +/** One bar of the split chart: a function on one polyfill. */ +export interface SplitDatum { + name: string; + set: Side; + package: string; + version: string; + floor: number; + code: number; + total: number; +} + +function floorRows(report: BundleReport, measure: Measure): FloorDatum[] { + const sets = polyfillSets(report); + return SIDES.flatMap((side) => { + const set = sets[side]; + const entry = set.entries[report.floor]; + if (!entry) return []; + return [ + { + set: side, + package: set.package, + version: set.version, + value: entry[measure], + }, + ]; + }); +} + +function splitRows(report: BundleReport, measure: Measure): SplitDatum[] { + const sets = polyfillSets(report); + return chartRows(report).flatMap((row) => + SIDES.map((side) => { + const part = (side === "shipped" ? row.shipped : row.previous)[measure]; + return { + name: row.name, + set: side, + package: sets[side].package, + version: sets[side].version, + floor: part.floor, + code: part.code, + total: part.total, + }; + }), + ); +} + +// --------------------------------------------------------------------------- +// Tooltips +// --------------------------------------------------------------------------- + +export function polyfillTooltips(report: BundleReport = liveReport): { + floor: (datum: FloorDatum | undefined) => ChartTooltipContent; + split: (datum: SplitDatum | undefined) => ChartTooltipContent; +} { + void report; + return { + floor: (datum) => + datum + ? { + title: `${datum.package} ${datum.version}`, + color: hueVar(datum.set), + rows: [{ label: "Polyfill", value: formatBytes(datum.value) }], + } + : { rows: [] }, + split: (datum) => + datum + ? { + title: datum.name, + color: hueVar(datum.set), + rows: [ + { label: "Package", value: `${datum.package} ${datum.version}` }, + { label: "Polyfill", value: formatBytes(datum.floor) }, + { label: "GMT code", value: formatBytes(datum.code) }, + { label: "Total", value: formatBytes(datum.total) }, + ], + } + : { rows: [] }, + }; +} + +// --------------------------------------------------------------------------- +// Key and summary +// --------------------------------------------------------------------------- + +export function polyfillLegendHtml( + kind: PolyfillChartKind, + report: BundleReport = liveReport, +): string { + const sets = polyfillSets(report); + if (kind === "floor") { + return chartKey( + SIDES.map((side) => ({ + kind: "own" as const, + hue: HUE[side], + words: label(sets[side]), + })), + ).toString(); + } + return chartKey( + SIDES.flatMap((side) => [ + { + kind: "own" as const, + hue: HUE[side], + words: `${sets[side].package} polyfill`, + }, + { + kind: "shared" as const, + hue: HUE[side], + words: `GMT code above ${sets[side].package}`, + }, + ]), + ).toString(); +} + +export function polyfillSummaryHtml( + kind: PolyfillChartKind, + measure: Measure, + report: BundleReport = liveReport, +): string { + const lines = + kind === "floor" + ? floorRows(report, measure).map( + (d) => `${d.package} ${d.version}: ${formatBytes(d.value)}.`, + ) + : splitRows(report, measure).map( + (d) => + `${d.name}, ${d.package}: polyfill ${formatBytes(d.floor)}, GMT code ${formatBytes(d.code)}, total ${formatBytes(d.total)}.`, + ); + return chartSummary(lines).toString(); +} + +// --------------------------------------------------------------------------- +// Definitions +// --------------------------------------------------------------------------- + +const axisBytes = { + scale: scaleLinear, + nice: true, + grid: true, + axis: { ticks: { format: (value: unknown) => formatBytes(Number(value)) } }, +}; + +function floorDefinition( + report: BundleReport, + measure: Measure, + tooltip?: ChartTooltipExtension, +) { + const content = polyfillTooltips(report).floor; + return defineChart({ + marks: [ + barX(floorRows(report, measure), { + y: "set", + x: "value", + yScale: "y", + xScale: "x", + fill: (d) => hueVar((d as FloorDatum).set), + stroke: "var(--gmt-border-strong)", + strokeWidth: 1, + radius: 0, + inset: 2, + maxThickness: 40, + }), + ], + scales: { + x: axisBytes, + y: { + scale: () => scaleBand().domain([...SIDES]), + padding: 0.3, + axis: { + tickLabels: false, + ticks: false, + }, + }, + }, + ...withTooltip(tooltip, (datum) => + content(datum as FloorDatum | undefined), + ), + }); +} + +function splitDefinition( + report: BundleReport, + measure: Measure, + tooltip?: ChartTooltipExtension, +) { + const content = polyfillTooltips(report).split; + const rows = splitRows(report, measure); + const layout = group({ + scale: scaleBand().domain([...SIDES]), + padding: 0.08, + }); + const common = { + y: "name", + z: "set", + yScale: "y", + xScale: "x", + layout, + stroke: (d: unknown) => + `var(--gmt-${HUE[(d as SplitDatum).set]}-ink, var(--gmt-border-strong))`, + strokeWidth: 1.5, + radius: 0, + inset: 1, + maxThickness: 22, + } as const; + return defineChart({ + marks: [ + barX(rows, { + ...common, + x1: () => 0, + x2: "floor", + fill: (d) => hueVar((d as SplitDatum).set), + stroke: "var(--gmt-border-strong)", + }), + barX(rows, { + ...common, + x1: "floor", + x2: "total", + fill: (d) => `url(#${barHatchId(HUE[(d as SplitDatum).set])})`, + }), + ], + scales: { + x: axisBytes, + y: { scale: scaleBand, padding: 0.25 }, + }, + ...withTooltip(tooltip, (datum) => + content(datum as SplitDatum | undefined), + ), + }); +} + +// --------------------------------------------------------------------------- +// Registry +// --------------------------------------------------------------------------- + +const WIDTH = 1200; +const FLOOR_HEIGHT = 200; +const ROW_HEIGHT = 64; +const SPLIT_CHROME = 80; + +const PATTERNS = [barHatch("polyfill-shipped"), barHatch("polyfill-previous")]; + +export function bundleSizeCharts( + report: BundleReport = liveReport, +): Record { + const sets = polyfillSets(report); + const rows = chartRows(report).length; + const build = ( + kind: PolyfillChartKind, + measure: Measure, + ): [BundleSizeChartId, BarChart] => [ + `polyfill-${kind}-${measure}` as BundleSizeChartId, + { + ariaLabel: + kind === "floor" + ? `Size of ${sets.shipped.package} and ${sets.previous.package} alone, ${measure}` + : `Size of each function on ${sets.shipped.package} and on ${sets.previous.package}, ${measure}`, + idPrefix: `polyfill-${kind}-${measure}`, + width: WIDTH, + height: + kind === "floor" ? FLOOR_HEIGHT : rows * ROW_HEIGHT + SPLIT_CHROME, + gradients: [], + patterns: kind === "floor" ? [] : PATTERNS, + definition: ((tooltip?: ChartTooltipExtension) => + kind === "floor" + ? floorDefinition(report, measure, tooltip) + : splitDefinition( + report, + measure, + tooltip, + )) as unknown as BarChart["definition"], + }, + ]; + return Object.fromEntries([ + build("floor", "gzipped"), + build("floor", "minified"), + build("split", "gzipped"), + build("split", "minified"), + ]) as Record; +} + +export const BUNDLE_SIZE_CHARTS = bundleSizeCharts(); diff --git a/apps/dox/src/lib/bundle-size-figures.fixture.ts b/apps/dox/src/lib/bundle-size-figures.fixture.ts new file mode 100644 index 000000000..6a2ce1599 --- /dev/null +++ b/apps/dox/src/lib/bundle-size-figures.fixture.ts @@ -0,0 +1,54 @@ +/** + * A small bundle report for the tests of the bundle-size figures and charts: two polyfill sets, a + * floor, a `root`, three function entries and one `null` entry in the previous set. No test reads + * the live JSON's numbers through it, so none breaks when the sizes are measured again. + */ +import type { BundleReport } from "./bundle-size-figures"; + +export const FIXTURE_FLOOR = "base"; + +export function fixtureReport(): BundleReport { + return { + floor: FIXTURE_FLOOR, + entries: { + root: { minified: 50000, gzipped: 15000, budget: 51000 }, + base: { minified: 5000, gzipped: 2000, budget: null }, + fnSmall: { minified: 5800, gzipped: 2300, budget: 6000 }, + fnMid: { minified: 7000, gzipped: 2600, budget: 7200 }, + fnBig: { minified: 9000, gzipped: 3400, budget: 9500 }, + }, + // The previous set comes first on purpose: sets are found by the flag, never by index. + polyfills: [ + { + package: "beta-poly", + version: "0.5.1", + import: "beta-poly", + shipped: false, + gmt: "9.9.9", + from: "npm", + entries: { + root: { minified: 57000, gzipped: 17800 }, + base: { minified: 12000, gzipped: 4800 }, + fnSmall: { minified: 12800, gzipped: 5100 }, + fnMid: null, + fnBig: { minified: 16000, gzipped: 6200 }, + }, + }, + { + package: "alpha-poly", + version: "2.0.0", + import: "alpha-poly/full", + shipped: true, + gmt: "9.9.9", + from: "source", + entries: { + root: { minified: 50000, gzipped: 15000 }, + base: { minified: 5000, gzipped: 2000 }, + fnSmall: { minified: 5800, gzipped: 2300 }, + fnMid: { minified: 7000, gzipped: 2600 }, + fnBig: { minified: 9000, gzipped: 3400 }, + }, + }, + ], + }; +} diff --git a/apps/dox/src/lib/bundle-size-figures.test.ts b/apps/dox/src/lib/bundle-size-figures.test.ts new file mode 100644 index 000000000..3c65c2cc6 --- /dev/null +++ b/apps/dox/src/lib/bundle-size-figures.test.ts @@ -0,0 +1,202 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import live from "../generated/bundle-size.json"; +import { + chartRows, + comparisonRows, + formatBytes, + leadFigures, + polyfillSets, + smallestFunction, + splitOf, + type BundleReport, +} from "./bundle-size-figures"; +import { FIXTURE_FLOOR, fixtureReport } from "./bundle-size-figures.fixture"; + +const NBSP = " "; + +describe("polyfillSets", () => { + it("finds the sets by the flag when the previous set is listed first", () => { + const { shipped, previous } = polyfillSets(fixtureReport()); + expect(shipped.package).toBe("alpha-poly"); + expect(previous.package).toBe("beta-poly"); + }); + + it("throws for zero shipped sets", () => { + const report = fixtureReport(); + for (const set of report.polyfills ?? []) set.shipped = false; + expect(() => polyfillSets(report)).toThrow(/shipped/); + }); + + it("throws for two shipped sets", () => { + const report = fixtureReport(); + for (const set of report.polyfills ?? []) set.shipped = true; + expect(() => polyfillSets(report)).toThrow(/shipped/); + }); + + it("throws for a report with no polyfills", () => { + const { polyfills: _dropped, ...rest } = fixtureReport(); + expect(() => polyfillSets(rest as BundleReport)).toThrow(/polyfills/); + }); +}); + +describe("formatBytes", () => { + it("writes bytes under 1,000 and kB from 1,000, with a no-break space", () => { + expect(formatBytes(0)).toBe(`0${NBSP}B`); + expect(formatBytes(999)).toBe(`999${NBSP}B`); + expect(formatBytes(1000)).toBe(`1.0${NBSP}kB`); + expect(formatBytes(23_349)).toBe(`23.3${NBSP}kB`); + }); +}); + +describe("splitOf", () => { + const { shipped } = polyfillSets(fixtureReport()); + + it("splits each measure into total, floor and the code above the floor", () => { + expect(splitOf(shipped, "fnBig", FIXTURE_FLOOR)).toEqual({ + minified: { total: 9000, floor: 5000, code: 4000 }, + gzipped: { total: 3400, floor: 2000, code: 1400 }, + }); + }); + + it("is null for a null entry and for a missing one", () => { + const { previous } = polyfillSets(fixtureReport()); + expect(splitOf(previous, "fnMid", FIXTURE_FLOOR)).toBeNull(); + expect(splitOf(previous, "absent", FIXTURE_FLOOR)).toBeNull(); + }); +}); + +describe("comparisonRows and chartRows", () => { + it("keep the shipped-set order, drop the floor and keep root", () => { + expect(comparisonRows(fixtureReport()).map((r) => r.name)).toEqual([ + "root", + "fnSmall", + "fnMid", + "fnBig", + ]); + }); + + it("hold a null previous split where the previous set lacks the entry", () => { + const rows = comparisonRows(fixtureReport()); + expect(rows.find((r) => r.name === "fnMid")?.previous).toBeNull(); + expect(rows.find((r) => r.name === "fnBig")?.previous).not.toBeNull(); + }); + + it("chartRows also drops root and the null row", () => { + expect(chartRows(fixtureReport()).map((r) => r.name)).toEqual([ + "fnSmall", + "fnBig", + ]); + }); +}); + +describe("smallestFunction", () => { + it("ignores root and the floor, even though the floor is smaller", () => { + expect(smallestFunction(fixtureReport())).toBe("fnSmall"); + }); +}); + +describe("the figures follow the data", () => { + it("changes leadFigures and comparisonRows with one byte count", () => { + const before = fixtureReport(); + const after = fixtureReport(); + const shipped = after.polyfills?.find((p) => p.shipped); + if (!shipped?.entries.base) throw new Error("fixture has no base"); + shipped.entries.base.gzipped = 2500; + expect(leadFigures(after).floorGzipped).not.toBe( + leadFigures(before).floorGzipped, + ); + expect(comparisonRows(after)).not.toEqual(comparisonRows(before)); + }); + + it("holds the renamed package, and not the old name, in every output", () => { + const report = fixtureReport(); + const shipped = report.polyfills?.find((p) => p.shipped); + if (!shipped) throw new Error("fixture has no shipped set"); + shipped.package = "gamma-poly"; + shipped.import = "gamma-poly/full"; + const everything = JSON.stringify([ + leadFigures(report), + comparisonRows(report), + polyfillSets(report), + ]); + expect(everything).toContain("gamma-poly"); + expect(everything).not.toContain("alpha-poly"); + }); + + it("states the lead figures from the fixture", () => { + const figures = leadFigures(fixtureReport()); + expect(figures).toMatchObject({ + shippedVersion: "2.0.0", + previousVersion: "0.5.1", + previousGmt: "9.9.9", + floorGzipped: `2.0${NBSP}kB`, + previousFloorGzipped: `4.8${NBSP}kB`, + floorDifferenceGzipped: `2.8${NBSP}kB`, + floorDifferenceMinified: `7.0${NBSP}kB`, + smallestName: "fnSmall", + smallestCodeMinified: `800${NBSP}B`, + smallestCodeGzipped: `300${NBSP}B`, + smallestTotalGzipped: `2.3${NBSP}kB`, + largestName: "fnBig", + largestCodeGzipped: `1.4${NBSP}kB`, + rootGzipped: `15.0${NBSP}kB`, + previousRootGzipped: `17.8${NBSP}kB`, + }); + }); + + it("names how the previous set was measured by the field", () => { + const report = fixtureReport(); + expect(leadFigures(report).previousMeasuredFrom).toBe("the published"); + const previous = report.polyfills?.find((p) => !p.shipped); + if (!previous) throw new Error("fixture has no previous set"); + previous.from = "source"; + expect(leadFigures(report).previousMeasuredFrom).toBe("the source of"); + }); + + it("never prints the shipped set's GMT version", () => { + const report = fixtureReport(); + const shipped = report.polyfills?.find((p) => p.shipped); + if (!shipped) throw new Error("fixture has no shipped set"); + shipped.gmt = "7.7.7"; + expect(JSON.stringify(leadFigures(report))).not.toContain("7.7.7"); + }); +}); + +describe("the module states no name of its own", () => { + it("holds no package name and no entry name from the live JSON", () => { + const source = readFileSync( + resolve(import.meta.dirname, "bundle-size-figures.ts"), + "utf8", + ); + const { polyfills, entries } = live as unknown as BundleReport; + for (const set of polyfills ?? []) { + expect(source).not.toContain(set.package); + } + const quoted = Object.keys(entries).filter((name) => name !== "root"); + for (const name of quoted) { + expect(source).not.toMatch(new RegExp(`["'\`]${name}["'\`]`)); + } + }); +}); + +describe("the live report", () => { + const report = live as unknown as BundleReport; + + it("has two sets whose entries are the top-level entries (slice 6 landed)", () => { + const { shipped, previous } = polyfillSets(report); + const keys = Object.keys(report.entries); + expect(Object.keys(shipped.entries)).toEqual(keys); + expect(Object.keys(previous.entries)).toEqual(keys); + }); + + it("makes the polyfill the larger part of almost every import", () => { + const { shipped } = polyfillSets(report); + const rows = comparisonRows(report); + const polyfillLarger = rows.filter((row) => { + const split = splitOf(shipped, row.name, report.floor); + return split !== null && split.gzipped.floor > split.gzipped.code; + }); + expect(polyfillLarger.length).toBeGreaterThanOrEqual(rows.length - 1); + }); +}); diff --git a/apps/dox/src/lib/bundle-size-figures.ts b/apps/dox/src/lib/bundle-size-figures.ts new file mode 100644 index 000000000..dd95b1537 --- /dev/null +++ b/apps/dox/src/lib/bundle-size-figures.ts @@ -0,0 +1,240 @@ +/** + * Every figure the /bundle-size page states about the two polyfills, computed in one place from + * `src/generated/bundle-size.json` (written by `scripts/bundle-size.mjs report`). + * + * This module imports the report and nothing else. The chart module is in the client graph, and the + * reference corpus is not allowed there, so nothing here may reach `bundle-size.ts`, the corpus or + * `gmt-stats`. No package name, version or entry name is typed in: they come from the report. The + * only literals are the measure names, `"root"` and the report's `floor` field, which the JSON + * defines. A size is in kB, 1 kB being 1,000 bytes. + */ +import data from "../generated/bundle-size.json"; + +export type Measure = "minified" | "gzipped"; +export const MEASURES: readonly Measure[] = ["minified", "gzipped"]; + +export interface Sized { + minified: number; + gzipped: number; +} + +export interface PolyfillSet { + package: string; + version: string; + import: string; + shipped: boolean; + /** The GMT release this set was measured with. */ + gmt: string; + /** Where that GMT came from: the repository's source, or the published package on npm. */ + from: "source" | "npm"; + /** `null` where the GMT of this set does not export the entry. */ + entries: Record; +} + +export interface BundleReport { + floor: string; + entries: Record; + polyfills?: PolyfillSet[]; +} + +const report = data as unknown as BundleReport; + +/** The entry that measures the whole package. */ +const ROOT = "root"; + +/** One measure of one entry: its total, the floor of its set, and the code above that floor. */ +export interface Part { + total: number; + floor: number; + code: number; +} + +export type Split = Record; + +export interface ComparisonRow { + name: string; + shipped: Split; + previous: Split | null; +} + +/** Bytes as kB with one decimal. */ +export const kb = (bytes: number): string => (bytes / 1000).toFixed(1); + +/** Under 1,000 B in bytes, from 1,000 B in kB, with a no-break space before the unit. */ +export function formatBytes(bytes: number): string { + return bytes < 1000 ? `${bytes} B` : `${kb(bytes)} kB`; +} + +/** The two polyfill sets, found by their flag. Throws unless there is exactly one of each. */ +export function polyfillSets(source: BundleReport = report): { + shipped: PolyfillSet; + previous: PolyfillSet; +} { + const sets = source.polyfills; + if (!sets) { + throw new Error( + "[bundle-size] the generated report has no polyfills list; run generate", + ); + } + const shipped = sets.filter((set) => set.shipped); + const previous = sets.filter((set) => !set.shipped); + if (shipped.length !== 1 || previous.length !== 1) { + throw new Error( + `[bundle-size] expected one shipped and one previous polyfill set, found ${shipped.length} shipped and ${previous.length} previous`, + ); + } + return { shipped: shipped[0], previous: previous[0] }; +} + +/** One entry of one set split into the polyfill and GMT's code; `null` when the set lacks it. */ +export function splitOf( + set: PolyfillSet, + name: string, + floorName: string = report.floor, +): Split | null { + const entry = set.entries[name]; + const floor = set.entries[floorName]; + if (!entry || !floor) return null; + const part = (measure: Measure): Part => ({ + total: entry[measure], + floor: floor[measure], + code: entry[measure] - floor[measure], + }); + return { minified: part("minified"), gzipped: part("gzipped") }; +} + +/** One row per entry in shipped-set order, the floor left out and `root` kept. */ +export function comparisonRows(source: BundleReport = report): ComparisonRow[] { + const { shipped, previous } = polyfillSets(source); + return Object.keys(shipped.entries) + .filter((name) => name !== source.floor) + .flatMap((name) => { + const split = splitOf(shipped, name, source.floor); + if (!split) return []; + return [ + { + name, + shipped: split, + previous: splitOf(previous, name, source.floor), + }, + ]; + }); +} + +/** The rows the charts draw: no `root`, and no row the previous set lacks. */ +export function chartRows( + source: BundleReport = report, +): (ComparisonRow & { previous: Split })[] { + return comparisonRows(source).filter( + (row): row is ComparisonRow & { previous: Split } => + row.name !== ROOT && row.previous !== null, + ); +} + +/** The function entries (not `root`, not the floor) in shipped-set order. */ +function functionRows(source: BundleReport): ComparisonRow[] { + return comparisonRows(source).filter((row) => row.name !== ROOT); +} + +/** The function entry with the smallest minified total on the shipped set. */ +export function smallestFunction(source: BundleReport = report): string { + const rows = functionRows(source); + if (rows.length === 0) { + throw new Error("[bundle-size] the report has no function entries"); + } + return rows.reduce((least, row) => + row.shipped.minified.total < least.shipped.minified.total ? row : least, + ).name; +} + +/** The function entry with the most of GMT's code, gzipped, on the shipped set. */ +function largestFunction(source: BundleReport): string { + const rows = functionRows(source); + if (rows.length === 0) { + throw new Error("[bundle-size] the report has no function entries"); + } + return rows.reduce((most, row) => + row.shipped.gzipped.code > most.shipped.gzipped.code ? row : most, + ).name; +} + +/** The text the lead and the section state, each a finished string. */ +export interface LeadFigures { + shippedVersion: string; + previousVersion: string; + previousGmt: string; + /** + * The first GMT release on the shipped polyfill: the minor release after `previousGmt`. The + * pages name it before it is published; `bundle-size.test.ts` holds it to the pending + * changesets, then to the changelog. + */ + firstShippedGmt: string; + /** "the published" or "the source of": how the previous set's GMT was measured. */ + previousMeasuredFrom: string; + floorGzipped: string; + floorMinified: string; + previousFloorGzipped: string; + previousFloorMinified: string; + floorDifferenceGzipped: string; + floorDifferenceMinified: string; + smallestName: string; + smallestCodeMinified: string; + smallestCodeGzipped: string; + smallestTotalGzipped: string; + largestName: string; + largestCodeGzipped: string; + rootGzipped: string; + previousRootGzipped: string; +} + +/** `1.21.0` to `1.22.0`. */ +function nextMinor(version: string): string { + const [major, minor] = version.split(".").map(Number); + return `${major}.${minor + 1}.0`; +} + +export function leadFigures(source: BundleReport = report): LeadFigures { + const { shipped, previous } = polyfillSets(source); + const need = (set: PolyfillSet, name: string): Split => { + const split = splitOf(set, name, source.floor); + if (!split) { + throw new Error(`[bundle-size] ${set.package} has no entry ${name}`); + } + return split; + }; + const floor = need(shipped, source.floor); + const previousFloor = need(previous, source.floor); + const smallestName = smallestFunction(source); + const smallest = need(shipped, smallestName); + const largestName = largestFunction(source); + const largest = need(shipped, largestName); + return { + shippedVersion: shipped.version, + previousVersion: previous.version, + previousGmt: previous.gmt, + firstShippedGmt: nextMinor(previous.gmt), + previousMeasuredFrom: + previous.from === "npm" ? "the published" : "the source of", + floorGzipped: formatBytes(floor.gzipped.total), + floorMinified: formatBytes(floor.minified.total), + previousFloorGzipped: formatBytes(previousFloor.gzipped.total), + previousFloorMinified: formatBytes(previousFloor.minified.total), + floorDifferenceGzipped: formatBytes( + previousFloor.gzipped.total - floor.gzipped.total, + ), + floorDifferenceMinified: formatBytes( + previousFloor.minified.total - floor.minified.total, + ), + smallestName, + smallestCodeMinified: formatBytes(smallest.minified.code), + smallestCodeGzipped: formatBytes(smallest.gzipped.code), + smallestTotalGzipped: formatBytes(smallest.gzipped.total), + largestName, + largestCodeGzipped: formatBytes(largest.gzipped.code), + rootGzipped: formatBytes(need(shipped, ROOT).gzipped.total), + previousRootGzipped: formatBytes(need(previous, ROOT).gzipped.total), + }; +} + +/** `leadFigures()` on the live report, evaluated once for the MDX page. */ +export const polyfillFigures: LeadFigures = leadFigures(); diff --git a/apps/dox/src/lib/bundle-size.ts b/apps/dox/src/lib/bundle-size.ts index 9f53713d8..6786bbe38 100644 --- a/apps/dox/src/lib/bundle-size.ts +++ b/apps/dox/src/lib/bundle-size.ts @@ -2,10 +2,17 @@ * The rows of the bundle-size table, from `src/generated/bundle-size.json` (written by * `scripts/bundle-size.mjs report` during `generate`) and the reference corpus. Shared by the page's * component and by its Markdown twin, so the two show the same figures. A size is in kB, 1 kB being - * 1,000 bytes. + * 1,000 bytes; the two "over the polyfill" columns drop to bytes under 1,000 B. */ import report from "../generated/bundle-size.json"; import corpus from "../generated/reference/gmt-corpus.json"; +import { + comparisonRows, + formatBytes, + kb, + polyfillSets, + splitOf, +} from "./bundle-size-figures"; type Measured = { minified: number; gzipped: number; budget: number | null }; @@ -20,14 +27,11 @@ type BundleRow = { overGz: number | null; }; -/** Bytes as kB with one decimal. */ -const kb = (bytes: number): string => (bytes / 1000).toFixed(1); - /** The import that loads one entry: the package, the polyfill, or one function by its module. */ function importOf(name: string): string { if (name === "root") return 'import * as gmt from "@northguild/gmt"'; if (name === report.floor) { - return 'import { Temporal } from "@js-temporal/polyfill"'; + return `import { Temporal } from "${polyfillSets().shipped.import}"`; } const found = corpus.find((e) => e.kind === "function" && e.name === name); if (!found) { @@ -63,8 +67,54 @@ export function bundleCells(row: BundleRow): string[] { row.importLine, `${kb(row.minified)} kB`, `${kb(row.gzipped)} kB`, - row.overMin === null ? "floor" : `${kb(row.overMin)} kB`, - row.overGz === null ? "floor" : `${kb(row.overGz)} kB`, + row.overMin === null ? "floor" : formatBytes(row.overMin), + row.overGz === null ? "floor" : formatBytes(row.overGz), row.budget === null ? "none" : `${kb(row.budget)} kB`, ]; } + +/** The columns of the polyfill comparison. A package name sits in backticks, for ``. */ +export function compareColumns(): string[] { + const { shipped, previous } = polyfillSets(); + return [ + "Import", + `\`${shipped.package}\` gzipped`, + `\`${previous.package}\` gzipped`, + `GMT code over \`${shipped.package}\``, + `GMT code over \`${previous.package}\``, + ]; +} + +/** + * The comparison's rows as text, floor first, then every entry of `comparisonRows()`. The + * previous set's cells read "not in GMT {version}" where its GMT does not export the entry. + */ +export function compareCells(): { importLine: string; cells: string[] }[] { + const { shipped, previous } = polyfillSets(); + const absent = `not in GMT ${previous.gmt}`; + const floorShipped = splitOf(shipped, report.floor); + const floorPrevious = splitOf(previous, report.floor); + if (!floorShipped || !floorPrevious) { + throw new Error("[bundle-size] a polyfill set lacks the floor entry"); + } + return [ + { + importLine: importOf(report.floor), + cells: [ + formatBytes(floorShipped.gzipped.total), + formatBytes(floorPrevious.gzipped.total), + "floor", + "floor", + ], + }, + ...comparisonRows().map((row) => ({ + importLine: importOf(row.name), + cells: [ + formatBytes(row.shipped.gzipped.total), + row.previous ? formatBytes(row.previous.gzipped.total) : absent, + formatBytes(row.shipped.gzipped.code), + row.previous ? formatBytes(row.previous.gzipped.code) : absent, + ], + })), + ]; +} diff --git a/apps/dox/src/lib/delivery-scheduler-charts.ts b/apps/dox/src/lib/delivery-scheduler-charts.ts index 894499c32..2a4397db6 100644 --- a/apps/dox/src/lib/delivery-scheduler-charts.ts +++ b/apps/dox/src/lib/delivery-scheduler-charts.ts @@ -4,7 +4,7 @@ * station spacing) and the To-scale view (a Gantt-style lane per leg on a * real time axis). Both are built from `ChartData` (`delivery-scheduler.ts`) * — nothing chart-library-specific lives there, mirroring how - * `why-gmt-charts.ts` sits beside its own plain data module. + * the bar-chart modules (`why-gmt-charts.ts`, `bundle-size-charts.ts`) sit beside their own plain data modules. * * Colours are `var(--gmt-*)` strings passed straight into mark options — * the same pattern `why-gmt-charts.ts` already uses (`stroke: "var(--gmt- @@ -18,7 +18,7 @@ * contrast-checked "ink" text variants) the leg-card form and the itinerary * rail use, never amber, which stays the sentinel's alone. */ -import { Temporal } from "@js-temporal/polyfill"; +import { Temporal } from "@northguild/gmt"; import type { ChartDefinition, ChartMark, SceneNode } from "@tanstack/charts"; import { defineChart, dot, link, ruleX, text } from "@tanstack/charts"; import { barX } from "@tanstack/charts/bar"; diff --git a/apps/dox/src/lib/mdx-jsx.test.ts b/apps/dox/src/lib/mdx-jsx.test.ts index d20003b42..fec6ad8c0 100644 --- a/apps/dox/src/lib/mdx-jsx.test.ts +++ b/apps/dox/src/lib/mdx-jsx.test.ts @@ -1,6 +1,7 @@ import { alternativesStack } from "../data/date-alternatives"; import { dateFaults } from "../data/date-faults"; import { competitorComparisons } from "../data/library-comparison"; +import { comparisonRows, polyfillSets } from "./bundle-size-figures"; import { renderMdxComponents } from "./mdx-jsx"; import { whyGmtFigures } from "./why-gmt-figures"; @@ -79,3 +80,61 @@ describe("competitor data the library table leans on", () => { expect(lib.timeResolution).toBe("millisecond"); }); }); + +describe("the polyfill comparison in the text surfaces", () => { + const md = renderMdxComponents(""); + const rows = rowsOf(md); + + it("names both packages in its header", () => { + const { shipped, previous } = polyfillSets(); + expect(rows[0]).toContain(`\`${shipped.package}\` gzipped`); + expect(rows[0]).toContain(`\`${previous.package}\` gzipped`); + }); + + it("has a row for the floor and one for every compared entry", () => { + // header + separator + floor + rows + expect(rows).toHaveLength(2 + 1 + comparisonRows().length); + }); + + it("leaves no component tag behind", () => { + expect(md).not.toMatch(/<[A-Z]/); + }); +}); + +describe("the captions of a chart's views in the text surfaces", () => { + const body = [ + "", + ].join("\n"); + + it("keeps each view's caption as a line of text, with its expressions as {…}", () => { + const out = renderMdxComponents(body); + expect(out).toContain("First view, {one} items."); + expect(out).toContain("Second view."); + expect(out).not.toContain(" { + const out = renderMdxComponents( + '', + ); + expect(out).toContain("**T — One.**"); + }); +}); + +describe("an aside in the text surfaces", () => { + it("keeps its title as a bold line above its text", () => { + const out = renderMdxComponents( + '', + ); + expect(out).toContain( + "**Never throws**\n\nInvalid input returns a fallback.", + ); + expect(out).not.toContain(" code.trim() ? `\n\`\`\`js\n${code.trim()}\n\`\`\`\n` : ""; +/** + * The caption of each view of a `ChartContainer`, one line each. The views are a JS array in the + * tag, so the captions are read from the text: a string or a template literal after `caption:`. + * A template literal's `${expr}` becomes `{expr}`, which `stripMdx` replaces with the figure. + */ +function viewCaptions(views: string | undefined): string { + if (!views) return ""; + const captions = [ + ...views.matchAll( + /\bcaption:\s*(?:`((?:[^`\\]|\\.)*)`|"((?:[^"\\]|\\.)*)")/g, + ), + ].map((found) => (found[1] ?? found[2]).replace(/\$\{/g, "{")); + return captions.map((caption) => `\n${caption}\n`).join(""); +} + /** `` → heading, description, and the wrong and right samples as code blocks. */ function renderMistake(props: Record): string { const parts = [`### ${props.title ?? "Mistake"}`]; @@ -332,13 +353,7 @@ function renderUpstreamDefects(): string { ) .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 `|` - // would end the cell early and `_` or `[` would turn into Markdown the page never shows. - const reason = - group.state === "guard" && group.guard - ? `. ${escapeMarkdownInline(group.guard.reason)}` - : ""; - const state = `${badge} — ${count}${reason}`; + const state = `${badge} — ${count}`; return `| **${escapeMarkdownInline(groupLabel(group))}** — ${escapeMarkdownInline(groupWhatBreaks(group))} | ${state} | ${sent || "—"} |`; }); @@ -365,6 +380,20 @@ function renderBundleSize(): string { ].join("\n"); } +/** `` as a Markdown table of the same figures. */ +function renderPolyfillCompare(): string { + const columns = compareColumns(); + return [ + "", + `| ${columns.join(" | ")} |`, + `| ${columns.map(() => "---").join(" | ")} |`, + ...compareCells().map( + (row) => `| \`${row.importLine}\` | ${row.cells.join(" | ")} |`, + ), + "", + ].join("\n"); +} + /** `` as a Markdown table: their call, the GMT functions, a note. */ function renderMigrationMap(props: Record): string { const view = mapView( @@ -496,6 +525,8 @@ export function renderMdxComponents(body: string): string { "Card", "HomeCards", "HomeCard", + // An aside's title is its point ("Public helpers never throw"), so it stays as a line. + "Aside", ]) { out = replaceElements(out, wrapper, (props, children) => { // A template-literal title's `${expr}` becomes `{expr}`, which `stripMdx` replaces with the figure. @@ -503,7 +534,7 @@ export function renderMdxComponents(body: string): string { .filter(Boolean) .join(" — ") .replace(/\$\{/g, "{"); - return `${caption ? `\n**${caption}**\n` : ""}${dedent(children)}`; + return `${caption ? `\n**${caption}**\n` : ""}${viewCaptions(props.views)}${dedent(children)}`; }); } @@ -512,6 +543,7 @@ export function renderMdxComponents(body: string): string { out = replaceElements(out, "UpstreamTracker", renderUpstreamTracker); out = replaceElements(out, "UpstreamListings", renderUpstreamListings); out = replaceElements(out, "BundleSize", renderBundleSize); + out = replaceElements(out, "PolyfillCompare", renderPolyfillCompare); out = replaceElements(out, "MigrationMap", renderMigrationMap); out = replaceElements(out, "BehaviourDiffs", renderBehaviourDiffs); out = replaceElements(out, "BehaviourMatrix", renderBehaviourMatrix); diff --git a/apps/dox/src/lib/page-expression-values.test.ts b/apps/dox/src/lib/page-expression-values.test.ts index f2968fadb..ac73742a8 100644 --- a/apps/dox/src/lib/page-expression-values.test.ts +++ b/apps/dox/src/lib/page-expression-values.test.ts @@ -1,6 +1,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; +import { polyfillFigures } from "./bundle-size-figures"; import { pageExpressionValues } from "./page-expression-values"; import { stripMdx } from "./page-markdown"; @@ -17,6 +18,8 @@ const PAGES = [ "index.mdx", "why-gmt.mdx", "compare.mdx", + "bundle-size.mdx", + "upstream.mdx", "compare/behaviour.mdx", "migrate/index.mdx", "migrate/date-fns.mdx", @@ -51,6 +54,13 @@ describe("page expression values", () => { }); } + it("holds a value for every polyfill figure, so a new key cannot be forgotten", () => { + const values = pageExpressionValues(); + for (const [key, value] of Object.entries(polyfillFigures)) { + expect(values[`polyfillFigures.${key}`], key).toBe(value); + } + }); + it("states no figure of its own: every value comes from the data modules", () => { const source = readFileSync( resolve(import.meta.dirname, "page-expression-values.ts"), diff --git a/apps/dox/src/lib/page-expression-values.ts b/apps/dox/src/lib/page-expression-values.ts index c780ab74d..1b7b43556 100644 --- a/apps/dox/src/lib/page-expression-values.ts +++ b/apps/dox/src/lib/page-expression-values.ts @@ -27,9 +27,12 @@ import { formatCount, formatNamespaceList, gmtStats, + industryFunctions, industryNamespaces, runsPerTest, } from "../data/gmt-stats"; +import { nativeFailures } from "../data/native-engine-failures"; +import { polyfillFigures } from "./bundle-size-figures"; import { measurementDateRange } from "./library-compare-tables"; import { familyCounts, formatFamilyCounts } from "./locale-families"; import { formatOffset, zoneOffsetRange } from "./timezone-offset-range"; @@ -60,6 +63,19 @@ export function pageExpressionValues(): Record { return { ...checkedLines, + // The /bundle-size figures: one entry per key, so a new key cannot be forgotten. + ...Object.fromEntries( + Object.entries(polyfillFigures).map(([key, value]) => [ + `polyfillFigures.${key}`, + value, + ]), + ), + ...Object.fromEntries( + Object.entries(nativeFailures).map(([key, value]) => [ + `nativeFailures.${key}`, + value, + ]), + ), "matrix.measuredOn": matrix.measuredOn, "matrix.runtime.node": matrix.runtime.node, 'matrix.runtime.hostZones.join(", ")': matrix.runtime.hostZones.join(", "), @@ -83,6 +99,7 @@ export function pageExpressionValues(): Record { "industryNamespaces.length": String(industryNamespaces.length), coreNamespaceList: formatNamespaceList(coreNamespaces), industryNamespaceList: formatNamespaceList(industryNamespaces), + industryFunctions: String(industryFunctions), "formatCount(coreFunctions)": formatCount(coreFunctions), "formatCount(plainAndZoned)": formatCount(plainAndZoned), offsetWindowHours: String(offsetWindowHours), diff --git a/apps/dox/src/lib/page-markdown.test.ts b/apps/dox/src/lib/page-markdown.test.ts index f49b83635..38157075f 100644 --- a/apps/dox/src/lib/page-markdown.test.ts +++ b/apps/dox/src/lib/page-markdown.test.ts @@ -152,3 +152,37 @@ describe("stripMdx link prefixing", () => { expect(out).not.toMatch(/\]\(\/(?!gmt\/|not-a-link)/); }); }); + +describe("stripMdx code in prose", () => { + // MDX prints a backtick span as written, braces and all, so the text surfaces must too: a figure + // the page shows as `{name}` is the bug, and the twin has to show it rather than hide it. + it("leaves an expression inside a backtick span unresolved, as the page prints it", () => { + const md = stripMdx( + "Built on `gmt@{version}` and gmt {version}, GMT {gmtVersion}.", + { + gmtVersion: "1.0.0", + values: { version: "1.21.0" }, + }, + ); + expect(md).toBe("Built on `gmt@{version}` and gmt 1.21.0, GMT 1.0.0."); + }); + + it("pairs backticks left to right, so text between two spans still resolves", () => { + const md = stripMdx("| `gmt` | {gmtVersion} | `2024` |", { + gmtVersion: "1.0.0", + }); + expect(md).toBe("| `gmt` | 1.0.0 | `2024` |"); + }); + + it("turns a element holding a resolved value into a code span", () => { + const md = stripMdx("It adds {name} to the floor.", { + values: { name: "isValidDate" }, + }); + expect(md).toBe("It adds `isValidDate` to the floor."); + }); + + it("leaves a element that holds a tag inside it", () => { + const md = stripMdx("A ac here.", {}); + expect(md).toContain(""); + }); +}); diff --git a/apps/dox/src/lib/page-markdown.ts b/apps/dox/src/lib/page-markdown.ts index 1f834b9b2..c57b781b9 100644 --- a/apps/dox/src/lib/page-markdown.ts +++ b/apps/dox/src/lib/page-markdown.ts @@ -175,23 +175,34 @@ export function stripMdx( part.replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, ""), ); - // Substitute template variables - if (vars.gmtVersion != null) { - md = md.replace(/\{gmtVersion\}/g, vars.gmtVersion); - } - - // Figures the pages state as expressions over the stats modules. - const values = vars.values ?? {}; + // Figures the pages state as expressions: `{gmtVersion}` and any `values` given. A backtick + // span is skipped, because MDX prints its braces as written; resolving one here would hide + // from the text surfaces a figure the page itself shows as `{name}`. + const values = { ...vars.values }; + if (vars.gmtVersion != null) values.gmtVersion = vars.gmtVersion; md = outsideFences(md, (part) => part - .replace(/\{([^{}\n]+)\}/g, (whole, expression: string) => { - const resolved = values[expression.trim()]; - return resolved === undefined ? whole : resolved; - }) + .replace( + /(`[^`\n]*`)|\{([^{}\n]+)\}/g, + ( + whole, + codeSpan: string | undefined, + expression: string | undefined, + ) => { + if (codeSpan !== undefined || expression === undefined) return whole; + return values[expression.trim()] ?? whole; + }, + ) // `{" "}` is JSX line-break padding. .replace(/\{"\s*"\}/g, " "), ); + // Prose that names a function from a figure writes it as `{name}`, because a + // backtick span cannot hold an expression. Once the value is in, it is a code span again. + md = outsideFences(md, (part) => + part.replace(/([^<>\n]+)<\/code>/g, "`$1`"), + ); + // A `.map(…)` block is a generated table or chart, whose figures the prose already states. md = outsideFences(md, dropMapBlocks); diff --git a/apps/dox/src/lib/upstream-defects-markdown.test.ts b/apps/dox/src/lib/upstream-defects-markdown.test.ts index dab1ccffa..3e3ae3009 100644 --- a/apps/dox/src/lib/upstream-defects-markdown.test.ts +++ b/apps/dox/src/lib/upstream-defects-markdown.test.ts @@ -17,7 +17,7 @@ const rows = renderMdxComponents("") .split("\n") .filter((line) => line.startsWith("| **")); -/** The middle cell: the state badge, the count and, on a guard row, the reason. */ +/** The middle cell: the state badge, and the count. */ const stateCell = (row: string): string => row.split(/(? as Markdown", () => { @@ -28,22 +28,6 @@ describe(" as Markdown", () => { }); }); - it("shows 'Kept on purpose' on exactly the guard rows, each with its reason", () => { - const guards = compatGroups.filter((g) => g.state === "guard"); - const kept = rows.filter((row) => row.includes("Kept on purpose")); - expect(kept).toHaveLength(guards.length); - for (const group of guards) { - const row = rows[compatGroups.indexOf(group)]!; - expect(row, groupLabel(group)).toContain("Kept on purpose"); - expect(row, groupLabel(group)).toContain( - group.guard!.reason.replaceAll("|", "\\|"), - ); - expect(stateCell(row)).toBe( - `Kept on purpose — ${group.probes} of ${group.probes} checks pass. ${group.guard!.reason.replaceAll("|", "\\|")}`, - ); - } - }); - it("shows '✓ Yes' on exactly the still-needed and out-of-scope rows and 'No' on exactly the removable ones", () => { const count = (state: string) => compatGroups.filter((g) => g.state === state).length; @@ -61,7 +45,6 @@ describe(" as Markdown", () => { const expected = { "still-needed": "✓ Yes", removable: "No", - guard: "Kept on purpose", "out-of-scope": `✓ Yes, on ${(group.engines ?? []).map(engineLabel).join(" and ")}`, }[group.state]; expect(cell.startsWith(`${expected} — `), groupLabel(group)).toBe(true); @@ -94,7 +77,7 @@ describe("escapeMarkdownInline", () => { it("leaves plain prose, digits, parentheses, dots and # alone", () => { const text = - "Polyfill 0.5.1 is older (tc39/proposal-temporal#3292), so it passes."; + "Polyfill 1.0.8 is newer (tc39/proposal-temporal#3292), so it passes."; expect(escapeMarkdownInline(text)).toBe(text); }); @@ -104,32 +87,6 @@ describe("escapeMarkdownInline", () => { }); describe(" free text as Markdown", () => { - it("leaves every real guard reason unchanged apart from its pipes", () => { - for (const g of compatGroups.filter((g) => g.guard)) { - expect(escapeMarkdownInline(g.guard!.reason)).toBe( - g.guard!.reason.replaceAll("|", "\\|"), - ); - } - }); - - it("escapes Markdown in a guard reason", () => { - const hostile = "a*b_c[d](e) `f` h\\i | j"; - const guard = compatGroups.find((g) => g.guard)!; - const saved = guard.guard!.reason; - try { - guard.guard!.reason = hostile; - const row = renderMdxComponents("") - .split("\n") - .filter((line) => line.startsWith("| **"))[ - compatGroups.indexOf(guard) - ]!; - expect(stateCell(row)).toContain(escapeMarkdownInline(hostile)); - expect(row).not.toContain(hostile); - } finally { - guard.guard!.reason = saved; - } - }); - it("escapes every what-breaks cell the way the helper does", () => { compatGroups.forEach((group, i) => { expect(rows[i]).toContain( diff --git a/apps/dox/src/lib/why-gmt-charts.test.ts b/apps/dox/src/lib/why-gmt-charts.test.ts index 804c18174..f7ddedfe2 100644 --- a/apps/dox/src/lib/why-gmt-charts.test.ts +++ b/apps/dox/src/lib/why-gmt-charts.test.ts @@ -9,15 +9,14 @@ import { } from "../data/gmt-stats"; import { raw } from "~/widgets/builders/html"; import { renderHtml } from "~/widgets/test-fixture"; +import { barGradientId, barHatchId } from "./bar-chart-kit"; import { libraryComparisons } from "../data/library-comparison"; import { - BAR_CHARTS, + WHY_GMT_CHARTS, CORE_FUNCTION_TOTAL, INDUSTRY_FUNCTION_TOTAL, NAMESPACE_COUNTS, OWN_SERIES, - barGradientId, - barHatchId, ciExecutionRows, ciExecutionTooltip, ciSuiteRows, @@ -25,13 +24,12 @@ import { industrySegments, industrySummary, industryTooltip, - isBarChartId, namespaceTooltip, - type BarChartId, + type WhyGmtChartId, } from "../lib/why-gmt-charts"; -function renderStatic(id: BarChartId): string { - const chart = BAR_CHARTS[id]; +function renderStatic(id: WhyGmtChartId): string { + const chart = WHY_GMT_CHARTS[id]; const runtime = createChartRuntime(); const scene = runtime.render(chart.definition(), { width: chart.width, @@ -58,7 +56,7 @@ function barRects(svg: string) { } /** The rects of a static render with their stacking position, for the stacked chart. */ -function renderStaticRects(id: BarChartId) { +function renderStaticRects(id: WhyGmtChartId) { const attr = (rect: string, name: string) => rect.match(new RegExp(` ${name}="([^"]*)"`))?.[1] ?? ""; return [ @@ -471,10 +469,10 @@ describe("static bar chart render", () => { }); it("only references gradients and patterns its container declares", () => { - for (const id of Object.keys(BAR_CHARTS) as BarChartId[]) { + for (const id of Object.keys(WHY_GMT_CHARTS) as WhyGmtChartId[]) { const declared = [ - ...BAR_CHARTS[id].gradients.map((g) => g.id), - ...BAR_CHARTS[id].patterns.map((p) => p.id), + ...WHY_GMT_CHARTS[id].gradients.map((g) => g.id), + ...WHY_GMT_CHARTS[id].patterns.map((p) => p.id), ]; for (const rect of barRects(renderStatic(id))) { expect(declared).toContain(rect.gradient); @@ -483,16 +481,16 @@ describe("static bar chart render", () => { }); it("declares a hatch for the industry chart and for no other", () => { - expect(BAR_CHARTS.industries.patterns.map((p) => p.id)).toEqual([ + expect(WHY_GMT_CHARTS.industries.patterns.map((p) => p.id)).toEqual([ barHatchId("spring"), ]); - for (const id of Object.keys(BAR_CHARTS) as BarChartId[]) { - if (id !== "industries") expect(BAR_CHARTS[id].patterns).toEqual([]); + for (const id of Object.keys(WHY_GMT_CHARTS) as WhyGmtChartId[]) { + if (id !== "industries") expect(WHY_GMT_CHARTS[id].patterns).toEqual([]); } }); it("names the industry chart for what it shows, own and shared", () => { - expect(BAR_CHARTS.industries.ariaLabel).toBe( + expect(WHY_GMT_CHARTS.industries.ariaLabel).toBe( "Public functions by industry layer, own and shared", ); }); @@ -507,7 +505,7 @@ describe("namespace chart labels", () => { ] as const)( "keeps every %s label at the page's real chart width", (id, expected) => { - const chart = BAR_CHARTS[id]; + const chart = WHY_GMT_CHARTS[id]; const width = 524; const runtime = createChartRuntime(); const scene = runtime.render(chart.definition(), { @@ -529,13 +527,3 @@ describe("namespace chart labels", () => { }, ); }); - -describe("isBarChartId", () => { - it("accepts registered charts and rejects everything else", () => { - expect(isBarChartId("namespaces")).toBe(true); - expect(isBarChartId("industries")).toBe(true); - expect(isBarChartId("ci-suite")).toBe(true); - expect(isBarChartId("locale-matrix")).toBe(false); - expect(isBarChartId(undefined)).toBe(false); - }); -}); diff --git a/apps/dox/src/lib/why-gmt-charts.ts b/apps/dox/src/lib/why-gmt-charts.ts index 26f033c40..793d38a5c 100644 --- a/apps/dox/src/lib/why-gmt-charts.ts +++ b/apps/dox/src/lib/why-gmt-charts.ts @@ -10,7 +10,6 @@ * and the marks reference them with url(#id). The shaded segments of the * "By industry" chart use a hatch pattern declared the same way. */ -import type { ChartDefinition, ChartPoint } from "@tanstack/charts"; import { barX, barY, defineChart, stack } from "@tanstack/charts"; import { chartKey, chartSummary } from "~/widgets/builders"; import { scaleBand } from "@tanstack/charts/scales/band"; @@ -20,6 +19,15 @@ import type { ChartTooltipExtension, ChartTooltipRow, } from "@tanstack/charts/tooltip"; +import { + barGradient, + barGradientId, + barHatch, + barHatchId, + withTooltip, + type BarChart, + type BarHue, +} from "./bar-chart-kit"; import { coreFunctions, coreNamespaces, @@ -32,86 +40,12 @@ import { libraryComparisons, type LibraryComparison, } from "../data/library-comparison"; -import { chartTooltipMotion } from "./chart-motion"; - -type TooltipOption = Parameters[0]["tooltip"]; const shareFormat = new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 1, }); -// --------------------------------------------------------------------------- -// Gradients -// --------------------------------------------------------------------------- - -type BarHue = "spring" | "signal" | "cyan"; - -export interface BarGradient { - id: string; - hue: BarHue; - top: number; - bottom: number; -} - -// Same recipe as the locale matrix tiles: the bottom stop sits 0.09 under the top. -const BAR_OPACITY = { top: 0.32, bottom: 0.23 }; - -export function barGradientId(hue: BarHue): string { - return `gmt-bar-${hue}`; -} - -function barGradient(hue: BarHue): BarGradient { - return { id: barGradientId(hue), hue, ...BAR_OPACITY }; -} - -/** - * A hatch: a tint of the hue with diagonal lines over it, declared once as a page-level SVG - * pattern (`ChartContainer.astro`). The tint and the lines are both the hue's token at reduced - * strength, so the difference from a solid bar never rests on colour alone. - */ -export interface BarPattern { - id: string; - hue: BarHue; - /** The fill strength of the tint under the lines. */ - tint: number; - /** The strength of the lines. */ - line: number; - /** The side of the repeating tile, in user units. */ - size: number; - lineWidth: number; -} - -export function barHatchId(hue: BarHue): string { - return `gmt-bar-${hue}-hatch`; -} - -function barHatch(hue: BarHue): BarPattern { - return { - id: barHatchId(hue), - hue, - tint: 0.12, - line: 0.6, - size: 7, - lineWidth: 2, - }; -} - -function withTooltip( - extension: ChartTooltipExtension | undefined, - content: (datum: unknown) => ChartTooltipContent, -): { tooltip?: TooltipOption } { - if (!extension) return {}; - return { - tooltip: { - use: extension, - ...chartTooltipMotion(), - content: (points: readonly ChartPoint[]) => - content(points[0]?.datum), - } as TooltipOption, - }; -} - // --------------------------------------------------------------------------- // CI executions per library // --------------------------------------------------------------------------- @@ -510,29 +444,17 @@ function industryDefinition(tooltip?: ChartTooltipExtension) { // Registry // --------------------------------------------------------------------------- -export type BarChartId = +export type WhyGmtChartId = | "ci-executions" | "ci-suite" | "namespaces" | "industries"; -interface BarChart { - ariaLabel: string; - idPrefix: string; - width: number; - height: number; - gradients: readonly BarGradient[]; - /** Hatches the chart's shaded marks refer to, declared as page-level patterns. */ - patterns: readonly BarPattern[]; - /** Widened to the runtime's untyped definition so both charts share a caller. */ - definition: (tooltip?: ChartTooltipExtension) => ChartDefinition; -} - /** * Both charts render at the locale matrix's natural width of 1200, so they * fill the content column the same way. */ -export const BAR_CHARTS: Record = { +export const WHY_GMT_CHARTS: Record = { "ci-executions": { ariaLabel: "CI test execution volume comparison", idPrefix: "test-executions", @@ -570,7 +492,3 @@ export const BAR_CHARTS: Record = { definition: industryDefinition as unknown as BarChart["definition"], }, }; - -export function isBarChartId(value: string | undefined): value is BarChartId { - return value !== undefined && value in BAR_CHARTS; -} diff --git a/apps/dox/src/styles/gmt-charts.css b/apps/dox/src/styles/gmt-charts.css index 3155be060..d5bf4a1b5 100644 --- a/apps/dox/src/styles/gmt-charts.css +++ b/apps/dox/src/styles/gmt-charts.css @@ -93,6 +93,18 @@ stroke: var(--gmt-spring-ink); } +/* The /bundle-size hatched segment: the GMT code above a polyfill. Its edge is the hue's own token, + * which clears 3:1 against the chart surface in both themes (polyfill-tokens.test.ts). */ +.gmt-chart .ts-chart__bar-x rect[fill$="polyfill-shipped-hatch)"] { + stroke: var(--gmt-polyfill-shipped); + stroke-width: 1.5; +} + +.gmt-chart .ts-chart__bar-x rect[fill$="polyfill-previous-hatch)"] { + stroke: var(--gmt-polyfill-previous); + stroke-width: 1.5; +} + /* Cell tiles — locale matrix cards */ .gmt-chart .ts-chart__cell rect { stroke: var(--gmt-border-strong); @@ -149,10 +161,17 @@ @media (forced-colors: active) { /* The hatch may not survive system colours, so a shaded segment keeps a dashed edge. */ - .gmt-chart .ts-chart__bar-y rect[fill*="-hatch"] { + .gmt-chart .ts-chart__bar-y rect[fill*="-hatch"], + .gmt-chart .ts-chart__bar-x rect[fill*="-hatch"] { stroke-dasharray: 4 3; } + /* System colours drop the two hues, so the shipped polyfill's bars keep a heavier edge. */ + .gmt-chart .ts-chart__bar-x rect[fill$="polyfill-shipped)"] { + stroke: CanvasText; + stroke-width: 2; + } + .gmt-chart-toggle-button[aria-pressed="true"] { forced-color-adjust: none; background: Highlight; diff --git a/apps/dox/src/styles/gmt-tokens.css b/apps/dox/src/styles/gmt-tokens.css index ae2779f17..7b9620773 100644 --- a/apps/dox/src/styles/gmt-tokens.css +++ b/apps/dox/src/styles/gmt-tokens.css @@ -565,6 +565,13 @@ --gmt-series-4: var(--gmt-severity-high); --gmt-series-4-ink: var(--gmt-severity-high-ink); + /* Series pair for the polyfill comparison on /bundle-size: green is the shipped polyfill, a neutral + slate grey the previous one, so the old package recedes. Not --gmt-spring / --gmt-signal: light + spring is under 3:1 on the light glass, and amber is kept for NO SIGNAL. One value for both + themes; every chart surface measures ≥ 3:1. Marks only, never text. */ + --gmt-polyfill-shipped: #0f9a47; + --gmt-polyfill-previous: #64748b; + /* `--gmt-cyan` was the biggest of these: it is the site's link/accent colour, so every `color:` use of `--gmt-cyan` *and* `--gmt-cyan-bright` (the same problem — light-theme #0e7490 only reaches ~5:1) now reads diff --git a/apps/dox/src/widgets/builders/chart-key.module.css b/apps/dox/src/widgets/builders/chart-key.module.css index c8ac60f5d..1cb67a4d0 100644 --- a/apps/dox/src/widgets/builders/chart-key.module.css +++ b/apps/dox/src/widgets/builders/chart-key.module.css @@ -45,6 +45,38 @@ } } +/* The polyfill pair of /bundle-size: the same two fills in the hue of each package. The solid + swatch is the token at full strength; the hatched one keeps a full-strength border. */ +.swatch[data-hue^="polyfill-"] { + &[data-kind="own"] { + background-color: var(--gmt-swatch-hue); + } + + &[data-kind="shared"] { + border-color: var(--gmt-swatch-hue); + background-color: color-mix( + in srgb, + var(--gmt-swatch-hue) 12%, + transparent + ); + background-image: repeating-linear-gradient( + 45deg, + var(--gmt-swatch-hue) 0, + var(--gmt-swatch-hue) 2px, + transparent 2px, + transparent 5px + ); + } +} + +.swatch[data-hue="polyfill-shipped"] { + --gmt-swatch-hue: var(--gmt-polyfill-shipped); +} + +.swatch[data-hue="polyfill-previous"] { + --gmt-swatch-hue: var(--gmt-polyfill-previous); +} + /* Visually hidden, still read. */ .summary { position: absolute; @@ -59,7 +91,8 @@ } @media (forced-colors: active) { - .swatch { + .swatch, + .swatch[data-hue^="polyfill-"] { border-color: CanvasText; &[data-kind="own"] { @@ -67,6 +100,7 @@ } &[data-kind="shared"] { + border-color: CanvasText; background-color: Canvas; background-image: repeating-linear-gradient( 45deg, @@ -84,7 +118,8 @@ color: var(--gmt-ice); } - .swatch { + .swatch, + .swatch[data-hue^="polyfill-"][data-kind="shared"] { border-color: var(--gmt-ice); } } diff --git a/apps/dox/src/widgets/builders/chart-key.test.ts b/apps/dox/src/widgets/builders/chart-key.test.ts index dc8d468ec..8823d8f85 100644 --- a/apps/dox/src/widgets/builders/chart-key.test.ts +++ b/apps/dox/src/widgets/builders/chart-key.test.ts @@ -21,6 +21,42 @@ describe("chartKey", () => { await expectNoAxeViolations(host); }); + it("takes a hue for each item and still lists the words", async () => { + const { host } = renderHtml( + chartKey([ + { kind: "own", hue: "polyfill-shipped", words: "shipped polyfill" }, + { kind: "shared", hue: "polyfill-shipped", words: "shipped GMT code" }, + { kind: "own", hue: "polyfill-previous", words: "previous polyfill" }, + { + kind: "shared", + hue: "polyfill-previous", + words: "previous GMT code", + }, + ]), + ); + const key = screen.getByRole("list", { name: "Key" }); + expect( + within(key) + .getAllByRole("listitem") + .map((item) => item.textContent), + ).toEqual([ + "shipped polyfill", + "shipped GMT code", + "previous polyfill", + "previous GMT code", + ]); + await expectNoAxeViolations(host); + }); + + // The key sits inside page prose, whose lists draw a dash before each item; the swatch is the + // item's mark, so the key opts out the way Starlight's own widgets do: from an ancestor, since + // the prose rule skips only what sits inside a `.not-content` element. + it("opts out of the prose list styling, so no bullet sits beside a swatch", () => { + renderHtml(chartKey([{ kind: "own", words: "its own functions" }])); + const key = screen.getByRole("list", { name: "Key" }); + expect(key.parentElement).toHaveClass("not-content"); + }); + it("escapes the words", () => { renderHtml(chartKey([{ kind: "own", words: "x" }])); expect(screen.getByText("x")).toBeInTheDocument(); diff --git a/apps/dox/src/widgets/builders/chart-key.ts b/apps/dox/src/widgets/builders/chart-key.ts index 78f9a8007..499ede30d 100644 --- a/apps/dox/src/widgets/builders/chart-key.ts +++ b/apps/dox/src/widgets/builders/chart-key.ts @@ -11,17 +11,23 @@ import styles from "./chart-key.module.css"; export type ChartKeyKind = "own" | "shared"; +/** The series colour of a swatch: spring unless the chart names another. */ +export type ChartKeyHue = "spring" | "polyfill-shipped" | "polyfill-previous"; + export interface ChartKeyItem { kind: ChartKeyKind; + /** The series colour; `spring` when omitted. */ + hue?: ChartKeyHue; /** What the swatch stands for. Required. */ words: string; } export function chartKey(items: readonly ChartKeyItem[]): SafeHtml { - return html`
      ${items.map( + // Page prose draws a dash before each list item; Starlight's opt-out works only on an ancestor. + return html`
        ${items.map( (item) => - html`
      • ${item.words}
      • `, - )}
      `; + html`
    • ${item.words}
    • `, + )}
    `; } export function chartSummary(lines: readonly string[]): SafeHtml { diff --git a/apps/dox/vitest.config.ts b/apps/dox/vitest.config.ts index 367f1cffc..20e776b93 100644 --- a/apps/dox/vitest.config.ts +++ b/apps/dox/vitest.config.ts @@ -55,10 +55,11 @@ export default defineConfig({ setupFiles: ["./src/test/setup-dom.ts"], // Vitest's default is 5 s, which was never chosen for this suite. Several tests here are // import-bound rather than slow: they `await import()` a GMT namespace, which pulls in - // `@js-temporal/polyfill` and costs ~3.9 s in a fresh worker on an idle machine - // (`dst-inspector.test.ts`'s instant-format test, measured). `pnpm run validate` then runs - // this suite alongside `packages/gmt`'s 36k tests through `pnpm -r run test`, and on a shared - // CPU that 3.9 s crossed 5 s and failed the whole gate. 20 s leaves five times the measured + // `temporal-polyfill` and, measured on the library's previous polyfill, cost ~3.9 s in a fresh + // worker on an idle machine (`dst-inspector.test.ts`'s instant-format test). That figure is + // not re-measured on `temporal-polyfill`: the limit stays where it was. `pnpm run validate` + // then runs this suite alongside `packages/gmt`'s 36k tests through `pnpm -r run test`, and on + // a shared CPU a 3.9 s import crossed 5 s and failed the whole gate. 20 s leaves five times that // cost while still failing a test that has genuinely hung. testTimeout: 20_000, hookTimeout: 20_000, From caaff1ecb554aaaf8d3060e3f37520d92a2a31c4 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 6 Nov 2026 11:17:02 +0200 Subject: [PATCH 14/40] docs(dox): name temporal-polyfill in the guides (CORE-108, #460) - The guides and the mistakes pages name `temporal-polyfill` 1.0.8 where they named `@js-temporal/polyfill` 0.5.1. - The calendar-systems guide says GMT computes `ethiopic`, `ethioaa` and `coptic` each in its own calendar, and drops the section on runtime corrections that no longer exist. - The reference corpus is regenerated from the library's JSDoc. --- .../docs/guides/concepts/standards.mdx | 2 +- .../core-date-operations/calendar-systems.mdx | 14 +-- .../core-date-operations/get-current.mdx | 6 +- .../dox/src/content/docs/migrate/temporal.mdx | 4 +- .../docs/mistakes/format-date-time.mdx | 2 +- .../content/docs/mistakes/parse-date-time.mdx | 4 +- .../src/generated/reference/gmt-corpus.json | 86 +++++++++---------- 7 files changed, 55 insertions(+), 63 deletions(-) diff --git a/apps/dox/src/content/docs/guides/concepts/standards.mdx b/apps/dox/src/content/docs/guides/concepts/standards.mdx index 1f2b3e3b1..9a78a1cd6 100644 --- a/apps/dox/src/content/docs/guides/concepts/standards.mdx +++ b/apps/dox/src/content/docs/guides/concepts/standards.mdx @@ -28,7 +28,7 @@ maintains two specifications: replace `Date`. It has separate types for plain and zoned values, explicit time zones and calendars, and instants counted in nanoseconds. -**GMT** is built on Temporal (through `@js-temporal/polyfill`) and follows its specification for +**GMT** is built on Temporal (through `temporal-polyfill`) and follows its specification for every type and every piece of arithmetic. No `Date` object appears anywhere, and three dedicated lint packages enforce that. Where the polyfill disagrees with the specification, GMT returns the specified answer and reports the difference upstream; see diff --git a/apps/dox/src/content/docs/guides/core-date-operations/calendar-systems.mdx b/apps/dox/src/content/docs/guides/core-date-operations/calendar-systems.mdx index 69fb6ae1e..e2af63f45 100644 --- a/apps/dox/src/content/docs/guides/core-date-operations/calendar-systems.mdx +++ b/apps/dox/src/content/docs/guides/core-date-operations/calendar-systems.mdx @@ -105,20 +105,10 @@ addDate("2020-02-24[u-ca=islamic-umalqura]", { months: 1 }); // "2020-03-24[u-ca addDate("2020-02-24[u-ca=islamic-tbla]", { months: 1 }); // "2020-03-25[u-ca=islamic-tbla]" ``` -## The Ethiopic family computes in `ethioaa` +## The Ethiopic family `ethiopic`, `ethioaa` and `coptic` share months, days and arithmetic, and differ only by a -constant year offset. `@js-temporal/polyfill` cannot read `ethiopic` and `coptic` fields under -ICU 78 or later (`Temporal.PlainDate.from("2024-10-03[u-ca=ethiopic]").year` throws there), -so GMT computes all three in `ethioaa` and writes the id you asked for. GMT's results are -the same either way, and only the written id differs. - -## Where the runtime computes a calendar wrongly - -Where the polyfill or the runtime's ICU computes a calendar wrongly (Buddhist before 1582, -Hebrew years ≤ 0, Indian dates before ISO year 1, dates near either range limit), GMT's -arithmetic computes the specified answer instead. Each correction probes the runtime once -and stays inactive where the runtime is already right. +constant year offset. GMT computes each one in the calendar you name. ## Calendar-aware arithmetic diff --git a/apps/dox/src/content/docs/guides/core-date-operations/get-current.mdx b/apps/dox/src/content/docs/guides/core-date-operations/get-current.mdx index 045e492f3..c517dfb01 100644 --- a/apps/dox/src/content/docs/guides/core-date-operations/get-current.mdx +++ b/apps/dox/src/content/docs/guides/core-date-operations/get-current.mdx @@ -97,7 +97,7 @@ When you need the current value as a Temporal object for further manipulation (rather than a string), use `Temporal.Now` directly: ```typescript -import { Temporal } from "@js-temporal/polyfill"; +import { Temporal } from "@northguild/gmt"; Temporal.Now.instant(); // Temporal.Instant — absolute point in time Temporal.Now.plainDateISO(); // Temporal.PlainDate — system timezone @@ -105,8 +105,8 @@ Temporal.Now.plainDateTimeISO(); // Temporal.PlainDateTime — system timezone Temporal.Now.zonedDateTimeISO("Australia/Sydney"); // Temporal.ZonedDateTime ``` -GMT re-exports `Temporal` from `@northguild/gmt` if you don't want to depend on the -polyfill directly. +These are the same `Temporal` objects GMT's functions read, so you can pass a value +between them and a GMT function. ## See also diff --git a/apps/dox/src/content/docs/migrate/temporal.mdx b/apps/dox/src/content/docs/migrate/temporal.mdx index 432be46f6..f39390ddf 100644 --- a/apps/dox/src/content/docs/migrate/temporal.mdx +++ b/apps/dox/src/content/docs/migrate/temporal.mdx @@ -3,7 +3,9 @@ title: Native Temporal and GMT description: Which runtimes ship Temporal, how the proposal stands in ECMA-262, and the GMT function for each Temporal call. --- -GMT is built on `@js-temporal/polyfill`, so it runs on a runtime that has no native Temporal. This page lists where Temporal is native and which GMT function matches each Temporal call. +import { polyfillFigures } from "~/lib/bundle-size-figures"; + +GMT is built on a Temporal polyfill, `temporal-polyfill` in {polyfillFigures.firstShippedGmt} and later and `@js-temporal/polyfill` up to {polyfillFigures.previousGmt}, so it runs on a runtime that has no native Temporal. This page lists where Temporal is native and which GMT function matches each Temporal call. ## Where Temporal runs diff --git a/apps/dox/src/content/docs/mistakes/format-date-time.mdx b/apps/dox/src/content/docs/mistakes/format-date-time.mdx index 984850dcd..2b423d0b7 100644 --- a/apps/dox/src/content/docs/mistakes/format-date-time.mdx +++ b/apps/dox/src/content/docs/mistakes/format-date-time.mdx @@ -96,7 +96,7 @@ formatMonthDay("--12-25", "en-US"); // "12/25"`} >): string", + "signature": "durationFromUnits(units: Partial>): string", "description": "Write an amount given as a unit object, such as `{ minutes: 15 }`, as an ISO 8601 duration string.", "sourcePath": "packages/gmt/src/duration/calculate/durationFromUnits.ts", "examples": [ @@ -1429,7 +1429,7 @@ "namespace": "duration", "module": "calculate", "kind": "function", - "signature": "getDurationUnit(value: string, unit: keyof DurationLike | DateTimeUnit): number | null", + "signature": "getDurationUnit(value: string, unit: keyof DurationLikeObject | DateTimeUnit): number | null", "description": "Read a single component out of an ISO 8601 duration string.", "sourcePath": "packages/gmt/src/duration/calculate/getDurationUnit.ts", "examples": [ @@ -1540,7 +1540,7 @@ "namespace": "duration", "module": "calculate", "kind": "function", - "signature": "totalDuration(value: string, unit: keyof DurationLike | DateTimeUnit, options?: { relativeTo?: DurationRelativeTo; }): number | null", + "signature": "totalDuration(value: string, unit: keyof DurationLikeObject | DateTimeUnit, options?: { relativeTo?: DurationRelativeTo; }): number | null", "description": "Express an ISO 8601 duration as a single fractional total in one unit.", "sourcePath": "packages/gmt/src/duration/calculate/totalDuration.ts", "examples": [ @@ -1682,7 +1682,7 @@ "namespace": "duration", "module": "calculate", "kind": "function", - "signature": "totalUnitsFromNow(units: Partial>, unit: keyof DurationLike | DateTimeUnit, options?: { timeZone?: string; }): number | null", + "signature": "totalUnitsFromNow(units: Partial>, unit: keyof DurationLikeObject | DateTimeUnit, options?: { timeZone?: string; }): number | null", "description": "Express a length of time from now as one fractional total in one unit.", "sourcePath": "packages/gmt/src/duration/calculate/totalUnitsFromNow.ts", "examples": [ @@ -1754,7 +1754,7 @@ "namespace": "duration", "module": "calculate", "kind": "function", - "signature": "ttlFromNow(units: Partial>): Ttl | null", + "signature": "ttlFromNow(units: Partial>): Ttl | null", "description": "Express one length of time from now in every form a receiver wants: seconds, milliseconds, a Unix epoch, an HTTP date and a UTC string.", "sourcePath": "packages/gmt/src/duration/calculate/ttlFromNow.ts", "examples": [ @@ -2046,7 +2046,7 @@ "namespace": "duration", "module": "parse", "kind": "function", - "signature": "parseDuration(value: string, options?: { smallestUnit?: SmallestUnit<\"minute\" | \"second\" | \"millisecond\" | \"microsecond\" | \"nanosecond\"> | undefined; fractionalSecondDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | \"auto\" | 8 | 9 | undefined; roundingMode?: RoundingMode | undefined; }): string", + "signature": "parseDuration(value: string, options?: { smallestUnit?: PluralizeUnit<\"second\" | \"millisecond\" | \"microsecond\" | \"nanosecond\"> | undefined; fractionalSecondDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | \"auto\" | 8 | 9 | undefined; roundingMode?: \"ceil\" | \"floor\" | \"expand\" | \"trunc\" | \"halfCeil\" | \"halfFloor\" | \"halfExpand\" | \"halfTrunc\" | \"halfEven\" | undefined; }): string", "description": "Parse and re-normalize an ISO 8601 duration string.", "sourcePath": "packages/gmt/src/duration/parse/parseDuration.ts", "examples": [ @@ -6047,7 +6047,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "addDateTime(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "addDateTime(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Return a PlainDateTime ISO string with `units` added to `value`.", "sourcePath": "packages/gmt/src/plain/calculate/addDateTime.ts", "examples": [ @@ -6405,7 +6405,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "diffDateTime(dateTime1: string, dateTime2: string, units: keyof DurationLike | DateTimeUnit | (keyof DurationLike | DateTimeUnit)[], options?: RoundingOptions): number | Record | null", + "signature": "diffDateTime(dateTime1: string, dateTime2: string, units: keyof DurationLikeObject | DateTimeUnit | (keyof DurationLikeObject | DateTimeUnit)[], options?: RoundingOptions): number | Record | null", "description": "Return the difference between two PlainDateTime values in the requested unit.", "sourcePath": "packages/gmt/src/plain/calculate/diffDateTime.ts", "examples": [ @@ -6430,7 +6430,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "diffDateTimeAsDuration(dateTime1: string, dateTime2: string, unit: keyof DurationLike | DateTimeUnit, options?: (RoundingOptions & DurationStringOptions)): string", + "signature": "diffDateTimeAsDuration(dateTime1: string, dateTime2: string, unit: keyof DurationLikeObject | DateTimeUnit, options?: (RoundingOptions & DurationStringOptions)): string", "description": "Return the difference between two PlainDateTime values as an ISO 8601 duration string, bridging to the `duration` namespace (see `parseDuration`, `normalizeDuration`).", "sourcePath": "packages/gmt/src/plain/calculate/diffDateTimeAsDuration.ts", "examples": [ @@ -6889,7 +6889,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "getLargestDateTimeDurationUnit(units: (keyof DurationLike | DateTimeUnit)[]): keyof DurationLike | \"\"", + "signature": "getLargestDateTimeDurationUnit(units: (keyof DurationLikeObject | DateTimeUnit)[]): \"\" | keyof DurationLikeObject", "description": "Return the largest DateTimeDurationUnit from the provided array.", "sourcePath": "packages/gmt/src/plain/calculate/getLargestDateTimeDurationUnit.ts", "examples": [ @@ -7758,7 +7758,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "setDate(value: string, fields: Omit, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "setDate(value: string, fields: PlainDateFields, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Return a PlainDate ISO string with the given `fields` set on `value`.", "sourcePath": "packages/gmt/src/plain/calculate/setDate.ts", "examples": [ @@ -7811,7 +7811,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "setDateTime(value: string, fields: Omit, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "setDateTime(value: string, fields: PlainDateTimeFields, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Return a PlainDateTime ISO string with the given `fields` set on `value`.", "sourcePath": "packages/gmt/src/plain/calculate/setDateTime.ts", "examples": [ @@ -7848,7 +7848,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "setTime(value: string, fields: PlainTimeLike, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "setTime(value: string, fields: PlainTimeFields, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Return a PlainTime ISO string with the given `fields` set on `value`.", "sourcePath": "packages/gmt/src/plain/calculate/setTime.ts", "examples": [ @@ -8213,7 +8213,7 @@ "namespace": "plain", "module": "calculate", "kind": "function", - "signature": "subtractDateTime(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "subtractDateTime(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Return a PlainDateTime ISO string with `units` subtracted from `value`.", "sourcePath": "packages/gmt/src/plain/calculate/subtractDateTime.ts", "examples": [ @@ -10108,7 +10108,7 @@ "namespace": "plain", "module": "get", "kind": "function", - "signature": "getDateTimeAgo(units: Partial>): string", + "signature": "getDateTimeAgo(units: Partial>): string", "description": "Return the PlainDateTime before now, as an ISO string, counted from the current time.", "sourcePath": "packages/gmt/src/plain/get/getDateTimeAgo.ts", "examples": [ @@ -10137,7 +10137,7 @@ "namespace": "plain", "module": "get", "kind": "function", - "signature": "getDateTimeIn(units: Partial>): string", + "signature": "getDateTimeIn(units: Partial>): string", "description": "Return the PlainDateTime after now, as an ISO string, counted from the current time.", "sourcePath": "packages/gmt/src/plain/get/getDateTimeIn.ts", "examples": [ @@ -14186,7 +14186,7 @@ "namespace": "plain", "module": "validate", "kind": "function", - "signature": "isValidDateTimeDurationUnit(unit: unknown): unit is keyof DurationLike", + "signature": "isValidDateTimeDurationUnit(unit: unknown): unit is keyof DurationLikeObject", "description": "Return true when `unit` is a valid DateTimeDurationUnit.", "sourcePath": "packages/gmt/src/plain/validate/isValidDateTimeDurationUnit.ts", "examples": [ @@ -22089,7 +22089,7 @@ "namespace": "unix", "module": "calculate", "kind": "function", - "signature": "addUnix(value: string | number, units: Partial>, options?: { epochUnit?: UnixUnit; timeZone?: string; overflow?: \"reject\" | \"constrain\" | undefined; }): number | null", + "signature": "addUnix(value: string | number, units: Partial>, options?: { epochUnit?: UnixUnit; timeZone?: string; overflow?: \"reject\" | \"constrain\" | undefined; }): number | null", "description": "Add a temporal amount to a Unix epoch value and return the resulting epoch.", "sourcePath": "packages/gmt/src/unix/calculate/addUnix.ts", "examples": [ @@ -22130,7 +22130,7 @@ "namespace": "unix", "module": "calculate", "kind": "function", - "signature": "diffUnix(value1: string | number, value2: string | number, units: keyof DurationLike | DateTimeUnit | (keyof DurationLike | DateTimeUnit)[], options?: ({ epochUnit?: UnixUnit; timeZone?: string; } & RoundingOptions)): number | Record | null", + "signature": "diffUnix(value1: string | number, value2: string | number, units: keyof DurationLikeObject | DateTimeUnit | (keyof DurationLikeObject | DateTimeUnit)[], options?: ({ epochUnit?: UnixUnit; timeZone?: string; } & RoundingOptions)): number | Record | null", "description": "Return the difference between two Unix timestamps measured in the given unit.", "sourcePath": "packages/gmt/src/unix/calculate/diffUnix.ts", "examples": [ @@ -22167,7 +22167,7 @@ "namespace": "unix", "module": "calculate", "kind": "function", - "signature": "diffUnixAsDuration(value1: string | number, value2: string | number, unit: keyof DurationLike | DateTimeUnit, options?: ({ epochUnit?: UnixUnit; timeZone?: string; } & RoundingOptions & DurationStringOptions)): string", + "signature": "diffUnixAsDuration(value1: string | number, value2: string | number, unit: keyof DurationLikeObject | DateTimeUnit, options?: ({ epochUnit?: UnixUnit; timeZone?: string; } & RoundingOptions & DurationStringOptions)): string", "description": "Return the difference between two Unix timestamps as an ISO 8601 duration string, bridging to the `duration` namespace (see `parseDuration`, `normalizeDuration`).", "sourcePath": "packages/gmt/src/unix/calculate/diffUnixAsDuration.ts", "examples": [ @@ -22451,7 +22451,7 @@ "namespace": "unix", "module": "calculate", "kind": "function", - "signature": "setUnix(value: string | number, fields: Omit, options?: { epochUnit?: UnixUnit; timeZone?: string; overflow?: \"reject\" | \"constrain\" | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; offset?: \"reject\" | \"use\" | \"prefer\" | \"ignore\" | undefined; }): number | null", + "signature": "setUnix(value: string | number, fields: ZonedDateTimeFields, options?: { epochUnit?: UnixUnit; timeZone?: string; overflow?: \"reject\" | \"constrain\" | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; offset?: \"reject\" | \"use\" | \"ignore\" | \"prefer\" | undefined; }): number | null", "description": "Return a Unix epoch value with the given `fields` set on `value`, interpreted in `timeZone`.", "sourcePath": "packages/gmt/src/unix/calculate/setUnix.ts", "examples": [ @@ -22607,7 +22607,7 @@ "namespace": "unix", "module": "calculate", "kind": "function", - "signature": "subtractUnix(value: string | number, units: Partial>, options?: { epochUnit?: UnixUnit; timeZone?: string; overflow?: \"reject\" | \"constrain\" | undefined; }): number | null", + "signature": "subtractUnix(value: string | number, units: Partial>, options?: { epochUnit?: UnixUnit; timeZone?: string; overflow?: \"reject\" | \"constrain\" | undefined; }): number | null", "description": "Subtract a temporal amount from a Unix epoch value and return the resulting epoch.", "sourcePath": "packages/gmt/src/unix/calculate/subtractUnix.ts", "examples": [ @@ -23237,7 +23237,7 @@ "namespace": "unix", "module": "get", "kind": "function", - "signature": "getUnixAgo(units: Partial>, options?: { epochUnit?: UnixUnit; }): number | null", + "signature": "getUnixAgo(units: Partial>, options?: { epochUnit?: UnixUnit; }): number | null", "description": "Return the Unix epoch before now, counted from the current time in UTC.", "sourcePath": "packages/gmt/src/unix/get/getUnixAgo.ts", "examples": [ @@ -23304,7 +23304,7 @@ "namespace": "unix", "module": "get", "kind": "function", - "signature": "getUnixIn(units: Partial>, options?: { epochUnit?: UnixUnit; }): number | null", + "signature": "getUnixIn(units: Partial>, options?: { epochUnit?: UnixUnit; }): number | null", "description": "Return the Unix epoch after now, counted from the current time in UTC.", "sourcePath": "packages/gmt/src/unix/get/getUnixIn.ts", "examples": [ @@ -23451,7 +23451,7 @@ "namespace": "unix", "module": "get", "kind": "function", - "signature": "getUnixNowUnit(unit: PluralUnit | UnixNowUnit): string", + "signature": "getUnixNowUnit(unit: UnixNowUnit | PluralUnit): string", "description": "Return the requested unit value from the current Unix timestamp in UTC.", "sourcePath": "packages/gmt/src/unix/get/getUnixNowUnit.ts", "examples": [ @@ -24799,7 +24799,7 @@ "namespace": "utc", "module": "calculate", "kind": "function", - "signature": "addUtc(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "addUtc(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Add a temporal amount to a UTC datetime string and return a new UTC Instant string.", "sourcePath": "packages/gmt/src/utc/calculate/addUtc.ts", "examples": [ @@ -24824,7 +24824,7 @@ "namespace": "utc", "module": "calculate", "kind": "function", - "signature": "diffUtc(value1: string, value2: string, units: keyof DurationLike | DateTimeUnit | (keyof DurationLike | DateTimeUnit)[], options?: RoundingOptions): number | Record | null", + "signature": "diffUtc(value1: string, value2: string, units: keyof DurationLikeObject | DateTimeUnit | (keyof DurationLikeObject | DateTimeUnit)[], options?: RoundingOptions): number | Record | null", "description": "Return the difference between two UTC datetimes measured in the given date-time unit.", "sourcePath": "packages/gmt/src/utc/calculate/diffUtc.ts", "examples": [ @@ -24853,7 +24853,7 @@ "namespace": "utc", "module": "calculate", "kind": "function", - "signature": "diffUtcAsDuration(value1: string, value2: string, unit: keyof DurationLike | DateTimeUnit, options?: (RoundingOptions & DurationStringOptions)): string", + "signature": "diffUtcAsDuration(value1: string, value2: string, unit: keyof DurationLikeObject | DateTimeUnit, options?: (RoundingOptions & DurationStringOptions)): string", "description": "Return the difference between two UTC datetimes as an ISO 8601 duration string, bridging to the `duration` namespace (see `parseDuration`, `normalizeDuration`).", "sourcePath": "packages/gmt/src/utc/calculate/diffUtcAsDuration.ts", "examples": [ @@ -25130,7 +25130,7 @@ "namespace": "utc", "module": "calculate", "kind": "function", - "signature": "setUtc(value: string, fields: Omit, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "setUtc(value: string, fields: ZonedDateTimeFields, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Return a UTC Instant string with the given `fields` set on `value`.", "sourcePath": "packages/gmt/src/utc/calculate/setUtc.ts", "examples": [ @@ -25250,7 +25250,7 @@ "namespace": "utc", "module": "calculate", "kind": "function", - "signature": "subtractUtc(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "subtractUtc(value: string, units: Partial>, options?: { overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Subtract a temporal amount from a UTC datetime string and return a new UTC Instant string.", "sourcePath": "packages/gmt/src/utc/calculate/subtractUtc.ts", "examples": [ @@ -25658,7 +25658,7 @@ "namespace": "utc", "module": "format", "kind": "function", - "signature": "formatHttpDateFromNow(units: Partial>): string", + "signature": "formatHttpDateFromNow(units: Partial>): string", "description": "Return the RFC 9110 HTTP date (IMF-fixdate) after now, counted from the current time. It is the value for an `Expires` attribute or header.", "sourcePath": "packages/gmt/src/utc/format/formatHttpDateFromNow.ts", "examples": [ @@ -25851,7 +25851,7 @@ "namespace": "utc", "module": "get", "kind": "function", - "signature": "getUtcAgo(units: Partial>): string", + "signature": "getUtcAgo(units: Partial>): string", "description": "Return the UTC instant before now, as an ISO Instant string, counted from the current time.", "sourcePath": "packages/gmt/src/utc/get/getUtcAgo.ts", "examples": [ @@ -25914,7 +25914,7 @@ "namespace": "utc", "module": "get", "kind": "function", - "signature": "getUtcIn(units: Partial>): string", + "signature": "getUtcIn(units: Partial>): string", "description": "Return the UTC instant after now, as an ISO Instant string, counted from the current time.", "sourcePath": "packages/gmt/src/utc/get/getUtcIn.ts", "examples": [ @@ -27566,7 +27566,7 @@ "namespace": "zoned", "module": "calculate", "kind": "function", - "signature": "addZoned(value: string, units: Partial>, optionsArg?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "addZoned(value: string, units: Partial>, optionsArg?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Add a temporal amount to a zoned ISO 8601 datetime string and return a zoned ISO 8601 string.", "sourcePath": "packages/gmt/src/zoned/calculate/addZoned.ts", "examples": [ @@ -27726,7 +27726,7 @@ "namespace": "zoned", "module": "calculate", "kind": "function", - "signature": "cycleZoned(value: string, field: DateTimeCycleField, amount: number, options?: { round?: boolean; overflow?: \"reject\" | \"constrain\" | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; offset?: \"reject\" | \"use\" | \"prefer\" | \"ignore\" | undefined; }): string", + "signature": "cycleZoned(value: string, field: DateTimeCycleField, amount: number, options?: { round?: boolean; overflow?: \"reject\" | \"constrain\" | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; offset?: \"reject\" | \"use\" | \"ignore\" | \"prefer\" | undefined; }): string", "description": "Return a ZonedDateTime ISO string with `field` cycled by `amount`, wrapping at that field's own min/max instead of carrying into the next larger field.", "sourcePath": "packages/gmt/src/zoned/calculate/cycleZoned.ts", "examples": [ @@ -27771,7 +27771,7 @@ "namespace": "zoned", "module": "calculate", "kind": "function", - "signature": "diffZoned(value1: string, value2: string, units: keyof DurationLike | DateTimeUnit | (keyof DurationLike | DateTimeUnit)[], options?: RoundingOptions): number | Record | null", + "signature": "diffZoned(value1: string, value2: string, units: keyof DurationLikeObject | DateTimeUnit | (keyof DurationLikeObject | DateTimeUnit)[], options?: RoundingOptions): number | Record | null", "description": "Return the difference between two zoned datetimes measured in the given date-time unit.", "sourcePath": "packages/gmt/src/zoned/calculate/diffZoned.ts", "examples": [ @@ -27828,7 +27828,7 @@ "namespace": "zoned", "module": "calculate", "kind": "function", - "signature": "diffZonedAsDuration(value1: string, value2: string, unit: keyof DurationLike | DateTimeUnit, options?: (RoundingOptions & DurationStringOptions)): string", + "signature": "diffZonedAsDuration(value1: string, value2: string, unit: keyof DurationLikeObject | DateTimeUnit, options?: (RoundingOptions & DurationStringOptions)): string", "description": "Return the difference between two zoned datetimes as an ISO 8601 duration string, bridging to the `duration` namespace (see `parseDuration`, `normalizeDuration`).", "sourcePath": "packages/gmt/src/zoned/calculate/diffZonedAsDuration.ts", "examples": [ @@ -28219,7 +28219,7 @@ "namespace": "zoned", "module": "calculate", "kind": "function", - "signature": "setZoned(value: string, fields: Omit, options?: { overflow?: \"reject\" | \"constrain\" | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; offset?: \"reject\" | \"use\" | \"prefer\" | \"ignore\" | undefined; }): string", + "signature": "setZoned(value: string, fields: ZonedDateTimeFields, options?: { overflow?: \"reject\" | \"constrain\" | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; offset?: \"reject\" | \"use\" | \"ignore\" | \"prefer\" | undefined; }): string", "description": "Return a zoned ISO 8601 datetime string with the given `fields` set on `value`.", "sourcePath": "packages/gmt/src/zoned/calculate/setZoned.ts", "examples": [ @@ -28363,7 +28363,7 @@ "namespace": "zoned", "module": "calculate", "kind": "function", - "signature": "subtractZoned(value: string, units: Partial>, optionsArg?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; overflow?: \"reject\" | \"constrain\" | undefined; }): string", + "signature": "subtractZoned(value: string, units: Partial>, optionsArg?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; overflow?: \"reject\" | \"constrain\" | undefined; }): string", "description": "Subtract a temporal amount from a zoned ISO 8601 datetime string and return a zoned ISO 8601 string.", "sourcePath": "packages/gmt/src/zoned/calculate/subtractZoned.ts", "examples": [ @@ -28984,7 +28984,7 @@ "namespace": "zoned", "module": "convert", "kind": "function", - "signature": "convertPlainDateTimeToZoned(value: string, timeZone: string, optionsArg?: { smallestUnit?: SmallestUnit<\"minute\" | \"second\" | \"millisecond\" | \"microsecond\" | \"nanosecond\"> | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; }): string", + "signature": "convertPlainDateTimeToZoned(value: string, timeZone: string, optionsArg?: { smallestUnit?: PluralizeUnit<\"minute\" | \"second\" | \"millisecond\" | \"microsecond\" | \"nanosecond\"> | undefined; disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" | undefined; }): string", "description": "Attach the specified `timeZone` to a plain datetime string and return a zoned ISO 8601 datetime string.", "sourcePath": "packages/gmt/src/zoned/convert/convertPlainDateTimeToZoned.ts", "examples": [ @@ -29755,7 +29755,7 @@ "namespace": "zoned", "module": "get", "kind": "function", - "signature": "getZonedAgo(timeZone: string, units: Partial>): string", + "signature": "getZonedAgo(timeZone: string, units: Partial>): string", "description": "Return the zoned datetime before now in `timeZone`, counted from the current time.", "sourcePath": "packages/gmt/src/zoned/get/getZonedAgo.ts", "examples": [ @@ -29847,7 +29847,7 @@ "namespace": "zoned", "module": "get", "kind": "function", - "signature": "getZonedIn(timeZone: string, units: Partial>): string", + "signature": "getZonedIn(timeZone: string, units: Partial>): string", "description": "Return the zoned datetime after now in `timeZone`, counted from the current time.", "sourcePath": "packages/gmt/src/zoned/get/getZonedIn.ts", "examples": [ @@ -29981,7 +29981,7 @@ "namespace": "zoned", "module": "get", "kind": "function", - "signature": "getZonedNow(ianaTimezone: string, optionsArg?: { smallestUnit?: SmallestUnit<\"minute\" | \"second\" | \"millisecond\" | \"microsecond\" | \"nanosecond\"> | undefined; }): string", + "signature": "getZonedNow(ianaTimezone: string, optionsArg?: { smallestUnit?: PluralizeUnit<\"minute\" | \"second\" | \"millisecond\" | \"microsecond\" | \"nanosecond\"> | undefined; }): string", "description": "Return the current zoned datetime for the specified IANA timeZone.", "sourcePath": "packages/gmt/src/zoned/get/getZonedNow.ts", "examples": [ From c6a28e482d9279685257d5819ef8e886ebeba46d Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 6 Nov 2026 11:17:20 +0200 Subject: [PATCH 15/40] docs(context): GMT runs on temporal-polyfill (CORE-108, #460) - AGENTS.md, the coding standards, the overviews and the audits name `temporal-polyfill` 1.0.8 and the one import seam. - The story file, the tracker row and the CORE-108 specs, which are folded into the story file when it closes. - A first draft of the changeset (minor). --- .changeset/move-onto-temporal-polyfill.md | 8 + AGENTS.md | 2 +- context/coding-standards.md | 11 +- context/domination/issues/CORE-102.md | 13 +- .../issues/CORE-102/design-notes.md | 4 +- context/domination/issues/CORE-103.md | 14 +- context/domination/issues/CORE-105.md | 2 +- context/domination/issues/CORE-108.md | 62 ++++++ context/domination/issues/CORE-8.md | 2 +- context/domination/issues/CORE-80.md | 4 +- context/domination/issues/CORE-84.md | 2 +- context/domination/issues/index.md | 7 +- .../domination/js-temporal-polyfill-bugs.md | 2 + context/domination/overview.md | 4 +- context/domination/research/index.md | 4 +- .../research/range-edge-correctness-audit.md | 2 + .../research/temporal-polyfill-swap.md | 2 + .../domination/specs/CORE-108/bundle-size.md | 113 +++++++++++ .../specs/CORE-108/docs-readmes-changeset.md | 90 +++++++++ context/domination/specs/CORE-108/index.md | 133 +++++++++++++ context/domination/specs/CORE-108/lint.md | 47 +++++ .../domination/specs/CORE-108/range-check.md | 132 +++++++++++++ .../specs/CORE-108/seam-and-types.md | 112 +++++++++++ .../specs/CORE-108/upgrade-check.md | 91 +++++++++ .../domination/specs/CORE-108/workarounds.md | 108 +++++++++++ context/domination/tracker.md | 95 +++++----- context/dox/built.md | 20 +- context/dox/reference/design-system.md | 15 ++ context/dox/specs/core-108/charts.md | 179 ++++++++++++++++++ context/dox/specs/core-108/figures.md | 113 +++++++++++ context/dox/specs/core-108/index.md | 120 ++++++++++++ context/dox/specs/core-108/page.md | 155 +++++++++++++++ context/perf-and-bundle-size-audit.md | 12 +- .../agent-changes-and-decisions.md | 2 +- .../perf-and-bundle-size-audit/bundle-size.md | 54 +++--- .../loop-performance.md | 6 +- context/project-overview.md | 8 +- context/testing-standards/references/index.md | 4 +- 38 files changed, 1626 insertions(+), 128 deletions(-) create mode 100644 .changeset/move-onto-temporal-polyfill.md create mode 100644 context/domination/issues/CORE-108.md create mode 100644 context/domination/specs/CORE-108/bundle-size.md create mode 100644 context/domination/specs/CORE-108/docs-readmes-changeset.md create mode 100644 context/domination/specs/CORE-108/index.md create mode 100644 context/domination/specs/CORE-108/lint.md create mode 100644 context/domination/specs/CORE-108/range-check.md create mode 100644 context/domination/specs/CORE-108/seam-and-types.md create mode 100644 context/domination/specs/CORE-108/upgrade-check.md create mode 100644 context/domination/specs/CORE-108/workarounds.md create mode 100644 context/dox/specs/core-108/charts.md create mode 100644 context/dox/specs/core-108/figures.md create mode 100644 context/dox/specs/core-108/index.md create mode 100644 context/dox/specs/core-108/page.md diff --git a/.changeset/move-onto-temporal-polyfill.md b/.changeset/move-onto-temporal-polyfill.md new file mode 100644 index 000000000..eb51bd744 --- /dev/null +++ b/.changeset/move-onto-temporal-polyfill.md @@ -0,0 +1,8 @@ +--- +"@northguild/gmt": minor +--- + +GMT runs on `temporal-polyfill` in place of `@js-temporal/polyfill`. Every import is smaller, month arithmetic takes bounded time for any amount, and `Temporal`, `Intl` and `toTemporalInstant` are re-exported from `temporal-polyfill`. + +- `compareDurations` returns `0` for two equal durations; it returned `null`. +- The `smallestUnit` of `parseDuration` and `toStringSmallestUnit` of `DurationStringOptions` no longer accept `"minute"` or `"minutes"` at the type level, as the Temporal specification has it. What they do at run time is unchanged. diff --git a/AGENTS.md b/AGENTS.md index 151941dd7..3aa009c78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,7 @@ ask in plain words. These are the non-negotiables. Full detail is in the context files above. -1. **No `Date` object.** Use `@js-temporal/polyfill` exclusively, imported only through `packages/gmt/src/internal/temporal.ts`. +1. **No `Date` object.** Use `temporal-polyfill` exclusively (`/full/implementation`), imported only through `packages/gmt/src/internal/temporal.ts`. 2. **String-in, string-out.** Public APIs accept ISO 8601 strings; return strings, numbers, booleans, arrays, `bigint`, or plain objects — never Temporal objects. 3. **Invalid input returns a sentinel, never throws.** `""` for strings, `null` for numbers and objects, `false` for booleans, `[]` for arrays — the full table (bigint, span, exceptions) is [coding-standards § API Contract](./context/coding-standards.md#api-contract). 4. **Wrap all Temporal calls in `try-catch`.** `.from()`, `.add()`, `.since()`, etc. throw `RangeError` on bad input. One exception: a zero-argument reader that calls only `Temporal.Now.instant()`, then reads a field through an explicit `"UTC"` conversion or calls `.toString()` with no options, cannot fail, so it has no catch and no sentinel. The exception does not cover a read of the system time zone — see [coding-standards § Scoped exception: the UTC clock readers](./context/coding-standards.md#scoped-exception-the-utc-clock-readers). diff --git a/context/coding-standards.md b/context/coding-standards.md index 207d92894..30d4bcaee 100644 --- a/context/coding-standards.md +++ b/context/coding-standards.md @@ -218,10 +218,6 @@ which records the native Temporal evidence for each rule below. - **No converter from the pre-1.16.0 calendar-native-digit strings.** No standard defines them, and most are also valid RFC 9557 strings, so the two readings cannot be told apart. Do not add heuristic detection; a stored old string is regenerated from its ISO date. -- **`ethiopic` and `coptic` compute in `ethioaa`** (`computationCalendarId`): polyfill 0.5.1 cannot - read their fields under ICU ≥ 78, and the three share months, days and arithmetic, differing by a - constant year. A parsed value therefore carries `ethioaa`; code that writes a string back takes the - calendar from `calendarSystemOfDateValue` / `calendarSystemOfZonedValue`, never from `calendarId`. - **Where it is accepted.** `plain/`: `isValidCalendarDate` and the functions gated on it (`convertDateToCalendar`, `addDate`, `subtractDate`, `diffDate`, `diffDateAsDuration`, the `Date`-suffixed `plain/interval/*`), plus `duration/`'s `relativeTo` (`internal/resolveDurationRelativeTo.ts`, @@ -260,7 +256,7 @@ Avoid `while` loops in new code. Prefer `for` loops or array methods (`map`, `fi - **Formula first.** Before stepping day by day, use epoch-day arithmetic (`epochDayOf`, `isoFieldsOf`, `isoWeekdayOf` in `internal/epochDay.ts`), whole-week jumps, and binary search over sorted arrays (`lowerBound`, `countWithin`). Walk only the remainder, at most a week, and only the dates near a zone transition. - **Temporal at the edges.** Parse inputs once on the way in; format once on the way out. Build or parse no Temporal object per loop step or inside a sort comparator. - **Resolve once.** Validate and resolve a calendar, schedule, zone or rule set once per public call, and pass it in resolved form to an `internal/` core. A public function never calls another public function; both call the core. -- **Remember only what is pure.** A module-level memo holds only facts that are a pure function of their key for the life of the process (zone transitions, parsed holiday strings, validated zone ids, `Intl` formatters built from explicit arguments). It is bounded and cleared on overflow, stores no answer that depends on the clock, on process defaults or on a global the caller can replace (the formatter cache drops a kind once `Intl[kind]` is no longer the constructor that built it), and does no work at import time. The existing memos are in `internal/zonedTransitionSearch.ts`, `internal/businessCalendar.ts`, `internal/formatterCache.ts` and `internal/validatedZones.ts`; reuse them before adding one. `internal/temporalCompat/` keeps its own probe caches for its workarounds. +- **Remember only what is pure.** A module-level memo holds only facts that are a pure function of their key for the life of the process (zone transitions, parsed holiday strings, validated zone ids, `Intl` formatters built from explicit arguments). It is bounded and cleared on overflow, stores no answer that depends on the clock, on process defaults or on a global the caller can replace (the formatter cache drops a kind once `Intl[kind]` is no longer the constructor that built it), and does no work at import time. The existing memos are in `internal/businessCalendar.ts`, `internal/formatterCache.ts` and `internal/validatedZones.ts`; reuse them before adding one. `internal/temporalCompat/` keeps its own probe caches for its workarounds. - **No `new Intl.*Format` outside `internal/formatterCache.ts`**, except the default-locale read in `internal/resolveLocale.ts`. - **Nothing runs at import, and no fixtures ship.** No top-level Temporal or `Intl` call. Test data, repros and canary tables never live in a module that shipped code imports. - **Measure what you add.** A function with a span-dependent loop gets a `packages/gmt/bench/` row for a short, a 1-year and a 10-year input. The handoff gives the numbers and the size delta of each touched entry from `pnpm size --files `. Put no timing assertion in an `it` row: it is flaky across the CI matrix. @@ -321,7 +317,7 @@ Never compute a zoned start-of-unit by truncating the wall clock and resolving i | `America/Havana` | 2024-11-03 (midnight repeated on the same date) | | `America/Goose_Bay` | 2010-11-07 (fall-back reopens the previous date) | | `Pacific/Apia` | 2011-12-30 (deleted day) | -| `Asia/Manila`, `Pacific/Guam`, `Pacific/Saipan`, `Pacific/Kosrae`, `Pacific/Palau` | 1844-12-31 (deleted day crossing the date line, before the polyfill's 1847-01-01 transition search floor; `dateLineCrossingTimeZones` in `src/test/timeZoneMatrix.ts`, workaround `zoned.E`) | +| `Asia/Manila`, `Pacific/Guam`, `Pacific/Saipan`, `Pacific/Kosrae`, `Pacific/Palau` | 1844-12-31 (deleted day crossing the date line; `dateLineCrossingTimeZones` in `src/test/timeZoneMatrix.ts`) | - **When a transition opens a new bucket.** Hours: when the clock lands on an hour boundary or the label jumps — New York's repeated 01:00 is its own hour, so a fall-back day has 25 hour buckets. Day and larger: only when the local label changes — Havana's repeated midnight on 2024-11-03 stays one 25-hour day (matching `hoursInDay`), while Goose_Bay's fall-back into 6 November is its own 59-minute bucket because the date changed. @@ -437,8 +433,7 @@ them back as instants, so every instant reader follows the zoned reading. - **Everything else keeps the written offset.** The complete list: a string without a bracket; a `Z` instant; an offset written with seconds (TC39 matches it exactly, so `-00:45:00[Africa/Monrovia]` is −00:45:00 to an instant reader and invalid as a zoned string; - polyfill 0.5.1 matches it by minutes, which `zonedDateTimeFrom` corrects as temporalCompat - D12); a bracket whose zone does not exist; and a bracket whose zone has no instant in range + `@js-temporal/polyfill` 0.5.1 matched it by minutes); a bracket whose zone does not exist; and a bracket whose zone has no instant in range with that wall time at the written offset or at one that rounds to it. An instant reader does not validate such a bracket; a function that keeps the zone (`transitTime`, `toOffsetInstant`, every `zoned/` function) rejects it. A string whose written reading is outside the instant diff --git a/context/domination/issues/CORE-102.md b/context/domination/issues/CORE-102.md index 6cc06e17e..f4abbb25f 100644 --- a/context/domination/issues/CORE-102.md +++ b/context/domination/issues/CORE-102.md @@ -62,10 +62,10 @@ try both. `parseDateTimeWithPattern` read `15 марта 2024`. 8. **Polyfill defect D20.** `ParseTemporalMonthDayString` (0.5.1, `lib/ecmascript.ts`, :641, comparison at :648 (throws at :649)) compares the calendar id with `iso8601` before lower-casing it, so `--12-25[u-ca=ISO8601]` throws. A - `temporalCompat` workaround reads it the way the specification does, until a polyfill release - carries the fix. Bug record **V** in `js-temporal-polyfill-bugs.md`. -9. **Polyfill defect, record W.** The polyfill accepts `--02-30` and `--04-31`, which the - IsValidMonthDay early error rejects. gmt's month-day regex encodes that check, so no workaround + `temporalCompat` workaround read it the way the specification does, until a polyfill release + carried the fix. `temporal-polyfill` 1.0.8 parses it, and CORE-108 deleted the workaround. Bug record **V** in `js-temporal-polyfill-bugs.md`. +9. **Polyfill defect, record W.** `@js-temporal/polyfill` 0.5.1 accepted `--02-30` and `--04-31`, which the + IsValidMonthDay early error rejects; `temporal-polyfill` 1.0.8 rejects both (it throws "Cannot parse"). gmt's month-day regex encodes that check, so no workaround is needed; the record holds the repro for filing. 10. **Polyfill defect, record X.** `toLocaleString` rebuilds its Temporal formats from `resolvedOptions()`, so in zh-CN, zh-TW and ja-JP a requested month width comes back numeric. @@ -95,8 +95,8 @@ try both. 19. **Polyfill defect, record Y.** `PlainYearMonth#add` and `#subtract` in 0.5.1 predate tc39 `41faca474a`: they accept days and weeks, and a subtraction starts from the last day of the month (`+275760-09` minus one month throws; `-271821-05` minus one month gives `-271821-04`). - gmt runs the specification's steps on `PlainDate`, so no workaround is needed; the record holds - the repro. + `temporal-polyfill` follows the specification, so gmt calls `PlainYearMonth#add` and + `#subtract` directly; the record holds the 0.5.1 repro. ### The `Intl` format guard @@ -145,7 +145,6 @@ Left to `dox-architect`. `internal/isoStringBody.ts` - `internal/readDurationUnits.ts`, `internal/resolveDurationUnit.ts`, `internal/isObject.ts` (`isOptionsArgument`) and `internal/yearWindowStart.ts` -- `internal/temporalCompat/monthDayFrom.ts` (D20 for month-day; renamed and widened here) - `internal/temporalCompat/`: the workaround registry, probes and README - `src/test/localeMatrix.ts` (`MustTestLocales`) and `src/test/icuVariants.ts` diff --git a/context/domination/issues/CORE-102/design-notes.md b/context/domination/issues/CORE-102/design-notes.md index b108ef7bc..ab295a7ab 100644 --- a/context/domination/issues/CORE-102/design-notes.md +++ b/context/domination/issues/CORE-102/design-notes.md @@ -34,8 +34,8 @@ Part of [CORE-102](../CORE-102.md). with no calendar. Input is the extended form only: `202610` is refused, as for dates. - **No day is invented.** The ISO reference day 1 stays internal. There is no `overflow` option: day 1 exists in every month, so `constrain` and `reject` never differ. -- **Arithmetic follows AddDurationToYearMonth as amended by tc39 `41faca474a`** (merged 2026-01-29), run on - `PlainDate` from day 1, so every engine gives the specification's result. A consequence: the +- **Arithmetic follows AddDurationToYearMonth as amended by tc39 `41faca474a`** (merged 2026-01-29), + through `PlainYearMonth#add` and `#subtract`, which start from day 1 of the month. A consequence: the lowest year-month, `-271821-04`, cannot be moved or have its first day, because its day 1 is outside the PlainDate range; its `getDaysInYearMonth` is still `30`. Likewise `+275760-09` has no last day. diff --git a/context/domination/issues/CORE-103.md b/context/domination/issues/CORE-103.md index a53ba8fb8..3b20d6358 100644 --- a/context/domination/issues/CORE-103.md +++ b/context/domination/issues/CORE-103.md @@ -166,16 +166,10 @@ checklist say when a file is shared and how to undo global state. - **D20.** Tests that depended on another test's state are fixed, not skipped: `element-identity` disconnects its observer and drops its window state, and `dev-worker-proxy` waits on the proxied path with each probe bounded. -- **D21.** The clock readers in `internal/temporalCompat/clock.ts` (`nowInstant`, - `nowZonedDateTimeISO`, `nowPlainDateTimeISO`, `nowPlainDateISO`, `nowPlainTimeISO`) work around - [tc39/proposal-temporal#3335](https://github.com/tc39/proposal-temporal/issues/3335). After a - clock reading before 1970, the polyfill's next `Temporal.Now` reading carries a negative - sub-millisecond tail and can land 1 ms before `Date.now()`. A reader takes `Date.now()` first, - then `Temporal.Now`, and adds 1 ms only when the reading falls exactly 1 ms short. It stays - dormant on a fixed polyfill or a native `Temporal`. Every clock-reading function goes through - these readers, and a guard test fails on a direct `Temporal.Now` call in library source. - `api-surface` treats the readers as clock reads. The removal steps are in the temporalCompat - README and the workaround registry. +- **D21.** GMT reads `Temporal.Now` directly. The polyfill (`temporal-polyfill`) takes the exact + `Date.now()` for the reading, so [tc39/proposal-temporal#3335](https://github.com/tc39/proposal-temporal/issues/3335) + (a reading 1 ms early after a clock before 1970) does not reach GMT and no clock reader is + needed. - **D22.** The `pnpm audit` run ignores GHSA-g3hv-75wg-m249 (minimatch below 11.0.1). Only ESLint 9 and typescript-eslint reach it, no published package depends on it, and an override to minimatch 11 removes functions those tools call. The entry is deleted once `pnpm why minimatch` diff --git a/context/domination/issues/CORE-105.md b/context/domination/issues/CORE-105.md index 61581d113..65ee19e6c 100644 --- a/context/domination/issues/CORE-105.md +++ b/context/domination/issues/CORE-105.md @@ -95,7 +95,7 @@ Settled by the owner. They are the current rules for this code. `runAtRangeLimit`, marked `// defect 2`. The three-argument form measured `root` at 567917 and was not used. - **Line counts.** Facade 372 (was 2297), `operations.ts` 1383, `rangeLimit.ts` 121, - `utcValidity.ts` 28, `calendarArithmetic.ts` 227, `nudgeWindow.ts` 246, `nudgeOrigin.ts` 166. + `utcValidity.ts` 28, `calendarArithmetic.ts` 227, `nudgeWindow.ts` 246, `nudgeOrigin.ts` 166. Of these, only `operations.ts` and `nudgeOrigin.ts` exist today in `internal/zonedDifference/`; CORE-108 deleted the rest with their workarounds. - **Fallow.** `fallow audit --base main` reports no issues in 23 changed files. - **Removal text** is kept in three places that must agree: the module headers, the `steps` in `scripts/lib/workarounds.mjs`, and the README `## Removal steps`. Review added a sentence that the diff --git a/context/domination/issues/CORE-108.md b/context/domination/issues/CORE-108.md new file mode 100644 index 000000000..2ce19cf1a --- /dev/null +++ b/context/domination/issues/CORE-108.md @@ -0,0 +1,62 @@ +# CORE-108 — Core: Move GMT onto `temporal-polyfill` + +**Scope:** `packages/gmt` depends on `temporal-polyfill` instead of `@js-temporal/polyfill`. The +workarounds the new polyfill does not need are removed, the weekly swap job becomes an upgrade +check, and Dox `/bundle-size` compares the two polyfills. Adds no function. Tracked as #460. + +## Gap + +The polyfill is the floor of every GMT bundle: importing one function ships all of it. +`@js-temporal/polyfill` 0.5.1 is 44.2 kB gzipped on its own, and `temporal-polyfill` 1.0.8 is +23.3 kB (#460 has the full table). Most of `internal/temporalCompat/` exists for +`@js-temporal/polyfill` defects. + +On the CORE-92 swap check for 1.0.8, Node passes all 71,340 tests and Chromium has no swap-only +failure. Firefox and WebKit each have one: the D9 row in `largeMonthArithmetic.test.ts`, where +`addZoned` on a non-ISO calendar with `{ months: 4294967295 }` returns the right value but takes +1.2–1.4 s against the 1,000 ms limit. 1.0.8 does in-range month arithmetic in bounded time but is +slow to throw `RangeError` on an out-of-range month amount, and GMT's zoned non-ISO path reaches +that call. The offset sweep finds 0 zones that differ from `Intl.DateTimeFormat` in 418 zones. + +## Scope + +1. **Range check first.** GMT rejects a month amount past Temporal's range before it calls the + polyfill, so the D9 rows stay inside their limit on every leg. D9 stays, its trigger pointing + at `temporal-polyfill`. +2. **The seam.** `src/internal/temporal.ts` imports `temporal-polyfill/full/implementation` and stays + the only file that names the implementation. The ambient module in `src/test/hostModules.d.ts` + goes, so the package's own types apply. +3. **Types.** The type errors the new declarations raise in `packages/gmt` are fixed in the source. +4. **Workarounds.** Each `temporalCompat` group is judged on `temporal-polyfill` by its canary, on + Node and in the browsers it targets. One no longer needed is removed with its sentinel and + README entry; one still needed stays, its trigger pointing at the `temporal-polyfill` behaviour. +5. **CI.** The weekly swap job becomes an upgrade check: the newest `temporal-polyfill` release + against the pinned version, on Node and in all three browsers. +6. **Lint plugins.** `gmt-oxlint`, `gmt-eslint` and `gmt-biome` name `temporal-polyfill` wherever + they name the polyfill today. +7. **Bundle size.** Budgets are set from the new measured sizes. `/bundle-size` gains a section on + the move with charts comparing the two polyfills, `temporal-polyfill` in green and + `@js-temporal/polyfill` in orange. Both sets of figures are generated by + `scripts/bundle-size.mjs`, never typed in. +8. **Docs.** The `/upstream/` "Why this polyfill" section, the guides and the generated reference + describe `temporal-polyfill`. Every filing on both polyfill repos stays listed. +9. **READMEs and a changeset** describe the change. + +Out of scope: native Node 26 `normalizeDuration` (#440), which is native Temporal only. + +## What gmt provides (do not re-implement) + +- CORE-92: the swap job in `.github/workflows/temporal-oracle.yml` and `scripts/polyfill-swap.mjs` +- `node scripts/temporal-compat.mjs check` and the workaround canaries +- `scripts/bundle-size.mjs` and `apps/dox/src/generated/bundle-size.json` + +## Verification + +- The whole `packages/gmt` suite passes on Node and in Playwright Chromium, Firefox and WebKit. +- `node scripts/temporal-compat.mjs check` passes. +- `pnpm run validate` stays green. + +## Decisions + +1. Work starts on `temporal-polyfill` 1.0.8 although Firefox and WebKit each fail the one D9 row. + The range check in Scope 1 fixes it in GMT, and Verification still needs all four legs green. diff --git a/context/domination/issues/CORE-8.md b/context/domination/issues/CORE-8.md index 58d49d485..24d5dc0f5 100644 --- a/context/domination/issues/CORE-8.md +++ b/context/domination/issues/CORE-8.md @@ -146,7 +146,7 @@ Every unit's full report, with sources, deciding rungs, oracles and reproduced f | Class | Units | What was wrong | Resolution | Bucket | | --- | --- | --- | --- | --- | | Throws on invalid input | D3 | 62 functions threw a `TypeError` or `RangeError` on nullish or wrong-typed arguments (`add*`/`subtract*` nullish duration, `round*` missing options, `min*`/`max*`/`sort*` non-array, `formatRelative*`/`formatCalendar*` `null` options, `isValid*Range` nullish); the `cycle*` family read `null`, `""`, `[]`, `true` as a step of 0; `minUnix`/`maxUnix` overflowed the stack on 200,000 values | Sentinels; `src/test/noThrow.test.ts` feeds garbage to every export in every argument position | `patch` | -| Unbounded output | D3, D9 | 14 list-building functions and `bucketRange` could exhaust the heap or run for a minute; `splitIntervalByUnitTime` looped forever across midnight on valid input; non-ISO calendar month arithmetic aborted the process past a few million months (polyfill steps one month at a time) | `maxPieces` option (default 1,000,000, owner decision); span pre-counts; `internal/temporalCompat/largeMonthSpan.ts` jumps whole years from Temporal's own calendar reads, dormant below 1,200 months, with a `pnpm compat` canary | `patch` + additive `minor` | +| Unbounded output | D3, D9 | 14 list-building functions and `bucketRange` could exhaust the heap or run for a minute; `splitIntervalByUnitTime` looped forever across midnight on valid input; non-ISO calendar month arithmetic aborted the process past a few million months (polyfill steps one month at a time) | `maxPieces` option (default 1,000,000, owner decision); span pre-counts; `internal/temporalCompat/largeMonthSpan.ts` (deleted in CORE-108; `temporal-polyfill` 1.0.8 adds months in bounded work) jumped whole years from Temporal's own calendar reads, dormant below 1,200 months, with a `pnpm compat` canary | `patch` + additive `minor` | | RFC and HTTP date grammars | D5, N5 | `parseRfc2822` rejected RFC 5322 §3.3 receiver syntax and the §4 obsolete syntax a receiver MUST accept; `parseHttpDate` rejected rfc850-date and asctime-date (RFC 9110 §5.6.7 MUST); neither checked the weekday; formatters emitted out-of-grammar years and sub-minute offsets; comment folding was quadratic | Grammar-exact parsers; mismatched weekday → `""`; out-of-grammar output → `""` with Temporal compatibility paths; linear comment scan checked against an ABNF oracle over 12 million strings | `patch` | | Leap seconds, zone names, annotations | D6, N5, N3 | `23:59:60` in `t`/space/basic spellings was clamped to `:59` by every zoned function; `timeZoneLike` rejected 42 IANA names (`Japan`, `Zulu`, `EST5EDT`) and `formatUtc` rendered UTC for them; `relativeTo` calendar strings changed meaning with spelling; guards accepted calendar ids the bodies rejected; `isLeapYear`/`getWeekNumber` parsed without validating; `-000000` years and `+99:99` offsets matched regexes | Every spelling rejected; Temporal `TimeZoneIANAName` grammar; guards and bodies agree on GMT `CalendarSystem` ids; validate-then-parse | `patch` | | DST arithmetic and zoned differences | D8, D7 | `addZoned`/`subtractZoned`/`intervalFromDurationZoned` re-resolved an exact-time result (adding 10 minutes could land 50 minutes back); `diffZoned`/`diffZonedAsDuration`/`intervalLengthZoned` measured calendar units in UTC; `intervalOverlappingDays{Zoned,Unix}` miscounted fall-backs that re-enter the previous date and deleted days | Temporal §6.5.5 AddZonedDateTime and §6.5.6 DifferenceZonedDateTime; distinct local dates touched; calendar units across two zones → sentinel | `patch` | diff --git a/context/domination/issues/CORE-80.md b/context/domination/issues/CORE-80.md index c06a27910..988f2a695 100644 --- a/context/domination/issues/CORE-80.md +++ b/context/domination/issues/CORE-80.md @@ -13,7 +13,7 @@ | `internal/dutyEngine.ts` (`dutyViolations`) | 99 ms for a 6-month log, 390 ms for 1 year | Quadratic in log length | | `internal/operatingSchedule.ts` (`operatingTimeBetween`) | 44 ms for 1 year, 395 ms for 10 years | Linear in days | | `internal/freeTimeLedger.ts` (`chargeableDays`) | 0.8 ms for 2 weeks, 36 ms for 2 years | Linear in days | -| `internal/zonedTransitionSearch.ts`, `zoneBucketCap.ts` | Up to ~370k zone reads for one pre-check | Linear in span, uncached | +| `internal/zonedTransitionSearch.ts` (deleted in CORE-108), `zoneBucketCap.ts` | Up to ~370k zone reads for one pre-check | Linear in span, uncached | | `internal/businessCalendar.ts` and its callers | Flat 1.6–3 ms per call with 480 holidays | Linear in holidays | `Intl.DateTimeFormat` is also built on every call, often twice. @@ -31,7 +31,7 @@ In build order. Each part leaves `pnpm run validate` green on its own. 5. **Zone transitions.** Pass `until` in `certainlyTouchesMoreBuckets`. Keep a per-zone memo of transitions found and of stretches verified to have none. Read the clock once per public call. 6. **Epoch-day walks.** `walkSchedule` and `walkFreeTime` work in epoch days and epoch nanoseconds inside each stretch with no offset change. Counts use whole weeks times the weekly total, plus the leftover days, minus holidays found by binary search. Wall times resolve straight to epoch nanoseconds, with no string round-trip. 7. **Calendar resolution and formatter caches.** Holidays parsed once, by integer arithmetic, into a sorted array of epoch days. Calendars, schedules and zones resolved once per public call and handed to an internal core. Formatters cached by locale and resolved options. -8. **Polyfill strategy.** `@js-temporal/polyfill` stays the only engine in the published package. The seam from part 2 exists so CORE-82 can run the suite on native `Temporal`, not to switch engines. Host `Temporal` is reconsidered only when both hold: a stable Safari release ships `Temporal`, and CORE-82's weekly leg has passed on Node 26, Chromium, Firefox and WebKit for 12 consecutive weekly runs. Until then a host engine would change GMT's answers by browser, and the bundle saving would reach only some users. +8. **Polyfill strategy.** One polyfill stays the only engine in the published package (`@js-temporal/polyfill` when this story closed; `temporal-polyfill` 1.0.8 since CORE-108). The seam from part 2 exists so CORE-82 can run the suite on native `Temporal`, not to switch engines. Host `Temporal` is reconsidered only when both hold: a stable Safari release ships `Temporal`, and CORE-82's weekly leg has passed on Node 26, Chromium, Firefox and WebKit for 12 consecutive weekly runs. Until then a host engine would change GMT's answers by browser, and the bundle saving would reach only some users. 9. **Agent and rule changes.** A *Performance shape* section in `.agents/tdd-dev.md`, a *Cost* step in `.agents/gmt-reviewer.md`, three items in `context/code-review-checklist.md`, and a *Loop cost* paragraph in `context/coding-standards.md § Loop Style`. The text is in Part 3 of the audit. ## Tool diff --git a/context/domination/issues/CORE-84.md b/context/domination/issues/CORE-84.md index ed4527436..5f4449efa 100644 --- a/context/domination/issues/CORE-84.md +++ b/context/domination/issues/CORE-84.md @@ -43,7 +43,7 @@ Not in scope: iCalendar files, `VTIMEZONE`, alarms, `EXRULE` (deprecated by RFC - CORE-54 — `nthWeekdayEpochDay` (`internal/nthWeekday`), the ordinal-weekday formula. This story split it into `nthWeekdayInRange` and `nthWeekdayWithin`, and `nthWeekdayEpochDay` now delegates; the engine calls `nthWeekdayWithin` for `BYDAY` with an ordinal - `classifyWall` (`internal/earlierOccurrence`) — wall time to its readings under TC39 disambiguation; `internal/localResolution` falls back to it - `epochDayOf`, `isoFieldsOf`, `isoDateString` and `isoWeekdayOf` (`internal/epochDay`) — epoch-day and weekday arithmetic for `BYWEEKNO`, `BYDAY` and the cron day rule -- `zoneFrame` (`internal/zoneFrame`) and `nextTransitionAfter` (`internal/zonedTransitionSearch`) — the zone and its offset changes +- `zoneFrame` (`internal/zoneFrame`) and `nextTransitionAfter` (`internal/zonedWallClock`) — the zone and its offset changes - `Disambiguation` (`types/disambiguation.ts`) ## Verification diff --git a/context/domination/issues/index.md b/context/domination/issues/index.md index 815a9c1f2..ad9879716 100644 --- a/context/domination/issues/index.md +++ b/context/domination/issues/index.md @@ -42,7 +42,11 @@ generated by `pnpm deps:sync` from [the tracker](../tracker.md); do not edit it - [CORE-103](CORE-103.md) — Core validators take `unknown` and narrow it to `string`; calls that cannot fail drop `null` - [CORE-104](CORE-104.md) — Lengths of time counted from now: seconds, epoch, HTTP date, seconds until - [CORE-91](CORE-91.md) — Past tense only on the Canada checker after 1 November 2026 +- [CORE-105](CORE-105.md) — One file per workaround in `zonedWallClockDifference.ts` - [CORE-106](CORE-106.md) — Database audit: SQL offset timestamps read and validated, a guide matrix per database +- [CORE-107](CORE-107.md) — A changelog page in Dox, and the You-Dont-Need-Momentjs PR on `/upstream` +- [CORE-92](CORE-92.md) — Weekly check for a `temporal-polyfill` release GMT can swap to +- [CORE-108](CORE-108.md) — Move GMT onto `temporal-polyfill` (smaller bundle, fewer workarounds) - [SPA-46](SPA-46.md) — TAI64 / TAI64N / TAI64NA text labels - [SPA-47](SPA-47.md) — `toTT` + `toTCG` - [SPA-49](SPA-49.md) — Two-part Julian Date + MJD + J2000 @@ -57,6 +61,3 @@ generated by `pnpm deps:sync` from [the tracker](../tracker.md); do not edit it - [RAI-100](RAI-100.md) — GTFS times to instants: `gtfsToInstant` - [IOT-101](IOT-101.md) — PTP time: `ptpToUtc`, `utcToPtp`, `isValidPtpTimestamp` - [CORE-90](CORE-90.md) — A US clock-change checker in Dox, once permanent daylight time is law -- [CORE-92](CORE-92.md) — Weekly check for a `temporal-polyfill` release GMT can swap to -- [CORE-105](CORE-105.md) — One file per workaround in `zonedWallClockDifference.ts` -- [CORE-107](CORE-107.md) — A changelog page in Dox, and the You-Dont-Need-Momentjs PR on `/upstream` diff --git a/context/domination/js-temporal-polyfill-bugs.md b/context/domination/js-temporal-polyfill-bugs.md index 48122cac2..5bf2130a0 100644 --- a/context/domination/js-temporal-polyfill-bugs.md +++ b/context/domination/js-temporal-polyfill-bugs.md @@ -1,5 +1,7 @@ # `@js-temporal/polyfill` — upstream issues and PRs GMT needs +> **GMT no longer runs on `@js-temporal/polyfill`.** It runs on `temporal-polyfill` 1.0.8 (CORE-108). This file stays as the record of the 0.5.1 defects and of every filing; each item below describes the old package unless it says otherwise. + 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 diff --git a/context/domination/overview.md b/context/domination/overview.md index 990b35623..3368d1023 100644 --- a/context/domination/overview.md +++ b/context/domination/overview.md @@ -60,7 +60,7 @@ realm. [tracker.md](tracker.md) has the 51 stories in build order. | Authority order | **International first.** An international treaty or standards body, then a multinational industry body, then national sources only as labelled peers. No national system, agency or convention is a default, the sole authority, or gets its own named function; with no international source, a GMT rule backed by sources from at least two countries. Example: the six GNSS are peers because each is an IMO-recognised WWRNS component, not because any one nation's document says so. Examples are spread across regions (tracker, "Added for this epic"). | | Law | **GMT tracks no law.** Regulated windows, limits and tables — from legislatures, regulators, treaties and professional bodies alike — are caller parameters with no defaults; nothing names a statute, agency or jurisdiction in code or docs (tracker, "Added for this epic"). | | Calendar semantics | **TC39 Temporal is the authority.** Arithmetic clamps a non-existent day (`overflow: "constrain"`); parsers reject. Matches EU, UK and US law and every major library but date-fns. | -| Temporal engine | **The polyfill only.** `@js-temporal/polyfill` is the engine in the published package. CORE-80's seam lets CORE-82 run the suite on native `Temporal` weekly. Host `Temporal` is reconsidered when a stable Safari ships it and CORE-82's leg has passed on Node 26, Chromium, Firefox and WebKit for 12 consecutive weekly runs. | +| Temporal engine | **The polyfill only.** `temporal-polyfill` 1.0.8 (`/full/implementation`) is the engine in the published package. CORE-80's seam lets CORE-82 run the suite on native `Temporal` weekly. Host `Temporal` is reconsidered when a stable Safari ships it and CORE-82's leg has passed on Node 26, Chromium, Firefox and WebKit for 12 consecutive weekly runs. | | Zone-aware boundaries | **Real boundaries, never truncate-and-re-resolve.** `start ≤ input < next start`, via `internal/zonedBucket.ts`; tested on the probe zones. See [coding-standards § Calendar & zone semantics](../coding-standards.md#calendar--zone-semantics). | ### Why the build order changed @@ -97,7 +97,7 @@ which were correct, complete, or GMT's facts to assert. ## Architecture ``` -@js-temporal/polyfill ──► @northguild/gmt ──► @northguild/gmt (published) +temporal-polyfill ──► @northguild/gmt ──► @northguild/gmt (published) │ └── src/ ├── plain/ (existing) diff --git a/context/domination/research/index.md b/context/domination/research/index.md index 1b47d4420..733f24edf 100644 --- a/context/domination/research/index.md +++ b/context/domination/research/index.md @@ -20,8 +20,8 @@ the quotes and sources, and what could not be verified. charge basis and clock events - [range-edge-correctness-audit.md](range-edge-correctness-audit.md) — every range-edge defect found while building CORE-6, with root cause, fix and tests -- [temporal-polyfill-swap.md](temporal-polyfill-swap.md) — whether to replace - `@js-temporal/polyfill` with `temporal-polyfill`, what it costs, and the trigger to swap +- [temporal-polyfill-swap.md](temporal-polyfill-swap.md) — why GMT moved from + `@js-temporal/polyfill` to `temporal-polyfill` (CORE-108), what it cost, and the trigger that led to it ## Realm verification (spike-2026-09) diff --git a/context/domination/research/range-edge-correctness-audit.md b/context/domination/research/range-edge-correctness-audit.md index 89e25d11c..9cd101daf 100644 --- a/context/domination/research/range-edge-correctness-audit.md +++ b/context/domination/research/range-edge-correctness-audit.md @@ -1,5 +1,7 @@ # Range-Edge Correctness Audit (CORE-6) +This record dates from the `@js-temporal/polyfill` 0.5.1 era; GMT now runs on `temporal-polyfill` 1.0.8. + **Research Date:** 2026-09-14 **Purpose:** Record every range-edge defect found while building CORE-6, its root cause, fix and covering tests, the call sites proven safe, the `@js-temporal/polyfill` defects found along the way, and the zero-known-bugs rule that came out of it. diff --git a/context/domination/research/temporal-polyfill-swap.md b/context/domination/research/temporal-polyfill-swap.md index bda2580c1..518bc1904 100644 --- a/context/domination/research/temporal-polyfill-swap.md +++ b/context/domination/research/temporal-polyfill-swap.md @@ -1,5 +1,7 @@ # Temporal polyfill swap: `@js-temporal/polyfill` or `temporal-polyfill` +> GMT runs on `temporal-polyfill` 1.0.8 (CORE-108). The sections below record the comparison that led to it. + **Purpose:** Record whether GMT should replace `@js-temporal/polyfill` with `temporal-polyfill` (fullcalendar/temporal-polyfill), what the swap costs, and what tells us to make it. diff --git a/context/domination/specs/CORE-108/bundle-size.md b/context/domination/specs/CORE-108/bundle-size.md new file mode 100644 index 000000000..797c977be --- /dev/null +++ b/context/domination/specs/CORE-108/bundle-size.md @@ -0,0 +1,113 @@ +# Slice 6 — Bundle-size script, JSON and budgets + +`scripts/bundle-size.mjs` measures GMT on `temporal-polyfill` (gated, as today) and also measures +the last GMT release on `@js-temporal/polyfill` (reported, never gated), so Dox `/bundle-size` can +chart both from generated figures. The page and its charts are the Dox spec's; this slice fixes the +JSON they read. Authority row: index § Authority, "The old figures come from the last GMT release on +`@js-temporal/polyfill`, as published". + +## What is measured + +| Set | Source | Entries | Gated | +| --- | ------ | ------- | ----- | +| `temporal-polyfill` (shipped) | `packages/gmt/src`, as today | `root`, `polyfill` (floor), `isValidDate`, `formatDate`, `businessDaysBetween`, `addBusinessDays`, `chargeableDays`, `operatingTimeBetween`, `dutyViolations` | yes, `check` | +| `@js-temporal/polyfill` (previous) | the published `@northguild/gmt` release before this change, installed as a root devDependency alias | the same names | never | + +Why the published release and not GMT's new source on the old polyfill: the release is what users +ran, workarounds included; the new source on the old polyfill never shipped and would be missing the +workarounds slice 3 removes, so its figure would be too small and its code wrong. + +Root `package.json` devDependencies: + +```json +"gmt-js-temporal-release": "npm:@northguild/gmt@1.21.0" +``` + +1.21.0 is the newest published release today and the last on `@js-temporal/polyfill`. If another +release ships before this change merges, pin that one instead. This pin never moves afterwards: it +names a fixed past release, not a window. Check the lockfile resolves it from the registry (a tarball +URL), not by linking the workspace's `packages/gmt`. Add it to `.fallowrc.jsonc` +`ignoreDependencies` with a comment (only esbuild input strings name it). + +`@js-temporal/polyfill` itself is not added to any manifest: the release depends on it, and the floor +is resolved from the release's own directory. + +## Script changes + +- `ENTRIES` becomes per set. Shipped: `polyfill: export { Temporal } from "temporal-polyfill/full/implementation";`, + function entries from `./src/index.ts`, `resolveDir: GMT_DIR` (unchanged). Previous: function + entries `export { } from "gmt-js-temporal-release";`, `root: export * from "gmt-js-temporal-release";`, + `resolveDir: ROOT`; floor `export { Temporal } from "@js-temporal/polyfill";` with `resolveDir` = + `realpathSync` of the release's package directory (pnpm's strict layout). +- Same esbuild settings for both sets (minify, esm, neutral, `mainFields` module/main, es2022, gzip 9). +- `check` measures and gates the shipped set only (it runs in `ci.yml`; keep it fast). Only a run with + `--json` measures the previous set. An entry name missing from the release + (none today) is recorded as `null`, never an error. +- Versions are read, never typed: `temporal-polyfill`'s version from `packages/gmt/node_modules/temporal-polyfill/package.json`; + the release's version and its installed `@js-temporal/polyfill` version from their `package.json`s. +- `--compare` keeps comparing top-level `entries` only. +- `absent`: a listed path that is not a file under `packages/gmt` is a failure (`absent path … does + not exist`), so a list never goes stale. Then drop each path slice 3 deleted. +- Header comment: describe both sets and the JSON below. + +## JSON (`--json`, read by `apps/dox`) + +Top-level keys stay, so nothing that reads them breaks; one key is added. + +```jsonc +{ + "measuredAt": "…", "node": "…", "esbuild": "…", "commit": "…", "dirty": false, + "floor": "polyfill", + "entries": { "": { "minified": 0, "gzipped": 0, "budget": 0 } }, // shipped set, as today + "polyfills": [ + { + "package": "temporal-polyfill", "version": "1.0.8", + "import": "temporal-polyfill/full/implementation", + "shipped": true, "gmt": "", "from": "source", + "entries": { "": { "minified": 0, "gzipped": 0 } } + }, + { + "package": "@js-temporal/polyfill", "version": "0.5.1", + "import": "@js-temporal/polyfill", + "shipped": false, "gmt": "1.21.0", "from": "npm", + "entries": { "": { "minified": 0, "gzipped": 0 } | null } + } + ] +} +``` + +`polyfills[0].entries` equals top-level `entries` without `budget`. `gmt` is the measured GMT's +version, read from its `package.json`; `from` says whether it was bundled from this checkout's source +or from the published package. Order: shipped first. In `check` mode without `--json` nothing is written. + +## Dox reader, kept true + +`apps/dox/src/lib/bundle-size.ts` `importOf` hard-codes `import { Temporal } from "@js-temporal/polyfill"` +for the floor row. Change it to read the shipped entry of `report.polyfills` (`import { Temporal } +from "${shipped.import}"`) so the existing table is right the moment the polyfill changes. Everything +else on that page (the new section, charts, colours) is the Dox spec's. + +## Budgets + +After slices 2 and 3: `node scripts/bundle-size.mjs --update` (size + 1%), then review the edit to +`scripts/bundle-size.budgets.json` like any budget change. Every entry falls (the floor drops from +about 44.2 kB to 23.3 kB gzipped; research § 5). The root budget stays an absolute gate. Quote the +before/after table (`--compare` against a `main` JSON saved to the scratchpad) in the review notes. + +## Tests + +The script has no unit tests today; add `scripts/bundle-size.test.mjs` only for the pure parts +(the JSON shape builder, the `absent` existence check) if they are factored out. Otherwise verify by +running: + +- `node scripts/bundle-size.mjs check` → exit 0. +- `node scripts/bundle-size.mjs report --json /b.json` → both sets present, versions read, + the previous floor about 44 kB gzipped, the shipped floor about 23 kB. +- An `absent` entry naming a missing file → exit 1 with that message (then revert). +- `pnpm --filter @gmt/dox run generate` then the Dox build pass (`deploy-dox.yml` runs `pnpm install` + then `generate`, which now needs the alias installed; it is a root devDependency, so it is). + +## Done when + +`check` passes in CI with the new budgets; the generated JSON carries both sets; the Dox table's +floor row names `temporal-polyfill/full/implementation`. diff --git a/context/domination/specs/CORE-108/docs-readmes-changeset.md b/context/domination/specs/CORE-108/docs-readmes-changeset.md new file mode 100644 index 000000000..3e96bc563 --- /dev/null +++ b/context/domination/specs/CORE-108/docs-readmes-changeset.md @@ -0,0 +1,90 @@ +# Slice 7 — Docs, context files, READMEs, changeset + +Text only. Everything here states the current plan, in plain, factual, technical wording +([plain-english skill](../../../../.agents/skills/plain-english/SKILL.md)). No business or marketing +wording. A sentence that describes what 0.5.1 *did* stays where it is a record (bug docs, research, +Done stories' issue files); a sentence that says GMT *runs on* `@js-temporal/polyfill` changes. + +Find every site with `grep -rln "js-temporal" --exclude-dir=node_modules --exclude-dir=dist .` and +sort each hit into the tables below. Nothing found by the grep is left unsorted. + +## Changes + +| Where | Change | +| ----- | ------ | +| `AGENTS.md` § Core Rules, rule 1 | "Use `temporal-polyfill` exclusively (`/full/implementation`), imported only through `packages/gmt/src/internal/temporal.ts`" | +| `context/project-overview.md` (lines ~21–24) | The dependency table and the sentence after it name `temporal-polyfill` (npm and GitHub `fullcalendar/temporal-polyfill`) | +| `context/coding-standards.md` | Any statement of the runtime; the link to `js-temporal-polyfill-bugs.md § J` stays (a record) | +| `context/testing-standards/references/index.md`, `context/dox/built.md` | Runtime statements | +| `context/perf-and-bundle-size-audit.md` and `…/bundle-size.md` | The polyfill share of a bundle: quote the new `bundle-size.mjs report` figures, not the 44 kB | +| `context/domination/overview.md`, `research/index.md` | Runtime statements; `research/temporal-polyfill-swap.md` gains one line at the top: GMT runs on `temporal-polyfill` 1.0.8 (CORE-108) | +| `context/domination/js-temporal-polyfill-bugs.md` | Stays a record. Its header says GMT moved off the package; every filing stays listed | +| `.agents/{tdd-dev,tester,gmt-reviewer,researcher,architect}.md`, `.agents/skills/plain-english/SKILL.md` | Runtime statements and the example import. These are the owner's licensed files: show him the exact diff and apply on his word | +| `packages/gmt/skills/_artifacts/skill_spec.md` | Through `/tanstack-intent`, not by hand | +| `packages/gmt/src/internal/temporalCompat/README.md` | Done in slice 3 | +| `scripts/behaviour-matrix/README` (or its header) | One line: it pins `@js-temporal/polyfill` 0.5.1 on purpose, as one of the libraries it compares | + +## Dox content (library side only) + +The `/bundle-size` page, its new section and charts are the Dox spec's. This slice covers the pages +that state GMT's runtime: + +| Page | Change | +| ---- | ------ | +| `install.mdx` | Dependency named; ESM only (unchanged); no install step for the polyfill (it is a dependency) | +| `upstream.mdx` "Why this polyfill" | GMT runs on `temporal-polyfill` `/full/implementation`; one paragraph of reasons from research § 1 and § 3 (bounded month arithmetic, maintained release line, smaller), with figures read from `bundle-size.json`, not typed. Both repos' filings stay listed | +| `migrate/temporal.mdx` | Where it says which polyfill GMT re-exports | +| `guides/concepts/standards.mdx` | Where it names the implementation | +| `guides/core-date-operations/get-current.mdx` | D21 (the `Temporal.Now` millisecond) is a 0.5.1 defect; if slice 3 removed D21, drop the caveat | +| `guides/core-date-operations/calendar-systems.mdx` | Per-calendar caveats that were 0.5.1 defects (D1–D8, D10, D20) go with their groups | +| `apps/dox/src/data/upstream-filings.*` | Unchanged entries; tests assert both repos still listed | +| `apps/dox/src/widgets/families/holiday/*`, `components/MultiZoneScrubber.astro` | Comments or imports: imports moved in slice 2; fix any comment | +| `apps/dox/scripts/pr-status/fixtures/*-399.json` | Recorded API payloads: leave as they are | +| Generated reference | Regenerated by `generate`; no hand edit. Check the `Temporal`/`Intl` re-export pages read right | + +## READMEs + +Run `/update-readme`: it syncs the generated figures in `README.md` and `packages/gmt/README.md` +(identical files), including any bundle-size figure. No new section. Namespace READMEs stay stubs. + +## Changeset + +`.changeset/.md`, `@northguild/gmt`: **minor** (house policy: no 2.0.0; breaking changes ship +in the current line). Plain text, written with `/changelog` once the diff is final: + +- GMT now runs on `temporal-polyfill` 1.0.8 instead of `@js-temporal/polyfill` 0.5.1. Every function + returns the same values. +- Bundle sizes: the floor and each measured entry, before → after, from `bundle-size.mjs --compare`. +- **Types:** the `Temporal` and `Intl` re-exports now carry `temporal-spec`'s types. List the public + types whose `.d.ts` changed (slice 2 hands over the list). A consumer that used the old helper + names through `Temporal.*` (e.g. `Temporal.RoundingMode`) must use its own alias. +- Objects from the two polyfills are not interchangeable; a project that also imports + `@js-temporal/polyfill` directly should take `Temporal` from `@northguild/gmt`. +- A month amount past Temporal's range now returns the sentinel without running the polyfill's + month arithmetic (same value as before). + +No changeset for `gmt-oxlint`, `gmt-eslint`, `gmt-biome` (index § Corrections 1). `apps/dox` follows +the repo's Dox changeset practice. + +## Owner-approved steps + +Each step: draft the exact text, show it to the owner (AskUserQuestion), act only on his approval. + +1. **Filing on `fullcalendar/temporal-polyfill`: out-of-range month throw.** Search the repo's issues + for a duplicate first. Draft: an out-of-range non-ISO month amount (`PlainDate`, `PlainYearMonth`, + `ZonedDateTime` `add`; `Duration` `total`/`round`/`compare` with `relativeTo`) throws `RangeError` + only after work linear in the amount, with the slice 1 timings and a minimal repro. On approval, + file it, add it to `apps/dox/src/data/upstream-filings.json`, and link it from D9's row in the + temporalCompat README and its `WORKAROUNDS` trigger. +2. **Filing on `fullcalendar/temporal-polyfill`: `chinese`/`dangi` month adds.** Same steps. Draft: + in-range month adds are linear (50,000 months ≈ 2.5 s) and 4,000,000 months throws an ICU + `TypeError` instead of `RangeError`. Not GMT calendars, so no workaround; filing and + `upstream-filings.json` only. +3. **Issue #460 body.** It still says the browsers have not run on 1.0.8. Draft the replacement text + from this spec and the findings; `gh issue edit 460` only after approval. +4. **`.agents` persona and skill edits** (table above): show the exact diff, apply on his word. + +## Done when + +The grep above returns only records (bug docs, research, Done stories, CHANGELOGs, fixtures, +`behaviour-matrix`) and this spec; `pnpm run validate` green; `/update-readme` checks pass. diff --git a/context/domination/specs/CORE-108/index.md b/context/domination/specs/CORE-108/index.md new file mode 100644 index 000000000..15c1d21ba --- /dev/null +++ b/context/domination/specs/CORE-108/index.md @@ -0,0 +1,133 @@ +--- +story: CORE-108 +issue: 460 +status: approved +dox: context/dox/specs/core-108/index.md +--- + +# CORE-108 — Move GMT onto `temporal-polyfill` + +## Scope + +Story: [`issues/CORE-108.md`](../../issues/CORE-108.md) (#460). Evidence: +[`research/temporal-polyfill-swap.md`](../../research/temporal-polyfill-swap.md) § 5 (cost) and § 7 +(design notes). Prior art: [CORE-92](../CORE-92/index.md) (the swap job this story turns into an +upgrade check). + +`@northguild/gmt` depends on `temporal-polyfill` 1.0.8 (exact pin) instead of +`@js-temporal/polyfill` 0.5.1. No public function is added or removed. Public **types** change: +every `Temporal.*` type GMT re-exports or names in a signature now comes from `temporal-spec` +(slice 2). `apps/dox` moves in the same change, so Dox never mixes objects from two polyfills. + +Seven slices, in order. Each leaves `pnpm run validate` and the whole `packages/gmt` suite green. +Slice 1 runs on 0.5.1; slices 2–7 on 1.0.8. + +Out of scope: #440 (native Node 26 `normalizeDuration`), #462 (browser legs running Node-only +files). The Dox `/bundle-size` page and its charts are a separate dox-architect spec; this spec +fixes only the JSON that page reads (slice 6). + +### Corrections to the issue's Scope wording (decided here) + +1. **Scope 6, lint plugins.** `gmt-oxlint`, `gmt-eslint` and `gmt-biome` name no polyfill outside + their CHANGELOGs (checked: `grep -rl polyfill packages/gmt-{oxlint,eslint,biome}` minus + `node_modules`, `dist`, `CHANGELOG.md` is empty). The polyfill is named only in the repo's own + oxlint configs. Slice 5 edits those; the three plugins get no change and no changeset. +2. **Scope 4, "removed with its sentinel".** Workaround groups have no sentinels; a group is + removed with its repros, its `WORKAROUNDS` entry, its README rows and its removal steps. +3. **Research § 5 says keep zoned.E.** The 1.0.8 Node canary calls it removable. Slice 3 decides + every group by its canary on every engine in scope, not by the research list. + +## What ships + +| Part | Where | Slice | +| ---- | ----- | ----- | +| Month-range guard: an out-of-range month amount throws before any polyfill arithmetic | `packages/gmt/src/internal/temporalCompat/monthRange.ts` (new) + call sites | 1 | +| D9 retargeted: out-of-range month amount throws only after work linear in the amount | `repros.ts`, `scripts/lib/workarounds.mjs`, temporalCompat README | 1, 3 | +| Seam on `temporal-polyfill/full/implementation`; exact dependency pin | `src/internal/temporal.ts`, `packages/gmt/package.json` | 2 | +| Helper type aliases `temporal-spec` does not export | `src/internal/temporalTypes.ts` (new) | 2 | +| Dox imports `Temporal` from `@northguild/gmt` | 57 files under `apps/dox/src` | 2 | +| Workaround groups judged on 1.0.8 on every engine, removed or retargeted | `src/internal/temporalCompat/**`, `scripts/lib/workarounds.mjs` | 3 | +| Weekly upgrade check: newest `temporal-polyfill` vs the pinned one | `temporal-oracle.yml`, `polyfill-swap.mjs`, swap configs | 4 | +| Import restrictions name both polyfill packages | `oxlint.config.mts` (root, `packages/gmt`, `apps/dox`) | 5 | +| Bundle sizes of both polyfills, generated; budgets reset | `scripts/bundle-size.mjs`, `bundle-size.budgets.json` | 6 | +| Docs, context files, READMEs, changeset | see slice | 7 | + +## Signatures + +Internal only. Nothing new is exported from a public entry point. + +```ts +// packages/gmt/src/internal/temporalCompat/monthRange.ts +/** The largest month count between any two dates Temporal can represent, in any GMT calendar. */ +export const MAX_MONTHS_IN_RANGE: number; // 7_365_462 — derivation in slice 1 +/** Throws RangeError when |months| > MAX_MONTHS_IN_RANGE. Calls nothing on Temporal. */ +export function assertMonthsInRange(months: number): void; +``` + +The public functions keep their signatures and sentinels; a guarded call returns the sentinel it +already returns for an out-of-range result ([coding-standards § API Contract](../../../coding-standards.md#api-contract)). + +## Authority — what each rule rests on + +| Rule | Source | +| ---- | ------ | +| PlainDate range −271821-04-19 … +275760-09-13 (epoch days −100,000,001 … +100,000,000) | TC39 Temporal, abstract operation `ISODateWithinLimits` | +| A date + months result outside that range throws RangeError | TC39 Temporal, `CalendarDateAdd` (last step: `ISODateWithinLimits` false → throw RangeError); Intl era/monthCode proposal `NonISODateAdd` returns through the same check | +| A ZonedDateTime result outside the instant range throws RangeError | TC39 Temporal, `IsValidEpochNanoseconds` (limit ±10^8 days × 8.64 × 10^13 ns) | +| All non-zero Duration fields share one sign; \|years\|, \|months\|, \|weeks\| < 2^32 | TC39 Temporal, `IsValidDuration` | +| At most 13 months in any year of a GMT calendar | Intl era/monthCode proposal § 4.1.4 Table 3 (largest month code `M13`; hebrew's leap year adds `M05L` to 12) | +| Shortest year in a GMT calendar: 353 days (hebrew deficient common year) | Dershowitz & Reingold, *Calendrical Calculations* (Hebrew year lengths 353–355, 383–385), the source `largeMonthArithmetic.test.ts` already cites; checked by the runtime in slice 1 | +| `MAX_MONTHS_IN_RANGE = 13 × (⌈200,000,001 / 353⌉ + 1)` | **GMT rule.** An upper bound from the two rows above; slice 1's test proves it exceeds the real full-range month count of every calendar in `calendarSystemIds.ts` | +| The guard is always on, not probe-gated | **GMT rule.** A probe would cost the time the guard saves (1.0.8: up to 5 s on Node). It fires only where the spec throws, so every result equals the spec's | +| The seam imports `/full/implementation`, never `/full` or the default entry | **GMT rule** from research § 7: `/full` returns the runtime's built-in `Temporal`; the default entry supports only `iso8601` and `gregory` | +| A workaround group is removed only when its repros pass on every engine in its scope | **GMT rule:** [temporalCompat README § Rules](../../../../packages/gmt/src/internal/temporalCompat/README.md#rules) 2–3; [`native-suite.mjs`](../../../../scripts/native-suite.mjs) header | +| D9 repro: first call over 5,000 ms fails at once; else 10× the amount must throw in under 3× the time, + 10 ms | **GMT rule.** A ratio is independent of engine speed (linear ~10×, bounded ~1×); the ceiling caps 0.5.1 (~12-30 s a call) | +| The old figures come from the last GMT release on `@js-temporal/polyfill`, as published | **GMT rule.** It is the configuration users ran; GMT's new source on the old polyfill never shipped and lacks the workarounds it needs | +| Sentinels | [coding-standards § API Contract](../../../coding-standards.md#api-contract) | + +## Slices + +| # | Slice | Leaves green | +| - | ----- | ------------ | +| 1 | [Month-range guard and D9 retarget](./range-check.md) | on 0.5.1 | +| 2 | [Seam, dependency and types](./seam-and-types.md) | on 1.0.8, all workarounds still in | +| 3 | [Workaround removals](./workarounds.md) | on 1.0.8, compat snapshot regenerated | +| 4 | [Swap job becomes the upgrade check](./upgrade-check.md) | CI + `temporal-oracle` dry run | +| 5 | [Import restrictions](./lint.md) | `pnpm lint` | +| 6 | [Bundle-size script, JSON and budgets](./bundle-size.md) | `node scripts/bundle-size.mjs check` | +| 7 | [Docs, READMEs, changeset](./docs-readmes-changeset.md) | `pnpm run validate` | + +## CI and cron jobs after the swap + +| Job | Effect | Handled in | +| --- | ------ | ---------- | +| `ci.yml` `compat`: `temporal-compat.mjs snapshot --check` | Fails until `apps/dox/src/data/temporal-compat.json` is regenerated on 1.0.8 | 3 | +| `ci.yml`: `bundle-size.mjs check` | Fails until budgets are reset (sizes fall ~21 kB gzipped) | 6 | +| `temporal-oracle.yml` `native-suite` | Control pass is now 1.0.8; browser compat page needs the new import map | 4 | +| `temporal-oracle.yml` `swap-version` / `polyfill-swap` / `report` | Retargeted to the upgrade check | 4 | +| `deploy-dox.yml` | `generate` runs `bundle-size.mjs report --json`; needs the old release installed (root devDependency, `pnpm install` already runs) | 6 | +| `dox-gates-weekly.yml`, `leap-seconds.yml`, `release.yml` | No polyfill reference; lockfile change only | — | + +## Decisions (owner-approved) + +1. Old bundle figures come from the published `@northguild/gmt@1.21.0`, root devDependency alias + `gmt-js-temporal-release` (slice 6). +2. The month-range guard is always on with the fixed bound above, and covers year-months (slice 1). +3. The D9 canary is the timing-ratio repro (slice 1). +4. Dox imports `Temporal` from `@northguild/gmt` (slice 2), with a lint ban in Dox (slice 5). +5. D10 is removed if its repros pass on every engine, with the then-unused `guard` mechanism (slice 3). +6. D17, D18 and D19 are each judged only in their own browser (slice 3). +7. The swap job keeps its file names, verdict sources and issue key; the browser mode becomes + `"candidate"` (slice 4). +8. `scripts/behaviour-matrix` keeps its `@js-temporal/polyfill` 0.5.1 pin (slices 2, 7). +9. Upstream filings and the #460 body: the implementing session drafts the exact text, the owner + approves it, and only then is anything filed or edited (slice 7, Owner-approved steps). +10. `.agents` persona and skill edits: exact diff to the owner, applied on his word (slice 7). +11. Changeset: minor, with a note on the type change (slice 7). + +## Verification + +Story § Verification, plus: `node scripts/temporal-compat.mjs check` and `snapshot --check` pass; +`node scripts/bundle-size.mjs check` passes; `node scripts/native-suite.mjs ` passes on all four +legs with 1.0.8 as the control; `largeMonthArithmetic.test.ts` passes in Firefox and WebKit. +Build `packages/gmt/dist` only in the CORE-108 worktree, never in the main checkout. diff --git a/context/domination/specs/CORE-108/lint.md b/context/domination/specs/CORE-108/lint.md new file mode 100644 index 000000000..bd7492c5d --- /dev/null +++ b/context/domination/specs/CORE-108/lint.md @@ -0,0 +1,47 @@ +# Slice 5 — Import restrictions + +Issue Scope 6 says the lint plugins name the polyfill. They do not: `gmt-oxlint`, `gmt-eslint` and +`gmt-biome` mention it only in their CHANGELOGs (`no-date-library-imports` bans date libraries, not +Temporal polyfills). The polyfill is named in the repo's own lint configs, CORE-80's seam rule. So +this slice edits configs only; the three plugin packages get no change and no changeset +(index § Corrections 1). + +## Rule + +In each config below, `no-restricted-imports` bans **both** packages, so the old one cannot come back +and the new one is reached only through the seam: + +```ts +"no-restricted-imports": ["error", { + paths: [{ name: "@js-temporal/polyfill", message: "GMT runs on temporal-polyfill; import Temporal from internal/temporal" }], + patterns: [{ group: ["temporal-polyfill", "temporal-polyfill/**"], message: "Import Temporal from internal/temporal" }], +}] +``` + +Check the oxlint version in the lockfile supports `patterns` with `group` (oxlint's +`no-restricted-imports` follows ESLint's options); if it does not, list the subpaths GMT could +import (`temporal-polyfill`, `/full`, `/full/implementation`, `/implementation`, `/global`, +`/full/global`, `/shim`, `/full/shim`, `/fns/*`) as `paths` instead. + +| Config | Files | Exempt | +| ------ | ----- | ------ | +| `oxlint.config.mts` (root) | `packages/gmt/src/**` | `packages/gmt/src/internal/temporal.ts` | +| `packages/gmt/oxlint.config.mts` | `src/**`, `bench/**` | `src/internal/temporal.ts`; `src/test/swapEntry.ts` imports `temporal-polyfill-candidate/…`, which neither rule names, so no exemption is needed (slice 4 points it there; until then it is exempt) | +| `apps/dox/oxlint.config.mts` | `src/**`, `scripts/**`, `tests/**` (new override) | none: Dox takes `Temporal` from `@northguild/gmt` (slice 2); message "Import Temporal from @northguild/gmt" | + +`scripts/behaviour-matrix/**` keeps importing `@js-temporal/polyfill` (its own pinned comparison +tool); the root config does not cover it with this rule, and the existing override for it stays. +`scripts/bundle-size.mjs` names both packages only as strings in esbuild input, which the rule does +not see. + +## Tests + +- `internal/temporal.test.ts` (slice 2) already scans `src` and `bench` for both specifiers in forms + lint cannot see. +- A lint fixture is not needed; prove the rule once by hand: add `import { Temporal } from + "temporal-polyfill/full/implementation"` to one `packages/gmt/src` file and one `apps/dox/src` file, + run `pnpm lint`, see both errors, revert. + +## Done when + +`pnpm lint` (root, `packages/gmt`, `apps/dox`) passes; the hand check above fails as expected. diff --git a/context/domination/specs/CORE-108/range-check.md b/context/domination/specs/CORE-108/range-check.md new file mode 100644 index 000000000..7f3aaa18e --- /dev/null +++ b/context/domination/specs/CORE-108/range-check.md @@ -0,0 +1,132 @@ +# Slice 1 — Month-range guard and D9 retarget + +Runs on `@js-temporal/polyfill` 0.5.1 (the dependency does not change until slice 2). Rows from +[index § Authority](./index.md#authority--what-each-rule-rests-on): the range, `CalendarDateAdd`, +`IsValidEpochNanoseconds`, `IsValidDuration`, 13 months, 353 days, the bound, always-on. + +## The defect (measured, Node 26, `temporal-polyfill` 1.0.8) + +1.0.8 does in-range non-ISO month arithmetic in bounded work (3,000,000 months: ≤ 7 ms in every GMT +calendar), but it throws `RangeError` for an out-of-range month amount only after work linear in +the amount, with no `Intl` read. `{ months: 4294967295 }`: + +| Call | Time | +| ---- | ---- | +| `PlainDate(hebrew).add` | 5,028 ms | +| `PlainDate(indian).add` | 2,899 ms | +| `PlainYearMonth(hebrew).add` | 3,329 ms | +| `Duration.total` relativeTo PlainDate(hebrew) / ZonedDateTime(hebrew) | 3.9 s / 16 s | +| `PlainDate(persian / ethioaa / coptic / islamic-*)` | 0.3–1.4 s | +| iso8601, gregory, japanese, buddhist, roc | 0 ms | + +Firefox and WebKit run it 3–4× slower, which is the one swap-only failure of the CORE-92 run: +`largeMonthArithmetic.test.ts` › `addZoned(… [u-ca=ethioaa], { months: 4294967295 })`, 1,187–1,365 ms. +GMT's plain path never reaches the slow call (D9's `isLargeMonthSpan` branch is ungated); the zoned +path does (`addWithCalendarCompat` is gated on a probe that is false on 1.0.8). After slice 3 +deletes `largeMonthSpan.ts`, every path would reach it. + +Year amounts are not affected: `{ years: 4294967295 }` throws in 3 ms. + +## The bound + +`MAX_MONTHS_IN_RANGE = 13 × (⌈200,000,001 / 353⌉ + 1) = 13 × 566,574 = 7,365,462` + +- 200,000,001: days from −271821-04-19 to +275760-09-13 (`ISODateWithinLimits`). +- 353: the shortest year in any GMT calendar, so the range holds at most ⌈200,000,001 / 353⌉ whole + years; `+ 1` covers the partial years at both ends. +- 13: the most months in any year. + +Write the constant as that expression in code, with a one-line comment per factor, not as the literal. + +**Why |months| > bound proves the result is out of range.** `IsValidDuration` gives every non-zero +field one sign, so years, weeks and days never offset months; any months amount larger than the most +months between two in-range dates lands outside the range from every in-range start. The spec then +throws `RangeError`, so the guard's throw changes no result. A ZonedDateTime's range is narrower than +a PlainDate's, so the bound holds for it too. + +## Guard + +`packages/gmt/src/internal/temporalCompat/monthRange.ts`, exported through `temporalCompat/index.ts` +(README Rule 1). `assertMonthsInRange(months)` throws +`new RangeError("months amount past Temporal's date range")` when `Math.abs(months) > MAX_MONTHS_IN_RANGE`, +and reads nothing from `Temporal`. It takes the number, not a Duration, so callers pass +`duration.months` after they have a `Temporal.Duration` (parsing stays where it is). + +### Call sites + +Every internal place a caller-supplied duration with months meets a date. Build the list first: +`grep -rnE '\.(add|subtract|total|round)\(|Duration\.compare\(' packages/gmt/src --include='*.ts'` +minus tests, then keep each hit whose receiver is a `PlainDate`, `PlainDateTime`, `PlainYearMonth` +or `ZonedDateTime`, or whose options carry `relativeTo`. Put the call at the narrowest shared helper, +not in every public function. Known helpers: + +- `calendarDateAdd` (`temporalCompat/calendarDateArithmetic.ts`) +- `addToZoned`, `subtractFromZoned`, `addToZonedDisambiguated` (`internal/zonedWallClockOperations.ts`) +- the relativeTo paths in `internal/resolveDurationRelativeTo.ts`, `internal/exactDuration.ts`, + `internal/zonedWallClockDifference.ts` (`Duration.compare` at lines ~352, ~367) +- `addYearMonth` / year-month arithmetic, `addDateTime`, `intervalFromDuration{Date,DateTime,Zoned}` + +Record the final list as a table in the module header (helper → public functions that reach it). +A helper slice 3 deletes must hand its guard call to the code that replaces it; slice 3 checks this. + +## temporalCompat README + +Rule 2 ("dormant unless needed") gains one sentence: a guard that fires only where the spec throws +is always on, because its answer is the spec's and a probe would cost what it saves. The D9 row in +§ Workarounds becomes the retargeted text below; § Removal steps 9 is rewritten in slice 3. + +## D9 retarget + +Same defect class, both halves: non-ISO month arithmetic costs work linear in the amount. +0.5.1 has both halves (in-range OOM, handled by `largeMonthSpan.ts`); 1.0.8 has only the out-of-range +half (handled by the guard). This slice adds the guard alongside `largeMonthSpan.ts`; slice 3 removes +`largeMonthSpan.ts`. + +New canary-only repro in `repros.ts` (D9), raw `Temporal`, no GMT code: + +- `t1` = time for `Temporal.PlainDate.from("2024-01-15[u-ca=hebrew]").add({ months: 40_000_000 })` +- `t2` = the same with `400_000_000`; both must throw `RangeError` (anything else fails the repro) +- run `t1` first; fails at once, without `t2`, when `t1` > 5,000 ms (absolute ceiling) +- otherwise passes when `t2 < 3 × t1 + 10` ms (bounded work); linear work gives `t2 ≈ 10 × t1` + +Measure with `performance.now()`. On 1.0.8, `t1` is ~0.5 s on Node and ~2 s in a browser, under the +ceiling, so the ratio decides and fails (linear). On 0.5.1 the polyfill stops at the range limit but +`t1` alone is ~12-30 s, so the ceiling fails it without `t2` (the page timeout is 60 s). D9 stays +"still needed" on both polyfills. Keep the old D9 +repros (the `formatToParts` read count, `D9_INTL_READ_LIMIT`, `D9_MONTHS`) until slice 3. + +## Tests + +`monthRange.test.ts` (new): + +| Row | Expected | Why | +| --- | -------- | --- | +| `assertMonthsInRange(7_365_462)` | no throw | the bound itself | +| `assertMonthsInRange(7_365_463)` / `(-7_365_463)` | RangeError | one past, both signs | +| `assertMonthsInRange(4294967295)` | RangeError | largest valid months field | +| `MAX_MONTHS_IN_RANGE` | `13 * (Math.ceil(200_000_001 / 353) + 1)` | the derivation, not a pasted literal | +| for each id in `calendarSystemIds.ts`: `gmt.diffDate("-271821-04-19[u-ca=]", "+275760-09-13[u-ca=]", "months")` | `< MAX_MONTHS_IN_RANGE` | the bound covers every GMT calendar; run in `runInBoundedChild` (0.5.1 needs D9 for it) | +| same, hebrew | `6_772_637` | the real maximum; cross-check `floor((235y − 234) / 19)` (D–R) in a scratch script | + +Public rows: README Rule 5 forbids mocking Temporal, so no spy rows. Public rows are timing rows in +`largeMonthArithmetic.test.ts` (child process, `MAX_CALL_MS = 1_000`), one per family, hebrew date, +`{ months: 4294967295 }` / `P4294967295M`, expected the existing sentinel: +`addDate`, `subtractDate`, `addDateTime`, `addYearMonth`, `addZoned`, `subtractZoned`, +`totalDuration` (relativeTo date and zoned), `totalUnits`, `addDuration` and `subtractDuration` +(relativeTo), `normalizeDuration` (relativeTo), `compareDurations` (relativeTo), each +`intervalFromDuration*` that takes months, and any other public function the call-site table lists. + +**Red evidence.** These rows may pass on 0.5.1 already. Show red the way CORE-92's job does: in this +worktree only, `npm pkg set --prefix packages/gmt devDependencies.temporal-polyfill=1.0.8`, +`pnpm install --no-frozen-lockfile`, run the file with `vitest.swap.config.ts --fsModuleCache=false` +(at least the zoned rows fail), add the guard, rerun green, then revert `package.json` and the +lockfile. Record both runs in the review notes. + +Also in `largeMonthArithmetic.test.ts`: the bound rows `months: 7365462` → `""` and `7365463` → `""` on hebrew +(same answer either side of the guard). Update the file header: it describes 0.5.1's OOM; add the +1.0.8 out-of-range throw. + +## Done when + +Suite green on 0.5.1; `pnpm compat` shows D9 still needed; the swap-config run was red before the +guard and green after it. diff --git a/context/domination/specs/CORE-108/seam-and-types.md b/context/domination/specs/CORE-108/seam-and-types.md new file mode 100644 index 000000000..664092120 --- /dev/null +++ b/context/domination/specs/CORE-108/seam-and-types.md @@ -0,0 +1,112 @@ +# Slice 2 — Seam, dependency and types + +GMT runs on `temporal-polyfill` 1.0.8 from here on. No workaround is removed in this slice: every +group stays, gated as it is, so a failure here is the swap and nothing else. CORE-92 run +42021143232 showed the suite passes on 1.0.8 with only the D9 row failing, which slice 1 fixed. +Authority row: index § Authority, "The seam imports `/full/implementation`". + +## Dependency + +- `packages/gmt/package.json`: `dependencies` → `{ "temporal-polyfill": "1.0.8" }` (exact; the + upgrade check in slice 4 moves it by a reviewed edit). Remove `@js-temporal/polyfill`. `jsbi` + leaves the tree with it; check nothing else names `jsbi` (`grep -rn jsbi` outside `node_modules`; + `scripts/lib/native-suite-compat.mjs` and its test + `apps/dox/scripts/canary/native-suite-compat.test.ts` do, and slice 4 rewrites them). +- `apps/dox/package.json`: remove `@js-temporal/polyfill` (Dox takes `Temporal` from + `@northguild/gmt`, below). +- `pnpm install`; the lockfile gains `temporal-polyfill`, `temporal-spec`, `temporal-utils`. +- `temporal-polyfill` is ESM only; GMT already is (`"type": "module"`, tsdown `format: "esm"`). + `tsdown.config.ts` has `deps: { neverBundle: true }`, so no change; check `dist/internal/temporal.js` + after a worktree build: one `import … from "temporal-polyfill/full/implementation"` line. + +## Seam + +`packages/gmt/src/internal/temporal.ts`: + +```ts +export { + Intl, + Temporal, + toTemporalInstant, +} from "temporal-polyfill/full/implementation"; +``` + +`full/implementation.js` exports `IntlExtended as Intl, Temporal, toTemporalInstant`, so the three +public names stay. Keep the file's header comment, updated to name the new package and to say why +`/full/implementation` (research § 7: `/full` hands back a built-in `Temporal`; the default entry has +only `iso8601` and `gregory`). + +`internal/temporal.test.ts`: + +- `SPECIFIER` becomes `/["'`]temporal-polyfill(?:\/[^"'`]*)?["'`]/` (any subpath). +- New row: no file in `src` or `bench` names `@js-temporal/polyfill` as a module, seam included. +- New row: the seam's specifier is exactly `temporal-polyfill/full/implementation`. + +## Test harness + +| File | Change | +| ---- | ------ | +| `src/test/hostModules.d.ts` | Delete the `declare module "temporal-polyfill/full/implementation"` block (CORE-92). It hides the package's own types | +| `vitest.native.config.ts` | Alias `^temporal-polyfill\/full\/implementation$` → `src/test/nativeTemporal.ts` | +| `vitest.browser.config.ts` | Native mode aliases the new specifier. The `temporal-polyfill` mode is retargeted in slice 4; until then it aliases the seam's specifier to `SWAP_ENTRY` (a no-op on the same package) | +| `vitest.swap.config.ts` | Same: alias the new specifier; slice 4 points it at the candidate | +| `src/test/boundedChild.ts` | The child's resolve hook maps `temporal-polyfill/full/implementation` (native and swap legs), not `@js-temporal/polyfill` | +| `src/test/nativeTemporal.ts`, `src/test/noThrow.ts` | Comments; the `toTemporalInstant` shim keeps the same export | +| `.fallowrc.jsonc` | The comment naming the alias | + +Comments elsewhere in `src/test/*` that describe 0.5.1 behaviour (`setFakeSystemTime.ts`, the +`oh-*.test.ts` files, `annotationGrammar.test.ts` …) are corrected only where the statement is now +false on 1.0.8; a historical note that says "0.5.1" and is still true stays. + +## Types + +Delete `packages/gmt/tsconfig.tsbuildinfo` (and any other `*.tsbuildinfo`) before counting; stale +composite build info hides errors. Expect about 238 errors (research § 5; CORE-108 findings: +95 TS2694, 65 TS2724, 40 TS2322, 20 TS2345, 7 TS2578). + +1. **Helper types (TS2694, TS2724).** `temporal-spec` does not export `DateTimeUnit`, `SmallestUnit`, + `LargestUnit`, `TotalUnit`, `PluralUnit`, `RoundingMode`, `ToStringPrecisionOptions`, + `DifferenceOptions`, `DurationRoundTo`, `ToInstantOptions`, `ArithmeticOptions`, + `ZonedDateTimeAssignmentOptions`. New file `src/internal/temporalTypes.ts` exports one alias per + name GMT uses, **derived** from `temporal-spec` types by indexed access, never a hand-written + union where a spec type exists. Examples: `DateTimeUnit = Temporal.DateUnit | Temporal.TimeUnit`; + `PluralUnit = Temporal.PluralizeUnit`; + `RoundingMode = NonNullable["roundingMode"]>`; + option bags from the method parameter types (`Parameters[1]`). + It imports `type { Temporal }` from `./temporal`, never from the package. +2. **Call sites.** 67 non-test files write `Temporal.`. Replace with the named import from + `internal/temporalTypes` (a type-only rename; let `tsc` list every site, and run `oxfmt` after). + Test files the same. +3. **TS2578.** Delete each `@ts-expect-error` that no longer fires; if the line it guarded is now a + real call with a valid type, keep the row and its expected value. +4. **TS2322 / TS2345.** Mostly `ZonedDateTimeLike` objects without `timeZone`/`offset` and narrower + option types. Fix the GMT type, never with a cast to `any` or `as unknown as`. + +**Public types change.** GMT re-exports `Temporal` and `Intl` from every namespace entry (`src/index.ts` +and 18 `*/index.ts`), so consumers' `Temporal.*` types now come from `temporal-spec`. Any public +signature that named a removed helper type now names the alias. List every public type whose +emitted `.d.ts` text changes (`pnpm --filter @northguild/gmt build` in this worktree, diff +`dist/**/*.d.ts` against a build of `main` saved to scratch) and hand the list to slice 7 for the +changeset. + +## Dox + +57 files under `apps/dox/src`, `apps/dox/scripts` and `apps/dox/tests` import +`{ Temporal }` or `type { Temporal }` from `@js-temporal/polyfill` (research § 5 says 68; 57 is the +count today). Change each to `@northguild/gmt`, which re-exports the seam, so Dox runs the one +implementation GMT runs (research § 7). `apps/dox/vitest.config.ts:54` comment follows. Do not touch +`apps/dox/src/lib/bundle-size.ts` (slice 6 / Dox spec). + +Do not build `packages/gmt/dist` in the main checkout; the Dox dev server there reads it. + +## Not in this slice + +`scripts/behaviour-matrix` keeps its own `@js-temporal/polyfill` 0.5.1 pin: it is a separate, +private comparison tool outside the workspace (`.fallowrc` ignores it). Slice 7 states that in its +README. + +## Done when + +`tsc` clean in `packages/gmt` and `apps/dox`; whole suite green on Node; browser suite green in +Chromium, Firefox and WebKit (`vitest.browser.config.ts` with `GMT_TEMPORAL=polyfill`); +`node scripts/temporal-compat.mjs check` runs (groups may now report removable — that is slice 3). diff --git a/context/domination/specs/CORE-108/upgrade-check.md b/context/domination/specs/CORE-108/upgrade-check.md new file mode 100644 index 000000000..da1f95c38 --- /dev/null +++ b/context/domination/specs/CORE-108/upgrade-check.md @@ -0,0 +1,91 @@ +# Slice 4 — The swap job becomes the upgrade check + +CORE-92's weekly job ran the suite on `@js-temporal/polyfill` (control) and `temporal-polyfill` +(swap). After slice 2 the control *is* `temporal-polyfill` at the pinned version, so the job checks +the newest `temporal-polyfill` release (the candidate) against the pin, on Node, Chromium, Firefox +and WebKit, and opens one issue when the candidate passes every leg. Mechanism and verdict rules stay +CORE-92's ([CORE-92 index](../CORE-92/index.md), Corrections 2–3); this slice changes what is compared. + +**Names stay.** `scripts/polyfill-swap.mjs`, `vitest.swap.config.ts`, the verdict sources +`temporal-polyfill-swap-` and the issue key `temporal-polyfill-swap/ready` keep their names: the +job still swaps the implementation behind the seam, and a stable key keeps an open issue matched. +Only behaviour and text change. + +## Candidate install (job only, never committed) + +The candidate cannot be installed as `temporal-polyfill`: that would replace the pinned control. +Install it under an npm alias in the job's checkout: + +```sh +npm pkg set --prefix packages/gmt \ + "devDependencies.temporal-polyfill-candidate=npm:temporal-polyfill@$VERSION" +pnpm install --no-runtime --no-frozen-lockfile +``` + +`CANDIDATE_ENTRY = "temporal-polyfill-candidate/full/implementation"` replaces `SWAP_ENTRY` in +`polyfill-swap.mjs`, `vitest.swap.config.ts` (alias `^temporal-polyfill\/full\/implementation$` → +`CANDIDATE_ENTRY`, env `GMT_SWAP_ENTRY: CANDIDATE_ENTRY`), `vitest.browser.config.ts`, and +`src/test/boundedChild.ts` (its resolve hook maps the seam's specifier to `GMT_SWAP_ENTRY`). Keep +`--fsModuleCache=false` on every pass (research § 7). + +`src/test/swapEntry.ts` imports `CANDIDATE_ENTRY` to prove the swap pass ran the candidate's own +`Temporal` object. Outside the job that module does not resolve, so `src/test/hostModules.d.ts` gains +`declare module "temporal-polyfill-candidate/full/implementation"` (a name no real package uses, so, +unlike CORE-92's block deleted in slice 2, it hides nothing). `optimizeDeps.exclude` keeps excluding it +outside the swap pass. + +## Browser modes + +`vitest.browser.config.ts` `MODES`: `""` (native), `"polyfill"` (control: the pinned package, no +alias), `"candidate"` (was `"temporal-polyfill"`, which is now ambiguous). `native-suite.mjs` +`passSetup` and its tests follow. The error message lists the three modes. + +## Version pick (`swap-version` job) + +- No input: `npm view temporal-polyfill version`. Read the pin from `packages/gmt/package.json` + (`dependencies["temporal-polyfill"]`). Equal → output `skip=true`; the four legs skip and the + report files nothing (nothing to upgrade). The job summary says "pinned X is the newest release". +- `swap_version` input set: use it even when it equals the pin (a manual self-test of the job). +- Keep the `x.y.z` check. + +## Compat check in the browser (`scripts/lib/native-suite-compat.mjs`) + +The compat page loads `dist/internal/temporalCompat/{repros,capabilities}.js`, which import the seam, +which imports `temporal-polyfill/full/implementation`. That entry imports `../chunks/*.js` and +`temporal-utils/protected*`. Replace the `@js-temporal/polyfill` + `jsbi` import map with one entry: +bundle `temporal-polyfill/full/implementation` (resolved from `packages/gmt`) with esbuild into a +single ESM file in memory (`bundle: true, format: "esm", write: false`), serve it at `/polyfill.js`, +and map `{ "temporal-polyfill/full/implementation": "/polyfill.js" }`. No `jsbi`. Update +`apps/dox/scripts/canary/native-suite-compat.test.ts` (it names `jsbi` and the old map). +This part is needed by slice 3 Step 1; do it first if slice 3 runs before the rest of this slice. + +## Text + +| File | Change | +| ---- | ------ | +| `.github/workflows/temporal-oracle.yml` | Header comment and step names: "upgrade check: newest `temporal-polyfill` against the pin"; the install step uses the alias above; `swap-version` gains the skip output and `if:` on the legs | +| `scripts/polyfill-swap.mjs` | Header: control = pinned `temporal-polyfill`, swap = candidate; usage unchanged | +| `scripts/native-suite.mjs` | Header line 8 ("once on @js-temporal/polyfill (the control)") and the compat summary line name `temporal-polyfill` | +| `scripts/lib/canary-issues.mjs` | Swap-ready issue (≈ lines 1069–1251): title and body say "`temporal-polyfill` X passes on every runtime against the pinned Y: raise the pin in `packages/gmt/package.json`", with the steps (edit pin, `pnpm install`, `pnpm compat`, remove what turns removable, budgets). Line 110 and every other "@js-temporal/polyfill" that describes GMT's runtime → `temporal-polyfill`. The research link stays (history) | +| `scripts/lib/canary-summary.mjs`, `scripts/lib/canary-verdict.mjs` | Same wording | +| `apps/dox/scripts/canary/*.test.ts` | Expected strings follow; no assertion is dropped | +| `scripts/upstream.mjs` | No change: it keeps tracking `js-temporal/temporal-polyfill`, `tc39/proposal-temporal` and `fullcalendar/temporal-polyfill`, so every filing stays listed | + +`scripts/lib/offset-sweep.mjs` runs on the candidate on the Node leg, unchanged. + +## Tests + +- `native-suite.mjs` `passSetup` rows: `("chromium","swap")` → `{ GMT_TEMPORAL: "candidate" }`; + `("node","swap")` → `vitest.swap.config.ts`. +- `vitest.browser.config.ts` with `GMT_TEMPORAL=temporal-polyfill` throws the mode error. +- canary-issues: the swap-ready fixture produces the new title and body; `--force-swap-ready` still works. +- version pick: a script-level unit (or the workflow's shell) for pin == newest → skip; input given → + no skip. +- After merge (post-merge CI checks): dispatch `temporal-oracle.yml` with `swap_version` = the pin. + Every leg must run and report swap-ready; then close the issue it opens, which says the pin is + already that version. + +## Done when + +CI green; the four `polyfill-swap` legs run locally (`node scripts/polyfill-swap.mjs node --version=1.0.8` +after the alias install, reverted afterwards) with the candidate equal to the pin and report swap-ready. diff --git a/context/domination/specs/CORE-108/workarounds.md b/context/domination/specs/CORE-108/workarounds.md new file mode 100644 index 000000000..d0f0c0150 --- /dev/null +++ b/context/domination/specs/CORE-108/workarounds.md @@ -0,0 +1,108 @@ +# Slice 3 — Workaround removals + +Starts after slice 2 (GMT on 1.0.8, every group still present). Authority row: index § Authority, +"A workaround group is removed only when its repros pass on every engine in its scope", resting on +[temporalCompat README § Rules](../../../../packages/gmt/src/internal/temporalCompat/README.md#rules) +2 and 3 (same answer after removal: no test row's expected value changes). + +## Step 1 — verdicts on every engine, before any deletion + +Build `packages/gmt/dist` **in this worktree** (`temporal-compat.mjs` loads `dist`), then collect a +verdict per group on each engine: + +| Engine | How | +| ------ | --- | +| Node 26 | `node scripts/temporal-compat.mjs check` | +| Node at the `engines.node` floor (22.16.0) | the same, under that Node (`npx -y node@22.16.0 scripts/temporal-compat.mjs check`) — host-ICU halves (D3+D4, D16) are judged here too | +| Chromium, Firefox, WebKit | `runBrowserCompat` from `scripts/lib/native-suite-compat.mjs`, which needs slice 4's import-map change; do slice 4's compat-page part first, or run it through the slice-4 code on a scratch branch of this worktree | + +Save the seven verdict outputs under the scratchpad and quote the counts in the review notes. + +A group without `engines` is in scope everywhere: remove it only when **all five** engines report it +removable. A group with `engines` (D17 Firefox, D18 WebKit, D19 WebKit) is judged in its engines only. +CORE-108 findings record the Node 26 verdicts only; the browser verdicts on 1.0.8 have not been run. + +## Step 2 — expected outcome (to be confirmed by Step 1) + +| Group | Node 26 on 1.0.8 | Expected action | +| ----- | ---------------- | --------------- | +| D1, D2, D3+D4, D5, D6, D7, D8, D11, D12, D13, D14, D15, D20, D21, zoned.A, zoned.B, zoned.D, zoned.E | removable | remove if every engine agrees | +| D9 (old half: in-range months, `largeMonthSpan.ts`) | removable | remove; D9 itself stays, retargeted in slice 1 | +| D10 | GUARD (repros pass) | see below | +| D16 | still needed (ICU-20548) | keep; trigger unchanged (it names ICU, not a polyfill) | +| D22 | still needed (tc39/proposal-temporal#3336) | keep; retarget trigger | +| D17, D18, D19 | out of scope on Node | judge in Firefox / WebKit; keep or remove by that verdict | + +Any group Step 1 shows still needed on some engine stays, its trigger retargeted. + +**D10.** Its `guard` (`package: "@js-temporal/polyfill"`, `through: "0.5.1"`) exists because 0.5.1 +predates tc39/proposal-temporal#3292, the change that exposes the bug. `temporal-polyfill` is a +separate implementation, so the guard's premise does not apply: its repros (`fieldsFarMonth13`, +`fieldsFarMonth12`, ethioaa year 18196) test the behaviour directly. If they pass on every engine, +remove D10 like any other group. Then the `guard` mechanism in `scripts/lib/workarounds.mjs`, +`scripts/temporal-compat.mjs` (`guard` state, `guardReason`, `guardLapsed`, `GUARD`) and +`scripts/lib/canary-*.mjs` has no user: delete it with its tests, so no dead code stays (fallow +fails on it otherwise). If a D10 repro fails on some engine, D10 stays with no guard. + +## Step 3 — removal, one group per commit-sized step + +For each removable group, in README § Removal steps order: + +1. Follow its removal steps exactly (README § Removal steps and the `steps` in its `WORKAROUNDS` entry). + Respect the ordered steps: README step 6 (delete `nonIsoArithmetic.ts` once D1, D2, D3–D5, D6, D7 + are all gone), the `fieldSearch.ts` step once no D2–D5 range guard remains, zoned.D before zoned.A + (`rangeLimit.ts`). +2. Delete its repros (`probeRepros.ts` / `repros.ts`), its `WORKAROUNDS` entry, its rows in the README + § Workarounds and § Removal triggers tables, and its § Removal steps paragraph. +3. Run the whole suite. **No expected value in any test may change** (README Rule 3). A row that + would have to change means the group was wrong or the polyfill differs: stop and report it. +4. Remove only tests that test the deleted algorithm directly (`hebrewArithmetic.test.ts`, …). + Public rows stay. + +**Old D9 half.** Delete `largeMonthSpan.ts` and its calls in `readArithmeticModel.ts` and +`calendarDateArithmetic.ts` (README § Removal steps 9), plus the old D9 repros (`D9_INTL_READ_LIMIT`, +`D9_MONTHS`, the `formatToParts` counter). Keep slice 1's repro and guard. `largeMonthArithmetic.test.ts` +keeps every row: the in-range 3,000,000-month rows now run on the polyfill directly (≤ 7 ms each). +Rewrite README § Removal steps 9 for the guard: delete `monthRange.ts`, its calls and the D9 repro, +when a `temporal-polyfill` release throws for an out-of-range month amount in bounded time. + +**Guard call sites.** Slice 1 put `assertMonthsInRange` in helpers such as `calendarDateAdd` and +`addWithCalendarCompat`. When a removal deletes or inlines such a helper, move the guard call to the +code that replaces it, and update the call-site table in `monthRange.ts`. The slice-1 timing rows +must still pass on Node and in the three browsers. + +## Step 4 — retarget what stays + +- `scripts/lib/workarounds.mjs`: every remaining `trigger` names a `temporal-polyfill` release (or + ICU / an engine) and the observable it waits for, the way the current triggers do. No group says + "js-temporal" unless its removal truly depends on that project. +- `polyfillEntry()` / `polyfillVersion()` read `temporal-polyfill`'s `package.json` and entry. +- `scripts/temporal-compat.mjs` `runtimeLine()` prints `temporal-polyfill `; the + `native-suite.mjs` `compatLine` text likewise. +- temporalCompat README: header, Rules, the § Workarounds table, § Canary and native oracle, + § Removal triggers ("the release that becomes GMT's `temporal-polyfill` pin"), § Removal steps. + Renumber nothing that other files cite by number without updating those citations + (`grep -rn "Removal steps [0-9]"`). +- `src/internal/temporalCompat/index.ts` exports and `capabilities.ts` (`ARITHMETIC_DEFECTS`, probe + sets) lose removed groups; run fallow and delete what it reports unused. +- `scripts/bundle-size.budgets.json` `absent` lists: slice 6. + +## Step 5 — compat snapshot + +`pnpm compat:snapshot` regenerates `apps/dox/src/data/temporal-compat.json` from the new `dist`, so +`ci.yml`'s `node scripts/temporal-compat.mjs snapshot --check` passes. The snapshot schema does not +change; the Dox pages that render it are the Dox spec's concern. + +## Tests + +- Every public test file passes with no expected value changed (diff the test tree: only deleted + files, deleted rows of deleted-algorithm tests, and comments may differ). +- `scripts/lib/workarounds.mjs` tests and the canary script tests under `apps/dox/scripts/canary/` + pass with the removed ids gone. +- `node scripts/temporal-compat.mjs check` lists only the kept groups, each "still needed" (or out of + scope), none "removable". + +## Done when + +Step 1 verdicts recorded for all five engines; suite green on Node and three browsers; `temporal-compat +check` and `snapshot --check` pass; fallow clean. diff --git a/context/domination/tracker.md b/context/domination/tracker.md index 57fd95873..12ceaf797 100644 --- a/context/domination/tracker.md +++ b/context/domination/tracker.md @@ -7,7 +7,7 @@ ## Overview -`@northguild/gmt` expands with **56 stories across Core and 9 realms**, built in four phases. +`@northguild/gmt` expands with **58 stories across Core and 9 realms**, built in four phases. Reading the table top to bottom is the build order, and the `#` column is that order. A story ID is a permanent name: it is what every cross-reference, spec filename and GitHub issue uses, @@ -58,14 +58,15 @@ npm. A Core primitive ships with the realm that first uses it. The second Core r exception: it ships as two releases of its own, the first with `MAR-16` and `SPA-48`, the second ending with lengths of time counted from now, ahead of the remaining realms. -| Cut after | Ships | Why here | -| -------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| INT-58 (#11) | TRAN-8, INT-12, INT-58 | Dwell plus free time, demurrage and the billing deadline chain: the demurrage calculations, complete | -| TRAN-57 (#15) | CORE-55, TRAN-9, TRAN-10, TRAN-57, CORE-77 | The rest of the transport primitives, with operating hours | -| CORE-76 (#20) | INT-15, CORE-78, INT-14, CORE-76 | Intermodal complete with its tools (#304), and hours of work: the engine every duty rule runs on | -| CORE-88 (#29) | MAR-16 … CORE-88 (#21–#29) | GNSS time and leap seconds, then the second Core round: the site on its domain, the `Temporal` seam, the native suite, stored times, the Canada 2026 clock-change checker | -| CORE-104 (#38) | CORE-89 … CORE-104 (#30–#38) | The rest of the second Core round: the Morocco checker, identifiers, holiday rules, recurrence and cron, human durations, `Position`, month-day and year-month values, validators that take any value, lengths of time counted from now | -| SPA-52 (#44) | CORE-91 … SPA-52 (#39–#44) | The Canada checker in the past tense and the database audit, then the time-scale conversions: TAI64 text labels, TT and TCG, Julian Date, MJD and J2000, CCSDS ASCII time codes | +| Cut after | Ships | Why here | +| -------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| INT-58 (#11) | TRAN-8, INT-12, INT-58 | Dwell plus free time, demurrage and the billing deadline chain: the demurrage calculations, complete | +| TRAN-57 (#15) | CORE-55, TRAN-9, TRAN-10, TRAN-57, CORE-77 | The rest of the transport primitives, with operating hours | +| CORE-76 (#20) | INT-15, CORE-78, INT-14, CORE-76 | Intermodal complete with its tools (#304), and hours of work: the engine every duty rule runs on | +| CORE-88 (#29) | MAR-16 … CORE-88 (#21–#29) | GNSS time and leap seconds, then the second Core round: the site on its domain, the `Temporal` seam, the native suite, stored times, the Canada 2026 clock-change checker | +| CORE-106 (#41) | CORE-89 … CORE-106 (#30–#41) | The rest of the second Core round: the Morocco checker, identifiers, holiday rules, recurrence and cron, human durations, `Position`, month-day and year-month values, validators that take any value, lengths of time counted from now; then the Canada checker in the past tense, one file per workaround and the database audit | +| CORE-108 (#44) | CORE-107, CORE-92, CORE-108 (#42–#44) | Changelog pages, the weekly check for a `temporal-polyfill` release, and the move onto `temporal-polyfill`: a new runtime dependency and changed public types, with no new function beside them | +| SPA-52 (#48) | SPA-46 … SPA-52 (#45–#48) | The time-scale conversions: TAI64 text labels, TT and TCG, Julian Date, MJD and J2000, CCSDS ASCII time codes | --- @@ -102,34 +103,35 @@ ending with lengths of time counted from now, ahead of the remaining realms. | 27 | CORE-82 | Core | The suite runs on native `Temporal`:
    Node 26, Chromium, Firefox, WebKit, weekly | — | #322 | 1.20.0 | Done | | 28 | CORE-83 | Core | `classifyStoredZoned`: why a stored
    zoned time no longer resolves | — | #323 | 1.20.0 | Done | | 29 | CORE-88 | Core | The Canada 2026 clock-change checker in Dox | — | #329 | 1.20.0 | Done | -| 30 | CORE-89 | Core | The Morocco 2026 clock-change checker in Dox | — | #340 | — | Done | -| 31 | CORE-56 | Core | Time-ordered identifiers (UUID,
    ULID, Snowflake…) +
    Parquet/Arrow/protobuf | — | #258 | — | Done | -| 32 | CORE-54 | Core | Holiday rule engine: nth weekday,
    Easter, observance shifts | — | #256 | — | Done | -| 33 | CORE-84 | Core | Recurrence rules and cron lines in a
    zone: RRULE, RDATE, EXDATE, cron | — | #324 | — | Done | -| 34 | CORE-85 | Core | Human duration strings:
    `parseHumanDuration`, `formatHumanDuration` | — | #325 | — | Done | -| 35 | CORE-79 | Core | `Position` input type | — | #314 | — | Done | -| 36 | CORE-102 | Core | Month-day (`--MM-DD`) and year-month (`YYYY-MM`)
    values: validate, parse, format, compare, arithmetic | — | #416 | — | Done | -| 37 | CORE-103 | Core | Core validators take `unknown`
    and narrow it to `string`; calls that cannot fail drop `null` | — | #432 | — | Done | -| 38 | CORE-104 | Core | Lengths of time counted from now:
    seconds, epoch, HTTP date, seconds until | — | #433 | Cut | Done | -| 39 | CORE-91 | Core | Past tense only on the Canada checker
    after 1 November 2026 | — | #353 | — | Done | -| 40 | CORE-106 | Core | Database audit: SQL offset timestamps
    read and validated, a guide matrix per database | — | #438 | — | Done | -| 41 | SPA-46 | Space | TAI64 / TAI64N / TAI64NA text labels | — | #227 | — | Not started | -| 42 | SPA-47 | Space | `toTT` + `toTCG` | — | #228 | — | Not started | -| 43 | SPA-49 | Space | Two-part Julian Date + MJD + J2000 | SPA-47 | #230 | — | Not started | -| 44 | SPA-52 | Space | CCSDS ASCII time codes A and B | — | #233 | Cut | Not started | -| 45 | HLTH-93 | Healthcare | HL7 v2 timestamps: `parseHL7`,
    `formatHL7`, `isValidHL7` | — | #401 | — | Not started | -| 46 | HLTH-94 | Healthcare | FHIR datetimes: `parseFHIR`, `formatFHIR`,
    `isValidFHIR`, three FHIR regexes | HLTH-93 | #402 | — | Not started | -| 47 | FIN-95 | Finance | FIX UTC timestamps: parse, format and
    `isValidFixUtcTimestamp` | — | #403 | — | Not started | -| 48 | FIN-96 | Finance | SWIFT dates: `parseSwiftDate`,
    `formatSwiftDate`, `isValidSwiftDate` | FIN-95 | #404 | — | Not started | -| 49 | AV-97 | Aviation | SSIM dates: `parseSsimDate`,
    `formatSsimDate`, `isValidSsimDate` | — | #405 | — | Not started | -| 50 | AV-98 | Aviation | METAR and NOTAM times: parse,
    `isValidMetarTime`, `isValidNotamValidity` | AV-97 | #406 | — | Not started | -| 51 | RAI-99 | Rail | GTFS time strings: `parseGtfsTime`,
    `formatGtfsTime`, `isValidGtfsTime` | — | #407 | — | Not started | -| 52 | RAI-100 | Rail | GTFS times to instants: `gtfsToInstant` | RAI-99 | #408 | — | Not started | -| 53 | IOT-101 | IoT | PTP time: `ptpToUtc`, `utcToPtp`,
    `isValidPtpTimestamp` | — | #409 | — | Not started | -| 54 | CORE-90 | Core | A US clock-change checker in Dox, once
    permanent daylight time is law | — | #341 | — | Waiting | -| 55 | CORE-92 | Core | Weekly check for a `temporal-polyfill`
    release GMT can swap to | — | #386 | — | Done | -| 56 | CORE-105 | Core | One file per workaround in
    `zonedWallClockDifference.ts` | — | #437 | — | Done | -| 57 | CORE-107 | Core | A changelog page in Dox, and the
    You-Dont-Need-Momentjs PR on `/upstream` | — | #451 | — | Done | +| 30 | CORE-89 | Core | The Morocco 2026 clock-change checker in Dox | — | #340 | 1.21.0 | Done | +| 31 | CORE-56 | Core | Time-ordered identifiers (UUID,
    ULID, Snowflake…) +
    Parquet/Arrow/protobuf | — | #258 | 1.21.0 | Done | +| 32 | CORE-54 | Core | Holiday rule engine: nth weekday,
    Easter, observance shifts | — | #256 | 1.21.0 | Done | +| 33 | CORE-84 | Core | Recurrence rules and cron lines in a
    zone: RRULE, RDATE, EXDATE, cron | — | #324 | 1.21.0 | Done | +| 34 | CORE-85 | Core | Human duration strings:
    `parseHumanDuration`, `formatHumanDuration` | — | #325 | 1.21.0 | Done | +| 35 | CORE-79 | Core | `Position` input type | — | #314 | 1.21.0 | Done | +| 36 | CORE-102 | Core | Month-day (`--MM-DD`) and year-month (`YYYY-MM`)
    values: validate, parse, format, compare, arithmetic | — | #416 | 1.21.0 | Done | +| 37 | CORE-103 | Core | Core validators take `unknown`
    and narrow it to `string`; calls that cannot fail drop `null` | — | #432 | 1.21.0 | Done | +| 38 | CORE-104 | Core | Lengths of time counted from now:
    seconds, epoch, HTTP date, seconds until | — | #433 | 1.21.0 | Done | +| 39 | CORE-91 | Core | Past tense only on the Canada checker
    after 1 November 2026 | — | #353 | 1.21.0 | Done | +| 40 | CORE-105 | Core | One file per workaround in
    `zonedWallClockDifference.ts` | — | #437 | 1.21.0 | Done | +| 41 | CORE-106 | Core | Database audit: SQL offset timestamps
    read and validated, a guide matrix per database | — | #438 | 1.21.0 | Done | +| 42 | CORE-107 | Core | A changelog page in Dox, and the
    You-Dont-Need-Momentjs PR on `/upstream` | — | #451 | — | Done | +| 43 | CORE-92 | Core | Weekly check for a `temporal-polyfill`
    release GMT can swap to | — | #386 | — | Done | +| 44 | CORE-108 | Core | Move GMT onto `temporal-polyfill`
    (smaller bundle, fewer workarounds) | — | #460 | Cut | Not started | +| 45 | SPA-46 | Space | TAI64 / TAI64N / TAI64NA text labels | — | #227 | — | Not started | +| 46 | SPA-47 | Space | `toTT` + `toTCG` | — | #228 | — | Not started | +| 47 | SPA-49 | Space | Two-part Julian Date + MJD + J2000 | SPA-47 | #230 | — | Not started | +| 48 | SPA-52 | Space | CCSDS ASCII time codes A and B | — | #233 | Cut | Not started | +| 49 | HLTH-93 | Healthcare | HL7 v2 timestamps: `parseHL7`,
    `formatHL7`, `isValidHL7` | — | #401 | — | Not started | +| 50 | HLTH-94 | Healthcare | FHIR datetimes: `parseFHIR`, `formatFHIR`,
    `isValidFHIR`, three FHIR regexes | HLTH-93 | #402 | — | Not started | +| 51 | FIN-95 | Finance | FIX UTC timestamps: parse, format and
    `isValidFixUtcTimestamp` | — | #403 | — | Not started | +| 52 | FIN-96 | Finance | SWIFT dates: `parseSwiftDate`,
    `formatSwiftDate`, `isValidSwiftDate` | FIN-95 | #404 | — | Not started | +| 53 | AV-97 | Aviation | SSIM dates: `parseSsimDate`,
    `formatSsimDate`, `isValidSsimDate` | — | #405 | — | Not started | +| 54 | AV-98 | Aviation | METAR and NOTAM times: parse,
    `isValidMetarTime`, `isValidNotamValidity` | AV-97 | #406 | — | Not started | +| 55 | RAI-99 | Rail | GTFS time strings: `parseGtfsTime`,
    `formatGtfsTime`, `isValidGtfsTime` | — | #407 | — | Not started | +| 56 | RAI-100 | Rail | GTFS times to instants: `gtfsToInstant` | RAI-99 | #408 | — | Not started | +| 57 | IOT-101 | IoT | PTP time: `ptpToUtc`, `utcToPtp`,
    `isValidPtpTimestamp` | — | #409 | — | Not started | +| 58 | CORE-90 | Core | A US clock-change checker in Dox, once
    permanent daylight time is law | — | #341 | — | Waiting | **`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 @@ -172,10 +174,13 @@ passed, is done. validators take any value and narrow it to `string`) complete the second release. `CORE-102` and `CORE-103` build on shipped internals alone and no story consumes them; `CORE-103` changes types, fixes one `isValidTimeZone` result. `CORE-104` (lengths of time counted from now) comes straight -after it, on shipped functions alone, and closes the release. `CORE-106` (the database audit) opens -the next release with the time-scale conversions: it builds on shipped functions alone, no story +after it, on shipped functions alone. `CORE-91`, `CORE-105` (one file per workaround) and `CORE-106` +(the database audit) close the release. `CORE-106` builds on shipped functions alone, no story consumes it, and it settles the SQL and epoch readers before the industry timestamp formats lean on -the same primitives. +the same primitives. `CORE-107` (changelog pages), `CORE-92` (the weekly check for a +`temporal-polyfill` release) and `CORE-108` (the move onto `temporal-polyfill`) are a release of +their own. `CORE-108` changes the runtime dependency and some public types, so this release adds +no function beside it, and npm matches the docs site before the time-scale conversions build on it. **Demurrage comes straight after `TRAN-8`.** `INT-12` is the first consumer of `dwellTime.calendarDays`, and `INT-58` adds the billing deadline chain, every window a caller @@ -196,8 +201,8 @@ the wire, read and written. Every one draws only on shipped primitives (`CORE-1` it, with its subpaths, Dox industry, guide and mistakes page, and the second extends them, so four pairs are ordered: `HLTH-93` before `HLTH-94`, `FIN-95` before `FIN-96`, `AV-97` before `AV-98`, and `RAI-99` before `RAI-100`, which also turns `RAI-99`'s times into instants. The realms themselves -can be built in any order. They sit before the `CORE` rows that wait or run on a schedule, and no -`Cut` follows them yet. +can be built in any order. They sit before `CORE-90`, which waits, and no `Cut` follows them +yet. --- @@ -205,9 +210,9 @@ can be built in any order. They sit before the `CORE` rows that wait or run on a ### Phase 1 — Core Foundation (required for everything) -Core is thirty-three stories: the primitives several realms share, the tooling every story is held +Core is thirty-five stories: the primitives several realms share, the tooling every story is held to, and one pass over the whole surface before anything is built on top. Phase 1 is the eight -shipped stories; the later ones (`CORE-54` … `CORE-56`, `CORE-76` … `CORE-106`) are built inside +shipped stories; the later ones (`CORE-54` … `CORE-56`, `CORE-76` … `CORE-108`) are built inside Phase 2, each just before its first consumer, in the first open slot, or in the second Core round. - **CORE-1, CORE-2, CORE-3** — precision, spans and foreign epoch bridges. @@ -271,6 +276,8 @@ Highest commercial value and the thinnest coverage in the original plan. - **CORE-106** — the database audit: every major database's date and time types mapped to gmt calls, and the SQL `TIMESTAMP WITH TIME ZONE` text that PostgreSQL and SQL Server print, read and validated. +- **CORE-108** — GMT runs on `temporal-polyfill`: a smaller bundle and fewer workarounds, with the + weekly check from `CORE-92` watching each new release. ### Phase 3 — Space / Celestial diff --git a/context/dox/built.md b/context/dox/built.md index 651215641..9f4d27936 100644 --- a/context/dox/built.md +++ b/context/dox/built.md @@ -106,6 +106,22 @@ that bind future changes, the traps, and the runbooks. Every story is done; stat the freight offset are in `guides/concepts/standards`; the oracle and upstream text, CI counts, safeguards and the nanoseconds text are in `guides/concepts/correct-at-the-edges`; the full fault table is on `/why-gmt/` and the library table on `/compare/`. +- **`/bundle-size`** shows the size of GMT on each of the two polyfills. The report is + `src/generated/bundle-size.json` (`scripts/bundle-size.mjs report`); its `polyfills[]` lists one + set per package, found by the `shipped` flag and never by index. + - `src/lib/bundle-size-figures.ts` holds every figure and imports only the JSON, so the chart + module in the client graph never reaches the corpus. The page states them as + `polyfillFigures.` expressions; `page-expression-values.ts` has one entry per key. + No package name, version or entry name is typed in the module. + - Chart 1 is the floor of each polyfill alone. Chart 2 is each single-function import split + into the polyfill (solid) and GMT's code above it (hatched). `root` is in the table and not + in chart 2, because it is the whole package and would dwarf every function. A function the + previous release does not export has no bar and a "not in GMT {version}" cell. + - `PolyfillCompare.astro` is the table beside the charts and their text alternative. The charts + are `bundle-size-charts.ts`; `bar-charts.ts` joins them with `why-gmt-charts.ts` for + `ChartContainer`, through the shared `bar-chart-kit.ts`. + - A view's caption reaches the Markdown twin (`viewCaptions` in `mdx-jsx.ts`), and + `{name}` becomes a code span there (`stripMdx`). - **The dark island** (`.gmt-theme-dark`) carries its own dark `--sl-color-*` hues, because Starlight re-derives them in light and the hero must match in both. The token block lists `.gmt-theme-dark` last in its selector list; `zone-map.fixture.ts` finds it by that literal. @@ -2192,7 +2208,7 @@ Shared hooks come first, then the globe, then the clock-change pages. whose imports all reject. - **Trap: the notice covers a failed gmt import, not a failed page script.** The shell's `