UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

441 lines (439 loc) • 20.3 kB
import { Temporal } from "../temporal.js"; import { rangeFieldCases, rangeFieldProblem } from "./rangeFieldRepros.js"; import { probeRepros } from "./probeRepros.js"; // src/internal/temporalCompat/capabilities.ts /** The repro's output, or `ERR <name>: <message>` when it throws. */ function runRepro(repro) { try { return repro.run(); } catch (error) { const { name, message } = error instanceof Error ? error : new Error(String(error)); return `ERR ${name}: ${message}`; } } /** True when a repro's output is the spec-correct value, i.e. the installed runtime is fixed. */ function reproPasses(repro, output) { return output === repro.expected; } /** * True when any of `candidates` for this defect and Temporal calendar id fails. Stops at the first * failure, so the order of a defect's repros is the order they are tried in. */ function anyReproFails(candidates, defect, calendar) { return candidates.some((repro) => repro.defect === defect && repro.calendar === calendar && !reproPasses(repro, runRepro(repro))); } const cache = /* @__PURE__ */ new Map(); /** * True when any repro for this defect and Temporal calendar id fails in the installed runtime. * A calendar with no repro for the defect is not affected by it. */ function isDefectPresent(defect, calendar) { const key = `${defect}/${calendar}`; const cached = cache.get(key); if (cached !== void 0) return cached; const present = anyReproFails(probeRepros, defect, calendar); cache.set(key, present); return present; } /** * True when this runtime never retries the calendar nudge window (defect D11). * * TC39 bounds a duration between `relativeTo + r1 units` and `relativeTo + r2 units`, and recomputes * the window one unit further along when the target falls outside it. A runtime that computes the * window once answers `Duration#total`, `Duration#round` and `until`/`since` with a calendar * `smallestUnit` over the wrong bounds. Only a `relativeTo` on the 29th, 30th or 31st can reach it, * because only there does adding a month constrain the day. ISO-only: the non-ISO calendars already * take the spec path through `isCalendarArithmeticCompatNeeded`. */ function isNudgeWindowCompatNeeded() { return isDefectPresent("D11", "iso8601"); } /** * True when this runtime mismeasures from either pass of a repeated hour (defect D22). * * TC39 `ComputeNudgeWindow` takes the window's start from the origin's own exact time when no unit * has been added, and `DifferenceZonedDateTime` subtracts the exact times when both fall on one local * date. A runtime that turns the wall clock back into an exact time with `"compatible"` moves a * later-pass origin an hour early, and one with no same-date branch backs up a day from an earlier-pass * origin when the end falls in the later pass at a lower wall clock. So `Duration#total` in a date unit, * and `Duration#round` and `until` with a date `largestUnit`, answer from an instant the caller never * named. tc39/ecma262#3759 commit `1f4e6717ef23` decides when the window starts at the origin: an * empty start duration, not `r1 = 0`. */ function isNudgeOriginCompatNeeded() { return isDefectPresent("D22", "iso8601"); } /** * True when this runtime matches a zoned string's offset by minutes even when the offset is * written with seconds (defect D12). * * TC39 `ToTemporalZonedDateTime` matches by minutes only an offset with no seconds part; one * written with seconds must equal the zone's offset exactly. A runtime that always matches by * minutes accepts `-00:45:00[Africa/Monrovia]` for a zone at −00:44:30, and picks the wrong pass * of a second repeated by a sub-minute transition (Pacific/Niue, 1952). */ function isSecondsOffsetMatchCompatNeeded() { return isDefectPresent("D12", "iso8601"); } /** * True when this runtime's time zone transition search cannot be trusted (defect D13). * * TC39 `GetNamedTimeZoneNextTransition` returns the first offset change after an instant. A runtime * that samples the offset in steps longer than the gap between two changes skips a pair that * returns to the same offset, and can loop for ever on three different offsets in one step. The * skipped-pair repros come first and none of them can stall, so on such a runtime the probe * answers before a stalling repro is reached. Every repro has to pass for the workaround to go * dormant: a runtime that fixes the skipped pairs and still stalls on one zone keeps it. */ function isTransitionSearchCompatNeeded() { return isDefectPresent("D13", "iso8601"); } /** * True when this runtime rounds to the day wrongly where a date starts twice (defect D14). * * A fall-back across midnight re-enters a date after the next date has started, as * America/Goose_Bay did on 2010-11-06, and America/Sitka on 1867-10-18. TC39 * `ZonedDateTime#round` clamps an instant in the second piece of that date to the end of the date * (tc39/ecma262#3966, commit 5f44331e0a11; test262 `same-date-starts-twice.js`). A runtime without * that change answers the next date for `floor` and `trunc`, and in some zones (Sitka 1867) for the * half modes, `ceil` and `expand` too, or throws. */ function isDayRoundClampCompatNeeded() { return isDefectPresent("D14", "iso8601"); } /** * True when this runtime applies `offset: "ignore"` to a `Z` string (defect D15). * * TC39 `ToTemporalZonedDateTime` reads a `Z` string as an exact instant under every `offset` * option; `InterpretISODateTimeOffset` applies `ignore` only to an offset written as an option. A * runtime that ignores the `Z` and reads the wall clock in the zone returns a different instant * whenever the zone's offset is not zero. */ function isZIgnoreExactCompatNeeded() { return isDefectPresent("D15", "iso8601"); } const rangeZoneNameCache = /* @__PURE__ */ new Map(); /** * True when this runtime's `formatRange` changes the `timeZoneName` width of a range (defect D16). * * UTS #35 (Matching Skeletons) expects "fields in the skeleton and pattern ... to be adjusted in * parallel", so the range pattern chosen for a `timeZoneName: "long"` skeleton keeps a long zone * name; ECMA-402 §11.5.8 builds each range part with FormatDateTimePattern over the range * pattern's own fields, so it prints what that pattern holds. ICU-20548 makes `DateIntervalFormat` * cut `long` and `longGeneric` to short names and drop `shortOffset` and `longOffset`. The probe * runs once per style, on the first call for it. A style with no repro (an unknown one) is not * affected, and is not cached, so a caller passing arbitrary text cannot grow the cache. */ function isRangeZoneNameCompatNeeded(style) { const cached = rangeZoneNameCache.get(style); if (cached !== void 0) return cached; const name = `range.${style}`; const candidates = probeRepros.filter((repro) => repro.defect === "D16" && repro.name === name); if (candidates.length === 0) return false; const present = anyReproFails(candidates, "D16", "iso8601"); rangeZoneNameCache.set(style, present); return present; } /** * True when this runtime's `formatRange` writes the AM/PM day period where `dayPeriod` asks for a * flexible one, with a `timeZoneName` set (defect D17). * * Not a width rule (UTS #35 treats a, b and B as close matches). ECMA-402 §11.5.8 picks the range * pattern by the resolved [[HourCycle]] only: en-US resolves to h12 whether `hourCycle: "h12"` is * given or omitted, yet SpiderMonkey (Firefox 155) prints the flexible period for the first and * AM/PM for the second. Identical resolved options give two range outputs, and GMT's contract is * that a range keeps the fields the caller asked for. */ function isRangeDayPeriodCompatNeeded() { return isDefectPresent("D17", "iso8601"); } /** * True when this runtime's `ZonedDateTime#equals` answers false for two identifiers of one time * zone (defect D19). * * ECMA-262 TimeZoneEquals compares the two [[PrimaryIdentifier]]s, and ECMA-402 §6.5 fixes * `"UTC"` as primary and `"Etc/UTC"` as a non-primary identifier that resolves to it. The polyfill * finds a non-primary identifier's primary through `Intl.DateTimeFormat#resolvedOptions`, which * JavaScriptCore returns as written, so `Etc/UTC` and `UTC` compare unequal there. */ function isTimeZoneEqualsCompatNeeded() { return isDefectPresent("D19", "iso8601"); } /** Defects that make the runtime's calendar arithmetic or reads differ from the spec. */ const ARITHMETIC_DEFECTS = [ "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D10", "D18" ]; /** * True when calendar arithmetic in `calendarId` needs the compat layer in this runtime: any of its * add, until or read probes fails. `iso8601` never does, and costs nothing. * Callers that own a spec path for a whole operation (zoned differences, `Duration` rounding, * totals and comparisons) take it when this is true. */ function isCalendarArithmeticCompatNeeded(calendarId) { return calendarId !== "iso8601" && ARITHMETIC_DEFECTS.some((defect) => isDefectPresent(defect, calendarId)); } const engineProbeCache = /* @__PURE__ */ new Map(); /** `Intl.DateTimeFormat` text for a UTC date given as year, month and day (any year, 0 to 99 too). */ function textAt(locale, options, date) { const time = Temporal.PlainDate.from({ year: date[0], month: date[1], day: date[2] }).toZonedDateTime("UTC").epochMilliseconds; return new Intl.DateTimeFormat(locale, { ...options, timeZone: "UTC" }).format(time); } /** One engine probe, answered the first time it is asked and kept: `true` when the engine has the defect. */ function engineDefect(key, fails) { const cached = engineProbeCache.get(key); if (cached !== void 0) return cached; let present; try { present = fails(); } catch { present = false; } engineProbeCache.set(key, present); return present; } /** * True when this runtime's japanese calendar prints a Japanese era for a date the Gregorian * eras cover (defect D25, ICU-23341 and ICU-23619). * * Intl era/monthCode Table 2, as amended by tc39/proposal-intl-era-monthcode#86 (test262 * tc39/test262#4877): for dates up to and including 1872-12-31 the japanese calendar uses the * Gregorian eras. ICU 78 prints `-645 Taika` for ISO -0001-07-10 and `5 Meiji` for 1872-12-31. The * probe compares the japanese calendar's era and year with the Gregorian calendar's at both dates. */ function isJapaneseEraCompatNeeded() { return engineDefect("D25", () => [[ -1, 7, 10 ], [ 1872, 12, 31 ]].some((date) => textAt("en-u-ca-japanese", { era: "short", year: "numeric" }, date) !== textAt("en-u-ca-gregory", { era: "short", year: "numeric" }, date))); } /** * True when this runtime prints a date before the Hijra in the one Islamic era, as a negative year * (defect D26, ICU-23327). * * Intl era/monthCode Table 2 and § 4.1.12 give the `bh` era, and test262 * `intl402/DateTimeFormat/prototype/formatToParts/era.js` requires ISO 600 and 2025 to print * different era names. The probe compares the text with its digits and signs taken out. */ function isIslamicEraCompatNeeded() { const eraOf = (date) => textAt("en-u-ca-islamic-civil", { era: "short", year: "numeric" }, date).replace(/[\p{Nd}\p{Pd}\p{Z}−]/gu, ""); return engineDefect("D26", () => eraOf([ 600, 7, 10 ]) === eraOf([ 2025, 7, 10 ])); } /** * True when this runtime prints a coptic date before AM 1 without its signed year and its era * (defect D31, ICU-23277). * * Intl era/monthCode Table 2 gives the coptic calendar one era, `am`, with era years from * -infinity to +infinity, and 4.1.12 makes the era year the year; test262 * `intl402/Temporal/PlainDate/from/non-positive-single-era-year.js` keeps coptic era year -1 as -1. * ISO -000001-07-10 is therefore `-285 AM`. ICU prints `1 - year` (286) and an empty era. The * probe reads that date with the era and year fields: the text must hold the year as * `Intl.NumberFormat` writes -285 and the same era name as a date after AM 1 (digits, signs and * spaces taken out). */ function isCopticEraCompatNeeded() { const options = { era: "short", year: "numeric" }; const eraOf = (text) => text.replace(/[\p{Nd}\p{Pd}\p{Z}−]/gu, ""); return engineDefect("D31", () => { const before = textAt("en-u-ca-coptic", options, [ -1, 7, 10 ]); const after = textAt("en-u-ca-coptic", options, [ 2e3, 1, 1 ]); const signed = new Intl.NumberFormat("en", { useGrouping: false }).format(-285); return !(before.includes(signed) && eraOf(after) !== "" && eraOf(before) === eraOf(after)); }); } /** * True when this runtime changes the Islamic era in the middle of the first day of year 1 (defect * D32, WebKit 331724). * * Intl era/monthCode Table 2 and 4.1.12: the era `ah` starts on 1 Muharram of year 1, the whole * calendar day, in every zone. JavaScriptCore switches at one fixed instant (0622-07-19T07:52:58Z, * a day earlier for `islamic-tbla`), so the first hours of the day print year 0 and `Before Hijra`. * The probe formats the epoch day of each calendar (Calendrical Calculations, chapter 6: Friday 16 * July 622 Julian for the civil and umalqura calendars, Thursday for the tabular astronomical one) * at its first and its last hour in UTC: both must print the same era name. */ function isIslamicEpochEraCompatNeeded() { const eraOf = (calendar, day, hour) => new Intl.DateTimeFormat(`en-u-ca-${calendar}`, { era: "short", year: "numeric", timeZone: "UTC" }).format(Temporal.Instant.from(`0622-07-${day}T${String(hour).padStart(2, "0")}:00:00Z`).epochMilliseconds).replace(/[\p{Nd}\p{Pd}\p{Z}−]/gu, ""); return engineDefect("D32", () => [ ["islamic-civil", 19], ["islamic-tbla", 18], ["islamic-umalqura", 19] ].some(([calendar, day]) => eraOf(calendar, day, 0) !== eraOf(calendar, day, 23))); } /** * True when this runtime changes the Coptic era in the middle of 1 Tout AM 1 (defect D34, WebKit * 331724; fixed by WebKit/WebKit#81144). * * Intl era/monthCode Table 2 gives `coptic` one era, `am`, for every year, and 4.1.12 reads the era * from the calendar date, which has no time: every instant of one local day prints one era. * JavaScriptCore compares the instant with a fixed constant (0284-08-29T07:52:58Z), so the first * hours of ISO 0284-08-29 print `Anno Martyrum`. The probe formats ISO 0284-08-29 at 00:00 and * 23:00 UTC with `en-u-ca-coptic`, `{ era: "short", year: "numeric", timeZone: "UTC" }`: both must * print the same era name (digits, signs and spaces taken out). */ function isCopticEpochEraCompatNeeded() { const eraAt = (hour) => new Intl.DateTimeFormat("en-u-ca-coptic", { era: "short", year: "numeric", timeZone: "UTC" }).format(Temporal.Instant.from(`0284-08-29T${String(hour).padStart(2, "0")}:00:00Z`).epochMilliseconds).replace(/[\p{Nd}\p{Pd}\p{Z}−]/gu, ""); return engineDefect("D34", () => eraAt(0) !== eraAt(23)); } /** * True when this runtime prints a wrong Chinese or Dangi date for `calendar` (defect D33). * * Intl era/monthCode section 1.1 Table 1 bases `chinese` on Purple Mountain Observatory data and * `dangi` on KASI data. The probe formats UTC-noon instants in `en-u-ca-<calendar>` with numeric * year, month and day and compares the related year (the year part when there is none) and the * day with the Hong Kong Observatory conversion table (computed to GB/T 33661-2017, years 2018, * 2027, 2029 and 2030) for `chinese` and the KASI lunar-solar conversion service for `dangi`; * native Temporal (V8 with ICU4X) gives the same on every row. Month text is left out: ICU 78 * prints `6bis` and `Mo12` where older ICU prints `6` and `12`. * * @param calendar the calendar to probe * @returns `true` when any row of that calendar differs * * @example isLunisolarTextCompatNeeded("chinese") // true on Node 22, 24 and 26 (ICU 78.3) * @example isLunisolarTextCompatNeeded("dangi") // false on a host that prints KASI's dates */ function isLunisolarTextCompatNeeded(calendar) { const rows = calendar === "chinese" ? [ ["2027-02-06", "2027|1"], ["2030-02-02", "2029|30"], ["2030-02-03", "2030|1"], ["2018-11-07", "2018|30"] ] : [["2017-02-26", "2017|1"], ["2027-02-07", "2027|1"]]; return engineDefect(`D33:${calendar}`, () => { const formatter = new Intl.DateTimeFormat(`en-u-ca-${calendar}`, { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }); return rows.some(([iso, expected]) => { const parts = formatter.formatToParts(Temporal.Instant.from(`${iso}T12:00:00Z`).epochMilliseconds); const value = (type) => parts.find((part) => part.type === type)?.value; return `${value("relatedYear") ?? value("year")}|${value("day")}` !== expected; }); }); } /** * True when this runtime does not pad a Japanese era year under `year: "2-digit"` (defect D27, * ICU-23620). * * ECMA-402 FormatDateTimePattern, the "2-digit" branch: FormatNumeric with `minimumIntegerDigits: * 2`, so Reiwa 6 is `06`. ICU's `jpanyear` numbering ignores the minimum digit count. */ function isJapaneseTwoDigitYearCompatNeeded() { return engineDefect("D27", () => !/\p{Nd}{2}/u.test(textAt("ja-u-ca-japanese", { year: "2-digit" }, [ 2024, 7, 10 ]))); } /** * True when this runtime pads the related year of the chinese and dangi calendars under `year: * "2-digit"` (defect D28, ICU-23621). * * ECMA-402 FormatDateTimePattern: `relatedYear` is FormatNumeric of the related year at full width, * with no 2-digit form. ICU prints its `rr` field, padded to two digits: `05` for ISO 0005. */ function isRelatedYearWidthCompatNeeded() { return engineDefect("D28", () => /\p{Nd}+/u.exec(textAt("en-u-ca-chinese", { year: "2-digit" }, [ 5, 7, 10 ]))?.[0] !== "5"); } /** * True when this runtime resolves `islamic` to a calendar other than `islamic-tbla`, or resolves * `islamic-rgsa` at all (defect D30). * * Intl era/monthCode CreateDateTimeFormat turns a resolved `islamic` into `islamic-tbla`, and since * tc39/proposal-intl-era-monthcode#99 `islamic-rgsa` is not an available calendar, so a * DateTimeFormat ignores it and takes the locale's default (test262 * `intl402/DateTimeFormat/constructor-options-calendar-islamic-fallback.js`). ICU keeps both. */ function isIslamicCalendarResolutionCompatNeeded() { const calendarOf = (locale) => new Intl.DateTimeFormat(locale).resolvedOptions().calendar; return engineDefect("D30", () => calendarOf("en-u-ca-islamic") !== "islamic-tbla" || calendarOf("en-u-ca-islamic-rgsa") === "islamic-rgsa"); } /** * True when this runtime prints a Japanese era year in Latin digits under another numbering * system (defect D27, the numbering part). * * ECMA-402 FormatDateTimePattern: the year is FormatNumeric in the resolved numbering system, so * `ja-u-ca-japanese-nu-arab` prints Reiwa 6 as `令和٦年`. ICU's `jpanyear` numbering ignores `nu`. */ function isJapaneseNumberingSystemCompatNeeded() { return engineDefect("D27nu", () => /[0-9]/.test(textAt("ja-u-ca-japanese-nu-arab", { year: "numeric" }, [ 2024, 7, 10 ]))); } /** * True when this runtime prints a range that drops, repeats or garbles a field of one date * (defect D29). * * ECMA-402 PartitionDateTimeRangePattern and UTS #35 Part 4 (Interval Formats): each date's part of * a range holds every field the formatter's single `format` prints for that date. ICU with CLDR * 48 drops the chinese related year, a `B` day period, the end's hebrew month value and more * (`rangeFieldRepros.ts` has one range per upstream defect). The probe asks each of them once and * stays true while any one is broken, so the gate holds until every known cause is fixed. */ function isRangeFieldCompatNeeded() { return engineDefect("D29", () => rangeFieldCases.some((c) => rangeFieldProblem(c.locale, c.options, c.from, c.to) !== "complete")); } export { anyReproFails, isCalendarArithmeticCompatNeeded, isCopticEpochEraCompatNeeded, isCopticEraCompatNeeded, isDayRoundClampCompatNeeded, isDefectPresent, isIslamicCalendarResolutionCompatNeeded, isIslamicEpochEraCompatNeeded, isIslamicEraCompatNeeded, isJapaneseEraCompatNeeded, isJapaneseNumberingSystemCompatNeeded, isJapaneseTwoDigitYearCompatNeeded, isLunisolarTextCompatNeeded, isNudgeOriginCompatNeeded, isNudgeWindowCompatNeeded, isRangeDayPeriodCompatNeeded, isRangeFieldCompatNeeded, isRangeZoneNameCompatNeeded, isRelatedYearWidthCompatNeeded, isSecondsOffsetMatchCompatNeeded, isTimeZoneEqualsCompatNeeded, isTransitionSearchCompatNeeded, isZIgnoreExactCompatNeeded, reproPasses, runRepro };