@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.
293 lines (291 loc) • 12.2 kB
JavaScript
import { Temporal } from "./temporal.js";
import { utcOffset } from "../regex/utc-offset.js";
import { formatUtcOffset, parseUtcOffsetNanoseconds } from "./utcOffsetString.js";
import { readInstantOffsetInstant } from "./offsetInstant.js";
// src/internal/hl7DateTime.ts
/**
* The seven precisions of an HL7 v2 date-time, coarsest first. Every "lower or raise" test in
* the parser and the formatter compares ranks (`hl7PrecisionRank`); nothing compares strings.
*/
const HL7_PRECISIONS = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"fraction"
];
/**
* The index of a precision in `HL7_PRECISIONS`, coarsest first.
*
* @param precision candidate precision
* @returns its rank, or `-1` for anything that is not one of the seven
*
* @example hl7PrecisionRank("year") // 0
* @example hl7PrecisionRank("fraction") // 6
* @example hl7PrecisionRank("Second") // -1
*/
function hl7PrecisionRank(precision) {
return HL7_PRECISIONS.indexOf(precision);
}
/**
* Table 0529, degree of precision (2.A.77.2): "(Y = year, L = month, D = day, H = hour,
* M = minute, S = second)". Upper case only; `"fraction"` has no letter.
*/
const HL7_DEGREE_OF_PRECISION = Object.freeze({
Y: "year",
L: "month",
D: "day",
H: "hour",
M: "minute",
S: "second"
});
/**
* The precision a Table 0529 degree letter names.
*
* @param degree candidate degree of precision
* @returns the precision, or `null` for anything but an own upper-case key (`"toString"` and
* `"__proto__"` included)
*
* @example hl7DegreePrecision("L") // "month"
* @example hl7DegreePrecision("l") // null
* @example hl7DegreePrecision("toString") // null
*/
function hl7DegreePrecision(degree) {
return typeof degree === "string" && Object.hasOwn(HL7_DEGREE_OF_PRECISION, degree) ? HL7_DEGREE_OF_PRECISION[degree] : null;
}
/**
* The HL7 null value: two U+0022 characters (ch. 2 §2.5.3, "transmitted as two double quote
* marks (\"\"), is different from omitting an optional data field").
*/
const HL7_NULL_VALUE = "\"\"";
const YYYY = "(?<year>[0-9]{4})";
const MM = "(?<month>[0-9]{2})";
const DD = "(?<day>[0-9]{2})";
const HH = "(?<hour>[0-9]{2})";
const MI = "(?<minute>[0-9]{2})";
const SS = "(?<second>[0-9]{2})";
const FRACTION = "\\.(?<fraction>[0-9]{1,4})";
const ZZZZ = "(?<sign>[+-])(?<offsetHour>[0-9]{2})(?<offsetMinute>[0-9]{2})";
/**
* The `DTM` grammar of 2.A.22, anchored. Named groups: `year month day hour minute second
* fraction sign offsetHour offsetMinute`. The longest match is 24 characters, the `DTM` maximum
* length (2.A.22), so there is no separate length check. Shape only: the ranges and the calendar
* of the date and time fields are Temporal's to check; a partial value's offset is checked with the
* `utcOffset` regex and normalised with `formatUtcOffset` (parseHL7).
*/
const hl7Dtm = new RegExp(`^${YYYY}(?:${MM}(?:${DD}(?:${HH}(?:${MI}(?:${SS}(?:${FRACTION})?)?)?)?)?)?(?:${ZZZZ})?$`);
/**
* Reads a `DTM` against `hl7Dtm`. No range check here.
*
* @param dtm candidate `DTM` text
* @returns the matched groups and the precision written, or `null` when it does not match
*
* @example readHl7Dtm("20240615103000.1234") // { year: "2024", …, precision: "fraction", fractionDigits: 4 }
* @example readHl7Dtm("2024-0500") // { year: "2024", sign: "-", offsetHour: "05", offsetMinute: "00", precision: "year", … }
* @example readHl7Dtm("20240615103000.12345") // null
*/
function readHl7Dtm(dtm) {
if (typeof dtm !== "string") return null;
const groups = hl7Dtm.exec(dtm)?.groups;
if (groups === void 0) return null;
const fraction = groups["fraction"];
return {
year: groups["year"],
month: groups["month"],
day: groups["day"],
hour: groups["hour"],
minute: groups["minute"],
second: groups["second"],
fraction,
sign: groups["sign"],
offsetHour: groups["offsetHour"],
offsetMinute: groups["offsetMinute"],
precision: finestPrecision(groups, fraction),
fractionDigits: fraction === void 0 ? 0 : fraction.length
};
}
/** The finest of `year … second` whose group is present, or `"fraction"` when a fraction is. */
function finestPrecision(groups, fraction) {
if (fraction !== void 0) return "fraction";
let finest = "year";
for (const precision of HL7_PRECISIONS) if (precision !== "fraction" && groups[precision] !== void 0) finest = precision;
return finest;
}
const HL7_TS_PART = "[^\\u0000-\\u001f|~^&]*";
/** A whole `TS` field: `TS.1 ^ TS.2`, then any number of `^`-led extra components. */
const hl7TsField = new RegExp(`^${HL7_TS_PART}(?:\\^${HL7_TS_PART}(?:\\^[^\\u0000-\\u001f|~^]*)*)?$`);
/**
* Splits a `TS` (2.A.77: `DTM ^ degree of precision`) into its two components. A lone field
* carries no MSH-2, so `^` separates components, the separator Figure 2-1 recommends (ch. 2
* §2.5.4). GMT reads TS.1 as exactly a DTM and TS.2 as exactly a Table 0529 code (or empty) and
* rejects anything else inside them, a `&` included: that is GMT's strict-kind rule. A recipient ignores components "that are present but were not expected" (ch. 2 §2.6.2),
* and a later version adds components at the end of a data type (§2.8.1, §2.8.2), so each
* component after TS.2 is ignored: `20240615^D^X` is `20240615^D`. An empty component is not
* present (§2.6.2), so `20240615^` and `20240615^^D` are `20240615`.
*
* An ignored component is still a component of the field, so it cannot hold a field separator
* (`|`), a repetition separator (`~`) or a C0 control (a CR ends the segment). Anything else is
* ignored: a subcomponent (`&`, §2.8.2), an escape sequence (`\F\`, §2.7) and white space are text.
*
* @param value candidate `TS` text
* @returns the two components, each `""` when not present; `null` for a value that is not a string
* or whose components break these rules
*
* @example splitHl7Ts("199904011200^L") // { dtm: "199904011200", degree: "L" }
* @example splitHl7Ts("20240615^D^X") // { dtm: "20240615", degree: "D" }
* @example splitHl7Ts("2024&X") // null (GMT reads TS.1 as exactly a DTM)
* @example splitHl7Ts("20240615^D^X|Y") // null (the field separator ends the field)
*/
function splitHl7Ts(value) {
if (typeof value !== "string" || !hl7TsField.test(value)) return null;
const [dtm = "", degree = ""] = value.split("^", 2);
return {
dtm,
degree
};
}
const ISO_OFFSET = "(?<offset>Z|[+-][0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]{1,9})?)?)";
/**
* Which form an ISO 8601 extended string is written in, for `formatHL7` and `formatFHIR`. It reads the whole string, so an
* annotation of any kind does not match. It reads the form, never the values (Temporal checks those). Groups
* `year month day hour minute second fraction offset`:
* - `year` is exactly four digits, so `+010000` and `-000001` do not match.
* - `fraction` is one to nine digits after `.` or `,` (the decimal signs `plainDateTime` accepts).
* - `offset` follows a time only: `Z` or `±HH:MM` with the optional `:SS` and fraction Temporal
* writes for a sub-minute zone, so the formatter can refuse it rather than fail to match.
* - Upper-case `T` and `Z` only.
*/
const isoHl7Form = new RegExp(`^(?<year>[0-9]{4})(?:-(?<month>[0-9]{2})(?:-(?<day>[0-9]{2})(?:T(?<hour>[0-9]{2})(?::(?<minute>[0-9]{2})(?::(?<second>[0-9]{2})(?:[.,](?<fraction>[0-9]{1,9}))?)?)?${ISO_OFFSET}?)?)?)?$`);
/**
* The precision an `isoHl7Form` match is written at, as `readHl7Dtm` gives it for a `DTM`.
*
* @param match a successful `isoHl7Form.exec` result
* @returns the finest group present and the number of fraction digits written
*
* @example isoHl7Precision(isoHl7Form.exec("2024-06-15T10:30") as RegExpExecArray) // { precision: "minute", fractionDigits: 0 }
* @example isoHl7Precision(isoHl7Form.exec("2024-06-15T10:30:00,5") as RegExpExecArray) // { precision: "fraction", fractionDigits: 1 }
*/
function isoHl7Precision(match) {
const groups = match.groups ?? {};
const fraction = groups["fraction"];
return {
precision: finestPrecision(groups, fraction),
fractionDigits: fraction === void 0 ? 0 : fraction.length
};
}
/**
* The core of `parseHL7` and `isValidHL7`: the structured value an HL7 v2 `DTM` or `TS` names.
* Never throws.
*
* @param value an HL7 v2 `DTM`, or a `TS` with its degree of precision
* @returns the structured value, or `null` when `value` is not one
*
* @example readHl7DateTime("20240710143000+0200")?.kind // "instant"
* @example readHl7DateTime("202407")?.kind // "partial"
* @example readHl7DateTime("not a date") // null
*/
function readHl7DateTime(value) {
try {
if (typeof value !== "string") return null;
const ts = splitHl7Ts(value);
if (ts === null || ts.dtm === "") return null;
if (ts.dtm === "\"\"") return ts.degree === "" ? { kind: "null" } : null;
const fields = readHl7Dtm(ts.dtm);
if (fields === null) return null;
const precision = loweredPrecision(fields.precision, ts.degree);
if (precision === null) return null;
const local = writeHl7Local(fields, precision);
const offset = readHl7Offset(fields);
if (offset === null) return null;
if (isMomentPrecision(precision)) {
if (offset === "") return {
kind: "local",
local,
precision
};
const pair = readInstantOffsetInstant(local + offset);
if (pair === null) return null;
return {
kind: "instant",
instant: pair.instant,
offset: pair.offset,
local,
precision
};
}
return {
kind: "partial",
local,
offset,
precision
};
} catch {
return null;
}
}
/** A minute or finer names a moment; a coarser precision names a span. */
function isMomentPrecision(precision) {
return precision === "minute" || precision === "second" || precision === "fraction";
}
/** The precision after a `TS` degree (2.A.77.2 lowers only); `null` for a bad or finer degree. */
function loweredPrecision(written, degree) {
if (degree === "") return written;
const lowered = hl7DegreePrecision(degree);
return lowered === null || hl7PrecisionRank(lowered) > hl7PrecisionRank(written) ? null : lowered;
}
/** The sent offset as `±HH:MM` (`-0000` reads `+00:00`), `""` when none, `null` when out of range. */
function readHl7Offset(fields) {
if (fields.sign === void 0) return "";
const sent = `${fields.sign}${fields.offsetHour}:${fields.offsetMinute}`;
const nanoseconds = utcOffset.test(sent) ? parseUtcOffsetNanoseconds(sent) : null;
return nanoseconds === null ? null : formatUtcOffset(nanoseconds);
}
/**
* Validates the calendar of `fields` with Temporal (`overflow: "reject"`), then writes `local` at
* `precision`, cutting and never rounding. A field out of range throws a `RangeError`, which
* `parseHL7` catches.
*/
function writeHl7Local(fields, precision) {
const reject = { overflow: "reject" };
const date = Temporal.PlainDate.from({
year: Number(fields.year),
month: hl7Num(fields.month, 1),
day: hl7Num(fields.day, 1)
}, reject);
const hour = hl7Num(fields.hour, 0);
const minute = hl7Num(fields.minute, 0);
const second = hl7Num(fields.second, 0);
Temporal.PlainDateTime.from({
year: date.year,
month: date.month,
day: date.day,
hour,
minute,
second
}, reject);
if (precision === "year" || precision === "month" || precision === "day") return date.toString().slice(0, {
year: 4,
month: 7,
day: 10
}[precision]);
if (precision === "hour") return `${date.toString()}T${hl7Pad(hour)}`;
const clock = `${hl7Pad(hour)}:${hl7Pad(minute)}:${hl7Pad(second)}`;
return writeHl7Clock(Temporal.PlainDateTime.from(`${date.toString()}T${clock}${fields.fraction === void 0 ? "" : `.${fields.fraction}`}`), precision, fields.fractionDigits);
}
/** A minute or finer: cut to `precision`, seconds always written. */
function writeHl7Clock(dateTime, precision, fractionDigits) {
return precision === "fraction" ? dateTime.toString({ fractionalSecondDigits: fractionDigits }) : dateTime.round({
smallestUnit: precision,
roundingMode: "trunc"
}).toString({ smallestUnit: "second" });
}
/** An absent group reads as its first value (month 1, day 1, time 0). */
function hl7Num(group, absent) {
return group === void 0 ? absent : Number(group);
}
function hl7Pad(n) {
return String(n).padStart(2, "0");
}
export { HL7_DEGREE_OF_PRECISION, HL7_NULL_VALUE, HL7_PRECISIONS, hl7DegreePrecision, hl7Dtm, hl7PrecisionRank, isoHl7Form, isoHl7Precision, readHl7DateTime, readHl7Dtm, splitHl7Ts };