temporal-fmt 0.8.981 → 0.8.983
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-CSUIKL73.js → chunk-CG6A4HKZ.js} +11 -2
- package/dist/chunk-CG6A4HKZ.js.map +1 -0
- package/dist/{chunk-KCSGCK7L.js → chunk-GU7UNMND.js} +70 -30
- package/dist/chunk-GU7UNMND.js.map +1 -0
- package/dist/index.cjs +88 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/parse.cjs +69 -29
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.js +1 -1
- package/dist/parsePattern.d.cts +1 -0
- package/dist/parsePattern.d.ts +1 -0
- package/dist/pattern.d.cts +1 -0
- package/dist/pattern.d.ts +1 -0
- package/dist/recurrence.cjs +10 -1
- package/dist/recurrence.cjs.map +1 -1
- package/dist/recurrence.js +1 -1
- package/package.json +1 -1
- package/scripts/cli.mjs +23 -1
- package/dist/chunk-CSUIKL73.js.map +0 -1
- package/dist/chunk-KCSGCK7L.js.map +0 -1
|
@@ -99,12 +99,21 @@ function take(iter, n) {
|
|
|
99
99
|
}
|
|
100
100
|
return result;
|
|
101
101
|
}
|
|
102
|
+
var MAX_SKIP_COLLECTION = 1e5;
|
|
102
103
|
function skip(iter, n) {
|
|
103
104
|
for (let i = 0; i < n; i++) {
|
|
104
105
|
const r = iter.next();
|
|
105
106
|
if (r.done) break;
|
|
106
107
|
}
|
|
107
|
-
|
|
108
|
+
const result = [];
|
|
109
|
+
while (result.length < MAX_SKIP_COLLECTION) {
|
|
110
|
+
const r = iter.next();
|
|
111
|
+
if (r.done) return result;
|
|
112
|
+
result.push(r.value);
|
|
113
|
+
}
|
|
114
|
+
throw new RangeError(
|
|
115
|
+
`temporal-fmt: skip() collected ${MAX_SKIP_COLLECTION} occurrences and the rule is still producing \u2014 add a count or until to the rule, or use take(iter, n) for a bounded read.`
|
|
116
|
+
);
|
|
108
117
|
}
|
|
109
118
|
function between(start, rule, rangeStart, rangeEnd) {
|
|
110
119
|
const iter = recurrence(start, rule);
|
|
@@ -212,4 +221,4 @@ export {
|
|
|
212
221
|
parseRRule,
|
|
213
222
|
formatRRule
|
|
214
223
|
};
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
224
|
+
//# sourceMappingURL=chunk-CG6A4HKZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recurrence.ts"],"sourcesContent":["// Recurrence engine. Deterministic RRULE-like\n// recurrence without pulling in a runtime dependency. Supports\n// secondly/minutely/hourly/daily/weekly/monthly/yearly frequencies,\n// interval, count, until, weekdays, monthDays, positional rules,\n// exclusions, inclusions.\n//\n// RRULE interop: parseRRule() / formatRRule() convert to/from the\n// standard iCalendar RRULE string format (RFC 5545). Implemented\n// without depending on a RRULE library — the grammar is small enough\n// to handle inline.\n\nimport { add } from './arithmetic.js';\nimport { compare } from './comparison.js';\n\nexport type RecurrenceFrequency = 'secondly' | 'minutely' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly';\n\nexport interface RecurrenceRule {\n frequency: RecurrenceFrequency;\n interval: number; // default 1\n count?: number; // max occurrences\n until?: unknown; // Temporal value — recurrence ends before this\n // For weekly: ISO weekdays to include (1=Mon..7=Sun). Empty = all.\n byWeekday?: number[];\n // For monthly/yearly: days of month to include (1-31, or negative\n // for end-of-month: -1 = last day).\n byMonthDay?: number[];\n // For yearly: months to include (1-12).\n byMonth?: number[];\n // For weekly: which week of the year (1-53).\n byWeek?: number[];\n // Exclusions: dates to skip even if they match the rule.\n exDates?: unknown[];\n // Inclusions: dates to add even if they don't match the rule.\n rDates?: unknown[];\n}\n\nexport interface RecurrenceIterator {\n next(): { value: unknown; done: boolean } | { value: undefined; done: true };\n previous(): { value: unknown; done: boolean } | { value: undefined; done: true };\n}\n\n// Creates a recurrence iterator starting from `start`. The first call\n// to next() returns `start` itself (if it matches the rule); subsequent\n// calls return the next matching occurrence.\nexport function recurrence(start: unknown, rule: RecurrenceRule): RecurrenceIterator {\n let current: unknown = start;\n let count = 0;\n // Track past values for previous() — keeps a ring buffer of the last\n // N occurrences so previous() can walk back without recomputing.\n const history: unknown[] = [];\n const MAX_HISTORY = 10_000;\n let atEnd = false;\n let atStart = true;\n\n function matches(value: unknown): boolean {\n const v = value as { dayOfWeek?: number; day?: number; month?: number; year?: number; hour?: number; minute?: number; second?: number };\n if (rule.byWeekday && rule.byWeekday.length > 0) {\n if (!rule.byWeekday.includes(v.dayOfWeek ?? 0)) return false;\n }\n if (rule.byMonthDay && rule.byMonthDay.length > 0) {\n if (!rule.byMonthDay.includes(v.day ?? 0)) return false;\n }\n if (rule.byMonth && rule.byMonth.length > 0) {\n if (!rule.byMonth.includes(v.month ?? 0)) return false;\n }\n if (rule.exDates && rule.exDates.some((d) => compare(d, value) === 0)) return false;\n return true;\n }\n\n function advance(value: unknown, steps: number): unknown {\n // Add `steps` * interval units to `value`.\n const unit = rule.frequency === 'secondly' ? 'seconds'\n : rule.frequency === 'minutely' ? 'minutes'\n : rule.frequency === 'hourly' ? 'hours'\n : rule.frequency === 'daily' ? 'days'\n : rule.frequency === 'weekly' ? 'weeks'\n : rule.frequency === 'monthly' ? 'months'\n : 'years';\n return add(value, steps * rule.interval, unit as Parameters<typeof add>[2]);\n }\n\n function recordHistory(value: unknown): void {\n history.push(value);\n if (history.length > MAX_HISTORY) history.shift();\n }\n\n function nextMatch(value: unknown): { value: unknown; found: boolean } {\n // Advance one step at a time until we find a match. For\n // byWeekday/byMonthDay rules this can skip multiple steps.\n let candidate = value;\n let safetyCounter = 0;\n do {\n candidate = advance(candidate, 1);\n safetyCounter++;\n if (safetyCounter > 1000) {\n // Defensive — if the rule is so restrictive no match exists\n // within 1000 steps, give up rather than spin forever. The\n // caller must treat this as \"no more occurrences\", not as a\n // real match — returning the unmatched candidate here used to\n // get handed back to next()'s caller as if it were valid.\n atEnd = true;\n return { value: candidate, found: false };\n }\n if (rule.until && compare(candidate, rule.until) > 0) {\n atEnd = true;\n return { value: candidate, found: false };\n }\n } while (!matches(candidate));\n return { value: candidate, found: true };\n }\n\n return {\n next() {\n if (atEnd) return { value: undefined, done: true };\n if (atStart) {\n atStart = false;\n if (matches(current)) {\n count++;\n if (rule.count !== undefined && count >= rule.count) atEnd = true;\n if (rule.until && compare(current, rule.until) > 0) {\n atEnd = true;\n return { value: undefined, done: true };\n }\n // Include rDates that match the current value.\n recordHistory(current);\n return { value: current, done: false };\n }\n // If start doesn't match, advance to first match.\n const advanced = nextMatch(current);\n if (!advanced.found) return { value: undefined, done: true };\n current = advanced.value;\n count++;\n if (rule.count !== undefined && count >= rule.count) atEnd = true;\n recordHistory(current);\n return { value: current, done: false };\n }\n const advanced = nextMatch(current);\n if (!advanced.found) return { value: undefined, done: true };\n current = advanced.value;\n count++;\n if (rule.count !== undefined && count >= rule.count) atEnd = true;\n recordHistory(current);\n return { value: current, done: false };\n },\n previous() {\n if (history.length === 0) return { value: undefined, done: true };\n const v = history.pop()!;\n return { value: v, done: false };\n },\n };\n}\n\n// Take N occurrences from a recurrence iterator.\nexport function take(iter: RecurrenceIterator, n: number): unknown[] {\n const result: unknown[] = [];\n for (let i = 0; i < n; i++) {\n const r = iter.next();\n if (r.done) break;\n result.push(r.value);\n }\n return result;\n}\n\n// Upper bound on how many occurrences skip() will collect after its\n// skip phase. skip() used to call take(iter, Number.MAX_SAFE_INTEGER),\n// and an iterator over an unbounded rule (no count, no until — e.g.\n// { frequency: 'daily', interval: 1 }) never returns done: next() always\n// has another day. The call then looped forever, pushing into a result\n// array until the process OOM'd. Same cap style as businessCalendar.ts.\nconst MAX_SKIP_COLLECTION = 100_000;\n\n// Skip N occurrences from a recurrence iterator, returning the ones\n// that follow. Throws a RangeError when the iterator is still producing\n// occurrences after MAX_SKIP_COLLECTION — that means the rule is\n// unbounded (no count/until) and \"everything after the skip\" has no\n// finite answer.\nexport function skip(iter: RecurrenceIterator, n: number): unknown[] {\n for (let i = 0; i < n; i++) {\n const r = iter.next();\n if (r.done) break;\n }\n const result: unknown[] = [];\n while (result.length < MAX_SKIP_COLLECTION) {\n const r = iter.next();\n if (r.done) return result;\n result.push(r.value);\n }\n throw new RangeError(\n `temporal-fmt: skip() collected ${MAX_SKIP_COLLECTION} occurrences and the rule is still ` +\n `producing — add a count or until to the rule, or use take(iter, n) for a bounded read.`\n );\n}\n\n// All occurrences between two dates (inclusive of start, exclusive of end).\nexport function between(start: unknown, rule: RecurrenceRule, rangeStart: unknown, rangeEnd: unknown): unknown[] {\n const iter = recurrence(start, rule);\n const result: unknown[] = [];\n while (true) {\n const r = iter.next();\n if (r.done) break;\n if (compare(r.value, rangeEnd) >= 0) break;\n if (compare(r.value, rangeStart) >= 0) result.push(r.value);\n }\n return result;\n}\n\n// Parses an RRULE string like \"FREQ=DAILY;INTERVAL=2;COUNT=5\" into a\n// RecurrenceRule. Doesn't support every RRULE feature (BYSETPOS,\n// BYHOUR, BYMINUTE, BYSECOND are parsed but not enforced by the\n// recurrence iterator above), but covers the common cases.\nexport function parseRRule(input: string): RecurrenceRule {\n const parts = input.trim().toUpperCase().replace(/^RRULE:/, '').split(';');\n const rule: RecurrenceRule = { frequency: 'daily', interval: 1 };\n const frequencies: ReadonlySet<string> = new Set([\n 'SECONDLY', 'MINUTELY', 'HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY',\n ]);\n for (const part of parts) {\n if (!part) continue;\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n const key = part.slice(0, eq);\n const value = part.slice(eq + 1);\n switch (key) {\n case 'FREQ':\n if (!frequencies.has(value)) {\n throw new RangeError(`temporal-fmt: unsupported RRULE frequency \"${value}\".`);\n }\n rule.frequency = value.toLowerCase() as RecurrenceFrequency;\n break;\n case 'INTERVAL': {\n const interval = Number(value);\n if (!Number.isSafeInteger(interval) || interval < 1) {\n throw new RangeError(`temporal-fmt: RRULE INTERVAL must be a positive safe integer (got \"${value}\").`);\n }\n rule.interval = interval;\n break;\n }\n case 'COUNT': {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 1) {\n throw new RangeError(`temporal-fmt: RRULE COUNT must be a positive safe integer (got \"${value}\").`);\n }\n rule.count = count;\n break;\n }\n case 'UNTIL':\n rule.until = value;\n break;\n case 'BYDAY':\n rule.byWeekday = value.split(',').map((d) => {\n const m = d.match(/^([+-]?\\d)?([A-Z]{2})$/);\n if (!m) return 0;\n const wd = m[2];\n const map: Record<string, number> = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };\n return map[wd!] ?? 0;\n });\n break;\n case 'BYMONTHDAY': {\n const values = value.split(',').map(Number);\n if (values.some((day) => !Number.isInteger(day) || day === 0 || day < -31 || day > 31)) {\n throw new RangeError(`temporal-fmt: RRULE BYMONTHDAY contains an out-of-range value.`);\n }\n rule.byMonthDay = values;\n break;\n }\n case 'BYMONTH': {\n const values = value.split(',').map(Number);\n if (values.some((month) => !Number.isInteger(month) || month < 1 || month > 12)) {\n throw new RangeError(`temporal-fmt: RRULE BYMONTH contains an out-of-range value.`);\n }\n rule.byMonth = values;\n break;\n }\n }\n }\n return rule;\n}\n\nexport function formatRRule(rule: RecurrenceRule): string {\n const parts: string[] = [`FREQ=${rule.frequency.toUpperCase()}`];\n if (rule.interval !== 1) parts.push(`INTERVAL=${rule.interval}`);\n if (rule.count !== undefined) parts.push(`COUNT=${rule.count}`);\n if (rule.until !== undefined) parts.push(`UNTIL=${String(rule.until)}`);\n if (rule.byWeekday && rule.byWeekday.length > 0) {\n const map: Record<number, string> = { 1: 'MO', 2: 'TU', 3: 'WE', 4: 'TH', 5: 'FR', 6: 'SA', 7: 'SU' };\n parts.push(`BYDAY=${rule.byWeekday.map((d) => map[d]).join(',')}`);\n }\n if (rule.byMonthDay && rule.byMonthDay.length > 0) parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`);\n if (rule.byMonth && rule.byMonth.length > 0) parts.push(`BYMONTH=${rule.by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;AAAA,EACnE;AACA,MAAI,KAAK,cAAc,KAAK,WAAW,SAAS,EAAG,OAAM,KAAK,cAAc,KAAK,WAAW,KAAK,GAAG,CAAC,EAAE;AACvG,MAAI,KAAK,WAAW,KAAK,QAAQ,SAAS,EAAG,OAAM,KAAK,WAAW,KAAK,QAAQ,KAAK,GAAG,CAAC,EAAE;AAC3F,SAAO,MAAM,KAAK,GAAG;AACvB;","names":["advanced"]}
|
|
@@ -230,37 +230,73 @@ function enumerateValidSplits(digits, tokens) {
|
|
|
230
230
|
function escapeRegExp2(literal) {
|
|
231
231
|
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
232
232
|
}
|
|
233
|
+
var MAX_AMBIGUITY_BITS = 12;
|
|
234
|
+
function widthChoicesBits(choices) {
|
|
235
|
+
return Math.ceil(Math.log2(Math.max(choices, 1)));
|
|
236
|
+
}
|
|
237
|
+
function isDigitConsumingStart(piece) {
|
|
238
|
+
if (piece === void 0) return false;
|
|
239
|
+
if (piece.kind === "literal") return /^[0-9]/.test(piece.value);
|
|
240
|
+
return DIGIT_LEADING_TOKENS.has(piece.value);
|
|
241
|
+
}
|
|
233
242
|
function buildCapturingPattern(pieces, locale) {
|
|
234
243
|
const groups = [];
|
|
235
244
|
const ambiguousRuns = [];
|
|
236
245
|
let source = "";
|
|
237
246
|
let i = 0;
|
|
238
|
-
let
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
247
|
+
let ambiguityBits = 0;
|
|
248
|
+
let currentRun = { names: [], tokens: [] };
|
|
249
|
+
const flushRun = (nextPiece) => {
|
|
250
|
+
if (currentRun.tokens.length === 1) {
|
|
251
|
+
const name = currentRun.names[0];
|
|
252
|
+
const token = currentRun.tokens[0];
|
|
253
|
+
source += `(?<${name}>${tokenFragment(token, locale)})`;
|
|
254
|
+
if (isDigitConsumingStart(nextPiece)) ambiguityBits += 1;
|
|
255
|
+
} else if (currentRun.tokens.length >= 2) {
|
|
256
|
+
const runName = `r${i++}`;
|
|
257
|
+
const tokenCount = currentRun.tokens.length;
|
|
258
|
+
source += `(?<${runName}>\\d{${tokenCount},${tokenCount * 2}})`;
|
|
259
|
+
ambiguousRuns.push({
|
|
260
|
+
groupName: runName,
|
|
261
|
+
groupNames: currentRun.names,
|
|
262
|
+
tokens: currentRun.tokens
|
|
263
|
+
});
|
|
264
|
+
if (isDigitConsumingStart(nextPiece)) {
|
|
265
|
+
ambiguityBits += widthChoicesBits(tokenCount + 1);
|
|
266
|
+
}
|
|
242
267
|
}
|
|
243
|
-
currentRun = {
|
|
268
|
+
currentRun = { names: [], tokens: [] };
|
|
244
269
|
};
|
|
245
270
|
for (const [idx, piece] of pieces.entries()) {
|
|
246
271
|
if (piece.kind === "literal") {
|
|
272
|
+
flushRun(piece);
|
|
247
273
|
source += escapeRegExp2(piece.value);
|
|
248
|
-
flushRun();
|
|
249
274
|
continue;
|
|
250
275
|
}
|
|
276
|
+
if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {
|
|
277
|
+
const name2 = `g${i++}`;
|
|
278
|
+
groups.push({ name: name2, token: piece.value });
|
|
279
|
+
currentRun.names.push(name2);
|
|
280
|
+
currentRun.tokens.push(piece.value);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
flushRun(piece);
|
|
251
284
|
const name = `g${i++}`;
|
|
252
285
|
groups.push({ name, token: piece.value });
|
|
253
286
|
const nextPiece = pieces[idx + 1];
|
|
254
287
|
const nextToken = nextPiece?.kind === "token" ? nextPiece.value : void 0;
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
currentRun.groupNames.push(name);
|
|
258
|
-
currentRun.tokens.push(piece.value);
|
|
288
|
+
if (piece.value === "yyyy" && nextToken === void 0 && isDigitConsumingStart(nextPiece)) {
|
|
289
|
+
source += `(?<${name}>${tokenFragment(piece.value, locale, "M")})`;
|
|
259
290
|
} else {
|
|
260
|
-
|
|
291
|
+
source += `(?<${name}>${tokenFragment(piece.value, locale, nextToken)})`;
|
|
261
292
|
}
|
|
262
293
|
}
|
|
263
|
-
flushRun();
|
|
294
|
+
flushRun(void 0);
|
|
295
|
+
if (ambiguityBits > MAX_AMBIGUITY_BITS) {
|
|
296
|
+
throw new Error(
|
|
297
|
+
`temporal-fmt: format string has too many variable-width numeric tokens glued to digit-consuming neighbors (ambiguity score ${ambiguityBits} > ${MAX_AMBIGUITY_BITS}). This shape makes the regex engine backtrack exponentially on near-miss input. Add a non-digit separator between these tokens (e.g. "-" or " ") or use their padded forms (MM/dd/HH/mm/ss).`
|
|
298
|
+
);
|
|
299
|
+
}
|
|
264
300
|
return { regex: new RegExp(`^(?:${source})$`, "ud"), groups, ambiguousRuns };
|
|
265
301
|
}
|
|
266
302
|
|
|
@@ -583,26 +619,28 @@ function parse(formatStr, input, options = {}) {
|
|
|
583
619
|
});
|
|
584
620
|
}
|
|
585
621
|
}
|
|
586
|
-
const
|
|
622
|
+
const runValues = /* @__PURE__ */ new Map();
|
|
587
623
|
for (const run of pattern.ambiguousRuns) {
|
|
588
|
-
const runDigits =
|
|
624
|
+
const runDigits = match.groups[run.groupName];
|
|
589
625
|
const splits = enumerateValidSplits(runDigits, run.tokens);
|
|
626
|
+
if (splits.length === 0) {
|
|
627
|
+
throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);
|
|
628
|
+
}
|
|
590
629
|
if (splits.length > 1) {
|
|
591
630
|
if (!options.lenient) {
|
|
592
631
|
throw new Error(
|
|
593
632
|
`temporal-fmt: "${runDigits}" in format string "${formatStr}" is ambiguous \u2014 ${splits.length} different ways to read tokens "${run.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). parse() won't guess; add a separator between these tokens, or use their padded form (e.g. "MM" instead of "M") so each one has a fixed width. Pass { lenient: true } to opt into a documented heuristic that picks one.`
|
|
594
633
|
);
|
|
595
634
|
}
|
|
596
|
-
|
|
635
|
+
const picked = pickLenientSplit(splits, run.tokens);
|
|
636
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));
|
|
637
|
+
} else {
|
|
638
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0][idx])));
|
|
597
639
|
}
|
|
598
640
|
}
|
|
599
641
|
const fields = {};
|
|
600
|
-
const lenientValues = /* @__PURE__ */ new Map();
|
|
601
|
-
for (const { groupNames, values } of runPicks) {
|
|
602
|
-
groupNames.forEach((name, i) => lenientValues.set(name, String(values[i])));
|
|
603
|
-
}
|
|
604
642
|
for (const { name, token } of pattern.groups) {
|
|
605
|
-
const raw =
|
|
643
|
+
const raw = runValues.get(name) ?? match.groups[name];
|
|
606
644
|
applyGroup(fields, token, raw, locale, formatStr);
|
|
607
645
|
}
|
|
608
646
|
const year = resolveYear(fields);
|
|
@@ -759,30 +797,32 @@ function parseToParts(formatStr, input, options = {}) {
|
|
|
759
797
|
});
|
|
760
798
|
}
|
|
761
799
|
}
|
|
762
|
-
const
|
|
800
|
+
const runValues = /* @__PURE__ */ new Map();
|
|
763
801
|
for (const run of pattern.ambiguousRuns) {
|
|
764
|
-
const runDigits =
|
|
802
|
+
const runDigits = match.groups[run.groupName];
|
|
765
803
|
const splits = enumerateValidSplits(runDigits, run.tokens);
|
|
804
|
+
if (splits.length === 0) {
|
|
805
|
+
throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);
|
|
806
|
+
}
|
|
766
807
|
if (splits.length > 1) {
|
|
767
808
|
if (!options.lenient) {
|
|
768
809
|
throw new Error(
|
|
769
810
|
`temporal-fmt: "${runDigits}" in format string "${formatStr}" is ambiguous \u2014 ${splits.length} different ways to read tokens "${run.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). parse() won't guess; add a separator between these tokens, or use their padded form (e.g. "MM" instead of "M") so each one has a fixed width. Pass { lenient: true } to opt into a documented heuristic that picks one.`
|
|
770
811
|
);
|
|
771
812
|
}
|
|
772
|
-
|
|
813
|
+
const picked = pickLenientSplit(splits, run.tokens);
|
|
814
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));
|
|
815
|
+
} else {
|
|
816
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0][idx])));
|
|
773
817
|
}
|
|
774
818
|
}
|
|
775
|
-
const lenientValues = /* @__PURE__ */ new Map();
|
|
776
|
-
for (const { groupNames, values } of runPicks) {
|
|
777
|
-
groupNames.forEach((name, i) => lenientValues.set(name, String(values[i])));
|
|
778
|
-
}
|
|
779
819
|
const parts = [];
|
|
780
820
|
const indices = match.indices;
|
|
781
821
|
const groupIndices = indices?.groups;
|
|
782
822
|
let consumed = 0;
|
|
783
823
|
for (const { name, token } of pattern.groups) {
|
|
784
|
-
const raw =
|
|
785
|
-
const fromIndices = !
|
|
824
|
+
const raw = runValues.get(name) ?? match.groups[name];
|
|
825
|
+
const fromIndices = !runValues.has(name) && groupIndices?.[name];
|
|
786
826
|
const position = fromIndices ? fromIndices[0] : (match.index ?? 0) + consumed;
|
|
787
827
|
parts.push({ token, raw, position });
|
|
788
828
|
consumed += raw.length;
|
|
@@ -824,4 +864,4 @@ export {
|
|
|
824
864
|
parseToParts,
|
|
825
865
|
compileParser
|
|
826
866
|
};
|
|
827
|
-
//# sourceMappingURL=chunk-
|
|
867
|
+
//# sourceMappingURL=chunk-GU7UNMND.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pattern.ts","../src/parsePattern.ts","../src/parse.ts"],"sourcesContent":["import { getLocaleVocab } from './localeVocab.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction alternation(values: string[], caseInsensitive = false): string {\n const escaped = values.map(escapeRegExp);\n if (!caseInsensitive) return `(?:${escaped.join('|')})`;\n // JS regex has no per-group inline case-insensitive flag, and this\n // fragment gets embedded in one larger pattern built with a single flag\n // set — so case-folding here means listing both cases explicitly rather\n // than relying on a flag.\n return `(?:${escaped.map(foldCase).join('|')})`;\n}\n\n// Expands \"PM\" into a character-class-per-letter pattern matching any\n// casing of it (\"[Pp][Mm]\"), so \"pm\", \"Pm\", \"PM\" all match the same\n// alternative. Only used for the day-period token (see the 'a' case\n// below) — not applied to month/weekday names, where case-folding across\n// scripts is a different and riskier problem this doesn't need to solve.\nfunction foldCase(value: string): string {\n return value.replace(/[a-zA-Z]/g, (ch) => `[${ch.toLowerCase()}${ch.toUpperCase()}]`);\n}\n\n// Every real IANA zone id is letters/digits/'_'/'+'/'-' segments joined by\n// '/' (e.g. \"America/Argentina/Buenos_Aires\", \"Etc/GMT+12\"); UTC and\n// fixed-offset strings are the only other shapes zzz accepts. Matching that\n// *shape* here — instead of alternating all ~400 zone names inline — keeps\n// the compiled regex small regardless of how many zzz tokens appear in a\n// format string. The captured text still gets checked against the real\n// zone set in isValidTimeZone() after the overall pattern matches, so this\n// is strictly a matching-cost change, not a validation-strictness change:\n// a bogus zone id fails \"no valid pattern matches\" exactly like it did when\n// the zone list was inlined (see isValidTimeZone's caller in parse.ts).\nconst TIME_ZONE_SHAPE = '(?:UTC|[+-]\\\\d{2}:\\\\d{2}(?::\\\\d{2}(?:\\\\.\\\\d{1,9})?)?|[A-Za-z_]+(?:[+-]\\\\d{1,2})?(?:\\\\/[A-Za-z0-9_+-]+)*)';\n\n// Per-variant regex shapes for the six offset tokens. Each matches the\n// shape its own format counterpart produces, so a round-trip\n// format->parse succeeds for any input the library itself emitted.\n//\n// Kept loose (no hour/minute range bounds inline) on purpose, mirroring\n// how TIME_ZONE_SHAPE is loose: a permissive shape here lets parse()\n// surface a descriptive out-of-range error post-match (see\n// parseOffsetString in parse.ts) instead of the generic \"no valid pattern\n// matches\" the regex throws when the shape itself fails. \"+99:99\" should\n// tell the user it's out of range, not look like the input never matched\n// the format at all.\n//\n// X / x accept an optional minutes group so whole-hour offsets can be\n// written short (\"+05\") while non-whole-hour offsets still parse\n// (\"+0530\"). The optional group is greedy, so for input \"+0530\" the\n// engine prefers the 4-digit match; only falls back to 2-digit when\n// there's nothing else to consume — same longer-first preference the\n// unpadded numeric tokens use elsewhere in this file (see the comment on\n// NUMERIC_FRAGMENTS).\nconst OFFSET_SHAPES: Record<string, string> = {\n X: '(?:Z|[+-]\\\\d{2}(?:\\\\d{2})?)',\n XX: '(?:Z|[+-]\\\\d{4})',\n XXX: '(?:Z|[+-]\\\\d{2}:\\\\d{2})',\n x: '[+-]\\\\d{2}(?:\\\\d{2})?',\n xx: '[+-]\\\\d{4}',\n xxx: '[+-]\\\\d{2}:\\\\d{2}',\n};\n\nfunction getTimeZoneFragment(): string {\n return TIME_ZONE_SHAPE;\n}\n\nlet validZoneSet: Set<string> | undefined;\n\n// Real zone ids plus the couple of aliases zzz has always accepted even\n// though Intl.supportedValuesOf('timeZone') doesn't list them (UTC isn't\n// itself an IANA zone name, it's the identity offset).\nfunction getValidZoneSet(): Set<string> {\n if (!validZoneSet) {\n validZoneSet = new Set(Intl.supportedValuesOf('timeZone'));\n validZoneSet.add('UTC');\n }\n return validZoneSet;\n}\n\nconst FIXED_OFFSET_RE = /^[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?$/;\n\n// Called post-match on whatever the bounded TIME_ZONE_SHAPE captured, since\n// that shape is deliberately looser than \"a real zone id\" (it has to be, to\n// stay a fixed-size regex fragment — see the comment above). A fixed offset\n// is valid by construction; anything else has to be a real IANA name.\nexport function isValidTimeZone(raw: string): boolean {\n return FIXED_OFFSET_RE.test(raw) || getValidZoneSet().has(raw);\n}\n\n// mirrors the ranges pad() in tokens.ts actually produces — keep in sync\n// if those ever change\n//\n// Unpadded alternatives (M, H, h, m, s) list the longer branch first\n// (e.g. '1[0-2]|[1-9]', not '[1-9]|1[0-2]'). This matters only when two\n// unpadded tokens are glued with no separator: with short-first ordering,\n// a regex engine takes the first successful overall match, and won't\n// backtrack into a token's second alternative unless its first choice\n// makes the *rest* of the pattern fail outright. If the short reading also\n// happens to leave a valid match for the next token, the engine stops\n// there — silently, deterministically, and with no relation to which\n// reading a human intended. E.g. \"Md\" against \"121\": short-first order\n// resolves it as month=1/day=21 (M grabs '1', d gets '21', which is a\n// valid day) instead of month=12/day=1. Longer-first ordering fixes this\n// by making the greedy match try to consume as many digits as possible\n// before ever handing digits to the next token, which is the reading\n// that matches how format() itself produces glued output in the first\n// place (format() always emits the token's natural width, so decoding\n// should prefer the same). Found via the token×token combinatorial glue\n// matrix in combinatorial.test.js — see that file for the full case list.\nconst NUMERIC_FRAGMENTS: Record<string, string> = {\n yy: '\\\\d{2}',\n MM: '(?:0[1-9]|1[0-2])',\n M: '(?:1[0-2]|[1-9])',\n dd: '(?:0[1-9]|[12]\\\\d|3[01])',\n d: '(?:[12]\\\\d|3[01]|[1-9])',\n HH: '(?:[01]\\\\d|2[0-3])',\n H: '(?:1\\\\d|2[0-3]|[0-9])',\n hh: '(?:0[1-9]|1[0-2])',\n h: '(?:1[0-2]|[1-9])',\n mm: '(?:[0-5]\\\\d)',\n m: '(?:[1-5]\\\\d|[0-9])',\n ss: '(?:[0-5]\\\\d)',\n s: '(?:[1-5]\\\\d|[0-9])',\n SSSSSSSSS: '\\\\d{9}',\n SSSSSSSS: '\\\\d{8}',\n SSSSSSS: '\\\\d{7}',\n SSSSSS: '\\\\d{6}',\n SSSSS: '\\\\d{5}',\n SSSS: '\\\\d{4}',\n SSS: '\\\\d{3}',\n SS: '\\\\d{2}',\n S: '\\\\d',\n // Q is always a single digit 1-4 (no padding variant, so no width ambiguity\n // with adjacent digit tokens the way M/d/H/m/s have).\n Q: '[1-4]',\n};\n\n// QQQ matches its own formatted output: the literal \"Q\" prefix plus a single\n// digit 1-4. Kept as a static fragment rather than routed through vocab,\n// since the \"Q\" prefix is part of the token's own contract, not locale-vocab\n// data that could ever differ.\nconst QQQ_FRAGMENT = 'Q[1-4]';\n\n// Format-only tokens — they have no parse counterpart. The tokenizer still\n// recognizes them (so format() can use them), but parse()'s regex builder\n// rejects them with a clear error rather than silently dropping the token\n// or falling through to the generic \"unknown token\" message.\n// Exported so analyze.ts can include them in the public analyzer surface.\nexport const FORMAT_ONLY_TOKENS = new Set(['do', 'ww', 'RRRR', 'D', 'DD', 'DDD', 'LLLL', 'LLL', 'cccc', 'ccc', 'GGGG', 'G', 'zzzz', 'z']);\n\n// pad()'s year formatter (tokens.ts) never truncates: it preserves the sign\n// for BCE years and doesn't cap width past 9999, so a formatted \"yyyy\" can\n// be longer than 4 digits or start with '-'. YYYY_EXTENDED accepts that;\n// YYYY_EXACT is the plain 4-unsigned-digit case. Which one a given \"yyyy\"\n// occurrence gets depends on what follows it — see buildCapturingPattern in\n// parsePattern.ts. Two separate fragments instead of one `-?\\d{4,}` because\n// an open-ended-width year directly followed by another digit token (e.g.\n// \"yyyyMM\") lets the year's own greediness silently eat digits meant for\n// the next token — same class of bug as UNPADDED_NUMERIC_TOKENS below, but\n// unbounded-width, so it can't reuse enumerateValidSplits' fixed-range\n// splitting. Restricting to exactly 4 digits whenever something could\n// follow closes that off entirely, at the cost of \"yyyyMM\" not being able\n// to represent a 5-digit year — an already-rare case doubly rare in\n// combination with a glued adjacent token.\nconst YYYY_EXACT = '-?\\\\d{4}';\nconst YYYY_EXTENDED = '-?\\\\d{4,}';\n\n// True for any token whose matched text can start with a digit — i.e.\n// every token here except the locale-named ones (MMMM/MMM/EEEE/EEE/a) and\n// zzz (which can start with a digit only via a fixed offset like \"+09:00\",\n// already handled by requiring a leading sign there). Used to decide\n// whether a \"yyyy\" immediately before this token needs the exact-4-digit\n// fragment instead of the open-ended one.\n// Exported for parsePattern.ts's ReDoS guard: a token whose regex\n// fragment can begin with a bare digit (see the guard comments there).\nexport const DIGIT_LEADING_TOKENS = new Set([\n 'yyyy', 'yy', 'MM', 'M', 'dd', 'd', 'HH', 'H', 'hh', 'h', 'mm', 'm', 'ss', 's',\n 'SSSSSSSSS', 'SSSSSSSS', 'SSSSSSS', 'SSSSSS', 'SSSSS', 'SSSS', 'SSS', 'SS', 'S',\n]);\n\nexport function tokenFragment(token: string, locale: string, nextToken?: string): string {\n if (token === 'yyyy') {\n return nextToken !== undefined && DIGIT_LEADING_TOKENS.has(nextToken) ? YYYY_EXACT : YYYY_EXTENDED;\n }\n\n const numeric = NUMERIC_FRAGMENTS[token];\n if (numeric) {\n return numeric;\n }\n\n if (token === 'QQQ') {\n return QQQ_FRAGMENT;\n }\n\n if (FORMAT_ONLY_TOKENS.has(token)) {\n throw new Error(\n `temporal-fmt: token \"${token}\" is format-only — it can't be parsed back into a value. ` +\n `Use a different token in the parse format string (e.g. \"d\" for \"do\", \"MM\" for \"ww\").`\n );\n }\n\n const vocab = getLocaleVocab(locale);\n switch (token) {\n case 'MMMM': return alternation(vocab.monthLong);\n case 'MMM': return alternation(vocab.monthShort);\n case 'EEEE': return alternation(vocab.weekdayLong);\n case 'EEE': return alternation(vocab.weekdayShort);\n // Case-insensitive on purpose: \"pm\"/\"Pm\"/\"PM\" all mean the same thing,\n // and unlike the Md-glue ambiguity elsewhere in this file, there's no\n // second valid reading to guess wrong — so rejecting on case buys no\n // correctness, only friction against real-world data (mixed-case CSV\n // exports, lowercase log timestamps).\n case 'a': return alternation(vocab.dayPeriod, true);\n case 'zzz': return getTimeZoneFragment();\n case 'X': case 'XX': case 'XXX':\n case 'x': case 'xx': case 'xxx':\n return OFFSET_SHAPES[token]!;\n /* c8 ignore start @preserve -- defensive guard, not reachable through\n the public API. tokenFragment's only caller (buildCapturingPattern\n in parsePattern.ts) always passes piece.value straight from\n tokenize.ts, which only ever emits strings from tokens.ts's TOKENS\n table. Every token in that table is handled above: the numeric\n ones via NUMERIC_FRAGMENTS, QQQ via QQQ_FRAGMENT, the format-only\n ones via the FORMAT_ONLY_TOKENS check earlier in this function, and\n everything else via one of the switch cases. There's no token\n string that can reach this default without either tokens.ts\n registering something new or tokenize.ts being bypassed, neither of\n which happens on the parse() path. */\n default:\n throw new Error(`temporal-fmt: unknown token \"${token}\"`);\n /* c8 ignore stop @preserve */\n }\n}\n\n// Tokens whose fragment is variable-width (1-2 digits, no leading zero).\n// Two or more of these glued with no literal separator between them can\n// have more than one digit-split that's independently valid against every\n// fragment in the run — see the big comment on NUMERIC_FRAGMENTS above.\n// Reordering alternation branches picks a winner for *some* of these\n// cases, but can't make both directions of a pair (e.g. \"Md\" and \"dM\")\n// agree, because the ambiguity is in the input string itself, not in how\n// any one fragment is written. exported so parsePattern.ts can find runs\n// of these that need split-counting at match time instead of a single\n// fixed regex.\nexport const UNPADDED_NUMERIC_TOKENS = new Set(['M', 'd', 'H', 'h', 'm', 's']);\n\n// Every accept width for a given unpadded numeric token, as plain min/max\n// value + digit-length pairs — used to enumerate candidate splits of a\n// digit run at match time. Mirrors NUMERIC_FRAGMENTS's semantics exactly\n// (same accepted values), just as data instead of regex source, since\n// enumerating splits against a compiled regex per-candidate would be\n// slower and harder to reason about than checking numeric ranges directly.\nexport const UNPADDED_NUMERIC_RANGES: Record<string, Array<{ digits: 1 | 2; min: number; max: number }>> = {\n M: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 12 }],\n d: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 31 }],\n H: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 23 }],\n h: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 12 }],\n m: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 59 }],\n s: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 59 }],\n};\n\n/**\n * Given the literal digit string a run of N adjacent unpadded-numeric\n * tokens matched as a whole (e.g. \"112\" for a 2-token run), enumerates\n * every way to split it into N pieces (one per token, each piece 1-2\n * digits per that token's own width rule) and returns every split where\n * every piece is independently valid for its token. Length 0 means the\n * run's regex match shouldn't have been possible in the first place\n * (shouldn't happen — the caller only invokes this after the whole\n * pattern already matched, meaning at least one split exists: the one the\n * regex actually took). Length 1 means the reading is unambiguous.\n * Length 2+ means true ambiguity — the caller should throw rather than\n * pick one.\n *\n * Recursive over token count rather than hardcoded to 2, so a 3+ token\n * unseparated run (e.g. \"Hms\") is covered by the same logic without a\n * special case — those are rarer in practice but not impossible, and a\n * partial fix that only covered pairs would leave the identical bug for\n * anyone writing a 3-token glued run.\n */\nexport function enumerateValidSplits(digits: string, tokens: string[]): number[][] {\n const memo = new Map<string, number[][]>();\n\n function solve(tokenIndex: number, offset: number): number[][] {\n const key = `${tokenIndex}:${offset}`;\n const cached = memo.get(key);\n if (cached) {\n return cached;\n }\n\n if (tokenIndex === tokens.length) {\n const result = offset === digits.length ? [[]] : [];\n memo.set(key, result);\n return result;\n }\n\n const token = tokens[tokenIndex];\n const ranges = UNPADDED_NUMERIC_RANGES[token!];\n /* c8 ignore start @preserve -- defensive guard, not reachable through\n the public API. enumerateValidSplits's only caller (parse.ts, both\n call sites) passes run.tokens straight from\n pattern.ambiguousRuns, which parsePattern.ts only ever populates\n with tokens already checked against UNPADDED_NUMERIC_TOKENS — the\n exact same key set as UNPADDED_NUMERIC_RANGES. There's no path\n where a token reaches here without having already passed that\n check. */\n if (!ranges) {\n throw new Error(`temporal-fmt: internal error — \"${token}\" is not an unpadded numeric token`);\n }\n /* c8 ignore stop @preserve */\n\n const results: number[][] = [];\n for (const { digits: width, min, max } of ranges) {\n if (offset + width > digits.length) continue;\n const piece = digits.slice(offset, offset + width);\n if (width === 2 && piece[0] === '0') continue;\n const value = Number(piece);\n if (value < min || value > max) continue;\n\n for (const restSplit of solve(tokenIndex + 1, offset + width)) {\n results.push([value, ...restSplit]);\n if (results.length === 2) break;\n }\n if (results.length === 2) break;\n }\n\n memo.set(key, results);\n return results;\n }\n\n return solve(0, 0);\n}","import type { Piece } from './tokenize.js';\nimport { tokenFragment, UNPADDED_NUMERIC_TOKENS, DIGIT_LEADING_TOKENS } from './pattern.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n// Guards against catastrophic-backtracking (ReDoS) patterns.\n//\n// Every confirmed ReDoS in this library shares one shape: two or more\n// variable-width digit-consuming regex fragments placed so the engine\n// can't tell where one ends and the next begins — either glued with no\n// separator (\"MdMdMd…\", \"HmsHms…\") or separated only by a literal that\n// itself starts with a digit (\"M1M1M1…\", \"yyyy1yyyy1…\"). Each fragment\n// then has multiple ways to divide the digit run, and a failing match\n// makes the engine explore every combination — exponential in the number\n// of fragments. Measured against the pre-fix code: \"Md\"×13 (26-char\n// format, 40-char input) ≈ 2.7 s; \"yyyy1\"×8 (48-char format) ≈ 26 s;\n// both grow roughly ×3–14 per additional fragment.\n//\n// Three structural defenses, applied at pattern-build time:\n//\n// 1. A run of 2+ glued unpadded-numeric tokens is emitted as ONE\n// bounded digit group `(?<rN>\\d{R,2R})` instead of R separate\n// variable-width fragments. The per-token split is resolved after\n// the match by enumerateValidSplits() (pattern.ts) — the exact\n// machinery parse() already used to detect ambiguous glued runs —\n// so the documented behavior (unique split resolves; 2+ valid\n// splits throws in strict mode / heuristic-picks in lenient; 0\n// splits is a mismatch) is preserved. A lone `\\d{R,2R}` group\n// backtracks at most R+1 times, which is linear.\n//\n// 2. yyyy uses the exact `-?\\d{4}` fragment not only when the next\n// *token* is digit-leading (existing rule) but also when the next\n// *literal* starts with a digit. An open-ended `-?\\d{4,}` year\n// glued to a digit literal is the cheapest exponential engine\n// there is (unbounded width choices per year), and the exact form\n// matches everything the open-ended form matched in that position\n// except years with 5+ digits glued directly to an unquoted digit\n// literal — a pathological corner deliberately traded away.\n//\n// 3. An ambiguity budget for what's left: every adjacency between a\n// variable-width digit consumer (a lone unpadded token, or a glued\n// run group) and a digit-consuming successor (a digit-leading token\n// or a literal starting with a digit) costs log2 of the consumer's\n// width choices. A pattern whose total exceeds MAX_AMBIGUITY_BITS\n// (12 — a hard ceiling of 4096 backtrack paths) is rejected at\n// build time. Realistic format strings score 0–3; the \"M1M1M1…\"\n// attack scores one bit per glued pair.\n//\n// (0.8.x note: main throws a typed FormatSyntaxError here. 0.8.x is LTS\n// and keeps the pre-0.9.0 plain-Error throw convention everywhere —\n// this backport throws `new Error(...)` to match, not the typed class.)\nconst MAX_AMBIGUITY_BITS = 12;\n\nfunction widthChoicesBits(choices: number): number {\n return Math.ceil(Math.log2(Math.max(choices, 1)));\n}\n\n// Does this piece's regex fragment START by consuming a bare digit?\n// (Tokens whose match can begin with 0-9, and literals whose first\n// character is a digit.) Used to find the boundaries where a preceding\n// variable-width digit consumer could trade digits with a successor.\nfunction isDigitConsumingStart(piece: Piece | undefined): boolean {\n if (piece === undefined) return false;\n if (piece.kind === 'literal') return /^[0-9]/.test(piece.value);\n return DIGIT_LEADING_TOKENS.has(piece.value);\n}\n\nexport interface CapturingPattern {\n regex: RegExp;\n groups: Array<{ name: string; token: string }>; // token pieces, in order\n // Runs of 2+ adjacent unpadded-numeric tokens with no literal separator\n // between them (e.g. \"Md\", \"dM\", \"Hms\"). Each run is captured by ONE\n // regex group named `groupName` spanning the run's whole digit run\n // (R..2·R digits); per-token values come from enumerateValidSplits()\n // at match time. `groupNames` lists the per-token group names — they\n // appear in `groups` for structure/positions but have no counterpart\n // in the regex itself, so consumers must read their values from the\n // split enumeration, not from match.groups.\n ambiguousRuns: Array<{ groupName: string; groupNames: string[]; tokens: string[] }>;\n}\n\n/**\n * Same walk as buildPatternSource() in pattern.ts, but each token piece\n * gets its own named capture group (positionally named so the same token,\n * e.g. \"yyyy\", could in theory appear twice) so a caller can pull the\n * matched substring for each token back out after a successful match.\n */\nexport function buildCapturingPattern(pieces: Piece[], locale: string): CapturingPattern {\n const groups: Array<{ name: string; token: string }> = [];\n const ambiguousRuns: Array<{ groupName: string; groupNames: string[]; tokens: string[] }> = [];\n let source = '';\n let i = 0;\n let ambiguityBits = 0;\n\n // Tracks the current run of adjacent unpadded-numeric token pieces (no\n // literal or non-unpadded token has broken it yet). Names are recorded\n // in declaration order so a run of 2+ can emit one group while its\n // member tokens still get individual entries in `groups`.\n let currentRun: { names: string[]; tokens: string[] } = { names: [], tokens: [] };\n\n const flushRun = (nextPiece: Piece | undefined) => {\n if (currentRun.tokens.length === 1) {\n // A lone unpadded token: emit its normal (two-way) fragment. Two\n // width choices are harmless on their own; if the next element\n // can consume a digit, charge one ambiguity bit for the boundary.\n const name = currentRun.names[0]!;\n const token = currentRun.tokens[0]!;\n source += `(?<${name}>${tokenFragment(token, locale)})`;\n if (isDigitConsumingStart(nextPiece)) ambiguityBits += 1;\n } else if (currentRun.tokens.length >= 2) {\n // Emit the accumulated run as ONE bounded digit group. R unpadded\n // tokens accept between R and 2R digits in total; anything outside\n // that span can't match regardless of how the digits split, so the\n // single group's acceptance region is exactly the union of the old\n // per-token fragments' regions. Backtracking into this group is\n // bounded at R+1 width choices — linear, not exponential.\n const runName = `r${i++}`;\n const tokenCount = currentRun.tokens.length;\n source += `(?<${runName}>\\\\d{${tokenCount},${tokenCount * 2}})`;\n // Note: no `groups` entry for the run group itself — `groups` lists\n // per-token pieces only (its members were already pushed when\n // visited), so consumers like parseToParts see exactly one entry\n // per token, same as before this run-group change. The regex group\n // is reached through ambiguousRuns[].groupName.\n ambiguousRuns.push({\n groupName: runName,\n groupNames: currentRun.names,\n tokens: currentRun.tokens,\n });\n // A run group adjacent to a digit-consuming successor keeps its\n // (R+1) width choices at that boundary — charge the budget.\n if (isDigitConsumingStart(nextPiece)) {\n ambiguityBits += widthChoicesBits(tokenCount + 1);\n }\n }\n currentRun = { names: [], tokens: [] };\n };\n\n for (const [idx, piece] of pieces.entries()) {\n if (piece.kind === 'literal') {\n flushRun(piece);\n source += escapeRegExp(piece.value);\n continue;\n }\n\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n // Part of a (potential) glued run — defer fragment emission to\n // flushRun so a run of 2+ collapses into one bounded group.\n const name = `g${i++}`;\n groups.push({ name, token: piece.value });\n currentRun.names.push(name);\n currentRun.tokens.push(piece.value);\n continue;\n }\n\n flushRun(piece);\n const name = `g${i++}`;\n groups.push({ name, token: piece.value });\n const nextPiece = pieces[idx + 1];\n const nextToken = nextPiece?.kind === 'token' ? nextPiece.value : undefined;\n // yyyy picks its fragment based on what follows: the exact 4-digit\n // form whenever a digit-consuming element comes next (digit-leading\n // token — the pre-existing rule — OR a literal starting with a\n // digit, added by the ReDoS fix; see the guard block above). The\n // open-ended form is only safe when nothing digit-consuming can\n // follow it.\n if (piece.value === 'yyyy' && nextToken === undefined && isDigitConsumingStart(nextPiece)) {\n source += `(?<${name}>${tokenFragment(piece.value, locale, 'M')})`;\n } else {\n source += `(?<${name}>${tokenFragment(piece.value, locale, nextToken)})`;\n }\n }\n flushRun(undefined);\n\n if (ambiguityBits > MAX_AMBIGUITY_BITS) {\n throw new Error(\n `temporal-fmt: format string has too many variable-width numeric tokens glued to digit-consuming neighbors ` +\n `(ambiguity score ${ambiguityBits} > ${MAX_AMBIGUITY_BITS}). ` +\n `This shape makes the regex engine backtrack exponentially on near-miss input. ` +\n `Add a non-digit separator between these tokens (e.g. \"-\" or \" \") or use their padded forms (MM/dd/HH/mm/ss).`\n );\n }\n\n // 'd' flag enables match.indices.groups — used by parseToParts to\n // report each token's actual position in the input. Without it,\n // computing per-group positions would require a separate walk of the\n // piece list against the input, duplicating logic the regex already\n // has. Backward-compatible: 'd' only adds an `indices` property to\n // the match result, no behavioral change to the match itself.\n return { regex: new RegExp(`^(?:${source})$`, 'ud'), groups, ambiguousRuns };\n}\n","import { DEFAULT_LOCALE, type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { buildCapturingPattern, type CapturingPattern } from './parsePattern.js';\nimport { enumerateValidSplits, isValidTimeZone } from './pattern.js';\nimport { getLocaleVocab, canonicalCacheKey } from './localeVocab.js';\nimport { getTemporal } from './temporalProvider.js';\nimport { MAX_FORMAT_LENGTH, MAX_INPUT_LENGTH } from './constants.js';\nimport { TemporalFmtError, InvalidTimeZoneError, wrapUntypedError } from './errors.js';\nimport { applyParseNumbering, type NumberingParseOptions } from './numbering.js';\n\n// format strings are short hand-written literals reused across many calls —\n// cache the compiled capturing pattern per (formatStr, locale) pair instead\n// of rebuilding it every call.\nconst patternCache = new Map<string, CapturingPattern>();\nconst MAX_CACHE_SIZE = 500;\n\nfunction getPattern(formatStr: string, locale: string): CapturingPattern {\n const key = JSON.stringify([canonicalCacheKey(locale), formatStr]);\n let pattern = patternCache.get(key);\n if (pattern) {\n return pattern;\n }\n if (patternCache.size >= MAX_CACHE_SIZE) {\n const oldestKey = patternCache.keys().next().value;\n if (oldestKey !== undefined) patternCache.delete(oldestKey);\n }\n pattern = buildCapturingPattern(tokenize(formatStr), locale);\n patternCache.set(key, pattern);\n return pattern;\n}\n\n// Requires an explicit `-u-ca-` extension (e.g. 'en-u-ca-hebrew') to apply\n// a non-Gregorian calendar, per parse()'s own docstring. 'gregory' counts\n// as \"no calendar\" so the default locale keeps constructing plain ISO 8601.\n//\n// Used to key off resolvedOptions().calendar instead — a locale's\n// *default* calendar, whether the caller asked for one or not. That broke\n// th-TH silently: its default is 'buddhist', so plain Gregorian-looking\n// digits parsed 543 years off, while format() has no matching calendar\n// step and just prints the object's own ISO fields either way.\nconst calendarCache = new Map<string, string | undefined>();\nconst MAX_CALENDAR_CACHE_SIZE = 500;\n\nfunction resolveCalendar(locale: string): string | undefined {\n // computed up front (not just at cache-miss time) so the cache key is\n // the canonical form too — otherwise 'en-US' and 'en-us' would each get\n // their own entry for what's really the same locale (see\n // canonicalCacheKey's comment in localeVocab.ts for why that matters).\n // Left un-lowercased/un-canonicalized calls into new Intl.Locale() below\n // would still throw on a genuinely malformed tag either way; doing it\n // here just means that throw happens before touching the cache instead\n // of after, which is the more natural place for it.\n const canonicalLocale = new Intl.Locale(locale).toString().toLowerCase();\n if (calendarCache.has(canonicalLocale)) {\n return calendarCache.get(canonicalLocale);\n }\n if (calendarCache.size >= MAX_CALENDAR_CACHE_SIZE) {\n const oldestKey = calendarCache.keys().next().value;\n if (oldestKey !== undefined) calendarCache.delete(oldestKey);\n }\n let calendar: string | undefined;\n const parts = canonicalLocale.split('-');\n const extensionIndex = parts.indexOf('u');\n const calendarKeyIndex = extensionIndex === -1 ? -1 : parts.indexOf('ca', extensionIndex + 1);\n if (calendarKeyIndex !== -1 && calendarKeyIndex + 1 < parts.length) {\n const resolved = new Intl.DateTimeFormat(canonicalLocale).resolvedOptions().calendar;\n calendar = resolved === 'gregory' ? undefined : resolved;\n }\n calendarCache.set(canonicalLocale, calendar);\n return calendar;\n}\n\ninterface Fields {\n year?: number;\n twoDigitYear?: number;\n month?: number;\n day?: number;\n hour?: number;\n hour12?: number;\n dayPeriodRaw?: string;\n isPM?: boolean;\n minute?: number;\n second?: number;\n millisecond?: number;\n microsecond?: number;\n nanosecond?: number;\n timeZoneId?: string;\n // Canonical `+HH:MM` form of any offset token (X/XX/XXX/x/xx/xxx)\n // captured in this pattern. Distinct from timeZoneId because the two\n // can coexist in the same pattern (e.g. \"yyyy-MM-dd HH:mm zzz XXX\") —\n // see the cross-check after construction for how a mismatch between\n // them is resolved.\n offsetString?: string;\n weekdayExpected?: number;\n weekdayRaw?: string;\n quarter?: number;\n}\n\n// Normalizes a captured offset-token string into the canonical `+HH:MM`\n// shape Temporal.ZonedDateTime.from accepts as a `timeZone` value. Throws\n// descriptive errors for out-of-range hours/minutes, since the regex\n// shape (OFFSET_SHAPES in pattern.ts) is deliberately permissive — a\n// post-match range check here gives the user a specific error (\"offset\n// hours 99 out of range, max 14\") instead of \"no valid pattern matches\".\n//\n// Range bounds: -12:00 to +14:00, the standard IANA offset range\n// (Baker/Howland at -12, Kiritimati at +14). +14:01 / -12:01 etc. are\n// rejected explicitly even though the per-piece bounds (hours ≤ 14,\n// minutes ≤ 59) alone wouldn't catch them.\nfunction parseOffsetString(raw: string, token: string): string {\n if (raw === 'Z') {\n /* c8 ignore start @preserve -- unreachable: lowercase tokens' regex\n (OFFSET_SHAPES in pattern.ts) has no \"Z\" alternative at all, so\n raw === 'Z' can only ever be reached when token is one of the\n uppercase variants (X/XX/XXX). A lowercase token can't even\n capture \"Z\" as `raw` in the first place. */\n if (token === 'x' || token === 'xx' || token === 'xxx') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" doesn't accept \"Z\" — only the uppercase variants (X/XX/XXX) emit \"Z\" for UTC. ` +\n `Use \"+00:00\", \"+0000\", or \"+00\" depending on the variant's width.`\n );\n }\n /* c8 ignore stop @preserve */\n return '+00:00';\n }\n\n const sign = raw[0];\n /* c8 ignore start @preserve -- unreachable: raw is a regex-captured\n group from an offset token, and every OFFSET_SHAPES pattern\n (pattern.ts) is anchored to either \"Z\" or a leading [+-]. raw's\n first character can never be anything else by the time it reaches\n this function. */\n if (sign !== '+' && sign !== '-') {\n throw new Error(`temporal-fmt: offset \"${raw}\" for token \"${token}\" doesn't start with \"+\", \"-\", or \"Z\".`);\n }\n /* c8 ignore stop @preserve */\n const body = raw.slice(1);\n let hoursStr: string;\n let minutesStr: string;\n if (body.length === 2) {\n /* c8 ignore start @preserve -- unreachable: each offset token's own\n regex shape in OFFSET_SHAPES (pattern.ts) already gates which\n body shapes it can capture. Only X and x ever match a 2-digit\n body — XX/xx/XXX/xxx's regexes can't produce one — so this\n mismatch can never actually fire through parse(). */\n // +HH — only X/x emit this shape; XX/xx/XXX/xxx always carry minutes.\n if (token !== 'X' && token !== 'x') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" can't match \"${raw}\" — it requires minutes, but \"${raw}\" has none.`\n );\n }\n /* c8 ignore stop @preserve */\n hoursStr = body;\n minutesStr = '00';\n } else if (body.length === 4) {\n /* c8 ignore start @preserve -- unreachable, same reason as the\n 2-digit case above: XXX/xxx's regex requires a colon, so it can\n never capture a 4-digit no-colon body in the first place. */\n // +HHMM — X/x (when minutes are non-zero) or XX/xx.\n if (token === 'XXX' || token === 'xxx') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" can't match \"${raw}\" — it requires a colon between hours and minutes (e.g. \"${sign}${body.slice(0, 2)}:${body.slice(2)}\").`\n );\n }\n /* c8 ignore stop @preserve */\n hoursStr = body.slice(0, 2);\n minutesStr = body.slice(2, 4);\n } else if (body.length === 5 && body[2] === ':') {\n /* c8 ignore start @preserve -- unreachable, same reason again: only\n XXX/xxx's regex can produce a colon-shaped body; X/x/XX/xx never\n capture one. */\n // +HH:MM — XXX/xxx only.\n if (token !== 'XXX' && token !== 'xxx') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" can't match \"${raw}\" — it doesn't use a colon (use \"${sign}${body.slice(0, 2)}${body.slice(3)}\" instead).`\n );\n }\n /* c8 ignore stop @preserve */\n hoursStr = body.slice(0, 2);\n minutesStr = body.slice(3, 5);\n /* c8 ignore start @preserve -- unreachable: every offset token's\n regex only ever produces a body of length 2, length 4, or length 5\n with a colon at index 2 (see OFFSET_SHAPES in pattern.ts) — no\n shape falls outside those three cases, so this else arm can't be\n taken through parse(). Kept as an exhaustiveness fallback so\n hoursStr/minutesStr are assigned on every path TypeScript can see. */\n } else {\n throw new Error(`temporal-fmt: offset \"${raw}\" doesn't match the shape token \"${token}\" accepts.`);\n }\n /* c8 ignore stop @preserve */\n\n const hours = Number(hoursStr);\n const minutes = Number(minutesStr);\n // Per-piece range checks catch most malformed input.\n if (hours > 14) {\n throw new Error(\n `temporal-fmt: offset hours ${hours} in \"${raw}\" out of range (max 14 — Kiritimati, Line Islands is +14:00).`\n );\n }\n if (minutes > 59) {\n throw new Error(`temporal-fmt: offset minutes ${minutes} in \"${raw}\" out of range (max 59).`);\n }\n // Boundary: +14:01..+14:59 and -12:01..-12:59 are out of range even\n // though each piece alone is in bounds — the overall offset exceeds\n // the IANA-supported range.\n if (sign === '+' && hours === 14 && minutes !== 0) {\n throw new Error(\n `temporal-fmt: offset \"${raw}\" exceeds the maximum supported UTC offset of +14:00.`\n );\n }\n if (sign === '-' && hours === 12 && minutes !== 0) {\n throw new Error(\n `temporal-fmt: offset \"${raw}\" exceeds the maximum supported negative UTC offset of -12:00.`\n );\n }\n return `${sign}${hoursStr}:${minutesStr}`;\n}\n\nfunction assignField<T>(fields: Fields, key: keyof Fields, value: T): void {\n (fields as Record<string, T | undefined>)[key] = value;\n}\n\nfunction applyGroup(fields: Fields, token: string, raw: string, locale: string, formatStr: string): void {\n const vocab = getLocaleVocab(locale);\n switch (token) {\n case 'yyyy':\n assignField(fields, 'year', Number(raw));\n break;\n case 'yy':\n assignField(fields, 'twoDigitYear', Number(raw));\n break;\n case 'MM': case 'M':\n assignField(fields, 'month', Number(raw));\n break;\n case 'MMMM':\n assignField(fields, 'month', vocab.monthLong.indexOf(raw) + 1);\n break;\n case 'MMM':\n assignField(fields, 'month', vocab.monthShort.indexOf(raw) + 1);\n break;\n case 'dd': case 'd':\n assignField(fields, 'day', Number(raw));\n break;\n case 'EEEE':\n assignField(fields, 'weekdayRaw', raw);\n assignField(fields, 'weekdayExpected', vocab.weekdayLong.indexOf(raw) + 1);\n break;\n case 'EEE':\n assignField(fields, 'weekdayRaw', raw);\n assignField(fields, 'weekdayExpected', vocab.weekdayShort.indexOf(raw) + 1);\n break;\n case 'HH': case 'H':\n assignField(fields, 'hour', Number(raw));\n break;\n case 'hh': case 'h':\n assignField(fields, 'hour12', Number(raw));\n break;\n case 'mm': case 'm':\n assignField(fields, 'minute', Number(raw));\n break;\n case 'ss': case 's':\n assignField(fields, 'second', Number(raw));\n break;\n case 'S': case 'SS': case 'SSS': case 'SSSS': case 'SSSSS':\n case 'SSSSSS': case 'SSSSSSS': case 'SSSSSSSS': case 'SSSSSSSSS': {\n // The captured digits are the leading N digits of a nanosecond-of-second\n // value, not the whole thing — \"5\" under SSSSSSSSS means 500000000ns\n // (half a second), not 5ns. Right-padding to 9 digits before splitting\n // is what makes that work; left-padding (or just Number(raw)) would\n // read \"5\" as 5ns instead.\n const nanoOfSecond = Number(raw.padEnd(9, '0'));\n assignField(fields, 'millisecond', Math.floor(nanoOfSecond / 1_000_000));\n assignField(fields, 'microsecond', Math.floor(nanoOfSecond / 1_000) % 1_000);\n assignField(fields, 'nanosecond', nanoOfSecond % 1_000);\n break;\n }\n case 'a': {\n // Matches case-insensitively (see pattern.ts's foldCase), so the\n // lookup here has to fold too, or \"pm\" would pass the regex and\n // then fail this indexOf against the exact-case vocab.\n const periodIndex = vocab.dayPeriod.findIndex((p) => p.toLowerCase() === raw.toLowerCase());\n /* c8 ignore start @preserve -- unreachable: the 'a' token's regex\n fragment (pattern.ts's alternation() over vocab.dayPeriod) can\n only ever capture a case-insensitive match of one of\n vocab.dayPeriod's own entries. Both the regex and this lookup\n derive their vocab from the same `locale` via getLocaleVocab(),\n so periodIndex can't come back negative through parse(). */\n if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period \"${raw}\" for locale \"${locale}\".`);\n /* c8 ignore stop @preserve */\n assignField(fields, 'dayPeriodRaw', raw);\n assignField(fields, 'isPM', periodIndex === 1);\n break;\n }\n case 'zzz':\n assignField(fields, 'timeZoneId', raw);\n break;\n case 'X': case 'XX': case 'XXX':\n case 'x': case 'xx': case 'xxx':\n assignField(fields, 'offsetString', parseOffsetString(raw, token));\n break;\n case 'Q':\n assignField(fields, 'quarter', Number(raw));\n break;\n case 'QQQ':\n // strips the literal \"Q\" prefix the token itself formats; the suffix\n // digit is the quarter value 1-4\n assignField(fields, 'quarter', Number(raw.slice(1)));\n break;\n }\n}\n\n// The lenient split-selection heuristic for ambiguous glued numeric runs.\n// See README \"Lenient parse mode\" — the strict default throws on these,\n// lenient mode opts into picking one split instead.\nfunction pickLenientSplit(splits: number[][], tokens: string[]): number[] {\n // Prefer the split where a \"d\" (day) token, if any, has a value of 12 or\n // less. Rationale: when a person writes a glued run like \"121\" for an\n // Md format string, the reading \"Dec 1\" (M=12, d=1) is what they\n // typically meant — if they meant \"Jan 21\" they would more often have\n // written it as \"1/21\" or \"01/21\" with a separator or padding, since the\n // 2-digit day is the more naturally-cohesive unit to keep glued. This\n // isn't a guarantee, which is exactly why lenient mode is opt-in — but\n // it's a reasonable default when the caller has asked us to guess.\n const dayIndex = tokens.indexOf('d');\n if (dayIndex !== -1) {\n const smallDaySplits = splits.filter((s) => s[dayIndex]! <= 12);\n if (smallDaySplits.length > 0) {\n return smallDaySplits[0]!;\n }\n }\n // Fallback to the first valid split when the day heuristic doesn't\n // narrow it down — deterministic, and \"first\" here means \"whichever\n // enumerateValidSplits returned first\", which is a depth-first\n // leftmost-shortest walk over the candidate splits.\n return splits[0]!;\n}\n\n// emulates strptime (POSIX) for 2-digit years so the result doesn't depend\n// on the current clock: 00-68 -> 2000-2068, 69-99 -> 1900-1999\n// https://www.man7.org/linux//man-pages/man3/strptime.3p.html\nfunction resolveYear(fields: Fields): number | undefined {\n if (fields.year !== undefined && fields.twoDigitYear !== undefined) {\n throw new Error(\n 'temporal-fmt: format string mixes \"yyyy\" and \"yy\" year representations.'\n );\n }\n if (fields.year !== undefined) return fields.year;\n if (fields.twoDigitYear !== undefined) {\n return fields.twoDigitYear <= 68 ? 2000 + fields.twoDigitYear : 1900 + fields.twoDigitYear;\n }\n return undefined;\n}\n\nfunction resolveHour(fields: Fields, formatStr: string, locale: string): number | undefined {\n if (fields.hour !== undefined && fields.hour12 !== undefined) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" mixes a 24-hour token (\"HH\"/\"H\") with a ` +\n `12-hour token (\"hh\"/\"h\").`\n );\n }\n if (fields.hour !== undefined) {\n if (fields.dayPeriodRaw !== undefined) {\n const vocab = getLocaleVocab(locale);\n const expected = fields.hour < 12 ? vocab.dayPeriod[0] : vocab.dayPeriod[1];\n if (fields.dayPeriodRaw.toLowerCase() !== expected?.toLowerCase()) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" contains a day period that contradicts the 24-hour value.`\n );\n }\n }\n return fields.hour;\n }\n if (fields.hour12 !== undefined) {\n if (fields.isPM === undefined) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" uses a 12-hour token (\"hh\"/\"h\") without an \"a\" token, ` +\n `so parse() can't tell AM from PM.`\n );\n }\n return (fields.hour12 % 12) + (fields.isPM ? 12 : 0);\n }\n return undefined;\n}\n\n/**\n * Parses `input` against `formatStr` and builds the real Temporal value it\n * describes: a `Temporal.PlainDate`, `PlainTime`, `PlainDateTime`, or\n * `ZonedDateTime` depending on which tokens are present.\n *\n * Returns `unknown` — this package has no ambient `Temporal` types to return\n * a real one against.\n *\n * `options.locale` picks the calendar the result is built in. Pass a locale\n * tag with a `-u-ca-` extension (e.g. `'en-u-ca-hebrew'`) to parse into a\n * non-Gregorian calendar.\n *\n * @throws if `input` doesn't match `formatStr`'s shape at all\n * @throws if it matches the shape but describes an impossible date (e.g. Feb\n * 30) or self-contradictory data (e.g. a weekday name that doesn't match the\n * actual date)\n *\n * @example\n * parse('yyyy-MM-dd HH:mm', '2026-08-04 15:45') // Temporal.PlainDateTime\n * parse('yyyy-MM', '2026-08-04T15:45:30') // throws — shape doesn't match\n * parse('yyyy-MM-dd', '2026-02-30') // throws — not a real date\n */\nexport function parse(formatStr: string, input: string, options: NumberingParseOptions = {}): unknown | undefined {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n\n if (input.length > MAX_INPUT_LENGTH) {\n throw new Error(\n `temporal-fmt: input exceeds maximum length of ${MAX_INPUT_LENGTH} characters (got ${input.length}).`\n );\n }\n\n // Transliterate non-ASCII numerals to ASCII before any matching happens,\n // when the caller opts in via parseNumberingSystem. Every regex this\n // module builds expects 0-9; this is the one place that assumption\n // could otherwise be violated by locale-native input digits.\n if (options.parseNumberingSystem) {\n input = applyParseNumbering(input, options);\n }\n\n const locale = options.locale ?? DEFAULT_LOCALE;\n const calendar = resolveCalendar(locale);\n const pattern = getPattern(formatStr, locale);\n const match = pattern.regex.exec(input);\n if (!match) {\n throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);\n }\n\n if (pattern.groups.length === 0) {\n throw new Error(`temporal-fmt: format string \"${formatStr}\" has no tokens — nothing to parse into a value.`);\n }\n\n // The regex's zzz fragment only matches a bounded zone-id *shape* (see\n // TIME_ZONE_SHAPE in pattern.ts) rather than alternating every real IANA\n // name inline, so a shape match isn't proof of a real zone yet — check\n // Zone ids can't be enumerated in the regex itself (there are ~400 of\n // them and they change over time as IANA updates the tz database), so\n // the regex only captures the zzz group's shape and this loop checks\n // each captured zzz group against the actual zone list here. Unlike a\n // regex-shape mismatch, this failure has a specific cause worth\n // naming: the shape matched but the zone id itself isn't recognized.\n for (const { name, token } of pattern.groups) {\n if (token === 'zzz' && !isValidTimeZone(match.groups![name]!)) {\n throw new InvalidTimeZoneError({\n input, format: formatStr, actual: match.groups![name],\n reason: 'not a recognized IANA time zone identifier',\n });\n }\n }\n\n // A run of 2+ adjacent unpadded-numeric tokens with no literal separator\n // (e.g. \"Md\", \"dM\", \"Hms\") can have more than one way to split the\n // digits it matched that's independently valid for every token in the\n // run — see the comment on NUMERIC_FRAGMENTS in pattern.ts for the\n // mechanism. The regex above only ever finds one such split (whichever\n // its alternation ordering happens to prefer); silently trusting that\n // one would mean parse() sometimes returns a value indistinguishable\n // from a different, equally valid value the same input could describe.\n // Rather than guess, check every ambiguous run explicitly. Strict mode\n // (the default) throws; lenient mode opts into picking one split via a\n // documented heuristic. The input itself is what's ambiguous, not a\n // fixable property of the pattern.\n // Glued-run split handling (0.9.2 ReDoS fix): each run of 2+ adjacent\n // unpadded-numeric tokens is now captured by a SINGLE bounded regex\n // group (see buildCapturingPattern in parsePattern.ts) instead of one\n // variable-width fragment per token — the per-token split is resolved\n // here, after the match, by the same enumerateValidSplits() machinery\n // that already detected ambiguous runs. Unique split resolves; 2+\n // valid splits throws in strict mode / heuristic-picks in lenient\n // mode (unchanged from before); a span that matched the run's overall\n // width window but names no valid per-token assignment (0 splits) is\n // a mismatch, which the old per-token fragments used to reject at\n // match time — surface the same \"no valid pattern matches\" error here\n // instead of letting it slip through as a phantom match.\n const runValues = new Map<string, string>();\n for (const run of pattern.ambiguousRuns) {\n const runDigits = match.groups![run.groupName]!;\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length === 0) {\n throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);\n }\n if (splits.length > 1) {\n // Strict default — throw on ambiguity. The whole point of the\n // library's parse() is to refuse to guess when the same input has\n // more than one valid reading. Lenient mode (opt-in via\n // options.lenient) instead picks one split via a documented\n // heuristic — see pickLenientSplit() above and the README section\n // \"Lenient parse mode\" for why this is strictly additive and never\n // the default.\n if (!options.lenient) {\n throw new Error(\n `temporal-fmt: \"${runDigits}\" in format string \"${formatStr}\" is ambiguous — ` +\n `${splits.length} different ways to read tokens \"${run.tokens.join('')}\" (with no separator ` +\n `between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). ` +\n `parse() won't guess; add a separator between these tokens, or use their padded form ` +\n `(e.g. \"MM\" instead of \"M\") so each one has a fixed width. ` +\n `Pass { lenient: true } to opt into a documented heuristic that picks one.`\n );\n }\n const picked = pickLenientSplit(splits, run.tokens);\n run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));\n } else {\n run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0]![idx])));\n }\n }\n\n const fields: Fields = {};\n // Per-token values for glued-run members come from the split\n // enumeration above (runValues); every other token reads its own\n // regex group directly.\n for (const { name, token } of pattern.groups) {\n const raw = runValues.get(name) ?? match.groups![name]!;\n applyGroup(fields, token, raw, locale, formatStr);\n }\n\n const year = resolveYear(fields);\n const hour = resolveHour(fields, formatStr, locale);\n const { month, day, minute, second, millisecond, microsecond, nanosecond, timeZoneId, offsetString, weekdayExpected, weekdayRaw, quarter } = fields;\n\n const hasAnyDatePart = year !== undefined || month !== undefined || day !== undefined;\n const hasFullDate = year !== undefined && month !== undefined && day !== undefined;\n if (hasAnyDatePart && !hasFullDate) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" has an incomplete date — ` +\n `year, month, and day tokens must all be present together.`\n );\n }\n\n const hasTime = hour !== undefined || minute !== undefined || second !== undefined || millisecond !== undefined;\n\n if (timeZoneId !== undefined && !(hasFullDate && hasTime)) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" has a \"zzz\" token but needs a full date and time ` +\n `to build a ZonedDateTime.`\n );\n }\n\n // Mirror zzz's full-date-and-time requirement: an offset alone is\n // meaningless without a wall-clock instant to anchor it to. Throws the\n // same kind of \"needs full date and time\" error zzz throws — separate\n // message so a caller reading it can tell which token type they\n // forgot to pair with a full date+time.\n if (offsetString !== undefined && !(hasFullDate && hasTime)) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" has an offset token (X/XX/XXX/x/xx/xxx) but needs a full date and time ` +\n `to build a ZonedDateTime.`\n );\n }\n\n if (weekdayExpected !== undefined && !hasFullDate) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" has a weekday token (\"EEEE\"/\"EEE\") but needs ` +\n `a full date to validate it against.`\n );\n }\n\n if (!hasFullDate && !hasTime) {\n // shouldn't happen — every token maps to a date, time, zone, or\n // weekday field, and weekday-without-date already threw above\n throw new Error(`temporal-fmt: format string \"${formatStr}\" has no date or time tokens to parse.`);\n }\n\n const temporal = getTemporal();\n const timeFields = {\n hour: hour ?? 0,\n minute: minute ?? 0,\n second: second ?? 0,\n millisecond: millisecond ?? 0,\n microsecond: microsecond ?? 0,\n nanosecond: nanosecond ?? 0,\n };\n // omitted entirely for the default calendar (see resolveCalendar) so\n // construction stays plain ISO 8601 unless a caller's locale asks for\n // something else — Temporal calendars don't apply to time-only values.\n const calendarField = calendar ? { calendar } : {};\n\n // overflow: 'reject' — without it Temporal *clamps* out-of-range fields\n // (Feb 30 silently becomes Feb 28) instead of throwing, which would\n // contradict the \"throws on genuinely invalid data\" behavior parse() promises.\n const reject = { overflow: 'reject' as const };\n\n let result: unknown;\n try {\n if (timeZoneId !== undefined) {\n // offset: 'prefer' never throws on a mismatch — it just falls back to\n // the zone's real offset at this instant, silently overriding\n // whatever the offset token said. That's also what resolves a\n // repeated wall-clock time (DST fall-back): without an explicit\n // offset, Temporal defaults to the first occurrence, so passing the\n // token's offset here is what lets a second-occurrence input resolve\n // to the second occurrence instead of always falling back to the\n // first. Either way, \"prefer\" can't be used to detect disagreement —\n // that's checked explicitly below, once we have a real ZonedDateTime\n // to compare against, instead of relying on the wording of whatever\n // error Temporal's active implementation happens to throw (that\n // wording isn't part of the spec and differs between the native\n // Temporal global and userland polyfills).\n const zoneOptions: Temporal.ZonedDateTimeFromOptions = { overflow: 'reject', offset: 'prefer' };\n result = temporal.ZonedDateTime.from(\n {\n year: year!, month: month!, day: day!, ...timeFields, ...calendarField,\n timeZone: timeZoneId,\n ...(offsetString !== undefined ? { offset: offsetString } : {}),\n },\n zoneOptions\n );\n if (offsetString !== undefined) {\n // 'prefer' silently rewrites the wall-clock time itself when the\n // input falls in a DST gap (the time never occurred, so there's\n // no instant to prefer toward) — it doesn't just pick a\n // different offset for the same clock time, the way it does for\n // an overlap. Checking offsetString alone can't tell \"gap,\n // silently moved\" apart from \"overlap, correctly resolved,\"\n // since both can produce an actualOffset that differs from what\n // was parsed. Comparing the wall-clock fields catches the gap\n // case: they can only drift from the parsed input if Temporal\n // moved the clock time to escape the gap.\n //\n // Only checked when an offset token was given: with no offset\n // token to disagree with, a gap shifting forward is the\n // documented, wanted behavior (there's nothing to reject against).\n const zdt = result as Temporal.ZonedDateTime;\n const wallClockShifted =\n zdt.hour !== timeFields.hour ||\n zdt.minute !== timeFields.minute ||\n zdt.second !== timeFields.second;\n if (wallClockShifted) {\n throw new Error(\n `\"${timeZoneId}\" has no such wall-clock time on this date — it falls in a DST gap, ` +\n `not an ambiguous or valid instant.`\n );\n }\n const actualOffset = zdt.offset;\n if (actualOffset !== offsetString) {\n throw new Error(\n `has both a \"zzz\" zone (${timeZoneId}) and an offset token (${offsetString}), ` +\n `but the zone's actual offset at this date/time is ${actualOffset}, not ${offsetString}.`\n );\n }\n }\n } else if (offsetString !== undefined) {\n // Pattern had an offset token but no zzz. Use the offset string\n // directly as the timeZone — Temporal accepts a fixed-offset\n // string and produces a ZonedDateTime whose timeZoneId is the\n // offset string itself (e.g. \"+09:00\"). Same shape zzz produces\n // when it parses a fixed offset, just reached via a different\n // token.\n result = temporal.ZonedDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField, timeZone: offsetString }, reject);\n } else if (hasFullDate && hasTime) {\n result = temporal.PlainDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField }, reject);\n } else if (hasFullDate) {\n result = temporal.PlainDate.from({ year: year!, month: month!, day: day!, ...calendarField }, reject);\n } else {\n result = temporal.PlainTime.from(timeFields, reject);\n }\n } catch (err) {\n throw new Error(\n `temporal-fmt: \"${input}\" doesn't describe a valid date/time for format \"${formatStr}\": ` +\n `${(err as Error).message}`\n );\n }\n\n if (weekdayExpected !== undefined) {\n const actual = (result as { dayOfWeek: number }).dayOfWeek;\n if (actual !== weekdayExpected) {\n const vocab = getLocaleVocab(locale);\n throw new Error(\n `temporal-fmt: \"${weekdayRaw}\" doesn't match the actual weekday (${vocab.weekdayLong[actual - 1]}) ` +\n `for the parsed date.`\n );\n }\n }\n\n // Q/QQQ is a derived field of the month: 1-3 -> Q1, 4-6 -> Q2, 7-9 -> Q3,\n // 10-12 -> Q4. If a format string carries a quarter token alongside\n // month/date tokens, parse() cross-checks the parsed quarter against the\n // month the same way EEEE cross-checks weekday against date — silently\n // accepting a mismatch would defeat the point of having a quarter token\n // at all, since you'd be telling parse() one thing and the date another.\n if (quarter !== undefined && month !== undefined) {\n const expectedQuarter = Math.ceil(month / 3);\n if (quarter !== expectedQuarter) {\n throw new Error(\n `temporal-fmt: format string \"${formatStr}\" contains a quarter token (Q/QQQ) whose value ` +\n `(Q${quarter}) disagrees with the parsed month's actual quarter — month ${month} is in ` +\n `Q${expectedQuarter}.`\n );\n }\n }\n\n return result;\n}\n\n// safeParse: returns a discriminated union instead of throwing. The\n// happy path returns `{ ok: true, value }` with the Temporal instance\n// (typed as `unknown` since this package has no ambient Temporal types).\n// The error path returns `{ ok: false, error }` where `error` is a\n// `TemporalFmtError` subclass when the failure is one the typed-error\n// surface in errors.ts knows how to classify (most of them), or a\n// wrapped plain `Error` (still inside a TemporalFmtError shell) when\n// the throw site hasn't been migrated yet. Callers needing the original\n// thrown object for backward compatibility should use parse() directly.\nexport type SafeParseResult =\n | { ok: true; value: unknown }\n | { ok: false; error: TemporalFmtError };\n\nexport function safeParse(formatStr: string, input: string, options: NumberingParseOptions = {}): SafeParseResult {\n try {\n return { ok: true, value: parse(formatStr, input, options) };\n } catch (err) {\n // Pass through typed errors unchanged — preserves the structured\n // fields (code/token/position/etc.) the existing typed-error\n // surface already populated.\n if (err instanceof TemporalFmtError) {\n return { ok: false, error: err };\n }\n return { ok: false, error: wrapUntypedError(err as Error, { input, format: formatStr }) };\n }\n}\n\n// tryParse: best-effort variant. Returns the parsed value or undefined.\n// Suppresses diagnostics entirely — when callers need the reason for\n// a failure, they should use safeParse(). Intentionally loose on the\n// return type (unknown) since this package has no ambient Temporal\n// types to return a real one against.\nexport function tryParse(formatStr: string, input: string, options: NumberingParseOptions = {}): unknown | undefined {\n try {\n return parse(formatStr, input, options);\n } catch {\n return undefined;\n }\n}\n\n// parseToParts: returns the matched groups with token labels, before\n// any Temporal construction. Useful for callers that want to inspect\n// what each token captured (e.g. to build a non-Temporal result, or to\n// cross-check fields themselves) without committing to the inferred\n// Temporal type parse() would build.\n//\n// Throws the same errors parse() throws for early validation (unknown\n// token, unterminated quote, no-match, ambiguity in strict mode) since\n// those failures happen before any group assignment. Construction-time\n// errors (Feb 30, weekday mismatch, etc.) do not happen here —\n// parseToParts doesn't construct anything, so it can't fail at that step.\nexport interface ParsedPart {\n token: string;\n raw: string;\n // Field name (year/month/day/...) this token would assign if handed\n // to parse()'s applyGroup loop. undefined for tokens that don't map\n // to a single field (none today, but kept here so future additions\n // don't have to widen the type).\n field?: string;\n // Position of `raw` in `input`, 0-indexed. Lets a caller highlight\n // the matched span in an editor/CLI.\n position: number;\n}\n\nexport function parseToParts(formatStr: string, input: string, options: NumberingParseOptions = {}): ParsedPart[] {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n if (input.length > MAX_INPUT_LENGTH) {\n throw new Error(\n `temporal-fmt: input exceeds maximum length of ${MAX_INPUT_LENGTH} characters (got ${input.length}).`\n );\n }\n\n // Same numeral transliteration parse() does — see the comment there.\n if (options.parseNumberingSystem) {\n input = applyParseNumbering(input, options);\n }\n\n const locale = options.locale ?? DEFAULT_LOCALE;\n const pattern = getPattern(formatStr, locale);\n const match = pattern.regex.exec(input);\n if (!match) {\n throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);\n }\n if (pattern.groups.length === 0) {\n throw new Error(`temporal-fmt: format string \"${formatStr}\" has no tokens — nothing to parse into a value.`);\n }\n // Same zzz shape-validation parse() does — kept here for parity, so\n // a caller using parseToParts sees the same InvalidTimeZoneError for\n // a bogus zone id, not a silently-accepted bogus zone.\n for (const { name, token } of pattern.groups) {\n if (token === 'zzz' && !isValidTimeZone(match.groups![name]!)) {\n throw new InvalidTimeZoneError({\n input, format: formatStr, actual: match.groups![name],\n reason: 'not a recognized IANA time zone identifier',\n });\n }\n }\n\n // Glued-run split handling (0.9.2 ReDoS fix): same as parse() — each\n // run's single regex group is split into per-token values by\n // enumerateValidSplits(); unique split resolves, 2+ splits throws in\n // strict mode / heuristic-picks in lenient, 0 splits is a shape\n // mismatch. parseToParts mirrors parse() so callers switching between\n // the two on the same input get consistent results.\n const runValues = new Map<string, string>();\n for (const run of pattern.ambiguousRuns) {\n const runDigits = match.groups![run.groupName]!;\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length === 0) {\n throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);\n }\n if (splits.length > 1) {\n if (!options.lenient) {\n throw new Error(\n `temporal-fmt: \"${runDigits}\" in format string \"${formatStr}\" is ambiguous — ` +\n `${splits.length} different ways to read tokens \"${run.tokens.join('')}\" (with no separator ` +\n `between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). ` +\n `parse() won't guess; add a separator between these tokens, or use their padded form ` +\n `(e.g. \"MM\" instead of \"M\") so each one has a fixed width. ` +\n `Pass { lenient: true } to opt into a documented heuristic that picks one.`\n );\n }\n const picked = pickLenientSplit(splits, run.tokens);\n run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));\n } else {\n run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0]![idx])));\n }\n }\n\n const parts: ParsedPart[] = [];\n // match.indices.groups (provided by the regex 'd' flag) gives the\n // [start, end] of each named group in the input. Used here so positions\n // are accurate even when literals separate tokens — summing raw\n // lengths alone wouldn't account for the literal characters between\n // groups. Falls back to the cumulative-raw-length heuristic on engines\n // without 'd' support (none we target, but the fallback keeps the\n // code robust if the flag is ever removed).\n const indices = (match as RegExpMatchArray & { indices?: { groups?: Record<string, [number, number]> } }).indices;\n const groupIndices = indices?.groups;\n let consumed = 0;\n for (const { name, token } of pattern.groups) {\n const raw = runValues.get(name) ?? match.groups![name]!;\n // Glued-run members have no regex group of their own — the regex's\n // recorded indices point at the run's overall span, not the\n // individual token's slice within it — so fall back to cumulative-\n // raw-length for them. Positions stay monotonic but may not be\n // exact for tokens inside a resolved run. Documented as a known\n // limitation; the alternative (re-running the regex with the chosen\n // split baked in) would mean a second match pass for a corner case\n // the caller opted into by gluing unpadded tokens.\n const fromIndices = !runValues.has(name) && groupIndices?.[name];\n /* c8 ignore next */\n const position = fromIndices ? fromIndices[0] : (match.index ?? 0) + consumed;\n parts.push({ token, raw, position });\n consumed += raw.length;\n }\n return parts;\n}\n\n// compileParser: pre-compiles a format string into an object whose\n// parse()/safeParse()/parseToParts() methods skip the per-call\n// pattern-cache lookup. The patternCache in this module means a plain\n// parse(fmt, input) call already pays only a Map lookup after the first\n// call, so compileParser is mostly an ergonomics affordance — useful\n// for callers who want to hold the compiled parser explicitly (e.g. to\n// inspect the pattern via the .pattern property).\nexport interface CompiledParser {\n parse(input: string, options?: NumberingParseOptions): unknown;\n safeParse(input: string, options?: NumberingParseOptions): SafeParseResult;\n tryParse(input: string, options?: NumberingParseOptions): unknown | undefined;\n parseToParts(input: string, options?: NumberingParseOptions): ParsedPart[];\n readonly formatStr: string;\n readonly pattern: CapturingPattern;\n}\n\nexport function compileParser(formatStr: string, options: NumberingParseOptions = {}): CompiledParser {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n // Pre-compile against the default locale; per-call locales will\n // re-resolve via getPattern() if they differ. Most callers use one\n // locale consistently, so pre-compiling against the default keeps\n // the fast path fast.\n const locale = options.locale ?? DEFAULT_LOCALE;\n const pattern = getPattern(formatStr, locale);\n return {\n formatStr,\n pattern,\n parse(input: string, opts: NumberingParseOptions = {}) {\n return parse(formatStr, input, { locale, ...opts });\n },\n safeParse(input: string, opts: NumberingParseOptions = {}) {\n return safeParse(formatStr, input, { locale, ...opts });\n },\n tryParse(input: string, opts: NumberingParseOptions = {}) {\n return tryParse(formatStr, input, { locale, ...opts });\n },\n parseToParts(input: string, opts: NumberingParseOptions = {}) {\n return parseToParts(formatStr, input, { locale, ...opts });\n },\n };\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,aAAa,SAAyB;AAC7C,SAAO,QAAQ,QAAQ,uBAAuB,MAAM;AACtD;AAEA,SAAS,YAAY,QAAkB,kBAAkB,OAAe;AACtE,QAAM,UAAU,OAAO,IAAI,YAAY;AACvC,MAAI,CAAC,gBAAiB,QAAO,MAAM,QAAQ,KAAK,GAAG,CAAC;AAKpD,SAAO,MAAM,QAAQ,IAAI,QAAQ,EAAE,KAAK,GAAG,CAAC;AAC9C;AAOA,SAAS,SAAS,OAAuB;AACvC,SAAO,MAAM,QAAQ,aAAa,CAAC,OAAO,IAAI,GAAG,YAAY,CAAC,GAAG,GA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