@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.
324 lines (322 loc) • 12.5 kB
JavaScript
import { Temporal } from "./temporal.js";
import { computationCalendarId } from "./calendarSystemIds.js";
// src/internal/weekYearText.ts
const ANY_DIGIT = /\p{Nd}/u;
/**
* The digit runs of `text`, walked by code point: Adlam, Chakma and other digit sets lie outside
* the Basic Multilingual Plane.
*/
function digitRuns(text, digits) {
const runs = [];
let start = -1;
let index = 0;
for (const character of text) {
const isDigit = digits.has(character) || ANY_DIGIT.test(character);
if (isDigit && start < 0) start = index;
else if (!isDigit && start >= 0) {
runs.push({
start,
end: index,
text: text.slice(start, index)
});
start = -1;
}
index += character.length;
}
if (start >= 0) runs.push({
start,
end: index,
text: text.slice(start, index)
});
return runs;
}
/** The number of code points in `text`. */
function codePointLength(text) {
return [...text].length;
}
/** The last two code points of `text`. */
function lastTwo(text) {
return [...text].slice(-2).join("");
}
const MAX_CACHED = 64;
const digitSets = /* @__PURE__ */ new Map();
const references = /* @__PURE__ */ new Map();
/** Forget every digit set and reference formatter (a replaced `Intl`, a test seam). */
function forgetWeekYearText() {
digitSets.clear();
references.clear();
}
/** The digits 0 to 9 of a numbering system, by value. */
function digitsOf(numberingSystem) {
let digits = digitSets.get(numberingSystem);
if (digits === void 0) {
digits = [...new Intl.NumberFormat("und", {
numberingSystem,
useGrouping: false
}).format(9876543210)].reverse();
if (digitSets.size >= MAX_CACHED) digitSets.clear();
digitSets.set(numberingSystem, digits);
}
return digits;
}
/** The set of a numbering system's digit characters. */
function digitSetOf(numberingSystem) {
return new Set(digitsOf(numberingSystem));
}
/** The reference for a calendar, numbering system and time zone, built once. */
function referenceFor(calendar, numberingSystem, timeZone) {
const key = `${calendar}|${numberingSystem}|${timeZone}`;
let reference = references.get(key);
if (reference === void 0) {
reference = {
format: new Intl.DateTimeFormat("und", {
calendar,
numberingSystem,
year: "numeric",
timeZone
}),
digits: digitSetOf(numberingSystem)
};
if (references.size >= MAX_CACHED) references.clear();
references.set(key, reference);
}
return reference;
}
const LETTER = /\p{L}/u;
/**
* The digit runs of `text` that can be its year. `text` is always root (`und`) text, from
* `referenceFor` or the range check's era formatter (`weekYearRange.ts`). Root data can add an
* era to the year, and the era is a name (UTS #35 Part 4 §8, `G`): ICU data without coptic or
* ethiopic era names prints the placeholder `ERA0` or `ERA1` ("1740 ERA1"). No current host does
* (Node 26.12.1 prints `1740 AM`, `7516 AA`, and `6 Reiwa` for the japanese calendar). So when
* there is more than one run, a run inside a word is part of a name; a lone run is the year even
* beside a letter.
*/
function yearRunsOf(text, digits) {
const runs = digitRuns(text, digits);
if (runs.length <= 1) return runs;
const free = runs.filter((run) => !LETTER.test(text.slice(0, run.start).slice(-1)) && !LETTER.test(text.slice(run.end, run.end + 1)));
return free.length > 0 ? free : runs;
}
/** The calendar year the reference prints at `ms`, or `null` when it prints no single number. */
function referenceYear(reference, ms) {
const runs = yearRunsOf(reference.format.format(ms), reference.digits);
return runs.length === 1 ? runs[0]?.text ?? null : null;
}
/** An era-and-year text with its year removed, so two eras compare by name alone. */
function withoutYear(text, digits) {
let rest = text;
for (const run of yearRunsOf(text, digits).reverse()) rest = rest.slice(0, run.start) + rest.slice(run.end);
return rest;
}
/**
* The calendar year of a mid-year date, the anchor every probe date is counted from. The year is
* the computation calendar's (`ethioaa` for `coptic` and `ethiopic`, `computationCalendarId`): the
* polyfill (0.5.1) throws "Era am ... was not matched by any era" for every `coptic` and
* `ethiopic` date. Probe years are only counted from it and passed to `dateIn`, never printed.
*/
function anchorYear(calendar) {
return Temporal.PlainDate.from("2024-07-01").withCalendar(computationCalendarId(calendar)).year;
}
/** The date `month` / `day` of `year` in a calendar, `year` counted as `anchorYear` counts it. */
function dateIn(calendar, year, month, day) {
return Temporal.PlainDate.from({
calendar: computationCalendarId(calendar),
year,
month,
day
});
}
/**
* The indexes of the digit runs that hold the year, or `null` when the run count changes between
* the three probe dates.
*
* A year run is equal a week apart in mid-January and different in the first following year whose
* 15 January falls on the same weekday: equal weekdays keep a weekday name with digits (luy `J4`)
* out of the set.
*
* @param runsAt the formatter's digit runs at a date
*/
function yearRunIndexes(calendar, runsAt) {
const first = anchorYear(calendar);
const january = dateIn(calendar, first, 1, 15);
let other = dateIn(calendar, first + 1, 1, 15);
for (let step = 1; step <= 14 && other.dayOfWeek !== january.dayOfWeek;) {
other = dateIn(calendar, first + step, 1, 15);
step++;
}
const base = runsAt(january);
const week = runsAt(january.add({ days: 7 }));
const year = runsAt(other);
if (base.length !== week.length || base.length !== year.length) return null;
return base.flatMap((run, index) => run.text === week[index]?.text && run.text !== year[index]?.text ? [index] : []);
}
/** The style of a year run read at mid-year, against the reference's year `year` there. */
function styleOf(run, year) {
return (year === null ? null : styleAgainst(run, year)) ?? { kind: codePointLength(run) === 2 ? "two" : "full" };
}
/** The style of a run that matches the reference year in some form, or `null`. */
function styleAgainst(run, year) {
if (run === year) return { kind: "full" };
if (codePointLength(run) === 2 && (run === lastTwo(year) || [...run][1] === year)) return { kind: "two" };
if (run.length > year.length && run.startsWith(year)) return {
kind: "full",
glued: "start",
rest: run.length - year.length
};
if (run.length > year.length && run.endsWith(year)) return {
kind: "full",
glued: "end",
rest: run.length - year.length
};
return null;
}
const PERTURBED_FIELDS = [
["day", { days: 1 }],
["month", { months: 1 }],
["hour", { hours: 1 }],
["minute", { minutes: 1 }],
["second", { seconds: 1 }],
["fractionalSecond", { milliseconds: 1 }]
];
/**
* Read a formatter's digit runs once: which hold the year, how each is written, and what field
* every other one holds. Only `format` is called, on the formatter itself, in its zone and with its
* time fields, and its text read through `mask`. `null` when the run count changes between probe
* dates.
*/
function analyse(format, resolved, mask) {
const calendar = resolved.calendar;
const timeZone = resolved.timeZone;
const numberingSystem = resolved.numberingSystem;
const digits = digitSetOf(numberingSystem);
const reference = referenceFor(calendar, numberingSystem, timeZone);
const zoned = (date) => date.toZonedDateTime({
timeZone,
plainTime: "10:20:30.456"
});
const runsOf = (ms) => digitRuns(mask(format(ms), ms), digits);
const runsAt = (date) => runsOf(zoned(date).epochMilliseconds);
const yearRuns = yearRunIndexes(calendar, runsAt);
if (yearRuns === null) return null;
const first = anchorYear(calendar);
const midYear = zoned(dateIn(calendar, first, 6, 1)).epochMilliseconds;
const midRuns = runsOf(midYear);
const midYearText = referenceYear(reference, midYear);
const styles = yearRuns.map((index) => styleOf(midRuns[index]?.text ?? "", midYearText));
const start = zoned(dateIn(calendar, first, 1, 15));
const base = runsOf(start.epochMilliseconds);
const moved = PERTURBED_FIELDS.map(([field, amount]) => ({
field,
runs: runsOf(start.add(amount).epochMilliseconds)
}));
return {
calendar,
timeZone,
numberingSystem,
digits,
reference,
yearRuns,
styles,
labels: base.map((run, index) => {
if (yearRuns.includes(index)) return "year";
const changed = moved.filter((entry) => entry.runs.length === base.length && entry.runs[index]?.text !== run.text);
const [only] = changed;
return changed.length === 1 && only !== void 0 ? only.field : changed.length === 0 ? "literal" : "text";
}),
count: base.length,
mask
};
}
/** The year as ECMA-402 writes it for a style: `numeric` is the reference's run, `2-digit` its last two digits, padded. */
function yearText(analysis, ms, style) {
const year = referenceYear(analysis.reference, ms);
if (year === null || style.kind === "full") return year;
return codePointLength(year) >= 2 ? lastTwo(year) : (digitsOf(analysis.numberingSystem)[0] ?? "0") + year;
}
/**
* `text` with every year run holding the calendar year, or `null` when the run count differs from
* the analysis (the text has a shape it did not read: the data canary fails on any such date, so a
* CLDR change that causes one is caught, not shipped).
*/
function repairText(analysis, text, ms) {
const runs = digitRuns(analysis.mask(text, ms), analysis.digits);
if (runs.length !== analysis.count) return null;
let out = "";
let position = 0;
const edits = [];
for (const [n, index] of analysis.yearRuns.entries()) {
const style = analysis.styles[n];
const run = runs[index];
const value = style === void 0 ? null : yearText(analysis, ms, style);
if (style === void 0 || run === void 0 || value === null) return null;
let from = run.start;
let to = run.end;
if (style.glued === "start") to = run.end - (style.rest ?? 0);
else if (style.glued === "end") from = run.start + (style.rest ?? 0);
out += text.slice(position, from);
edits.push({
from,
to,
start: out.length,
end: out.length + value.length,
value
});
out += value;
position = to;
}
return {
text: out + text.slice(position),
edits,
runs
};
}
/**
* Native parts with each year run written as the `year` part holding the calendar year. WebKit
* types the week-year `unknown`; a part that holds more than the run (a year glued to another
* number) keeps its type and has the run's slice replaced.
*
* @returns the patched parts, or `null` when a run is split across parts or the patched parts do
* not read as the repaired text
*/
function patchYearParts(parts, repaired) {
let offset = 0;
const out = [];
for (const part of parts) {
const start = offset;
const end = start + part.value.length;
offset = end;
const inside = repaired.edits.filter((edit) => edit.from < end && edit.to > start);
let value = part.value;
for (const edit of inside.toReversed()) {
if (edit.from < start || edit.to > end) return null;
value = value.slice(0, edit.from - start) + edit.value + value.slice(edit.to - start);
}
const exact = inside.length === 1 && inside[0]?.from === start && inside[0].to === end;
out.push({
type: exact ? "year" : part.type,
value
});
}
return out.map((part) => part.value).join("") === repaired.text ? out : null;
}
/**
* Whether every year run at `date` still reads as it does at the inside date `mid`, where the
* calendar year is the same.
*
* A run printing the week-year differs at a year boundary; a run printing the calendar year does
* not. A year glued to another number is compared by the year inside it: the boundary run must hold
* the boundary date's calendar year in the same form (full or last two digits).
*/
function checkYearRuns(yearRuns, at, mid, yearAt, yearMid) {
return yearRuns.every((index) => runMoves(at[index]?.text ?? "", mid[index]?.text ?? "", yearAt, yearMid));
}
/** Whether one year run changes between the boundary and mid-year by exactly the year it holds. */
function runMoves(here, inside, yearAt, yearMid) {
if (here === inside) return true;
if (yearMid === null || yearAt === null) return false;
if (inside.includes(yearMid)) return inside.length > yearMid.length && here.includes(yearAt);
if (codePointLength(yearMid) > 2 && inside.includes(lastTwo(yearMid))) return codePointLength(inside) > 2 && here.includes(lastTwo(yearAt));
return false;
}
export { analyse, anchorYear, checkYearRuns, dateIn, digitRuns, digitSetOf, digitsOf, forgetWeekYearText, patchYearParts, referenceFor, referenceYear, repairText, withoutYear, yearRunIndexes };