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.

271 lines (269 loc) • 11.5 kB
import { MAX_EPOCH_NANOSECONDS, MIN_EPOCH_NANOSECONDS } from "./epochNanoseconds.js"; import { nowInstant } from "./temporalCompat/clock.js"; import { POLYFILL_TRANSITION_SEARCH_FLOOR, missedNextTransition, missedPreviousTransition, offsetAt, transitionBetween } from "./zonedWallClock.js"; // src/internal/zonedTransitionSearch.ts const NANOSECONDS_PER_SECOND = 1000000000n; const NANOSECONDS_PER_DAY = 86400n * NANOSECONDS_PER_SECOND; /** * The sampling step: 5 days. It must stay under the smallest gap between two offset changes of * one zone, 601,200 s in tz 2026c (`zdump -v`, America/Boa_Vista 2000-10-08 to 2000-10-15). */ const TRANSITION_SEARCH_STEP_NANOSECONDS = 432000n * NANOSECONDS_PER_SECOND; /** * js-temporal `GetNamedTimeZoneNextTransition`: "the farthest that we'll look for a next * transition is 3 years after the later of epochNanoseconds or the current time" * (`DAY_MS * 366 * 3`). */ const NO_FURTHER_TRANSITION_HORIZON_NANOSECONDS = 3n * 366n * NANOSECONDS_PER_DAY; /** Steps one search may take: 200,000 five-day steps is 2,700 years. */ const MAX_SEARCH_STEPS = 2e5; /** Forward searches when walking a zone's tabled future changes; Africa/Casablanca has about 120. */ const MAX_TABLED_TRANSITIONS = 1e3; /** Halvings to pin a whole second inside one step: 2^19 s is more than 5 days. */ const MAX_SECOND_BISECTION_STEPS = 20; function minimum(a, b) { return a < b ? a : b; } function maximum(a, b) { return a > b ? a : b; } function floorSecond(epochNanoseconds) { const seconds = epochNanoseconds / NANOSECONDS_PER_SECOND; return epochNanoseconds % NANOSECONDS_PER_SECOND < 0n ? seconds - 1n : seconds; } /** * The one change in `(low, high]`, given that the offsets at the two ends differ and the window is * no longer than a step. tz changes fall on whole seconds (RFC 9636 §3.2 stores transition times in * seconds), so the search runs over seconds; the result is checked one nanosecond earlier, and a * change that is not on a whole second is pinned to the nanosecond instead. */ function changeBetween(timeZone, low, high, lowOffset, highOffset) { let before = floorSecond(low); let after = floorSecond(high); for (let i = 0; i < MAX_SECOND_BISECTION_STEPS && after - before > 1n; i++) { const middle = (before + after) / 2n; if (offsetAt(timeZone, middle * NANOSECONDS_PER_SECOND) === lowOffset) before = middle; else after = middle; } const change = after * NANOSECONDS_PER_SECOND; if (after - before === 1n && change > low && offsetAt(timeZone, change) === highOffset && offsetAt(timeZone, change - 1n) === lowOffset) return change; return transitionBetween(timeZone, low, high, highOffset); } /** Zones remembered; the oldest is dropped past this. */ const MAX_MEMO_ZONES = 64; /** Changes remembered per zone; past this the zone's facts are cleared. */ const MAX_MEMO_CHANGES = 4096; /** Spans remembered per zone; past this the zone's facts are cleared. */ const MAX_MEMO_SPANS = 256; const transitionMemo = /* @__PURE__ */ new Map(); /** Forget every remembered span. Internal; tests call it to start from a cold memo. */ function clearTransitionMemo() { transitionMemo.clear(); } /** Two sorted arrays merged into one sorted array, a value in both kept once. */ function mergeSorted(a, b) { const merged = []; let i = 0; let j = 0; while (i < a.length && j < b.length) { const left = a[i]; const right = b[j]; if (left < right) { merged.push(left); i++; } else if (left > right) { merged.push(right); j++; } else { merged.push(left); i++; j++; } } while (i < a.length) merged.push(a[i++]); while (j < b.length) merged.push(b[j++]); return merged; } /** Remember that (low, high] changes offset exactly at `changes` and nowhere else. */ function recordSpan(timeZone, low, high, changes) { if (low >= high) return; let facts = transitionMemo.get(timeZone); if (facts === void 0) { if (transitionMemo.size >= MAX_MEMO_ZONES) { const oldest = transitionMemo.keys().next(); if (!oldest.done) transitionMemo.delete(oldest.value); } facts = { spans: [] }; transitionMemo.set(timeZone, facts); } let mergedLow = low; let mergedHigh = high; let mergedChanges = changes; const kept = []; const after = []; for (const span of facts.spans) if (span.high < low) kept.push(span); else if (span.low > high) after.push(span); else { mergedLow = minimum(mergedLow, span.low); mergedHigh = maximum(mergedHigh, span.high); mergedChanges = mergeSorted(mergedChanges, span.changes); } kept.push({ low: mergedLow, high: mergedHigh, changes: mergedChanges }); kept.push(...after); const total = kept.reduce((sum, span) => sum + span.changes.length, 0); facts.spans = kept.length > MAX_MEMO_SPANS || total > MAX_MEMO_CHANGES ? [{ low, high, changes: [...changes] }] : kept; } function spanAround(timeZone, holds) { return transitionMemo.get(timeZone)?.spans.find(holds); } function currentEpochNanoseconds() { return nowInstant().epochNanoseconds; } /** * TC39 `GetNamedTimeZoneNextTransition`: the first offset change strictly after `from`. * * @param timeZone a named zone * @param from the instant to search after (exclusive) * @param until optional: the last instant to search (inclusive); a later change returns null * @returns the change's epoch nanoseconds, or null when there is none up to `until` or none within * three years of the later of `from` and the current instant * @throws RangeError past `MAX_SEARCH_STEPS` steps */ function nextTransitionAfter(timeZone, from, until) { const end = minimum(MAX_EPOCH_NANOSECONDS, until !== void 0 && until <= from + NO_FURTHER_TRANSITION_HORIZON_NANOSECONDS ? until : minimum(until ?? 8640000000000000000000n, maximum(from, currentEpochNanoseconds()) + NO_FURTHER_TRANSITION_HORIZON_NANOSECONDS)); if (from >= end) return null; let low = from; if (low < -3881520000000000000n) { const missed = missedNextTransition(timeZone, low); if (missed !== null) return missed <= end ? missed : null; if (end <= -3881520000000000000n) return null; low = POLYFILL_TRANSITION_SEARCH_FLOOR; } return sampledNext(timeZone, low, end); } /** The first change in `(low, end]`, answered from the memo where it can be, else sampled. */ function sampledNext(timeZone, from, end) { const cutoff = from + BigInt(MAX_SEARCH_STEPS) * TRANSITION_SEARCH_STEP_NANOSECONDS; let low = from; const known = spanAround(timeZone, (span) => span.low <= low && low < span.high); if (known !== void 0) { const change = known.changes.find((c) => c > low); if (change !== void 0) { if (change <= minimum(end, cutoff)) return change; if (end <= cutoff) return null; throw outOfSteps(timeZone); } if (known.high >= end) { if (end <= cutoff) return null; throw outOfSteps(timeZone); } low = known.high; if (low >= cutoff) throw outOfSteps(timeZone); } const searchStart = low; const lowOffset = offsetAt(timeZone, low); while (low < cutoff) { const high = minimum(minimum(low + TRANSITION_SEARCH_STEP_NANOSECONDS, end), cutoff); const highOffset = offsetAt(timeZone, high); if (highOffset !== lowOffset) { const change = changeBetween(timeZone, low, high, lowOffset, highOffset); recordSpan(timeZone, searchStart, change, [change]); return change; } if (high >= end) { recordSpan(timeZone, searchStart, end, []); return null; } low = high; } throw outOfSteps(timeZone); } function outOfSteps(timeZone) { return /* @__PURE__ */ new RangeError(`Transition search in ${timeZone} ran past its bound`); } /** The last change in `(since, start]`, scanning back from `start`; null when there is none. */ function lastChangeBack(timeZone, start, since) { const cutoff = start - BigInt(MAX_SEARCH_STEPS) * TRANSITION_SEARCH_STEP_NANOSECONDS; const reachesSince = start - since <= BigInt(199999) * TRANSITION_SEARCH_STEP_NANOSECONDS; let high = start; const known = spanAround(timeZone, (span) => span.low < start && start <= span.high); if (known !== void 0) { const change = known.changes.filter((c) => c <= start).pop(); if (change !== void 0 && change > maximum(since, cutoff)) return change; if (change !== void 0 || known.low <= since) { if (reachesSince) return null; throw outOfSteps(timeZone); } high = known.low; } const searchStart = high; let highOffset; for (;;) { if (high <= since) { if (!reachesSince) throw outOfSteps(timeZone); recordSpan(timeZone, since, searchStart, []); return null; } if (high <= cutoff) throw outOfSteps(timeZone); highOffset ??= offsetAt(timeZone, searchStart); const low = maximum(maximum(high - TRANSITION_SEARCH_STEP_NANOSECONDS, since), cutoff); const lowOffset = offsetAt(timeZone, low); if (lowOffset !== highOffset) { const change = changeBetween(timeZone, low, high, lowOffset, highOffset); recordSpan(timeZone, change - 1n, searchStart, [change]); return change; } high = low; } } /** * The last change before an instant more than three years past the current one. The polyfill's * rule: when the zone has no change between now and three years from now, there is none later, so * the answer is the last change before that horizon. A zone whose rules repeat has one in the * three years before `from`. Otherwise its future changes are a finite table (Africa/Casablanca, * to 2087), walked forward to its end. A change at or before `since` is not looked for. */ function previousTransitionFarAhead(timeZone, from, now, since) { const recentStart = from - NO_FURTHER_TRANSITION_HORIZON_NANOSECONDS; const recent = lastChangeBack(timeZone, from - 1n, since === void 0 ? recentStart : maximum(since, recentStart)); if (recent !== null) return recent; if (since !== void 0 && since >= recentStart) return null; let last = previousTransitionBefore(timeZone, now + NO_FURTHER_TRANSITION_HORIZON_NANOSECONDS, since); if (last === null || last < now) return last; for (let i = 0; i < MAX_TABLED_TRANSITIONS; i++) { const next = nextTransitionAfter(timeZone, last); if (next === null || next >= from) return last; last = next; } throw new RangeError(`Transition walk in ${timeZone} ran past its bound`); } /** * TC39 `GetNamedTimeZonePreviousTransition`: the last offset change strictly before `from`. * * @param timeZone a named zone * @param from the instant to search before (exclusive) * @param since optional: the search stops here (exclusive); an earlier change returns null * @returns the change's epoch nanoseconds, or null when there is none after `since`, or, with no * `since`, none at all * @throws RangeError past `MAX_SEARCH_STEPS` steps or `MAX_TABLED_TRANSITIONS` tabled changes */ function previousTransitionBefore(timeZone, from, since) { if (from <= -8640000000000000000000n) return null; const now = currentEpochNanoseconds(); if (from - 1n > now + NO_FURTHER_TRANSITION_HORIZON_NANOSECONDS) return previousTransitionFarAhead(timeZone, from, now, since); const floor = maximum(since ?? -3881520000000000000n, POLYFILL_TRANSITION_SEARCH_FLOOR); const found = from - 1n > floor ? lastChangeBack(timeZone, from - 1n, floor) : null; if (found !== null) return found; if (since !== void 0 && since >= -3881520000000000000n) return null; const missed = missedPreviousTransition(timeZone, from); return missed !== null && (since === void 0 || missed > since) ? missed : null; } export { TRANSITION_SEARCH_STEP_NANOSECONDS, clearTransitionMemo, nextTransitionAfter, previousTransitionBefore };