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.

443 lines (441 loc) • 23.1 kB
import { Temporal } from "./temporal.js"; import { hasZonedDateTimeShape } from "./isoStringBody.js"; import { MAX_EPOCH_NANOSECONDS, MAX_ISO_EPOCH_DAYS, MIN_EPOCH_NANOSECONDS } from "./epochNanoseconds.js"; import { isSecondsOffsetMatchCompatNeeded, isTransitionSearchCompatNeeded, isZIgnoreExactCompatNeeded } from "./temporalCompat/capabilities.js"; import { stringOptionOrDefault } from "./typedOptions.js"; import { hasSecond60Field } from "./inputChecks.js"; // src/internal/zonedWallClock.ts const NANOSECONDS_PER_DAY = 86400000000000n; const NANOSECONDS_PER_MINUTE = 60000000000n; /** * Dates this many days from a range limit are the only ones either defect reaches: defect 1 needs * a wall clock within a day of the limit, defect 2 a transition within the scan's two-week step. */ const EDGE_WINDOW_DAYS = 31; /** * `getTimeZoneTransition("next")` looks at most three years (366-day years) past its receiver; * a `null` from further than this from the maximum is the polyfill's own horizon, not defect 2. */ const NEXT_TRANSITION_HORIZON_NANOSECONDS = BigInt(1129) * NANOSECONDS_PER_DAY; /** Previous-transition steps walked back from the maximum instant; real zones need two or three. */ const MAX_TRANSITIONS_BEFORE_MAXIMUM = 64; /** * Bisection steps to pin a transition to the nanosecond: 2^75 ns covers the whole representable * range (2 × 8.64e21 ns < 2^74), which `missedNextTransition` searches from the minimum instant. */ const MAX_BISECTION_STEPS = 75; /** * 1847-01-01T00:00:00Z: `BEFORE_FIRST_DST` in js-temporal `lib/ecmascript.ts`. The polyfill never * looks for a transition before it (defect 3). */ const POLYFILL_TRANSITION_SEARCH_FLOOR = -3881520000000000000n; /** The last local date whose start can lie before the floor: midnight 1847-01-01 at UTC+14. */ const LAST_DATE_BEFORE_TRANSITION_SEARCH = new Temporal.PlainDate(1847, 1, 1); /** * Every instant from here on has a local date after 1847-01-01 in every zone (a UTC offset is * always less than a day), so a zoned value can skip the date comparison and its offset read. */ const FIRST_INSTANT_AFTER_TRANSITION_SEARCH_DATE = POLYFILL_TRANSITION_SEARCH_FLOOR + 2n * NANOSECONDS_PER_DAY; const UNIX_EPOCH_DATE = new Temporal.PlainDate(1970, 1, 1); const UTC_REFERENCE = new Temporal.ZonedDateTime(0n, "UTC"); const TIME_SEPARATOR = /^[^[]*[Tt ]/; const UTC_OFFSET = /^[^[]*[Tt ][^[]*[+\-−]/; /** RFC 9557 offset with a seconds field — TC39 `ToTemporalZonedDateTime` then matches exactly. */ const UTC_OFFSET_WITH_SECONDS = /^[^[]*[Tt ][^[+\-−]*[+\-−]\d{2}:?\d{2}:?\d{2}/; /** A UTC designator (`Z` or `z`) ends the date-time before the bracketed annotations. */ const UTC_DESIGNATOR = /^[^[]*[Zz]\[/; function epochDays(date) { return UNIX_EPOCH_DATE.until(date.withCalendar("iso8601"), { largestUnit: "day" }).days; } /** * True when the date part of a wall clock is inside the TC39 `CheckISODaysRange` limit, which * Temporal applies to the local date (not only the instant) under `prefer` and `reject`. * * @example isWithinIsoDaysRange(Temporal.PlainDateTime.from("-271821-04-20T00:00:00")) // true * @example isWithinIsoDaysRange(Temporal.PlainDateTime.from("-271821-04-19T23:59:00")) // false */ function isWithinIsoDaysRange(wall) { return Math.abs(epochDays(wall.toPlainDate())) <= MAX_ISO_EPOCH_DAYS; } /** True for a date within `EDGE_WINDOW_DAYS` of either TC39 date limit. */ function isNearRangeEdge(date) { return Math.abs(epochDays(date)) >= MAX_ISO_EPOCH_DAYS - EDGE_WINDOW_DAYS; } /** Offset time zones (`+10:00`) and `UTC` never consult tz data, so neither defect reaches them. */ function isNamedTimeZone(timeZone) { return timeZone !== "UTC" && !timeZone.startsWith("+") && !timeZone.startsWith("-"); } /** TC39 `IsValidEpochNanoseconds`. */ function isValidEpoch(epochNanoseconds) { return epochNanoseconds >= -8640000000000000000000n && epochNanoseconds <= 8640000000000000000000n; } function clampEpoch(epochNanoseconds) { if (epochNanoseconds < -8640000000000000000000n) return MIN_EPOCH_NANOSECONDS; if (epochNanoseconds > 8640000000000000000000n) return MAX_EPOCH_NANOSECONDS; return epochNanoseconds; } /** UTC offset in force at an instant, reading the nearest limit for an instant outside the range. */ function offsetAt(timeZone, epochNanoseconds) { return BigInt(new Temporal.ZonedDateTime(clampEpoch(epochNanoseconds), timeZone).offsetNanoseconds); } /** TC39 `GetUTCEpochNanoseconds`: the wall clock read as if it were UTC (may lie outside the range). */ function utcEpochNanoseconds(wall) { const days = BigInt(epochDays(wall.toPlainDate())); const timeOfDay = BigInt(wall.hour) * 3600000000000n + BigInt(wall.minute) * NANOSECONDS_PER_MINUTE + BigInt(wall.second) * 1000000000n + BigInt(wall.millisecond) * 1000000n + BigInt(wall.microsecond) * 1000n + BigInt(wall.nanosecond); return days * NANOSECONDS_PER_DAY + timeOfDay; } /** TC39 `CheckISODaysRange`. */ function checkISODaysRange(date) { if (Math.abs(epochDays(date)) > 1e8) throw new RangeError(`${date.toString()} is outside the supported range`); } /** * TC39 `GetPossibleEpochNanoseconds` for a named zone, with 05ce7a3's clamp: the exact times whose * wall clock in `timeZone` is `wall`, ascending — none in a gap, two in an overlap. * * @throws RangeError when a matching exact time lies outside the representable range */ function possibleEpochNanoseconds(timeZone, wall) { const isoWall = wall.withCalendar("iso8601"); const utc = utcEpochNanoseconds(isoWall); const offsetBefore = offsetAt(timeZone, utc - NANOSECONDS_PER_DAY); const offsetAfter = offsetAt(timeZone, utc + NANOSECONDS_PER_DAY); const offsets = offsetBefore === offsetAfter ? [offsetBefore] : [offsetBefore, offsetAfter]; const candidates = []; for (const offset of offsets) { const candidate = utc - offset; if (!isValidEpoch(candidate)) { if (offsetAt(timeZone, candidate) === offset) throw new RangeError(`${isoWall.toString()} in ${timeZone} is outside the supported range`); continue; } const resolved = new Temporal.ZonedDateTime(candidate, timeZone).toPlainDateTime(); if (Temporal.PlainDateTime.compare(resolved, isoWall) === 0) candidates.push(candidate); } return candidates; } /** TC39 `DisambiguatePossibleEpochNanoseconds`. */ function disambiguatePossibleEpochNanoseconds(possible, timeZone, wall, disambiguation) { if (possible.length === 1) return possible[0]; if (disambiguation === "reject") throw new RangeError(`${wall.toString()} in ${timeZone} is ambiguous or does not exist`); if (possible.length > 1) return disambiguation === "later" ? possible[possible.length - 1] : possible[0]; const isoWall = wall.withCalendar("iso8601"); const utc = utcEpochNanoseconds(isoWall); const shift = Number(offsetAt(timeZone, utc + NANOSECONDS_PER_DAY) - offsetAt(timeZone, utc - NANOSECONDS_PER_DAY)); const shifted = disambiguation === "earlier" ? possibleEpochNanoseconds(timeZone, isoWall.subtract({ nanoseconds: shift })) : possibleEpochNanoseconds(timeZone, isoWall.add({ nanoseconds: shift })); if (shifted.length === 0) throw new RangeError(`${wall.toString()} in ${timeZone} cannot be resolved`); return disambiguation === "earlier" ? shifted[0] : shifted[shifted.length - 1]; } /** TC39 `GetEpochNanosecondsFor`. */ function epochNanosecondsFor(timeZone, wall, disambiguation) { return disambiguatePossibleEpochNanoseconds(possibleEpochNanoseconds(timeZone, wall), timeZone, wall, disambiguation); } /** * The first instant at or after `low` whose offset is `offset`, given that `low` has a different * offset and `high` has `offset`: the transition between them, to the nanosecond. */ function transitionBetween(timeZone, low, high, offset) { if (offsetAt(timeZone, high) !== offset || offsetAt(timeZone, low) === offset) throw new RangeError(`No transition in ${timeZone} between the bounds`); let before = low; let after = high; for (let step = 0; step < MAX_BISECTION_STEPS && after - before > 1n; step++) { const middle = (before + after) / 2n; if (offsetAt(timeZone, middle) === offset) after = middle; else before = middle; } if (after - before > 1n) throw new RangeError(`Transition in ${timeZone} not found`); return after; } /** * TC39 `GetStartOfDay`: the first valid wall-clock time on `date` in `timeZone` — midnight, or, * when midnight is skipped, the transition that skips it. */ function startOfDayEpochNanoseconds(timeZone, date) { const midnight = date.withCalendar("iso8601").toPlainDateTime(); const possible = possibleEpochNanoseconds(timeZone, midnight); if (possible.length > 0) return possible[0]; const utc = utcEpochNanoseconds(midnight); const offsetBefore = offsetAt(timeZone, utc - NANOSECONDS_PER_DAY); const offsetAfter = offsetAt(timeZone, utc + NANOSECONDS_PER_DAY); return transitionBetween(timeZone, clampEpoch(utc - offsetAfter), clampEpoch(utc - offsetBefore), offsetAfter); } /** * True when a start of day on this local date — or, for a zoned value, on its own local date — * may lie before the polyfill's transition search floor, so the polyfill's `GetStartOfDay` can * miss a transition that skips it. A zoned value from 1847-01-03T00:00Z on reads no offset. */ function isBeforePolyfillTransitionSearch(value) { if (value instanceof Temporal.ZonedDateTime) return value.epochNanoseconds < FIRST_INSTANT_AFTER_TRANSITION_SEARCH_DATE && isBeforePolyfillTransitionSearch(value.toPlainDate()); return Temporal.PlainDate.compare(value, LAST_DATE_BEFORE_TRANSITION_SEARCH) <= 0; } /** True when no instant in `timeZone` has `date`'s midnight as its wall time (it is skipped). */ function isMidnightSkipped(timeZone, date) { try { return possibleEpochNanoseconds(timeZone, date.withCalendar("iso8601").toPlainDateTime()).length === 0; } catch { return false; } } /** * True when the polyfill's `GetStartOfDay` cannot be trusted for this date in a named zone: it * lies before the transition search floor (defect 3), or its midnight is skipped while the * runtime's transition search can miss the change that skips it (defect 5). A midnight that exists * never reaches that search, so the polyfill's answer stands for it. */ function needsOwnStartOfDaySearch(timeZone, value) { if (isBeforePolyfillTransitionSearch(value)) return true; if (!isTransitionSearchCompatNeeded()) return false; return isMidnightSkipped(timeZone, value instanceof Temporal.ZonedDateTime ? value.toPlainDate() : value); } /** * `needsOwnStartOfDaySearch` for a measure that also reads the next day's start (`hoursInDay`, * rounding to the day). */ function needsOwnDayBoundsSearch(timeZone, zoned) { if (needsOwnStartOfDaySearch(timeZone, zoned)) return true; if (!isTransitionSearchCompatNeeded()) return false; try { return isMidnightSkipped(timeZone, zoned.toPlainDate().add({ days: 1 })); } catch { return false; } } /** * The first transition after `epochNanoseconds` in a named zone when it lies before the polyfill's * search floor, which `getTimeZoneTransition("next")` skips; null for any instant at or after the * floor, or when the offset is the same at both ends (then no zone changes in between, pinned by * the all-zones test in `zonedWallClock.test.ts`, and the polyfill's own answer stands). */ function missedNextTransition(timeZone, epochNanoseconds) { if (epochNanoseconds >= -3881520000000000000n) return null; const floorOffset = offsetAt(timeZone, POLYFILL_TRANSITION_SEARCH_FLOOR); if (offsetAt(timeZone, epochNanoseconds) === floorOffset) return null; return transitionBetween(timeZone, epochNanoseconds, POLYFILL_TRANSITION_SEARCH_FLOOR, floorOffset); } /** * The last transition strictly before `epochNanoseconds` and before the polyfill's search floor, * for a named zone where `getTimeZoneTransition("previous")` found none; null when the offset * never changes between the minimum instant and there. */ function missedPreviousTransition(timeZone, epochNanoseconds) { const high = epochNanoseconds - 1n < -3881520000000000000n ? epochNanoseconds - 1n : POLYFILL_TRANSITION_SEARCH_FLOOR; if (high <= -8640000000000000000000n) return null; const highOffset = offsetAt(timeZone, high); if (offsetAt(timeZone, -8640000000000000000000n) === highOffset) return null; return transitionBetween(timeZone, MIN_EPOCH_NANOSECONDS, high, highOffset); } /** TC39 `RoundNumberToIncrement(value, 1 minute, "half-expand")`. */ function roundToMinute(nanoseconds) { const sign = nanoseconds < 0n ? -1n : 1n; const magnitude = nanoseconds * sign; const quotient = magnitude / NANOSECONDS_PER_MINUTE; return (magnitude % NANOSECONDS_PER_MINUTE * 2n >= NANOSECONDS_PER_MINUTE ? quotient + 1n : quotient) * NANOSECONDS_PER_MINUTE * sign; } function matchingCandidate(possible, wall, offset, matchMinutes) { if (typeof offset === "string") return null; const utc = utcEpochNanoseconds(wall); for (const candidate of possible) { const candidateOffset = utc - candidate; if (candidateOffset === offset.nanoseconds || matchMinutes && roundToMinute(candidateOffset) === offset.nanoseconds) return candidate; } return null; } /** TC39 `InterpretISODateTimeOffset` for a named zone and a wall clock with a time of day. */ function interpretISODateTimeOffset(timeZone, wall, offset, disambiguation, offsetOption, matchMinutes) { const isoWall = wall.withCalendar("iso8601"); if (offset === "absent" || offsetOption === "ignore") return epochNanosecondsFor(timeZone, isoWall, disambiguation); if (offsetOption === "use") { const exact = offset === "out-of-range" ? null : utcEpochNanoseconds(isoWall) - offset.nanoseconds; if (exact === null || !isValidEpoch(exact)) throw new RangeError(`${isoWall.toString()} is outside the supported range`); return exact; } checkISODaysRange(isoWall.toPlainDate()); const possible = possibleEpochNanoseconds(timeZone, isoWall); const matched = matchingCandidate(possible, isoWall, offset, matchMinutes); if (matched !== null) return matched; if (offsetOption === "reject") throw new RangeError(`The offset is invalid for ${isoWall.toString()} in ${timeZone}`); return disambiguatePossibleEpochNanoseconds(possible, timeZone, isoWall, disambiguation); } /** Validates Temporal options exactly as `ZonedDateTime.from` does, without resolving anything. */ function validateFromOptions(options) { Temporal.ZonedDateTime.from(UTC_REFERENCE, options); } /** A zone id as Temporal canonicalizes it, from an identifier or any RFC 9557 string. */ function timeZoneIdOf(timeZoneLike) { return UTC_REFERENCE.withTimeZone(timeZoneLike).timeZoneId; } /** Offset nanoseconds of a UTC offset string (`"+10:00"`, `"-04:56:02"`), parsed by Temporal. */ function utcOffsetStringNanoseconds(offset) { return -Temporal.ZonedDateTime.from({ year: 1970, month: 1, day: 1, timeZone: "UTC", offset }, { offset: "use" }).epochNanoseconds; } /** * TC39 `ToTemporalZonedDateTime` for a zoned string in a named zone, from the wall clock and * zone Temporal has already parsed: the epoch nanoseconds the string names. Used where the * polyfill's own answer is unusable: near the range limits (defect 1) and for an offset written * with seconds (defect 4). */ function stringEpochAtEdge(item, timeZone, wall, options) { if (!TIME_SEPARATOR.test(item)) return startOfDayEpochNanoseconds(timeZone, wall.toPlainDate()); const disambiguation = stringOptionOrDefault(options?.disambiguation, "compatible"); if (!UTC_OFFSET.test(item)) return epochNanosecondsFor(timeZone, wall, disambiguation); let offset; try { offset = { nanoseconds: utcEpochNanoseconds(wall) - Temporal.Instant.from(item).epochNanoseconds }; } catch { offset = "out-of-range"; } return interpretISODateTimeOffset(timeZone, wall, offset, disambiguation, stringOptionOrDefault(options?.offset, "reject"), !UTC_OFFSET_WITH_SECONDS.test(item)); } function fromStringAtEdge(item, options) { let wall; let timeZone; try { validateFromOptions(options); wall = Temporal.PlainDateTime.from(item); timeZone = timeZoneIdOf(item); } catch { return null; } if (!isNamedTimeZone(timeZone) || !isNearRangeEdge(wall.toPlainDate())) return null; const epoch = stringEpochAtEdge(item, timeZone, wall.withCalendar("iso8601"), options); return new Temporal.ZonedDateTime(epoch, timeZone, wall.calendarId); } /** The offset a property bag carries, parsed by Temporal itself. */ function bagOffset(offset) { return offset === void 0 ? "absent" : { nanoseconds: utcOffsetStringNanoseconds(offset) }; } function fromBagAtEdge(item, options) { let wall; let timeZone; let offset; try { validateFromOptions(options); wall = Temporal.PlainDateTime.from(item, { overflow: options?.overflow }); timeZone = timeZoneIdOf(String(item.timeZone)); offset = bagOffset(item.offset); } catch { return null; } if (!isNamedTimeZone(timeZone) || !isNearRangeEdge(wall.toPlainDate())) return null; const epoch = interpretISODateTimeOffset(timeZone, wall, offset, stringOptionOrDefault(options?.disambiguation, "compatible"), stringOptionOrDefault(options?.offset, "reject"), false); return new Temporal.ZonedDateTime(epoch, timeZone, wall.calendarId); } /** * A date-only zoned string (TC39: its start of day) whose date is on or before 1847-01-01 in a * named zone, resolved with GMT's own `GetStartOfDay` (defect 3); null for anything else. */ function dateOnlyBeforeTransitionSearch(item, options) { if (TIME_SEPARATOR.test(item)) return null; let date; let timeZone; try { validateFromOptions(options); date = Temporal.PlainDate.from(item); timeZone = timeZoneIdOf(item); } catch { return null; } if (!isNamedTimeZone(timeZone) || !needsOwnStartOfDaySearch(timeZone, date)) return null; return new Temporal.ZonedDateTime(startOfDayEpochNanoseconds(timeZone, date), timeZone, date.calendarId); } /** * The polyfill's result for a zoned string, or the TC39 result when the polyfill matched an * offset written with seconds by minutes (defect 4, temporalCompat D12). * * Dormant unless the D12 probe fails. Then it acts only on a string whose offset has a seconds * part, read with `offset: "reject"` or `"prefer"` (the two options that match the offset * against the zone), whose result has a sub-minute offset: any other result was matched exactly, * because an earlier candidate would have matched by rounding first. For those it recomputes * `InterpretISODateTimeOffset` with match-exactly, which throws a `RangeError` under `"reject"` * when no candidate has the written offset. */ function matchSecondsOffsetExactly(item, zoned, options) { if (!UTC_OFFSET_WITH_SECONDS.test(item) || BigInt(zoned.offsetNanoseconds) % NANOSECONDS_PER_MINUTE === 0n || options?.offset === "use" || options?.offset === "ignore" || !isSecondsOffsetMatchCompatNeeded()) return zoned; const wall = Temporal.PlainDateTime.from(item).withCalendar("iso8601"); const epoch = stringEpochAtEdge(item, zoned.timeZoneId, wall, options); return epoch === zoned.epochNanoseconds ? zoned : new Temporal.ZonedDateTime(epoch, zoned.timeZoneId, zoned.calendarId); } /** * The options to read `item` with: `offset: "use"` in place of `"ignore"` for a string with a UTC * designator (defect 6, temporalCompat D15). TC39 reads `Z` as an exact instant under every * `offset` value, and `"use"` is that reading. Dormant unless the D15 probe fails. */ function zExactOptions(item, options) { return options?.offset === "ignore" && UTC_DESIGNATOR.test(item) && isZIgnoreExactCompatNeeded() ? { ...options, offset: "use" } : options; } /** * `Temporal.ZonedDateTime.from`, correct across the whole representable range. * * Returns the polyfill's result whenever it has one. When the polyfill throws for a named zone * within a month of either range limit, the TC39 result is recomputed (see the note at the top * of this file); every other failure re-throws the polyfill's own error. A string whose offset * is written with seconds is matched exactly, as TC39 requires (`matchSecondsOffsetExactly`), and * a string with a `Z` designator is an exact instant under every `offset` option (`zExactOptions`). * * @param item RFC 9557 zoned string or ZonedDateTime-like property bag * @param callerOptions Temporal `disambiguation` / `offset` / `overflow` * @returns the resolved Temporal.ZonedDateTime; throws where TC39 Temporal throws */ function zonedDateTimeFrom(item, callerOptions) { const options = typeof item === "string" ? zExactOptions(item, callerOptions) : callerOptions; const dateOnly = typeof item === "string" ? dateOnlyBeforeTransitionSearch(item, options) : null; if (dateOnly !== null) return dateOnly; try { const zoned = Temporal.ZonedDateTime.from(item, options); return typeof item === "string" ? matchSecondsOffsetExactly(item, zoned, options) : zoned; } catch (error) { const recovered = typeof item === "string" ? fromStringAtEdge(item, options) : fromBagAtEdge(item, options); if (recovered === null) throw error; return recovered; } } /** * The check behind `isValidZonedDateTime`: the ISO calendar `ZonedDateTime` a zoned string names, * or `null`. * * The string must have GMT's strict extended shape and no second 60, then `zonedDateTimeFrom` * reads it. The zone id must be non-empty and the calendar ISO. * * @param value the candidate; a value that is not a string is not a zoned date-time * @returns the `ZonedDateTime` `zonedDateTimeFrom` returns for it, else `null` * * @example zonedDateTimeOf("2024-03-10T12:00:00+00:00[UTC]")?.timeZoneId // "UTC" * @example zonedDateTimeOf("2024-03-10T12:00:00") // null * @example zonedDateTimeOf(null) // null */ function zonedDateTimeOf(value) { if (typeof value !== "string" || value.length === 0) return null; if (hasSecond60Field(value) || !hasZonedDateTimeShape(value)) return null; try { const zonedDateTime = zonedDateTimeFrom(value); return zonedDateTime.timeZoneId.length > 0 && zonedDateTime.calendarId === "iso8601" ? zonedDateTime : null; } catch { return null; } } /** * Every value in `values` that `zonedDateTimeOf` reads, in order, each parsed once. A value that * is not a zoned date-time is left out, and so is an empty slot of a sparse array. * * @param values the candidates * @returns the `ZonedDateTime` of each valid candidate * * @example zonedDateTimesOf(["2024-03-10T12:00:00+00:00[UTC]", "bad"]).length // 1 * @example zonedDateTimesOf([]).length // 0 */ function zonedDateTimesOf(values) { const parsed = []; values.forEach((value) => { const zonedDateTime = zonedDateTimeOf(value); if (zonedDateTime !== null) parsed.push(zonedDateTime); }); return parsed; } export { MAX_TRANSITIONS_BEFORE_MAXIMUM, NEXT_TRANSITION_HORIZON_NANOSECONDS, POLYFILL_TRANSITION_SEARCH_FLOOR, UTC_OFFSET_WITH_SECONDS, epochNanosecondsFor, interpretISODateTimeOffset, isNamedTimeZone, isNearRangeEdge, isValidEpoch, isWithinIsoDaysRange, missedNextTransition, missedPreviousTransition, needsOwnDayBoundsSearch, needsOwnStartOfDaySearch, offsetAt, possibleEpochNanoseconds, roundToMinute, startOfDayEpochNanoseconds, timeZoneIdOf, transitionBetween, utcEpochNanoseconds, utcOffsetStringNanoseconds, zonedDateTimeFrom, zonedDateTimeOf, zonedDateTimesOf };