temporal-fmt 0.8.0 → 0.8.2

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.
@@ -0,0 +1,2 @@
1
+ export declare const MAX_FORMAT_LENGTH = 1000;
2
+ export declare const MAX_INPUT_LENGTH = 100000;
@@ -0,0 +1,13 @@
1
+ import { type TemporalLike, type FormatOptions } from './tokens.cjs';
2
+ /**
3
+ * Format a Temporal.PlainDate, PlainTime, PlainDateTime, or ZonedDateTime
4
+ * using a date-fns-style token string.
5
+ *
6
+ * @example
7
+ * format(Temporal.Now.plainDateISO(), 'yyyy-MM-dd') // "2026-08-04"
8
+ * format(zdt, "MMM d, yyyy 'at' h:mm a") // "Aug 4, 2026 at 3:45 PM"
9
+ * format(zdt, 'MMMM d, yyyy', { locale: 'fr-FR' }) // "août 4, 2026"
10
+ *
11
+ * Throws on a token the input type doesn't support (e.g. 'HH' on a PlainDate).
12
+ */
13
+ export declare function format(temporal: TemporalLike, formatStr: string, options?: FormatOptions): string;
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var V=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var me=Object.prototype.hasOwnProperty;var de=(e,t)=>{for(var n in t)V(e,n,{get:t[n],enumerable:!0})},ue=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of se(t))!me.call(e,o)&&o!==n&&V(e,o,{get:()=>t[o],enumerable:!(r=ie(t,o))||r.enumerable});return e};var ce=e=>ue(V({},"__esModule",{value:!0}),e);var Le={};de(Le,{format:()=>q,parse:()=>re,setTemporal:()=>W});module.exports=ce(Le);var X;function W(e){X=e}function le(){return X??globalThis.Temporal}function C(){let e=le();if(!e)throw new Error("temporal-fmt: parse() needs a Temporal implementation to construct its result. Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal (native on Node 26+, or a polyfill like temporal-polyfill).");return e}function k(e,t){let n=e<0,r=String(Math.abs(e)).padStart(t,"0");return n?"-"+r:r}var A="en-US",P=new Map,pe=500;function J(e,t){let n=JSON.stringify([e,t]),r=P.get(n);if(r)return r;if(P.size>=pe){let o=P.keys().next().value;o!==void 0&&P.delete(o)}return r=new Intl.DateTimeFormat(e,t),P.set(n,r),r}var I;function ge(){if(I===void 0){I=!1;try{let e=C();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),I=!0}catch{}}return I}function S(e,t,n,r){let o=e?.calendarId,a={...n,...o&&o!=="iso8601"?{calendar:o}:{}};if(!ge())return e.toLocaleString(t,a);let{toInstant:i,timeZoneId:s}=e,m=typeof i=="function"&&typeof s=="string",p=m?e.toInstant():e,c={...a,...m?{timeZone:s}:{}},h=J(t,c).formatToParts(p),y=h.findIndex(H=>H.type===r);if(y===-1)throw new Error(`temporal-fmt: locale "${t}" produced no "${r}" part for this token. This usually means the Temporal object is missing the field the token needs.`);let f=h[y].value,d=h[y-1],g=h[y+1];return d?.type==="literal"&&!/\s/.test(d.value)&&(f=d.value+f),g?.type==="literal"&&!/\s/.test(g.value)&&(f=f+g.value),f}function fe(e,t){let n=new Date(Date.UTC(1970,0,1,e)),o=J(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(n).find(a=>a.type==="dayPeriod");if(!o)throw new Error(`temporal-fmt: locale "${t}" produced no "dayPeriod" part for token "a".`);return o.value}var R=[["yyyy",e=>k(e.year,4),"year"],["yy",e=>{if(e.year<0)throw new Error(`temporal-fmt: token "yy" doesn't support negative years (got ${e.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`);return k(e.year%100,2)},"year"],["MMMM",(e,t)=>S(e,t,{month:"long"},"month"),"month"],["MMM",(e,t)=>S(e,t,{month:"short"},"month"),"month"],["MM",e=>k(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>k(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,t)=>S(e,t,{weekday:"long"},"weekday"),"dayOfWeek"],["EEE",(e,t)=>S(e,t,{weekday:"short"},"weekday"),"dayOfWeek"],["HH",e=>k(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>k(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>k(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>k(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSS",e=>k(e.millisecond,3),"millisecond"],["a",(e,t)=>fe(e.hour,t),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"]];var he=R.map(([e])=>e).sort((e,t)=>t.length-e.length);function _(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r==="'"){if(e[n+1]==="'"){Y(t,"'"),n+=2;continue}let a=n+1,i="",s=!1;for(;a<e.length;){if(e[a]==="'"){if(e[a+1]==="'"){i+="'",a+=2;continue}s=!0,a+=1;break}i+=e[a],a+=1}if(!s)throw new Error(`temporal-fmt: unterminated quote in format string "${e}"`);Y(t,i),n=a;continue}let o=he.find(a=>e.startsWith(a,n));if(o){t.push({kind:"token",value:o}),n+=o.length;continue}Y(t,r),n+=1}return t}function Y(e,t){let n=e[e.length-1];n&&n.kind==="literal"?n.value+=t:e.push({kind:"literal",value:t})}var ye=new Map(R.map(([e,t,n])=>[e,{fn:t,field:n}]));function q(e,t,n={}){if(t.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${t.length}).`);let r=n.locale??A,o=_(t),a="";for(let i of o){if(i.kind==="literal"){a+=i.value;continue}let s=ye.get(i.value);if(!s)throw new Error(`temporal-fmt: unknown token "${i.value}"`);if(e[s.field]===void 0)throw new Error(`temporal-fmt: token "${i.value}" requires "${s.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`);a+=s.fn(e,r)}return a}var $=new Map,we=500;function x(e,t,n){let r=e.formatToParts(t),o=r.findIndex(m=>m.type===n);if(o===-1)throw new Error(`temporal-fmt: locale produced no "${n}" part while building match vocabulary.`);let a=r[o].value,i=r[o-1],s=r[o+1];return i?.type==="literal"&&!/\s/.test(i.value)&&(a=i.value+a),s?.type==="literal"&&!/\s/.test(s.value)&&(a=a+s.value),a}function Z(e,t,n){let r=new Map;for(let o=0;o<e.length;o++){let a=r.get(e[o]);if(a!==void 0)throw new Error(`temporal-fmt: locale "${n}" renders ${t} index ${a} and ${o} identically ("${e[o]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);r.set(e[o],o)}}function v(e){let t=$.get(e);if(t)return t;let n=new Intl.DateTimeFormat(e,{month:"long",timeZone:"UTC"}),r=new Intl.DateTimeFormat(e,{month:"short",timeZone:"UTC"}),o=[],a=[];for(let d=0;d<12;d++){let g=new Date(Date.UTC(2020,d,1));o.push(x(n,g,"month")),a.push(x(r,g,"month"))}Z(o,"MMMM month",e),Z(a,"MMM month",e);let i=new Intl.DateTimeFormat(e,{weekday:"long",timeZone:"UTC"}),s=new Intl.DateTimeFormat(e,{weekday:"short",timeZone:"UTC"}),m=[],p=[];for(let d=0;d<7;d++){let g=new Date(Date.UTC(2024,0,1+d));m.push(x(i,g,"weekday")),p.push(x(s,g,"weekday"))}Z(m,"EEEE weekday",e),Z(p,"EEE weekday",e);let c=new Intl.DateTimeFormat(e,{hour:"numeric",hour12:!0,timeZone:"UTC"}),l=x(c,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),h=x(c,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),y=[...new Set([l,h])],f={monthLong:o,monthShort:a,weekdayLong:m,weekdayShort:p,dayPeriod:y};if($.size>=we){let d=$.keys().next().value;d!==void 0&&$.delete(d)}return $.set(e,f),f}function B(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function M(e){return`(?:${e.map(B).join("|")})`}var U;function ke(){if(U)return U;let t=Intl.supportedValuesOf("timeZone").map(B);return U=`(?:UTC|[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?|${M(t)})`,U}var Ee={yyyy:"\\d{4}",yy:"\\d{2}",MM:"(?:0[1-9]|1[0-2])",M:"(?:1[0-2]|[1-9])",dd:"(?:0[1-9]|[12]\\d|3[01])",d:"(?:[12]\\d|3[01]|[1-9])",HH:"(?:[01]\\d|2[0-3])",H:"(?:1\\d|2[0-3]|[0-9])",hh:"(?:0[1-9]|1[0-2])",h:"(?:1[0-2]|[1-9])",mm:"(?:[0-5]\\d)",m:"(?:[1-5]\\d|[0-9])",ss:"(?:[0-5]\\d)",s:"(?:[1-5]\\d|[0-9])",SSS:"\\d{3}"};function Q(e,t){let n=Ee[e];if(n)return n;let r=v(t);switch(e){case"MMMM":return M(r.monthLong);case"MMM":return M(r.monthShort);case"EEEE":return M(r.weekdayLong);case"EEE":return M(r.weekdayShort);case"a":return M(r.dayPeriod);case"zzz":return ke();default:throw new Error(`temporal-fmt: unknown token "${e}"`)}}var ee=new Set(["M","d","H","h","m","s"]),Te={M:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],d:[{digits:1,min:1,max:9},{digits:2,min:10,max:31}],H:[{digits:1,min:0,max:9},{digits:2,min:10,max:23}],h:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],m:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}],s:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}]};function te(e,t){let n=new Map;function r(o,a){let i=`${o}:${a}`,s=n.get(i);if(s)return s;if(o===t.length){let l=a===e.length?[[]]:[];return n.set(i,l),l}let m=t[o],p=Te[m];if(!p)throw new Error(`temporal-fmt: internal error \u2014 "${m}" is not an unpadded numeric token`);let c=[];for(let{digits:l,min:h,max:y}of p){if(a+l>e.length)continue;let f=e.slice(a,a+l);if(l===2&&f[0]==="0")continue;let d=Number(f);if(!(d<h||d>y)){for(let g of r(o+1,a+l))if(c.push([d,...g]),c.length===2)break;if(c.length===2)break}}return n.set(i,c),c}return r(0,0)}function be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ne(e,t){let n=[],r=[],o="",a=0,i={groupNames:[],tokens:[]},s=()=>{i.tokens.length>=2&&r.push(i),i={groupNames:[],tokens:[]}};for(let m of e){if(m.kind==="literal"){o+=be(m.value),s();continue}let p=`g${a++}`;n.push({name:p,token:m.value}),o+=`(?<${p}>${Q(m.value,t)})`,ee.has(m.value)?(i.groupNames.push(p),i.tokens.push(m.value)):s()}return s(),{regex:new RegExp(`^(?:${o})$`,"u"),groups:n,ambiguousRuns:r}}var F=new Map,ve=500;function Me(e,t){let n=JSON.stringify([t,e]),r=F.get(n);if(r)return r;if(F.size>=ve){let o=F.keys().next().value;o!==void 0&&F.delete(o)}return r=ne(_(e),t),F.set(n,r),r}var D=new Map,De=500;function Pe(e){if(D.has(e))return D.get(e);if(D.size>=De){let i=D.keys().next().value;i!==void 0&&D.delete(i)}let t,n=new Intl.Locale(e).toString().toLowerCase(),r=n.split("-"),o=r.indexOf("u"),a=o===-1?-1:r.indexOf("ca",o+1);if(a!==-1&&a+1<r.length){let i=new Intl.DateTimeFormat(n).resolvedOptions().calendar;t=i==="gregory"?void 0:i}return D.set(e,t),t}function u(e,t,n){e[t]=n}function $e(e,t,n,r,o){let a=v(r);switch(t){case"yyyy":u(e,"year",Number(n));break;case"yy":u(e,"twoDigitYear",Number(n));break;case"MM":case"M":u(e,"month",Number(n));break;case"MMMM":u(e,"month",a.monthLong.indexOf(n)+1);break;case"MMM":u(e,"month",a.monthShort.indexOf(n)+1);break;case"dd":case"d":u(e,"day",Number(n));break;case"EEEE":u(e,"weekdayRaw",n),u(e,"weekdayExpected",a.weekdayLong.indexOf(n)+1);break;case"EEE":u(e,"weekdayRaw",n),u(e,"weekdayExpected",a.weekdayShort.indexOf(n)+1);break;case"HH":case"H":u(e,"hour",Number(n));break;case"hh":case"h":u(e,"hour12",Number(n));break;case"mm":case"m":u(e,"minute",Number(n));break;case"ss":case"s":u(e,"second",Number(n));break;case"SSS":u(e,"millisecond",Number(n));break;case"a":{let i=a.dayPeriod.indexOf(n);if(i<0)throw new Error(`temporal-fmt: unknown day period "${n}" for locale "${r}".`);u(e,"dayPeriodRaw",n),u(e,"isPM",i===1);break}case"zzz":u(e,"timeZoneId",n);break}}function Fe(e){if(e.year!==void 0&&e.twoDigitYear!==void 0)throw new Error('temporal-fmt: format string mixes "yyyy" and "yy" year representations.');if(e.year!==void 0)return e.year;if(e.twoDigitYear!==void 0)return e.twoDigitYear<=68?2e3+e.twoDigitYear:1900+e.twoDigitYear}function Ne(e,t,n){if(e.hour!==void 0&&e.hour12!==void 0)throw new Error(`temporal-fmt: format string "${t}" mixes a 24-hour token ("HH"/"H") with a 12-hour token ("hh"/"h").`);if(e.hour!==void 0){if(e.dayPeriodRaw!==void 0){let r=v(n),o=e.hour<12?r.dayPeriod[0]:r.dayPeriod[1];if(e.dayPeriodRaw!==o)throw new Error(`temporal-fmt: format string "${t}" contains a day period that contradicts the 24-hour value.`)}return e.hour}if(e.hour12!==void 0){if(e.isPM===void 0)throw new Error(`temporal-fmt: format string "${t}" uses a 12-hour token ("hh"/"h") without an "a" token, so parse() can't tell AM from PM.`);return e.hour12%12+(e.isPM?12:0)}}function re(e,t,n={}){if(e.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${e.length}).`);if(t.length>1e5)throw new Error(`temporal-fmt: input exceeds maximum length of ${1e5} characters (got ${t.length}).`);let r=n.locale??A,o=Pe(r),a=Me(e,r),i=a.regex.exec(t);if(!i)throw new Error("temporal-fmt: no valid pattern matches the format string and input shape");if(a.groups.length===0)throw new Error(`temporal-fmt: format string "${e}" has no tokens \u2014 nothing to parse into a value.`);for(let w of a.ambiguousRuns){let b=w.groupNames.map(ae=>i.groups[ae]).join(""),O=te(b,w.tokens);if(O.length>1)throw new Error(`temporal-fmt: "${b}" in format string "${e}" is ambiguous \u2014 ${O.length} different ways to read tokens "${w.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(O[0])} vs ${JSON.stringify(O[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.`)}let s={};for(let{name:w,token:b}of a.groups)$e(s,b,i.groups[w],r,e);let m=Fe(s),p=Ne(s,e,r),{month:c,day:l,minute:h,second:y,millisecond:f,timeZoneId:d,weekdayExpected:g,weekdayRaw:H}=s,oe=m!==void 0||c!==void 0||l!==void 0,E=m!==void 0&&c!==void 0&&l!==void 0;if(oe&&!E)throw new Error(`temporal-fmt: format string "${e}" has an incomplete date \u2014 year, month, and day tokens must all be present together.`);let z=p!==void 0||h!==void 0||y!==void 0||f!==void 0;if(d!==void 0&&!(E&&z))throw new Error(`temporal-fmt: format string "${e}" has a "zzz" token but needs a full date and time to build a ZonedDateTime.`);if(g!==void 0&&!E)throw new Error(`temporal-fmt: format string "${e}" has a weekday token ("EEEE"/"EEE") but needs a full date to validate it against.`);if(!E&&!z)throw new Error(`temporal-fmt: format string "${e}" has no date or time tokens to parse.`);let N=C(),j={hour:p??0,minute:h??0,second:y??0,millisecond:f??0},K=o?{calendar:o}:{},L={overflow:"reject"},T;try{d!==void 0?T=N.ZonedDateTime.from({year:m,month:c,day:l,...j,...K,timeZone:d},L):E&&z?T=N.PlainDateTime.from({year:m,month:c,day:l,...j,...K},L):E?T=N.PlainDate.from({year:m,month:c,day:l,...K},L):T=N.PlainTime.from(j,L)}catch(w){throw new Error(`temporal-fmt: "${t}" doesn't describe a valid date/time for format "${e}": ${w.message}`)}if(g!==void 0){let w=T.dayOfWeek;if(w!==g){let b=v(r);throw new Error(`temporal-fmt: "${H}" doesn't match the actual weekday (${b.weekdayLong[w-1]}) for the parsed date.`)}}return T}0&&(module.exports={format,parse,setTemporal});
1
+ "use strict";var j=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var le=(e,t)=>{for(var n in t)j(e,n,{get:t[n],enumerable:!0})},pe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ue(t))!ce.call(e,r)&&r!==n&&j(e,r,{get:()=>t[r],enumerable:!(o=de(t,r))||o.enumerable});return e};var ge=e=>pe(j({},"__esModule",{value:!0}),e);var Ue={};le(Ue,{format:()=>ee,parse:()=>ie,setTemporal:()=>B});module.exports=ge(Ue);var W,J=[];function q(e){J.push(e)}function B(e){W=e;for(let t of J)t()}function fe(){return W??globalThis.Temporal}function A(){let e=fe();if(!e)throw new Error("temporal-fmt: parse() needs a Temporal implementation to construct its result. Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal (native on Node 26+, or a polyfill like temporal-polyfill).");return e}function F(e){try{return new Intl.Locale(e.replace(/_/g,"-")).toString().toLowerCase()}catch{return e}}var P=new Map,he=500;function v(e,t,n){let o=e.formatToParts(t),r=o.findIndex(p=>p.type===n);if(r===-1)throw new Error(`temporal-fmt: locale produced no "${n}" part while building match vocabulary.`);let a=o[r].value,i=o[r-1],s=o[r+1];return i?.type==="literal"&&!/\s/.test(i.value)&&(a=i.value+a),s?.type==="literal"&&!/\s/.test(s.value)&&(a=a+s.value),a}function _(e,t,n){let o=new Map;for(let r=0;r<e.length;r++){let a=o.get(e[r]);if(a!==void 0)throw new Error(`temporal-fmt: locale "${n}" renders ${t} index ${a} and ${r} identically ("${e[r]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);o.set(e[r],r)}}function M(e){let t=F(e),n=P.get(t);if(n)return n;let o=new Intl.DateTimeFormat(e,{month:"long",timeZone:"UTC"}),r=new Intl.DateTimeFormat(e,{month:"short",timeZone:"UTC"}),a=[],i=[];for(let u=0;u<12;u++){let k=new Date(Date.UTC(2020,u,1));a.push(v(o,k,"month")),i.push(v(r,k,"month"))}_(a,"MMMM month",e),_(i,"MMM month",e);let s=new Intl.DateTimeFormat(e,{weekday:"long",timeZone:"UTC"}),p=new Intl.DateTimeFormat(e,{weekday:"short",timeZone:"UTC"}),c=[],m=[];for(let u=0;u<7;u++){let k=new Date(Date.UTC(2024,0,1+u));c.push(v(s,k,"weekday")),m.push(v(p,k,"weekday"))}_(c,"EEEE weekday",e),_(m,"EEE weekday",e);let d=new Intl.DateTimeFormat(e,{hour:"numeric",hour12:!0,timeZone:"UTC"}),f=v(d,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),w=v(d,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),h=[...new Set([f,w])],g={monthLong:a,monthShort:i,weekdayLong:c,weekdayShort:m,dayPeriod:h};if(P.size>=he){let u=P.keys().next().value;u!==void 0&&P.delete(u)}return P.set(t,g),g}function T(e,t){let n=e<0,o=String(Math.abs(e)).padStart(t,"0");return n?"-"+o:o}var Z="en-US",N=new Map,ye=500;function Q(e,t){let n=JSON.stringify([F(e),t]),o=N.get(n);if(o)return o;if(N.size>=ye){let r=N.keys().next().value;r!==void 0&&N.delete(r)}return o=new Intl.DateTimeFormat(e,t),N.set(n,o),o}var S;q(()=>{S=void 0});function we(){if(S===void 0){S=!1;try{let e=A();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),S=!0}catch{}}return S}function R(e,t,n,o){let r=e?.calendarId,a={...n,calendar:r&&r!=="iso8601"?r:"gregory"};if(!we())return e.toLocaleString(t,a);let{toInstant:i,timeZoneId:s}=e,p=typeof i=="function"&&typeof s=="string",c=p?e.toInstant():e,m={...a,...p?{timeZone:s}:{}},f=Q(t,m).formatToParts(c),w=f.findIndex(k=>k.type===o);if(w===-1)throw new Error(`temporal-fmt: locale "${t}" produced no "${o}" part for this token. This usually means the Temporal object is missing the field the token needs.`);let h=f[w].value,g=f[w-1],u=f[w+1];return g?.type==="literal"&&!/\s/.test(g.value)&&(h=g.value+h),u?.type==="literal"&&!/\s/.test(u.value)&&(h=h+u.value),h}function ke(e,t){let n=new Date(Date.UTC(1970,0,1,e)),r=Q(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(n).find(a=>a.type==="dayPeriod");if(!r)throw new Error(`temporal-fmt: locale "${t}" produced no "dayPeriod" part for token "a".`);return r.value}var H=[["yyyy",e=>T(e.year,4),"year"],["yy",e=>{if(e.year<0)throw new Error(`temporal-fmt: token "yy" doesn't support negative years (got ${e.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`);return T(e.year%100,2)},"year"],["MMMM",(e,t)=>R(e,t,{month:"long"},"month"),"month"],["MMM",(e,t)=>R(e,t,{month:"short"},"month"),"month"],["MM",e=>T(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>T(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,t)=>R(e,t,{weekday:"long"},"weekday"),"dayOfWeek"],["EEE",(e,t)=>R(e,t,{weekday:"short"},"weekday"),"dayOfWeek"],["HH",e=>T(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>T(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>T(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>T(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSS",e=>T(e.millisecond,3),"millisecond"],["a",(e,t)=>ke(e.hour,t),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"]];var Te=H.map(([e])=>e).sort((e,t)=>t.length-e.length);function U(e){let t=[],n=0;for(;n<e.length;){let o=e[n];if(o==="'"){if(e[n+1]==="'"){X(t,"'"),n+=2;continue}let a=n+1,i="",s=!1;for(;a<e.length;){if(e[a]==="'"){if(e[a+1]==="'"){i+="'",a+=2;continue}s=!0,a+=1;break}i+=e[a],a+=1}if(!s)throw new Error(`temporal-fmt: unterminated quote in format string "${e}"`);X(t,i),n=a;continue}let r=Te.find(a=>e.startsWith(a,n));if(r){t.push({kind:"token",value:r}),n+=r.length;continue}X(t,o),n+=1}return t}function X(e,t){let n=e[e.length-1];n&&n.kind==="literal"?n.value+=t:e.push({kind:"literal",value:t})}var Ee=new Map(H.map(([e,t,n])=>[e,{fn:t,field:n}]));function ee(e,t,n={}){if(t.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${t.length}).`);let o=n.locale??Z,r=U(t),a="";for(let i of r){if(i.kind==="literal"){a+=i.value;continue}let s=Ee.get(i.value);if(!s)throw new Error(`temporal-fmt: unknown token "${i.value}"`);if(e[s.field]===void 0)throw new Error(`temporal-fmt: token "${i.value}" requires "${s.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`);a+=s.fn(e,o)}return a}function be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $(e){return`(?:${e.map(be).join("|")})`}var xe="(?:UTC|[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?|[A-Za-z_]+(?:[+-]\\d{1,2})?(?:\\/[A-Za-z0-9_+-]+)*)";function ve(){return xe}var z;function Me(){return z||(z=new Set(Intl.supportedValuesOf("timeZone")),z.add("UTC")),z}var De=/^[+-]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?$/;function te(e){return De.test(e)||Me().has(e)}var Pe={yy:"\\d{2}",MM:"(?:0[1-9]|1[0-2])",M:"(?:1[0-2]|[1-9])",dd:"(?:0[1-9]|[12]\\d|3[01])",d:"(?:[12]\\d|3[01]|[1-9])",HH:"(?:[01]\\d|2[0-3])",H:"(?:1\\d|2[0-3]|[0-9])",hh:"(?:0[1-9]|1[0-2])",h:"(?:1[0-2]|[1-9])",mm:"(?:[0-5]\\d)",m:"(?:[1-5]\\d|[0-9])",ss:"(?:[0-5]\\d)",s:"(?:[1-5]\\d|[0-9])",SSS:"\\d{3}"},Fe="-?\\d{4}",Ne="-?\\d{4,}",Se=new Set(["yyyy","yy","MM","M","dd","d","HH","H","hh","h","mm","m","ss","s","SSS"]);function ne(e,t,n){if(e==="yyyy")return n!==void 0&&Se.has(n)?Fe:Ne;let o=Pe[e];if(o)return o;let r=M(t);switch(e){case"MMMM":return $(r.monthLong);case"MMM":return $(r.monthShort);case"EEEE":return $(r.weekdayLong);case"EEE":return $(r.weekdayShort);case"a":return $(r.dayPeriod);case"zzz":return ve();default:throw new Error(`temporal-fmt: unknown token "${e}"`)}}var re=new Set(["M","d","H","h","m","s"]),$e={M:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],d:[{digits:1,min:1,max:9},{digits:2,min:10,max:31}],H:[{digits:1,min:0,max:9},{digits:2,min:10,max:23}],h:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],m:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}],s:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}]};function oe(e,t){let n=new Map;function o(r,a){let i=`${r}:${a}`,s=n.get(i);if(s)return s;if(r===t.length){let d=a===e.length?[[]]:[];return n.set(i,d),d}let p=t[r],c=$e[p];if(!c)throw new Error(`temporal-fmt: internal error \u2014 "${p}" is not an unpadded numeric token`);let m=[];for(let{digits:d,min:f,max:w}of c){if(a+d>e.length)continue;let h=e.slice(a,a+d);if(d===2&&h[0]==="0")continue;let g=Number(h);if(!(g<f||g>w)){for(let u of o(r+1,a+d))if(m.push([g,...u]),m.length===2)break;if(m.length===2)break}}return n.set(i,m),m}return o(0,0)}function Ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ae(e,t){let n=[],o=[],r="",a=0,i={groupNames:[],tokens:[]},s=()=>{i.tokens.length>=2&&o.push(i),i={groupNames:[],tokens:[]}};for(let[p,c]of e.entries()){if(c.kind==="literal"){r+=Ce(c.value),s();continue}let m=`g${a++}`;n.push({name:m,token:c.value});let d=e[p+1],f=d?.kind==="token"?d.value:void 0;r+=`(?<${m}>${ne(c.value,t,f)})`,re.has(c.value)?(i.groupNames.push(m),i.tokens.push(c.value)):s()}return s(),{regex:new RegExp(`^(?:${r})$`,"u"),groups:n,ambiguousRuns:o}}var C=new Map,Le=500;function Oe(e,t){let n=JSON.stringify([F(t),e]),o=C.get(n);if(o)return o;if(C.size>=Le){let r=C.keys().next().value;r!==void 0&&C.delete(r)}return o=ae(U(e),t),C.set(n,o),o}var D=new Map,Ae=500;function _e(e){let t=new Intl.Locale(e).toString().toLowerCase();if(D.has(t))return D.get(t);if(D.size>=Ae){let i=D.keys().next().value;i!==void 0&&D.delete(i)}let n,o=t.split("-"),r=o.indexOf("u"),a=r===-1?-1:o.indexOf("ca",r+1);if(a!==-1&&a+1<o.length){let i=new Intl.DateTimeFormat(t).resolvedOptions().calendar;n=i==="gregory"?void 0:i}return D.set(t,n),n}function l(e,t,n){e[t]=n}function Re(e,t,n,o,r){let a=M(o);switch(t){case"yyyy":l(e,"year",Number(n));break;case"yy":l(e,"twoDigitYear",Number(n));break;case"MM":case"M":l(e,"month",Number(n));break;case"MMMM":l(e,"month",a.monthLong.indexOf(n)+1);break;case"MMM":l(e,"month",a.monthShort.indexOf(n)+1);break;case"dd":case"d":l(e,"day",Number(n));break;case"EEEE":l(e,"weekdayRaw",n),l(e,"weekdayExpected",a.weekdayLong.indexOf(n)+1);break;case"EEE":l(e,"weekdayRaw",n),l(e,"weekdayExpected",a.weekdayShort.indexOf(n)+1);break;case"HH":case"H":l(e,"hour",Number(n));break;case"hh":case"h":l(e,"hour12",Number(n));break;case"mm":case"m":l(e,"minute",Number(n));break;case"ss":case"s":l(e,"second",Number(n));break;case"SSS":l(e,"millisecond",Number(n));break;case"a":{let i=a.dayPeriod.indexOf(n);if(i<0)throw new Error(`temporal-fmt: unknown day period "${n}" for locale "${o}".`);l(e,"dayPeriodRaw",n),l(e,"isPM",i===1);break}case"zzz":l(e,"timeZoneId",n);break}}function Ze(e){if(e.year!==void 0&&e.twoDigitYear!==void 0)throw new Error('temporal-fmt: format string mixes "yyyy" and "yy" year representations.');if(e.year!==void 0)return e.year;if(e.twoDigitYear!==void 0)return e.twoDigitYear<=68?2e3+e.twoDigitYear:1900+e.twoDigitYear}function He(e,t,n){if(e.hour!==void 0&&e.hour12!==void 0)throw new Error(`temporal-fmt: format string "${t}" mixes a 24-hour token ("HH"/"H") with a 12-hour token ("hh"/"h").`);if(e.hour!==void 0){if(e.dayPeriodRaw!==void 0){let o=M(n),r=e.hour<12?o.dayPeriod[0]:o.dayPeriod[1];if(e.dayPeriodRaw!==r)throw new Error(`temporal-fmt: format string "${t}" contains a day period that contradicts the 24-hour value.`)}return e.hour}if(e.hour12!==void 0){if(e.isPM===void 0)throw new Error(`temporal-fmt: format string "${t}" uses a 12-hour token ("hh"/"h") without an "a" token, so parse() can't tell AM from PM.`);return e.hour12%12+(e.isPM?12:0)}}function ie(e,t,n={}){if(e.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${e.length}).`);if(t.length>1e5)throw new Error(`temporal-fmt: input exceeds maximum length of ${1e5} characters (got ${t.length}).`);let o=n.locale??Z,r=_e(o),a=Oe(e,o),i=a.regex.exec(t);if(!i)throw new Error("temporal-fmt: no valid pattern matches the format string and input shape");if(a.groups.length===0)throw new Error(`temporal-fmt: format string "${e}" has no tokens \u2014 nothing to parse into a value.`);for(let{name:y,token:E}of a.groups)if(E==="zzz"&&!te(i.groups[y]))throw new Error("temporal-fmt: no valid pattern matches the format string and input shape");for(let y of a.ambiguousRuns){let E=y.groupNames.map(me=>i.groups[me]).join(""),O=oe(E,y.tokens);if(O.length>1)throw new Error(`temporal-fmt: "${E}" in format string "${e}" is ambiguous \u2014 ${O.length} different ways to read tokens "${y.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(O[0])} vs ${JSON.stringify(O[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.`)}let s={};for(let{name:y,token:E}of a.groups)Re(s,E,i.groups[y],o,e);let p=Ze(s),c=He(s,e,o),{month:m,day:d,minute:f,second:w,millisecond:h,timeZoneId:g,weekdayExpected:u,weekdayRaw:k}=s,se=p!==void 0||m!==void 0||d!==void 0,b=p!==void 0&&m!==void 0&&d!==void 0;if(se&&!b)throw new Error(`temporal-fmt: format string "${e}" has an incomplete date \u2014 year, month, and day tokens must all be present together.`);let K=c!==void 0||f!==void 0||w!==void 0||h!==void 0;if(g!==void 0&&!(b&&K))throw new Error(`temporal-fmt: format string "${e}" has a "zzz" token but needs a full date and time to build a ZonedDateTime.`);if(u!==void 0&&!b)throw new Error(`temporal-fmt: format string "${e}" has a weekday token ("EEEE"/"EEE") but needs a full date to validate it against.`);if(!b&&!K)throw new Error(`temporal-fmt: format string "${e}" has no date or time tokens to parse.`);let I=A(),Y={hour:c??0,minute:f??0,second:w??0,millisecond:h??0},V=r?{calendar:r}:{},L={overflow:"reject"},x;try{g!==void 0?x=I.ZonedDateTime.from({year:p,month:m,day:d,...Y,...V,timeZone:g},L):b&&K?x=I.PlainDateTime.from({year:p,month:m,day:d,...Y,...V},L):b?x=I.PlainDate.from({year:p,month:m,day:d,...V},L):x=I.PlainTime.from(Y,L)}catch(y){throw new Error(`temporal-fmt: "${t}" doesn't describe a valid date/time for format "${e}": ${y.message}`)}if(u!==void 0){let y=x.dayOfWeek;if(y!==u){let E=M(o);throw new Error(`temporal-fmt: "${k}" doesn't match the actual weekday (${E.weekdayLong[y-1]}) for the parsed date.`)}}return x}0&&(module.exports={format,parse,setTemporal});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/temporalProvider.ts","../src/tokens.ts","../src/tokenize.ts","../src/format.ts","../src/localeVocab.ts","../src/pattern.ts","../src/parsePattern.ts","../src/parse.ts"],"sourcesContent":["export { format } from './format.js';\nexport { parse } from './parse.js';\nexport { setTemporal } from './temporalProvider.js';\nexport type { TemporalLike, FormatOptions } from './tokens.js';\nexport type { TemporalNamespace } from './temporalProvider.js';","// This package's tsconfig assumes lib: [\"ESNext\"] only — no ambient\n// `Temporal` namespace type. Everywhere else in this codebase only ever\n// *reads* fields off a Temporal-like object the caller already built\n// (TemporalLike in tokens.ts). This module is the single choke point for\n// touching a *namespace*-shaped Temporal (PlainDate.from, etc.): parse()\n// uses it to construct a result, tokens.ts uses it to probe native\n// Intl<->Temporal support. Consumers can hand us an implementation via\n// setTemporal(), or we fall back to globalThis.Temporal\ninterface TemporalFactory {\n from(fields: Record<string, number | string | undefined>, options?: { overflow?: 'constrain' | 'reject' }): unknown;\n}\n\nexport interface TemporalNamespace {\n PlainDate: TemporalFactory;\n PlainTime: TemporalFactory;\n PlainDateTime: TemporalFactory;\n ZonedDateTime: TemporalFactory;\n}\n\nlet injectedTemporal: TemporalNamespace | undefined;\n\n/**\n * Explicitly hand temporal-fmt the Temporal implementation to use, instead\n * of relying on a global `Temporal`. Call this once, before your first\n * `format()`/`parse()`\n *\n * Call with no argument (or `undefined`) to clear the override and fall\n * back to `globalThis.Temporal` again.\n *\n * @example\n * import { Temporal } from 'temporal-polyfill';\n * import { setTemporal } from 'temporal-fmt';\n * setTemporal(Temporal);\n */\nexport function setTemporal(temporal?: TemporalNamespace): void {\n injectedTemporal = temporal;\n}\n\nfunction resolveTemporal(): TemporalNamespace | undefined {\n return injectedTemporal ?? (globalThis as unknown as { Temporal?: TemporalNamespace }).Temporal;\n}\n\nexport function getTemporal(): TemporalNamespace {\n const temporal = resolveTemporal();\n if (!temporal) {\n throw new Error(\n 'temporal-fmt: parse() needs a Temporal implementation to construct its result. ' +\n 'Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal ' +\n '(native on Node 26+, or a polyfill like temporal-polyfill).'\n );\n }\n return temporal;\n}\n","import { getTemporal } from './temporalProvider.js';\n\nexport function pad(n: number, len: number): string {\n // padStart pads the whole string, sign included, so pad(-45, 4) used to\n // come out \"0-45\" instead of \"-045\" — split the sign off first.\n const negative = n < 0;\n const digits = String(Math.abs(n)).padStart(len, '0');\n return negative ? '-' + digits : digits;\n}\n\n// Not every field exists on every Temporal type (PlainDate has no .hour,\n// etc). Callers check for undefined before formatting a token.\nexport interface TemporalLike {\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n timeZoneId?: string;\n dayOfWeek?: number; // 1=Mon, 7=Sun, per Temporal spec\n calendarId?: string;\n toInstant?: () => unknown;\n toLocaleString?: (locale: string, options: Intl.DateTimeFormatOptions) => string;\n}\n\nexport interface FormatOptions {\n /** BCP 47 locale tag, e.g. 'en-US', 'fr-FR', 'ar-EG'. Defaults to 'en-US'. */\n locale?: string;\n}\n\nexport const DEFAULT_LOCALE = 'en-US';\n\n// Intl.DateTimeFormat is expensive to construct and format() can run in a\n// loop (rendering a table of dates), so cache by (locale, options).\nconst formatterCache = new Map<string, Intl.DateTimeFormat>();\nconst MAX_CACHE_SIZE = 500;\n\nfunction getFormatter(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = JSON.stringify([locale, options]);\n let formatter = formatterCache.get(key);\n if (formatter) {\n return formatter;\n }\n if (formatterCache.size >= MAX_CACHE_SIZE) {\n // not real LRU, just evicts oldest insertion — fine for this key space\n const oldestKey = formatterCache.keys().next().value;\n if (oldestKey !== undefined) formatterCache.delete(oldestKey);\n }\n formatter = new Intl.DateTimeFormat(locale, options);\n formatterCache.set(key, formatter);\n return formatter;\n}\n\n// Passing a Temporal object straight into `new Intl.DateTimeFormat().formatToParts()`\n// only works when the engine's Intl implementation has special-cased support for\n// *native* Temporal instances (checked via internal slots and/or gated behind a V8 flag,\n// not tied to a specific Node version).\n//\n// A Temporal polyfill's instances don't have those slots, so the engine falls back to ToNumber() -> .valueOf(),\n// which the polyfill deliberately throws on (\"Cannot use valueOf\").\n// Probed once and memoized and only from intlPart(), so it never\n// runs unless a format string actually uses a locale-aware token.\nlet nativeSupport: boolean | undefined;\nfunction intlSupportsNativeTemporal(): boolean {\n if (nativeSupport === undefined) {\n nativeSupport = false;\n try {\n const temporal = getTemporal();\n new Intl.DateTimeFormat('en-US', { day: 'numeric' })\n .formatToParts(temporal.PlainDate.from({ year: 1970, month: 1, day: 1 }) as Date);\n nativeSupport = true;\n } catch {\n // native Temporal absent, or present but not recognized by Intl — fall back\n }\n }\n return nativeSupport;\n}\n\nfunction intlPart(\n temporal: TemporalLike,\n locale: string,\n options: Intl.DateTimeFormatOptions,\n partType: Intl.DateTimeFormatPartTypes\n): string {\n // Intl throws \"Mismatching Calendars\" if the formatter's calendar doesn't\n // match the object's own (e.g. en-US formatter defaults to gregory, but\n // a hebrew/islamic PlainDate needs its own calendar passed through).\n //\n // skip this for iso8601 specifically — passing `calendar: 'iso8601'`\n // explicitly alongside a single-field options object makes formatToParts()\n // come back empty for some reason.\n const calendar = temporal?.calendarId;\n const formatterOptions: Intl.DateTimeFormatOptions = {\n ...options,\n ...(calendar && calendar !== 'iso8601' ? { calendar } : {}),\n };\n\n // Temporal.prototype.toLocaleString() is part of the Temporal spec itself:\n // polyfills implement the ICU formatting internally without needing the\n // engine to recognize the object, so it works without native Intl support.\n if (!intlSupportsNativeTemporal()) {\n return temporal.toLocaleString!(locale, formatterOptions);\n }\n\n // formatToParts() throws on ZonedDateTime directly (per spec), so convert\n // to Instant and pass the zone via `timeZone` instead. Don't convert to\n // PlainDateTime — that drops the zone, which breaks 'MMMM' + 'zzz' combos.\n const { toInstant, timeZoneId } = temporal;\n const isZoned = typeof toInstant === 'function' && typeof timeZoneId === 'string';\n // has to be called as temporal.toInstant() because destructuring it off breaks\n // the receiver and throws\n const intlSafeTemporal = isZoned ? temporal.toInstant!() : temporal;\n const nativeOptions: Intl.DateTimeFormatOptions = {\n ...formatterOptions,\n ...(isZoned ? { timeZone: timeZoneId } : {}),\n };\n\n const formatter = getFormatter(locale, nativeOptions);\n const parts = formatter.formatToParts(intlSafeTemporal as Date | number);\n const index = parts.findIndex((p) => p.type === partType);\n if (index === -1) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" produced no \"${partType}\" part for this token. ` +\n `This usually means the Temporal object is missing the field the token needs.`\n );\n }\n // some locales (ja-JP) split a field across two parts — e.g. month \"8\"\n // plus a counter suffix \"月\" as a separate sibling literal part. Merge in\n // an adjacent literal only if it has no whitespace, so a genuine suffix\n // gets folded in but an ordinary separator (the space before \"AM\") stays\n // a separator. Mirrors partValue() in localeVocab.ts, which builds the\n // vocab this token's output needs to match for parse() to round-trip.\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Temporal.prototype.toLocaleString() can't isolate a single field the way\n// formatToParts() can — asking for `hour` + `dayPeriod` together returns one\n// joined string (e.g. \"3 in the afternoon\"), and `dayPeriod` alone resolves\n// against a different, non-hour-anchored set of periods (\"in the\n// afternoon\"/\"昼\" instead of \"PM\"/\"午後\"). Day period only depends on the\n// hour anyway, so route it through a plain UTC Date and Intl.DateTimeFormat\n// instead — that's worked the same on every engine regardless of whether\n// Temporal itself is native or polyfilled.\nfunction dayPeriodPart(hour: number, locale: string): string {\n const date = new Date(Date.UTC(1970, 0, 1, hour));\n const formatter = getFormatter(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const part = formatter.formatToParts(date).find((p) => p.type === 'dayPeriod');\n if (!part) {\n throw new Error(`temporal-fmt: locale \"${locale}\" produced no \"dayPeriod\" part for token \"a\".`);\n }\n return part.value;\n}\n\ntype TokenHandler = (t: TemporalLike, locale: string) => string;\n\n// Longest-first — tokenizer is greedy, \"yyyy\" has to be tried before \"yy\".\n//\n// Numeric tokens always render in ASCII digits, never locale-native\n// (Arabic-Indic, Devanagari, etc). Padding non-ASCII digits isn't as simple\n// as padding \"3\", and most consumers parsing these back out want plain\n// digits anyway.\nexport const TOKENS: Array<[string, TokenHandler, keyof TemporalLike]> = [\n ['yyyy', (t) => pad(t.year!, 4), 'year'],\n ['yy', (t) => {\n // -45 % 100 === -45, so truncating negative years to 2 digits doesn't\n // work and Math.abs() would make 45 CE and 45 BCE render the same.\n if (t.year! < 0) {\n throw new Error(\n `temporal-fmt: token \"yy\" doesn't support negative years (got ${t.year}), ` +\n `since truncating to 2 digits would make it indistinguishable from a ` +\n `positive year. Use \"yyyy\" instead.`\n );\n }\n return pad(t.year! % 100, 2);\n }, 'year'],\n ['MMMM', (t, locale) => intlPart(t, locale, { month: 'long' }, 'month'), 'month'],\n ['MMM', (t, locale) => intlPart(t, locale, { month: 'short' }, 'month'), 'month'],\n ['MM', (t) => pad(t.month!, 2), 'month'],\n ['M', (t) => String(t.month!), 'month'],\n ['dd', (t) => pad(t.day!, 2), 'day'],\n ['d', (t) => String(t.day!), 'day'],\n ['EEEE', (t, locale) => intlPart(t, locale, { weekday: 'long' }, 'weekday'), 'dayOfWeek'],\n ['EEE', (t, locale) => intlPart(t, locale, { weekday: 'short' }, 'weekday'), 'dayOfWeek'],\n ['HH', (t) => pad(t.hour!, 2), 'hour'],\n ['H', (t) => String(t.hour!), 'hour'],\n ['hh', (t) => pad(t.hour! % 12 || 12, 2), 'hour'],\n ['h', (t) => String(t.hour! % 12 || 12), 'hour'],\n ['mm', (t) => pad(t.minute!, 2), 'minute'],\n ['m', (t) => String(t.minute!), 'minute'],\n ['ss', (t) => pad(t.second!, 2), 'second'],\n ['s', (t) => String(t.second!), 'second'],\n ['SSS', (t) => pad(t.millisecond!, 3), 'millisecond'],\n // dayPeriod text is locale-specific (AM/PM in en-US, م/ص in ar-EG) but\n // still needs .hour on the input to compute which period it is\n ['a', (t, locale) => dayPeriodPart(t.hour!, locale), 'hour'],\n ['zzz', (t) => t.timeZoneId!, 'timeZoneId'],\n];","import { TOKENS } from './tokens.js';\n\nexport type Piece =\n | { kind: 'token'; value: string }\n | { kind: 'literal'; value: string };\n\n// longest-first so the greedy scan never matches \"M\" when \"MMMM\" was there\nconst SORTED_TOKEN_STRINGS = TOKENS.map(([tok]) => tok).sort((a, b) => b.length - a.length);\n\n/**\n * Splits a format string like `\"yyyy-MM-dd 'at' HH:mm\"` into token/literal\n * pieces. Text in single quotes is always literal (e.g. write 'rd' in\n * \"3rd\" so it's not read as the day token). A doubled quote ('') means a\n * literal quote character, both inside a quoted span and standalone.\n */\nexport function tokenize(format: string): Piece[] {\n const pieces: Piece[] = [];\n let i = 0;\n\n while (i < format.length) {\n const ch = format[i];\n\n if (ch === \"'\") {\n // check doubled-quote first or \"''best''\" parses wrong\n if (format[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < format.length) {\n if (format[j] === \"'\") {\n if (format[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += format[j];\n j += 1;\n }\n\n if (!closed) {\n throw new Error(`temporal-fmt: unterminated quote in format string \"${format}\"`);\n }\n\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n\n const match = SORTED_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n\n // not a token or quote — pass through as-is\n appendLiteral(pieces, ch);\n i += 1;\n }\n\n return pieces;\n}\n\n// merges into the previous piece if it's also a literal, so \"---\" is one\n// piece instead of three\nfunction appendLiteral(pieces: Piece[], value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n}\n","import { TOKENS, DEFAULT_LOCALE, type TemporalLike, type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\n\nconst HANDLER_BY_TOKEN = new Map(TOKENS.map(([tok, fn, field]) => [tok, { fn, field }]));\n\n/**\n * Format a Temporal.PlainDate, PlainTime, PlainDateTime, or ZonedDateTime\n * using a date-fns-style token string.\n *\n * @example\n * format(Temporal.Now.plainDateISO(), 'yyyy-MM-dd') // \"2026-08-04\"\n * format(zdt, \"MMM d, yyyy 'at' h:mm a\") // \"Aug 4, 2026 at 3:45 PM\"\n * format(zdt, 'MMMM d, yyyy', { locale: 'fr-FR' }) // \"août 4, 2026\"\n *\n * Throws on a token the input type doesn't support (e.g. 'HH' on a PlainDate).\n */\nexport function format(temporal: TemporalLike, formatStr: string, options: FormatOptions = {}): string {\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 const locale = options.locale ?? DEFAULT_LOCALE;\n const pieces = tokenize(formatStr);\n let result = '';\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n\n const handler = HANDLER_BY_TOKEN.get(piece.value);\n if (!handler) {\n // shouldn't happen — tokenize() only emits tokens from TOKENS\n throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n }\n\n if (temporal[handler.field] === undefined) {\n throw new Error(\n `temporal-fmt: token \"${piece.value}\" requires \"${handler.field}\", ` +\n `which this Temporal object doesn't have. ` +\n `(e.g. PlainDate has no time fields, PlainTime has no date fields)`\n );\n }\n\n result += handler.fn(temporal, locale);\n }\n\n return result;\n}\n","// Name lists for the locale-aware tokens (MMMM, MMM, EEEE, EEE, a). Each\n// list is small and fixed (12 months, 7 weekdays, 2 day periods), so we\n// generate the real Intl strings for a locale once and cache them.\n\nexport interface LocaleVocab {\n monthLong: string[]; // index 0 = January\n monthShort: string[];\n weekdayLong: string[]; // index 0 = Monday, per Temporal's dayOfWeek numbering\n weekdayShort: string[];\n dayPeriod: string[]; // typically [AM-ish, PM-ish], deduped\n}\n\nconst vocabCache = new Map<string, LocaleVocab>();\nconst MAX_VOCAB_CACHE_SIZE = 500;\n\n// Some locales (ja-JP) split a field across two parts — month \"8\" plus a\n// counter suffix \"月\" as a separate sibling \"literal\" — while format()'s\n// tokens go through toLocaleString(), which concatenates everything into\n// \"8月\". Reading only the type-tagged part used to drop that suffix, so\n// this locale's vocab never matched what format() actually produced.\n// Only merges *adjacent* literals, not the whole string, since the\n// dayPeriod/weekday formatters below carry an extra hour part that a\n// join-everything approach would wrongly absorb.\nfunction partValue(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {\n const parts = formatter.formatToParts(date);\n const index = parts.findIndex((p) => p.type === type);\n if (index === -1) {\n throw new Error(`temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`);\n }\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n // skip whitespace literals (the separator before \"AM\") — only a\n // no-space suffix like ja-JP's \"月\" should get folded in\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Two entries rendering identically means parse()'s reverse lookup\n// (indexOf) can never tell them apart. Weekday collisions already surface\n// via parse()'s dayOfWeek cross-check, but with a confusing same-string\n// error; months have no equivalent cross-check, so a collision there would\n// otherwise resolve silently to the wrong month. Catching both here, once\n// at build time, gives one clear error instead.\nfunction assertNoCollision(names: string[], label: string, locale: string): void {\n const seen = new Map<string, number>();\n for (let i = 0; i < names.length; i++) {\n const prior = seen.get(names[i]!);\n if (prior !== undefined) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" renders ${label} index ${prior} and ${i} identically ` +\n `(\"${names[i]}\"). parse() can't reliably tell these apart for this locale/token, so this ` +\n `combination isn't supported.`\n );\n }\n seen.set(names[i]!, i);\n }\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n const cached = vocabCache.get(locale);\n if (cached) {\n return cached;\n }\n\n const monthLongFmt = new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' });\n const monthLong: string[] = [];\n const monthShort: string[] = [];\n for (let m = 0; m < 12; m++) {\n const date = new Date(Date.UTC(2020, m, 1));\n monthLong.push(partValue(monthLongFmt, date, 'month'));\n monthShort.push(partValue(monthShortFmt, date, 'month'));\n }\n assertNoCollision(monthLong, 'MMMM month', locale);\n assertNoCollision(monthShort, 'MMM month', locale);\n\n const weekdayLongFmt = new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' });\n const weekdayLong: string[] = [];\n const weekdayShort: string[] = [];\n // 2024-01-01 is a Monday (UTC) — walk 7 days from there for weekday names\n for (let d = 0; d < 7; d++) {\n const date = new Date(Date.UTC(2024, 0, 1 + d));\n weekdayLong.push(partValue(weekdayLongFmt, date, 'weekday'));\n weekdayShort.push(partValue(weekdayShortFmt, date, 'weekday'));\n }\n // redundant with parse()'s dayOfWeek cross-check, but gives a clearer error\n assertNoCollision(weekdayLong, 'EEEE weekday', locale);\n assertNoCollision(weekdayShort, 'EEE weekday', locale);\n\n const dayPeriodFmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), 'dayPeriod');\n const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), 'dayPeriod');\n const dayPeriod = [...new Set([am, pm])];\n\n const vocab: LocaleVocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };\n if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {\n const oldestKey = vocabCache.keys().next().value;\n if (oldestKey !== undefined) vocabCache.delete(oldestKey);\n }\n vocabCache.set(locale, vocab);\n return vocab;\n}","import { getLocaleVocab } from './localeVocab.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction alternation(values: string[]): string {\n return `(?:${values.map(escapeRegExp).join('|')})`;\n}\n\nlet timeZoneFragment: string | undefined;\n\nfunction getTimeZoneFragment(): string {\n if (timeZoneFragment) {\n return timeZoneFragment;\n }\n\n const supportedZones = Intl.supportedValuesOf('timeZone');\n const escapedZones = supportedZones.map(escapeRegExp);\n const offsetPattern = '[+-]\\\\d{2}:\\\\d{2}(?::\\\\d{2}(?:\\\\.\\\\d{1,9})?)?';\n timeZoneFragment = `(?:UTC|${offsetPattern}|${alternation(escapedZones)})`;\n return timeZoneFragment;\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 yyyy: '\\\\d{4}',\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 SSS: '\\\\d{3}',\n};\n\nexport function tokenFragment(token: string, locale: string): string {\n const numeric = NUMERIC_FRAGMENTS[token];\n if (numeric) {\n return numeric;\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 'a': return alternation(vocab.dayPeriod);\n case 'zzz': return getTimeZoneFragment();\n default:\n throw new Error(`temporal-fmt: unknown token \"${token}\"`);\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 if (!ranges) {\n throw new Error(`temporal-fmt: internal error — \"${token}\" is not an unpadded numeric token`);\n }\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}\n","import type { Piece } from './tokenize.js';\nimport { tokenFragment, UNPADDED_NUMERIC_TOKENS } from './pattern.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\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\", \"Hm\") — these need a split-ambiguity\n // check at match time, since a single fixed regex can't distinguish\n // \"the only valid split\" from \"one of several valid splits taken\n // arbitrarily\". Empty for the overwhelmingly common case (no such runs).\n ambiguousRuns: Array<{ 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<{ groupNames: string[]; tokens: string[] }> = [];\n let source = '';\n let i = 0;\n\n // tracks the group names/tokens of the current run of adjacent unpadded\n // numeric token pieces (no literal piece has broken it yet)\n let currentRun: { groupNames: string[]; tokens: string[] } = { groupNames: [], tokens: [] };\n const flushRun = () => {\n if (currentRun.tokens.length >= 2) {\n ambiguousRuns.push(currentRun);\n }\n currentRun = { groupNames: [], tokens: [] };\n };\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n source += escapeRegExp(piece.value);\n flushRun(); // a literal (even a single character) breaks adjacency\n continue;\n }\n const name = `g${i++}`;\n groups.push({ name, token: piece.value });\n source += `(?<${name}>${tokenFragment(piece.value, locale)})`;\n\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n currentRun.groupNames.push(name);\n currentRun.tokens.push(piece.value);\n } else {\n flushRun(); // a non-unpadded-numeric token (padded, locale-aware, zzz) also breaks adjacency\n }\n }\n flushRun();\n\n return { regex: new RegExp(`^(?:${source})$`, 'u'), 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 } from './pattern.js';\nimport { getLocaleVocab } from './localeVocab.js';\nimport { getTemporal } from './temporalProvider.js';\nimport { MAX_FORMAT_LENGTH, MAX_INPUT_LENGTH } from './constants.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([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 if (calendarCache.has(locale)) {\n return calendarCache.get(locale);\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 canonicalLocale = new Intl.Locale(locale).toString().toLowerCase();\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(locale, 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 timeZoneId?: string;\n weekdayExpected?: number;\n weekdayRaw?: string;\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 'SSS':\n assignField(fields, 'millisecond', Number(raw));\n break;\n case 'a': {\n const periodIndex = vocab.dayPeriod.indexOf(raw);\n if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period \"${raw}\" for locale \"${locale}\".`);\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 }\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 !== expected) {\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: FormatOptions = {}): 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 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 // 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 and throw if\n // more than one split is actually valid for the substring this call\n // matched — the input itself is what's ambiguous, not a fixable\n // property of the pattern.\n for (const run of pattern.ambiguousRuns) {\n const runDigits = run.groupNames.map((name) => match.groups![name]!).join('');\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length > 1) {\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 );\n }\n }\n\n const fields: Fields = {};\n for (const { name, token } of pattern.groups) {\n applyGroup(fields, token, match.groups![name]!, locale, formatStr);\n }\n\n const year = resolveYear(fields);\n const hour = resolveHour(fields, formatStr, locale);\n const { month, day, minute, second, millisecond, timeZoneId, weekdayExpected, weekdayRaw } = 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 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 = { hour: hour ?? 0, minute: minute ?? 0, second: second ?? 0, millisecond: millisecond ?? 0 };\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 result = temporal.ZonedDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField, timeZone: timeZoneId }, 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 return result;\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,YAAAE,EAAA,UAAAC,GAAA,gBAAAC,IAAA,eAAAC,GAAAL,ICmBA,IAAIM,EAeG,SAASC,EAAYC,EAAoC,CAC9DF,EAAmBE,CACrB,CAEA,SAASC,IAAiD,CACxD,OAAOH,GAAqB,WAA2D,QACzF,CAEO,SAASI,GAAiC,CAC/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oD7B,CAAS,MAChFyD,EAAc,OAAO,EAC3B,CACF,CAEA,GAAIX,IAAoB,OAAW,CACjC,IAAMY,EAAUF,EAAiC,UACjD,GAAIE,IAAWZ,EAAiB,CAC9B,IAAMxB,EAAQC,EAAetB,CAAM,EACnC,MAAM,IAAI,MACR,kBAAkB8C,CAAU,uCAAuCzB,EAAM,YAAYoC,EAAS,CAAC,CAAC,wBAElG,CACF,CACF,CAEA,OAAOF,CACT","names":["index_exports","__export","format","parse","setTemporal","__toCommonJS","injectedTemporal","setTemporal","temporal","resolveTemporal","getTemporal","pad","n","len","negative","digits","DEFAULT_LOCALE","formatterCache","MAX_CACHE_SIZE","getFormatter","locale","options","key","formatter","oldestKey","nativeSupport","intlSupportsNativeTemporal","temporal","getTemporal","intlPart","partType","calendar","formatterOptions","toInstant","timeZoneId","isZoned","intlSafeTemporal","nativeOptions","parts","index","p","value","prev","next","dayPeriodPart","hour","date","part","TOKENS","t","SORTED_TOKEN_STRINGS","TOKENS","tok","a","b","tokenize","format","pieces","i","ch","appendLiteral","j","literal","closed","match","value","last","HANDLER_BY_TOKEN","TOKENS","tok","fn","field","format","temporal","formatStr","options","locale","DEFAULT_LOCALE","pieces","tokenize","result","piece","handler","vocabCache","MAX_VOCAB_CACHE_SIZE","partValue","formatter","date","type","parts","index","p","value","prev","next","assertNoCollision","names","label","locale","seen","i","prior","getLocaleVocab","cached","monthLongFmt","monthShortFmt","monthLong","monthShort","m","weekdayLongFmt","weekdayShortFmt","weekdayLong","weekdayShort","dayPeriodFmt","am","pm","dayPeriod","vocab","oldestKey","escapeRegExp","literal","alternation","values","timeZoneFragment","getTimeZoneFragment","escapedZones","NUMERIC_FRAGMENTS","tokenFragment","token","locale","numeric","vocab","getLocaleVocab","UNPADDED_NUMERIC_TOKENS","UNPADDED_NUMERIC_RANGES","enumerateValidSplits","digits","tokens","memo","solve","tokenIndex","offset","key","cached","result","ranges","results","width","min","max","piece","value","restSplit","escapeRegExp","literal","buildCapturingPattern","pieces","locale","groups","ambiguousRuns","source","i","currentRun","flushRun","piece","name","tokenFragment","UNPADDED_NUMERIC_TOKENS","patternCache","MAX_CACHE_SIZE","getPattern","formatStr","locale","key","pattern","oldestKey","buildCapturingPattern","tokenize","calendarCache","MAX_CALENDAR_CACHE_SIZE","resolveCalendar","calendar","canonicalLocale","parts","extensionIndex","calendarKeyIndex","resolved","assignField","fields","value","applyGroup","token","raw","vocab","getLocaleVocab","periodIndex","resolveYear","resolveHour","expected","parse","input","options","DEFAULT_LOCALE","match","run","runDigits","name","splits","enumerateValidSplits","year","hour","month","day","minute","second","millisecond","timeZoneId","weekdayExpected","weekdayRaw","hasAnyDatePart","hasFullDate","hasTime","temporal","getTemporal","timeFields","calendarField","reject","result","err","actual"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/temporalProvider.ts","../src/localeVocab.ts","../src/tokens.ts","../src/tokenize.ts","../src/format.ts","../src/pattern.ts","../src/parsePattern.ts","../src/parse.ts"],"sourcesContent":["export { format } from './format.js';\nexport { parse } from './parse.js';\nexport { setTemporal } from './temporalProvider.js';\nexport type { TemporalLike, FormatOptions } from './tokens.js';\nexport type { TemporalNamespace } from './temporalProvider.js';","// This package's tsconfig assumes lib: [\"ESNext\"] only — no ambient\n// `Temporal` namespace type. Everywhere else in this codebase only ever\n// *reads* fields off a Temporal-like object the caller already built\n// (TemporalLike in tokens.ts). This module is the single choke point for\n// touching a *namespace*-shaped Temporal (PlainDate.from, etc.): parse()\n// uses it to construct a result, tokens.ts uses it to probe native\n// Intl<->Temporal support. Consumers can hand us an implementation via\n// setTemporal(), or we fall back to globalThis.Temporal\ninterface TemporalFactory {\n from(fields: Record<string, number | string | undefined>, options?: { overflow?: 'constrain' | 'reject' }): unknown;\n}\n\nexport interface TemporalNamespace {\n PlainDate: TemporalFactory;\n PlainTime: TemporalFactory;\n PlainDateTime: TemporalFactory;\n ZonedDateTime: TemporalFactory;\n}\n\nlet injectedTemporal: TemporalNamespace | undefined;\n\n// Anything that caches a result derived from *which* Temporal\n// implementation is active (right now: tokens.ts's native-Intl-support\n// probe) registers here so it gets invalidated whenever setTemporal()\n// swaps the implementation — see the comment on setTemporal() below for\n// why that matters. A plain array instead of an event-emitter-style API\n// since this only ever needs \"call every listener, in registration order,\n// with no payload\" — nothing here needs unsubscribe or payload data.\nconst onTemporalChanged: Array<() => void> = [];\n\nexport function subscribeToTemporalChanges(listener: () => void): void {\n onTemporalChanged.push(listener);\n}\n\n/**\n * Explicitly hand temporal-fmt the Temporal implementation to use, instead\n * of relying on a global `Temporal`. Call this once, before your first\n * `format()`/`parse()`\n *\n * Call with no argument (or `undefined`) to clear the override and fall\n * back to `globalThis.Temporal` again.\n *\n * @example\n * import { Temporal } from 'temporal-polyfill';\n * import { setTemporal } from 'temporal-fmt';\n * setTemporal(Temporal);\n */\nexport function setTemporal(temporal?: TemporalNamespace): void {\n injectedTemporal = temporal;\n // tokens.ts's native-Intl-support probe is keyed on whichever Temporal\n // implementation was active the first time a locale-aware format() ran —\n // if that implementation changes later (native -> polyfill or back), the\n // memoized probe result can go stale and disagree with what's now\n // actually active. Resetting it here means the next locale-aware format()\n // after any setTemporal() call re-probes against the implementation\n // that's active *now*, at the (small, one-time-per-switch) cost of\n // re-running the probe.\n for (const listener of onTemporalChanged) listener();\n}\n\nfunction resolveTemporal(): TemporalNamespace | undefined {\n return injectedTemporal ?? (globalThis as unknown as { Temporal?: TemporalNamespace }).Temporal;\n}\n\nexport function getTemporal(): TemporalNamespace {\n const temporal = resolveTemporal();\n if (!temporal) {\n throw new Error(\n 'temporal-fmt: parse() needs a Temporal implementation to construct its result. ' +\n 'Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal ' +\n '(native on Node 26+, or a polyfill like temporal-polyfill).'\n );\n }\n return temporal;\n}","// Name lists for the locale-aware tokens (MMMM, MMM, EEEE, EEE, a). Each\n// list is small and fixed (12 months, 7 weekdays, 2 day periods), so we\n// generate the real Intl strings for a locale once and cache them.\n\nexport interface LocaleVocab {\n monthLong: string[]; // index 0 = January\n monthShort: string[];\n weekdayLong: string[]; // index 0 = Monday, per Temporal's dayOfWeek numbering\n weekdayShort: string[];\n dayPeriod: string[]; // typically [AM-ish, PM-ish], deduped\n}\n\n// Every locale-keyed cache in this library (this one, formatterCache in\n// tokens.ts, patternCache/calendarCache in parse.ts) used to key on the\n// exact locale string a caller passed in. Intl treats spelling variants of\n// the same locale as equivalent ('en-US' / 'en-us' / 'en_US' all resolve\n// the same way), but a plain string-keyed Map doesn't — so callers mixing\n// spellings for what's really one locale would silently fragment across\n// separate cache entries instead of sharing one, making the bounded\n// eviction limits (MAX_*_CACHE_SIZE) less effective than they look. This\n// doesn't change any cache's *correctness* (each entry is still built from\n// -- and valid for -- whatever locale string produced it), only how many\n// distinct entries equivalent spellings end up costing. Falls back to the\n// original string on a malformed/unrecognized tag rather than throwing —\n// cache-key normalization shouldn't be where a bad locale first surfaces\n// as an error; whatever actually calls `new Intl.DateTimeFormat(locale)`\n// downstream is the right place for that.\nexport function canonicalCacheKey(locale: string): string {\n try {\n // Intl.Locale requires BCP-47 hyphens and rejects underscore-separated\n // tags like 'en_US' outright (RangeError), rather than normalizing\n // them — so without this replace, that spelling would just fall\n // through to the catch below and never fold with 'en-US'.\n return new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n return locale;\n }\n}\n\nconst vocabCache = new Map<string, LocaleVocab>();\nconst MAX_VOCAB_CACHE_SIZE = 500;\n\n// Some locales (ja-JP) split a field across two parts — month \"8\" plus a\n// counter suffix \"月\" as a separate sibling \"literal\" — while format()'s\n// tokens go through toLocaleString(), which concatenates everything into\n// \"8月\". Reading only the type-tagged part used to drop that suffix, so\n// this locale's vocab never matched what format() actually produced.\n// Only merges *adjacent* literals, not the whole string, since the\n// dayPeriod/weekday formatters below carry an extra hour part that a\n// join-everything approach would wrongly absorb.\nfunction partValue(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {\n const parts = formatter.formatToParts(date);\n const index = parts.findIndex((p) => p.type === type);\n if (index === -1) {\n throw new Error(`temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`);\n }\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n // skip whitespace literals (the separator before \"AM\") — only a\n // no-space suffix like ja-JP's \"月\" should get folded in\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Two entries rendering identically means parse()'s reverse lookup\n// (indexOf) can never tell them apart. Weekday collisions already surface\n// via parse()'s dayOfWeek cross-check, but with a confusing same-string\n// error; months have no equivalent cross-check, so a collision there would\n// otherwise resolve silently to the wrong month. Catching both here, once\n// at build time, gives one clear error instead.\nfunction assertNoCollision(names: string[], label: string, locale: string): void {\n const seen = new Map<string, number>();\n for (let i = 0; i < names.length; i++) {\n const prior = seen.get(names[i]!);\n if (prior !== undefined) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" renders ${label} index ${prior} and ${i} identically ` +\n `(\"${names[i]}\"). parse() can't reliably tell these apart for this locale/token, so this ` +\n `combination isn't supported.`\n );\n }\n seen.set(names[i]!, i);\n }\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n const cacheKey = canonicalCacheKey(locale);\n const cached = vocabCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const monthLongFmt = new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' });\n const monthLong: string[] = [];\n const monthShort: string[] = [];\n for (let m = 0; m < 12; m++) {\n const date = new Date(Date.UTC(2020, m, 1));\n monthLong.push(partValue(monthLongFmt, date, 'month'));\n monthShort.push(partValue(monthShortFmt, date, 'month'));\n }\n assertNoCollision(monthLong, 'MMMM month', locale);\n assertNoCollision(monthShort, 'MMM month', locale);\n\n const weekdayLongFmt = new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' });\n const weekdayLong: string[] = [];\n const weekdayShort: string[] = [];\n // 2024-01-01 is a Monday (UTC) — walk 7 days from there for weekday names\n for (let d = 0; d < 7; d++) {\n const date = new Date(Date.UTC(2024, 0, 1 + d));\n weekdayLong.push(partValue(weekdayLongFmt, date, 'weekday'));\n weekdayShort.push(partValue(weekdayShortFmt, date, 'weekday'));\n }\n // redundant with parse()'s dayOfWeek cross-check, but gives a clearer error\n assertNoCollision(weekdayLong, 'EEEE weekday', locale);\n assertNoCollision(weekdayShort, 'EEE weekday', locale);\n\n const dayPeriodFmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), 'dayPeriod');\n const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), 'dayPeriod');\n const dayPeriod = [...new Set([am, pm])];\n\n const vocab: LocaleVocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };\n if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {\n const oldestKey = vocabCache.keys().next().value;\n if (oldestKey !== undefined) vocabCache.delete(oldestKey);\n }\n vocabCache.set(cacheKey, vocab);\n return vocab;\n}","import { getTemporal, subscribeToTemporalChanges } from './temporalProvider.js';\nimport { canonicalCacheKey } from './localeVocab.js';\n\nexport function pad(n: number, len: number): string {\n // padStart pads the whole string, sign included, so pad(-45, 4) used to\n // come out \"0-45\" instead of \"-045\" — split the sign off first.\n const negative = n < 0;\n const digits = String(Math.abs(n)).padStart(len, '0');\n return negative ? '-' + digits : digits;\n}\n\n// Not every field exists on every Temporal type (PlainDate has no .hour,\n// etc). Callers check for undefined before formatting a token.\nexport interface TemporalLike {\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n timeZoneId?: string;\n dayOfWeek?: number; // 1=Mon, 7=Sun, per Temporal spec\n calendarId?: string;\n toInstant?: () => unknown;\n toLocaleString?: (locale: string, options: Intl.DateTimeFormatOptions) => string;\n}\n\nexport interface FormatOptions {\n /** BCP 47 locale tag, e.g. 'en-US', 'fr-FR', 'ar-EG'. Defaults to 'en-US'. */\n locale?: string;\n}\n\nexport const DEFAULT_LOCALE = 'en-US';\n\n// Intl.DateTimeFormat is expensive to construct and format() can run in a\n// loop (rendering a table of dates), so cache by (locale, options).\nconst formatterCache = new Map<string, Intl.DateTimeFormat>();\nconst MAX_CACHE_SIZE = 500;\n\nfunction getFormatter(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = JSON.stringify([canonicalCacheKey(locale), options]);\n let formatter = formatterCache.get(key);\n if (formatter) {\n return formatter;\n }\n if (formatterCache.size >= MAX_CACHE_SIZE) {\n // not real LRU, just evicts oldest insertion — fine for this key space\n const oldestKey = formatterCache.keys().next().value;\n if (oldestKey !== undefined) formatterCache.delete(oldestKey);\n }\n formatter = new Intl.DateTimeFormat(locale, options);\n formatterCache.set(key, formatter);\n return formatter;\n}\n\n// Passing a Temporal object straight into `new Intl.DateTimeFormat().formatToParts()`\n// only works when the engine's Intl implementation has special-cased support for\n// *native* Temporal instances (checked via internal slots and/or gated behind a V8 flag,\n// not tied to a specific Node version).\n//\n// A Temporal polyfill's instances don't have those slots, so the engine falls back to ToNumber() -> .valueOf(),\n// which the polyfill deliberately throws on (\"Cannot use valueOf\").\n// Probed once and memoized and only from intlPart(), so it never\n// runs unless a format string actually uses a locale-aware token.\nlet nativeSupport: boolean | undefined;\n// Invalidate the memoized probe whenever setTemporal() swaps the active\n// implementation — otherwise a probe result from \"is native Temporal\n// supported\" could keep being used after the active implementation is\n// no longer the one that was probed. See setTemporal() in\n// temporalProvider.ts for the other half of this.\nsubscribeToTemporalChanges(() => { nativeSupport = undefined; });\n\nfunction intlSupportsNativeTemporal(): boolean {\n if (nativeSupport === undefined) {\n nativeSupport = false;\n try {\n const temporal = getTemporal();\n new Intl.DateTimeFormat('en-US', { day: 'numeric' })\n .formatToParts(temporal.PlainDate.from({ year: 1970, month: 1, day: 1 }) as Date);\n nativeSupport = true;\n } catch {\n // native Temporal absent, or present but not recognized by Intl — fall back\n }\n }\n return nativeSupport;\n}\n\nfunction intlPart(\n temporal: TemporalLike,\n locale: string,\n options: Intl.DateTimeFormatOptions,\n partType: Intl.DateTimeFormatPartTypes\n): string {\n // Intl throws \"Mismatching Calendars\" if the formatter's calendar doesn't\n // match the object's own (e.g. en-US formatter defaults to gregory, but\n // a hebrew/islamic PlainDate needs its own calendar passed through).\n //\n // For iso8601 specifically, force 'gregory' rather than leaving calendar\n // unset: numeric fields (yyyy/dd, see tokens' pad()-based handlers) are\n // always pulled straight off the object's own ISO fields — so if the\n // *locale* carries a `-u-ca-*` extension (e.g. 'en-u-ca-hebrew') and this\n // step left calendar unset, the formatter would resolve its own default\n // calendar from the locale and format MMMM/EEEE in that calendar while\n // yyyy/dd stay ISO, producing a date that looks internally consistent\n // (a real Hebrew month name next to a real-looking day/year) but names a\n // completely different day than the object actually represents. Forcing\n // 'gregory' here keeps every field of an ISO object's output anchored to\n // the same (ISO/Gregorian) calendar — a locale's calendar extension only\n // takes effect when the object itself already carries a non-ISO calendar\n // (via `.withCalendar()`), matching what the README documents.\n //\n // 'gregory' specifically, not 'iso8601' — passing `calendar: 'iso8601'`\n // explicitly alongside a single-field options object makes\n // formatToParts() come back empty for some reason, but 'gregory' doesn't\n // have that problem and Temporal's iso8601 calendar is Gregorian-shaped\n // (proleptic Gregorian throughout, no Julian cutover) so the two agree\n // on every numeric field this library ever reads.\n const calendar = temporal?.calendarId;\n const formatterOptions: Intl.DateTimeFormatOptions = {\n ...options,\n calendar: calendar && calendar !== 'iso8601' ? calendar : 'gregory',\n };\n\n // Temporal.prototype.toLocaleString() is part of the Temporal spec itself:\n // polyfills implement the ICU formatting internally without needing the\n // engine to recognize the object, so it works without native Intl support.\n if (!intlSupportsNativeTemporal()) {\n return temporal.toLocaleString!(locale, formatterOptions);\n }\n\n // formatToParts() throws on ZonedDateTime directly (per spec), so convert\n // to Instant and pass the zone via `timeZone` instead. Don't convert to\n // PlainDateTime — that drops the zone, which breaks 'MMMM' + 'zzz' combos.\n const { toInstant, timeZoneId } = temporal;\n const isZoned = typeof toInstant === 'function' && typeof timeZoneId === 'string';\n // has to be called as temporal.toInstant() because destructuring it off breaks\n // the receiver and throws\n const intlSafeTemporal = isZoned ? temporal.toInstant!() : temporal;\n const nativeOptions: Intl.DateTimeFormatOptions = {\n ...formatterOptions,\n ...(isZoned ? { timeZone: timeZoneId } : {}),\n };\n\n const formatter = getFormatter(locale, nativeOptions);\n const parts = formatter.formatToParts(intlSafeTemporal as Date | number);\n const index = parts.findIndex((p) => p.type === partType);\n if (index === -1) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" produced no \"${partType}\" part for this token. ` +\n `This usually means the Temporal object is missing the field the token needs.`\n );\n }\n // some locales (ja-JP) split a field across two parts — e.g. month \"8\"\n // plus a counter suffix \"月\" as a separate sibling literal part. Merge in\n // an adjacent literal only if it has no whitespace, so a genuine suffix\n // gets folded in but an ordinary separator (the space before \"AM\") stays\n // a separator. Mirrors partValue() in localeVocab.ts, which builds the\n // vocab this token's output needs to match for parse() to round-trip.\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Temporal.prototype.toLocaleString() can't isolate a single field the way\n// formatToParts() can — asking for `hour` + `dayPeriod` together returns one\n// joined string (e.g. \"3 in the afternoon\"), and `dayPeriod` alone resolves\n// against a different, non-hour-anchored set of periods (\"in the\n// afternoon\"/\"昼\" instead of \"PM\"/\"午後\"). Day period only depends on the\n// hour anyway, so route it through a plain UTC Date and Intl.DateTimeFormat\n// instead — that's worked the same on every engine regardless of whether\n// Temporal itself is native or polyfilled.\nfunction dayPeriodPart(hour: number, locale: string): string {\n const date = new Date(Date.UTC(1970, 0, 1, hour));\n const formatter = getFormatter(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const part = formatter.formatToParts(date).find((p) => p.type === 'dayPeriod');\n if (!part) {\n throw new Error(`temporal-fmt: locale \"${locale}\" produced no \"dayPeriod\" part for token \"a\".`);\n }\n return part.value;\n}\n\ntype TokenHandler = (t: TemporalLike, locale: string) => string;\n\n// Longest-first — tokenizer is greedy, \"yyyy\" has to be tried before \"yy\".\n//\n// Numeric tokens always render in ASCII digits, never locale-native\n// (Arabic-Indic, Devanagari, etc). Padding non-ASCII digits isn't as simple\n// as padding \"3\", and most consumers parsing these back out want plain\n// digits anyway.\nexport const TOKENS: Array<[string, TokenHandler, keyof TemporalLike]> = [\n ['yyyy', (t) => pad(t.year!, 4), 'year'],\n ['yy', (t) => {\n // -45 % 100 === -45, so truncating negative years to 2 digits doesn't\n // work and Math.abs() would make 45 CE and 45 BCE render the same.\n if (t.year! < 0) {\n throw new Error(\n `temporal-fmt: token \"yy\" doesn't support negative years (got ${t.year}), ` +\n `since truncating to 2 digits would make it indistinguishable from a ` +\n `positive year. Use \"yyyy\" instead.`\n );\n }\n return pad(t.year! % 100, 2);\n }, 'year'],\n ['MMMM', (t, locale) => intlPart(t, locale, { month: 'long' }, 'month'), 'month'],\n ['MMM', (t, locale) => intlPart(t, locale, { month: 'short' }, 'month'), 'month'],\n ['MM', (t) => pad(t.month!, 2), 'month'],\n ['M', (t) => String(t.month!), 'month'],\n ['dd', (t) => pad(t.day!, 2), 'day'],\n ['d', (t) => String(t.day!), 'day'],\n ['EEEE', (t, locale) => intlPart(t, locale, { weekday: 'long' }, 'weekday'), 'dayOfWeek'],\n ['EEE', (t, locale) => intlPart(t, locale, { weekday: 'short' }, 'weekday'), 'dayOfWeek'],\n ['HH', (t) => pad(t.hour!, 2), 'hour'],\n ['H', (t) => String(t.hour!), 'hour'],\n ['hh', (t) => pad(t.hour! % 12 || 12, 2), 'hour'],\n ['h', (t) => String(t.hour! % 12 || 12), 'hour'],\n ['mm', (t) => pad(t.minute!, 2), 'minute'],\n ['m', (t) => String(t.minute!), 'minute'],\n ['ss', (t) => pad(t.second!, 2), 'second'],\n ['s', (t) => String(t.second!), 'second'],\n ['SSS', (t) => pad(t.millisecond!, 3), 'millisecond'],\n // dayPeriod text is locale-specific (AM/PM in en-US, م/ص in ar-EG) but\n // still needs .hour on the input to compute which period it is\n ['a', (t, locale) => dayPeriodPart(t.hour!, locale), 'hour'],\n ['zzz', (t) => t.timeZoneId!, 'timeZoneId'],\n];","import { TOKENS } from './tokens.js';\n\nexport type Piece =\n | { kind: 'token'; value: string }\n | { kind: 'literal'; value: string };\n\n// longest-first so the greedy scan never matches \"M\" when \"MMMM\" was there\nconst SORTED_TOKEN_STRINGS = TOKENS.map(([tok]) => tok).sort((a, b) => b.length - a.length);\n\n/**\n * Splits a format string like `\"yyyy-MM-dd 'at' HH:mm\"` into token/literal\n * pieces. Text in single quotes is always literal (e.g. write 'rd' in\n * \"3rd\" so it's not read as the day token). A doubled quote ('') means a\n * literal quote character, both inside a quoted span and standalone.\n */\nexport function tokenize(format: string): Piece[] {\n const pieces: Piece[] = [];\n let i = 0;\n\n while (i < format.length) {\n const ch = format[i];\n\n if (ch === \"'\") {\n // check doubled-quote first or \"''best''\" parses wrong\n if (format[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < format.length) {\n if (format[j] === \"'\") {\n if (format[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += format[j];\n j += 1;\n }\n\n if (!closed) {\n throw new Error(`temporal-fmt: unterminated quote in format string \"${format}\"`);\n }\n\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n\n const match = SORTED_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n\n // not a token or quote — pass through as-is\n appendLiteral(pieces, ch);\n i += 1;\n }\n\n return pieces;\n}\n\n// merges into the previous piece if it's also a literal, so \"---\" is one\n// piece instead of three\nfunction appendLiteral(pieces: Piece[], value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n}\n","import { TOKENS, DEFAULT_LOCALE, type TemporalLike, type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\n\nconst HANDLER_BY_TOKEN = new Map(TOKENS.map(([tok, fn, field]) => [tok, { fn, field }]));\n\n/**\n * Format a Temporal.PlainDate, PlainTime, PlainDateTime, or ZonedDateTime\n * using a date-fns-style token string.\n *\n * @example\n * format(Temporal.Now.plainDateISO(), 'yyyy-MM-dd') // \"2026-08-04\"\n * format(zdt, \"MMM d, yyyy 'at' h:mm a\") // \"Aug 4, 2026 at 3:45 PM\"\n * format(zdt, 'MMMM d, yyyy', { locale: 'fr-FR' }) // \"août 4, 2026\"\n *\n * Throws on a token the input type doesn't support (e.g. 'HH' on a PlainDate).\n */\nexport function format(temporal: TemporalLike, formatStr: string, options: FormatOptions = {}): string {\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 const locale = options.locale ?? DEFAULT_LOCALE;\n const pieces = tokenize(formatStr);\n let result = '';\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n\n const handler = HANDLER_BY_TOKEN.get(piece.value);\n if (!handler) {\n // shouldn't happen — tokenize() only emits tokens from TOKENS\n throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n }\n\n if (temporal[handler.field] === undefined) {\n throw new Error(\n `temporal-fmt: token \"${piece.value}\" requires \"${handler.field}\", ` +\n `which this Temporal object doesn't have. ` +\n `(e.g. PlainDate has no time fields, PlainTime has no date fields)`\n );\n }\n\n result += handler.fn(temporal, locale);\n }\n\n return result;\n}\n","import { getLocaleVocab } from './localeVocab.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction alternation(values: string[]): string {\n return `(?:${values.map(escapeRegExp).join('|')})`;\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\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 SSS: '\\\\d{3}',\n};\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.\nconst DIGIT_LEADING_TOKENS = new Set([\n 'yyyy', 'yy', 'MM', 'M', 'dd', 'd', 'HH', 'H', 'hh', 'h', 'mm', 'm', 'ss', 's', 'SSS',\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 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 'a': return alternation(vocab.dayPeriod);\n case 'zzz': return getTimeZoneFragment();\n default:\n throw new Error(`temporal-fmt: unknown token \"${token}\"`);\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 if (!ranges) {\n throw new Error(`temporal-fmt: internal error — \"${token}\" is not an unpadded numeric token`);\n }\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 } from './pattern.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\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\", \"Hm\") — these need a split-ambiguity\n // check at match time, since a single fixed regex can't distinguish\n // \"the only valid split\" from \"one of several valid splits taken\n // arbitrarily\". Empty for the overwhelmingly common case (no such runs).\n ambiguousRuns: Array<{ 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<{ groupNames: string[]; tokens: string[] }> = [];\n let source = '';\n let i = 0;\n\n // tracks the group names/tokens of the current run of adjacent unpadded\n // numeric token pieces (no literal piece has broken it yet)\n let currentRun: { groupNames: string[]; tokens: string[] } = { groupNames: [], tokens: [] };\n const flushRun = () => {\n if (currentRun.tokens.length >= 2) {\n ambiguousRuns.push(currentRun);\n }\n currentRun = { groupNames: [], tokens: [] };\n };\n\n for (const [idx, piece] of pieces.entries()) {\n if (piece.kind === 'literal') {\n source += escapeRegExp(piece.value);\n flushRun(); // a literal (even a single character) breaks adjacency\n continue;\n }\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 source += `(?<${name}>${tokenFragment(piece.value, locale, nextToken)})`;\n\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n currentRun.groupNames.push(name);\n currentRun.tokens.push(piece.value);\n } else {\n flushRun(); // a non-unpadded-numeric token (padded, locale-aware, zzz) also breaks adjacency\n }\n }\n flushRun();\n\n return { regex: new RegExp(`^(?:${source})$`, 'u'), groups, ambiguousRuns };\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';\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 timeZoneId?: string;\n weekdayExpected?: number;\n weekdayRaw?: string;\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 'SSS':\n assignField(fields, 'millisecond', Number(raw));\n break;\n case 'a': {\n const periodIndex = vocab.dayPeriod.indexOf(raw);\n if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period \"${raw}\" for locale \"${locale}\".`);\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 }\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 !== expected) {\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: FormatOptions = {}): 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 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 // each captured zzz group against the actual zone list here. Kept as the\n // same \"no valid pattern matches\" error the inline-alternation version\n // used to throw, since from the caller's perspective this is still the\n // regex rejecting the input, just checked in two steps instead of one.\n for (const { name, token } of pattern.groups) {\n if (token === 'zzz' && !isValidTimeZone(match.groups![name]!)) {\n throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);\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 and throw if\n // more than one split is actually valid for the substring this call\n // matched — the input itself is what's ambiguous, not a fixable\n // property of the pattern.\n for (const run of pattern.ambiguousRuns) {\n const runDigits = run.groupNames.map((name) => match.groups![name]!).join('');\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length > 1) {\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 );\n }\n }\n\n const fields: Fields = {};\n for (const { name, token } of pattern.groups) {\n applyGroup(fields, token, match.groups![name]!, locale, formatStr);\n }\n\n const year = resolveYear(fields);\n const hour = resolveHour(fields, formatStr, locale);\n const { month, day, minute, second, millisecond, timeZoneId, weekdayExpected, weekdayRaw } = 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 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 = { hour: hour ?? 0, minute: minute ?? 0, second: second ?? 0, millisecond: millisecond ?? 0 };\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 result = temporal.ZonedDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField, timeZone: timeZoneId }, 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 return result;\n}"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,YAAAE,GAAA,UAAAC,GAAA,gBAAAC,IAAA,eAAAC,GAAAL,ICmBA,IAAIM,EASEC,EAAuC,CAAC,EAEvC,SAASC,EAA2BC,EAA4B,CACrEF,EAAkB,KAAKE,CAAQ,CACjC,CAeO,SAASC,EAAYC,EAAoC,CAC9DL,EAAmBK,EASnB,QAAWF,KAAYF,EAAmBE,EAAS,CACrD,CAEA,SAASG,IAAiD,CACxD,OAAON,GAAqB,WAA2D,QACzF,CAEO,SAASO,GAAiC,CAC/C,IAAMF,EAAWC,GAAgB,EACjC,GAAI,CAACD,EACH,MAAM,IAAI,MACR,6NAGF,EAEF,OAAOA,CACT,CC/CO,SAASG,EAAkBC,EAAwB,CACxD,GAAI,CAKF,OAAO,IAAI,KAAK,OAAOA,EAAO,QAAQ,KAAM,GAAG,CAAC,EAAE,SAAS,EAAE,YAAY,CAC3E,MAAQ,CACN,OAAOA,CACT,CACF,CAEA,IAAMC,EAAa,IAAI,IACjBC,GAAuB,IAU7B,SAASC,EAAUC,EAAgCC,EAAYC,EAA4C,CACzG,IAAMC,EAAQH,EAAU,cAAcC,CAAI,EACpCG,EAAQD,EAAM,UAAW,GAAM,EAAE,OAASD,CAAI,EACpD,GAAIE,IAAU,GACZ,MAAM,IAAI,MAAM,qCAAqCF,CAAI,yCAAyC,EAEpG,IAAIG,EAAQF,EAAMC,CAAK,EAAG,MACpBE,EA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,EAAM,GAAGY,EAAY,GAAGC,EAAe,SAAUT,CAAW,EAAGU,CAAM,EACpIN,GAAeC,EACxBM,EAASL,EAAS,cAAc,KAAK,CAAE,KAAMb,EAAO,MAAOE,EAAQ,IAAKC,EAAM,GAAGY,EAAY,GAAGC,CAAc,EAAGC,CAAM,EAC9GN,EACTO,EAASL,EAAS,UAAU,KAAK,CAAE,KAAMb,EAAO,MAAOE,EAAQ,IAAKC,EAAM,GAAGa,CAAc,EAAGC,CAAM,EAEpGC,EAASL,EAAS,UAAU,KAAKE,EAAYE,CAAM,CAEvD,OAASE,EAAK,CACZ,MAAM,IAAI,MACR,kBAAkB7B,CAAK,oDAAoD9B,CAAS,MAChF2D,EAAc,OAAO,EAC3B,CACF,CAEA,GAAIX,IAAoB,OAAW,CACjC,IAAMY,EAAUF,EAAiC,UACjD,GAAIE,IAAWZ,EAAiB,CAC9B,IAAMzB,EAAQC,EAAevB,CAAM,EACnC,MAAM,IAAI,MACR,kBAAkBgD,CAAU,uCAAuC1B,EAAM,YAAYqC,EAAS,CAAC,CAAC,wBAElG,CACF,CACF,CAEA,OAAOF,CACT","names":["index_exports","__export","format","parse","setTemporal","__toCommonJS","injectedTemporal","onTemporalChanged","subscribeToTemporalChanges","listener","setTemporal","temporal","resolveTemporal","getTemporal","canonicalCacheKey","locale","vocabCache","MAX_VOCAB_CACHE_SIZE","partValue","formatter","date","type","parts","index","value","prev","next","assertNoCollision","names","label","seen","i","prior","getLocaleVocab","cacheKey","cached","monthLongFmt","monthShortFmt","monthLong","monthShort","m","weekdayLongFmt","weekdayShortFmt","weekdayLong","weekdayShort","d","dayPeriodFmt","am","pm","dayPeriod","vocab","oldestKey","pad","n","len","negative","digits","DEFAULT_LOCALE","formatterCache","MAX_CACHE_SIZE","getFormatter","locale","options","key","canonicalCacheKey","formatter","oldestKey","nativeSupport","subscribeToTemporalChanges","intlSupportsNativeTemporal","temporal","getTemporal","intlPart","partType","calendar","formatterOptions","toInstant","timeZoneId","isZoned","intlSafeTemporal","nativeOptions","parts","index","p","value","prev","next","dayPeriodPart","hour","date","part","TOKENS","t","SORTED_TOKEN_STRINGS","TOKENS","tok","a","b","tokenize","format","pieces","i","ch","appendLiteral","j","literal","closed","match","value","last","HANDLER_BY_TOKEN","TOKENS","tok","fn","field","format","temporal","formatStr","options","locale","DEFAULT_LOCALE","pieces","tokenize","result","piece","handler","escapeRegExp","literal","alternation","values","TIME_ZONE_SHAPE","getTimeZoneFragment","validZoneSet","getValidZoneSet","FIXED_OFFSET_RE","isValidTimeZone","raw","NUMERIC_FRAGMENTS","YYYY_EXACT","YYYY_EXTENDED","DIGIT_LEADING_TOKENS","tokenFragment","token","locale","nextToken","numeric","vocab","getLocaleVocab","UNPADDED_NUMERIC_TOKENS","UNPADDED_NUMERIC_RANGES","enumerateValidSplits","digits","tokens","memo","solve","tokenIndex","offset","key","cached","result","ranges","results","width","min","max","piece","value","restSplit","escapeRegExp","literal","buildCapturingPattern","pieces","locale","groups","ambiguousRuns","source","i","currentRun","flushRun","idx","piece","name","nextPiece","nextToken","tokenFragment","UNPADDED_NUMERIC_TOKENS","patternCache","MAX_CACHE_SIZE","getPattern","formatStr","locale","key","canonicalCacheKey","pattern","oldestKey","buildCapturingPattern","tokenize","calendarCache","MAX_CALENDAR_CACHE_SIZE","resolveCalendar","canonicalLocale","calendar","parts","extensionIndex","calendarKeyIndex","resolved","assignField","fields","value","applyGroup","token","raw","vocab","getLocaleVocab","periodIndex","resolveYear","resolveHour","expected","parse","input","options","DEFAULT_LOCALE","match","name","isValidTimeZone","run","runDigits","splits","enumerateValidSplits","year","hour","month","day","minute","second","millisecond","timeZoneId","weekdayExpected","weekdayRaw","hasAnyDatePart","hasFullDate","hasTime","temporal","getTemporal","timeFields","calendarField","reject","result","err","actual"]}
@@ -0,0 +1,5 @@
1
+ export { format } from './format.cjs';
2
+ export { parse } from './parse.cjs';
3
+ export { setTemporal } from './temporalProvider.cjs';
4
+ export type { TemporalLike, FormatOptions } from './tokens.cjs';
5
+ export type { TemporalNamespace } from './temporalProvider.cjs';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var G;function ne(e){G=e}function re(){return G??globalThis.Temporal}function C(){let e=re();if(!e)throw new Error("temporal-fmt: parse() needs a Temporal implementation to construct its result. Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal (native on Node 26+, or a polyfill like temporal-polyfill).");return e}function k(e,n){let t=e<0,r=String(Math.abs(e)).padStart(n,"0");return t?"-"+r:r}var A="en-US",P=new Map,oe=500;function X(e,n){let t=JSON.stringify([e,n]),r=P.get(t);if(r)return r;if(P.size>=oe){let a=P.keys().next().value;a!==void 0&&P.delete(a)}return r=new Intl.DateTimeFormat(e,n),P.set(t,r),r}var I;function ae(){if(I===void 0){I=!1;try{let e=C();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),I=!0}catch{}}return I}function S(e,n,t,r){let a=e?.calendarId,o={...t,...a&&a!=="iso8601"?{calendar:a}:{}};if(!ae())return e.toLocaleString(n,o);let{toInstant:i,timeZoneId:s}=e,m=typeof i=="function"&&typeof s=="string",p=m?e.toInstant():e,c={...o,...m?{timeZone:s}:{}},h=X(n,c).formatToParts(p),y=h.findIndex(H=>H.type===r);if(y===-1)throw new Error(`temporal-fmt: locale "${n}" produced no "${r}" part for this token. This usually means the Temporal object is missing the field the token needs.`);let f=h[y].value,d=h[y-1],g=h[y+1];return d?.type==="literal"&&!/\s/.test(d.value)&&(f=d.value+f),g?.type==="literal"&&!/\s/.test(g.value)&&(f=f+g.value),f}function ie(e,n){let t=new Date(Date.UTC(1970,0,1,e)),a=X(n,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(t).find(o=>o.type==="dayPeriod");if(!a)throw new Error(`temporal-fmt: locale "${n}" produced no "dayPeriod" part for token "a".`);return a.value}var R=[["yyyy",e=>k(e.year,4),"year"],["yy",e=>{if(e.year<0)throw new Error(`temporal-fmt: token "yy" doesn't support negative years (got ${e.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`);return k(e.year%100,2)},"year"],["MMMM",(e,n)=>S(e,n,{month:"long"},"month"),"month"],["MMM",(e,n)=>S(e,n,{month:"short"},"month"),"month"],["MM",e=>k(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>k(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,n)=>S(e,n,{weekday:"long"},"weekday"),"dayOfWeek"],["EEE",(e,n)=>S(e,n,{weekday:"short"},"weekday"),"dayOfWeek"],["HH",e=>k(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>k(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>k(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>k(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSS",e=>k(e.millisecond,3),"millisecond"],["a",(e,n)=>ie(e.hour,n),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"]];var se=R.map(([e])=>e).sort((e,n)=>n.length-e.length);function _(e){let n=[],t=0;for(;t<e.length;){let r=e[t];if(r==="'"){if(e[t+1]==="'"){V(n,"'"),t+=2;continue}let o=t+1,i="",s=!1;for(;o<e.length;){if(e[o]==="'"){if(e[o+1]==="'"){i+="'",o+=2;continue}s=!0,o+=1;break}i+=e[o],o+=1}if(!s)throw new Error(`temporal-fmt: unterminated quote in format string "${e}"`);V(n,i),t=o;continue}let a=se.find(o=>e.startsWith(o,t));if(a){n.push({kind:"token",value:a}),t+=a.length;continue}V(n,r),t+=1}return n}function V(e,n){let t=e[e.length-1];t&&t.kind==="literal"?t.value+=n:e.push({kind:"literal",value:n})}var me=new Map(R.map(([e,n,t])=>[e,{fn:n,field:t}]));function de(e,n,t={}){if(n.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${n.length}).`);let r=t.locale??A,a=_(n),o="";for(let i of a){if(i.kind==="literal"){o+=i.value;continue}let s=me.get(i.value);if(!s)throw new Error(`temporal-fmt: unknown token "${i.value}"`);if(e[s.field]===void 0)throw new Error(`temporal-fmt: token "${i.value}" requires "${s.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`);o+=s.fn(e,r)}return o}var $=new Map,ue=500;function x(e,n,t){let r=e.formatToParts(n),a=r.findIndex(m=>m.type===t);if(a===-1)throw new Error(`temporal-fmt: locale produced no "${t}" part while building match vocabulary.`);let o=r[a].value,i=r[a-1],s=r[a+1];return i?.type==="literal"&&!/\s/.test(i.value)&&(o=i.value+o),s?.type==="literal"&&!/\s/.test(s.value)&&(o=o+s.value),o}function Z(e,n,t){let r=new Map;for(let a=0;a<e.length;a++){let o=r.get(e[a]);if(o!==void 0)throw new Error(`temporal-fmt: locale "${t}" renders ${n} index ${o} and ${a} identically ("${e[a]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);r.set(e[a],a)}}function v(e){let n=$.get(e);if(n)return n;let t=new Intl.DateTimeFormat(e,{month:"long",timeZone:"UTC"}),r=new Intl.DateTimeFormat(e,{month:"short",timeZone:"UTC"}),a=[],o=[];for(let d=0;d<12;d++){let g=new Date(Date.UTC(2020,d,1));a.push(x(t,g,"month")),o.push(x(r,g,"month"))}Z(a,"MMMM month",e),Z(o,"MMM month",e);let i=new Intl.DateTimeFormat(e,{weekday:"long",timeZone:"UTC"}),s=new Intl.DateTimeFormat(e,{weekday:"short",timeZone:"UTC"}),m=[],p=[];for(let d=0;d<7;d++){let g=new Date(Date.UTC(2024,0,1+d));m.push(x(i,g,"weekday")),p.push(x(s,g,"weekday"))}Z(m,"EEEE weekday",e),Z(p,"EEE weekday",e);let c=new Intl.DateTimeFormat(e,{hour:"numeric",hour12:!0,timeZone:"UTC"}),l=x(c,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),h=x(c,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),y=[...new Set([l,h])],f={monthLong:a,monthShort:o,weekdayLong:m,weekdayShort:p,dayPeriod:y};if($.size>=ue){let d=$.keys().next().value;d!==void 0&&$.delete(d)}return $.set(e,f),f}function W(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function M(e){return`(?:${e.map(W).join("|")})`}var U;function ce(){if(U)return U;let n=Intl.supportedValuesOf("timeZone").map(W);return U=`(?:UTC|[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?|${M(n)})`,U}var le={yyyy:"\\d{4}",yy:"\\d{2}",MM:"(?:0[1-9]|1[0-2])",M:"(?:1[0-2]|[1-9])",dd:"(?:0[1-9]|[12]\\d|3[01])",d:"(?:[12]\\d|3[01]|[1-9])",HH:"(?:[01]\\d|2[0-3])",H:"(?:1\\d|2[0-3]|[0-9])",hh:"(?:0[1-9]|1[0-2])",h:"(?:1[0-2]|[1-9])",mm:"(?:[0-5]\\d)",m:"(?:[1-5]\\d|[0-9])",ss:"(?:[0-5]\\d)",s:"(?:[1-5]\\d|[0-9])",SSS:"\\d{3}"};function J(e,n){let t=le[e];if(t)return t;let r=v(n);switch(e){case"MMMM":return M(r.monthLong);case"MMM":return M(r.monthShort);case"EEEE":return M(r.weekdayLong);case"EEE":return M(r.weekdayShort);case"a":return M(r.dayPeriod);case"zzz":return ce();default:throw new Error(`temporal-fmt: unknown token "${e}"`)}}var q=new Set(["M","d","H","h","m","s"]),pe={M:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],d:[{digits:1,min:1,max:9},{digits:2,min:10,max:31}],H:[{digits:1,min:0,max:9},{digits:2,min:10,max:23}],h:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],m:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}],s:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}]};function B(e,n){let t=new Map;function r(a,o){let i=`${a}:${o}`,s=t.get(i);if(s)return s;if(a===n.length){let l=o===e.length?[[]]:[];return t.set(i,l),l}let m=n[a],p=pe[m];if(!p)throw new Error(`temporal-fmt: internal error \u2014 "${m}" is not an unpadded numeric token`);let c=[];for(let{digits:l,min:h,max:y}of p){if(o+l>e.length)continue;let f=e.slice(o,o+l);if(l===2&&f[0]==="0")continue;let d=Number(f);if(!(d<h||d>y)){for(let g of r(a+1,o+l))if(c.push([d,...g]),c.length===2)break;if(c.length===2)break}}return t.set(i,c),c}return r(0,0)}function ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q(e,n){let t=[],r=[],a="",o=0,i={groupNames:[],tokens:[]},s=()=>{i.tokens.length>=2&&r.push(i),i={groupNames:[],tokens:[]}};for(let m of e){if(m.kind==="literal"){a+=ge(m.value),s();continue}let p=`g${o++}`;t.push({name:p,token:m.value}),a+=`(?<${p}>${J(m.value,n)})`,q.has(m.value)?(i.groupNames.push(p),i.tokens.push(m.value)):s()}return s(),{regex:new RegExp(`^(?:${a})$`,"u"),groups:t,ambiguousRuns:r}}var F=new Map,he=500;function ye(e,n){let t=JSON.stringify([n,e]),r=F.get(t);if(r)return r;if(F.size>=he){let a=F.keys().next().value;a!==void 0&&F.delete(a)}return r=Q(_(e),n),F.set(t,r),r}var D=new Map,we=500;function ke(e){if(D.has(e))return D.get(e);if(D.size>=we){let i=D.keys().next().value;i!==void 0&&D.delete(i)}let n,t=new Intl.Locale(e).toString().toLowerCase(),r=t.split("-"),a=r.indexOf("u"),o=a===-1?-1:r.indexOf("ca",a+1);if(o!==-1&&o+1<r.length){let i=new Intl.DateTimeFormat(t).resolvedOptions().calendar;n=i==="gregory"?void 0:i}return D.set(e,n),n}function u(e,n,t){e[n]=t}function Ee(e,n,t,r,a){let o=v(r);switch(n){case"yyyy":u(e,"year",Number(t));break;case"yy":u(e,"twoDigitYear",Number(t));break;case"MM":case"M":u(e,"month",Number(t));break;case"MMMM":u(e,"month",o.monthLong.indexOf(t)+1);break;case"MMM":u(e,"month",o.monthShort.indexOf(t)+1);break;case"dd":case"d":u(e,"day",Number(t));break;case"EEEE":u(e,"weekdayRaw",t),u(e,"weekdayExpected",o.weekdayLong.indexOf(t)+1);break;case"EEE":u(e,"weekdayRaw",t),u(e,"weekdayExpected",o.weekdayShort.indexOf(t)+1);break;case"HH":case"H":u(e,"hour",Number(t));break;case"hh":case"h":u(e,"hour12",Number(t));break;case"mm":case"m":u(e,"minute",Number(t));break;case"ss":case"s":u(e,"second",Number(t));break;case"SSS":u(e,"millisecond",Number(t));break;case"a":{let i=o.dayPeriod.indexOf(t);if(i<0)throw new Error(`temporal-fmt: unknown day period "${t}" for locale "${r}".`);u(e,"dayPeriodRaw",t),u(e,"isPM",i===1);break}case"zzz":u(e,"timeZoneId",t);break}}function Te(e){if(e.year!==void 0&&e.twoDigitYear!==void 0)throw new Error('temporal-fmt: format string mixes "yyyy" and "yy" year representations.');if(e.year!==void 0)return e.year;if(e.twoDigitYear!==void 0)return e.twoDigitYear<=68?2e3+e.twoDigitYear:1900+e.twoDigitYear}function be(e,n,t){if(e.hour!==void 0&&e.hour12!==void 0)throw new Error(`temporal-fmt: format string "${n}" mixes a 24-hour token ("HH"/"H") with a 12-hour token ("hh"/"h").`);if(e.hour!==void 0){if(e.dayPeriodRaw!==void 0){let r=v(t),a=e.hour<12?r.dayPeriod[0]:r.dayPeriod[1];if(e.dayPeriodRaw!==a)throw new Error(`temporal-fmt: format string "${n}" contains a day period that contradicts the 24-hour value.`)}return e.hour}if(e.hour12!==void 0){if(e.isPM===void 0)throw new Error(`temporal-fmt: format string "${n}" uses a 12-hour token ("hh"/"h") without an "a" token, so parse() can't tell AM from PM.`);return e.hour12%12+(e.isPM?12:0)}}function xe(e,n,t={}){if(e.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${e.length}).`);if(n.length>1e5)throw new Error(`temporal-fmt: input exceeds maximum length of ${1e5} characters (got ${n.length}).`);let r=t.locale??A,a=ke(r),o=ye(e,r),i=o.regex.exec(n);if(!i)throw new Error("temporal-fmt: no valid pattern matches the format string and input shape");if(o.groups.length===0)throw new Error(`temporal-fmt: format string "${e}" has no tokens \u2014 nothing to parse into a value.`);for(let w of o.ambiguousRuns){let b=w.groupNames.map(te=>i.groups[te]).join(""),O=B(b,w.tokens);if(O.length>1)throw new Error(`temporal-fmt: "${b}" in format string "${e}" is ambiguous \u2014 ${O.length} different ways to read tokens "${w.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(O[0])} vs ${JSON.stringify(O[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.`)}let s={};for(let{name:w,token:b}of o.groups)Ee(s,b,i.groups[w],r,e);let m=Te(s),p=be(s,e,r),{month:c,day:l,minute:h,second:y,millisecond:f,timeZoneId:d,weekdayExpected:g,weekdayRaw:H}=s,ee=m!==void 0||c!==void 0||l!==void 0,E=m!==void 0&&c!==void 0&&l!==void 0;if(ee&&!E)throw new Error(`temporal-fmt: format string "${e}" has an incomplete date \u2014 year, month, and day tokens must all be present together.`);let z=p!==void 0||h!==void 0||y!==void 0||f!==void 0;if(d!==void 0&&!(E&&z))throw new Error(`temporal-fmt: format string "${e}" has a "zzz" token but needs a full date and time to build a ZonedDateTime.`);if(g!==void 0&&!E)throw new Error(`temporal-fmt: format string "${e}" has a weekday token ("EEEE"/"EEE") but needs a full date to validate it against.`);if(!E&&!z)throw new Error(`temporal-fmt: format string "${e}" has no date or time tokens to parse.`);let N=C(),j={hour:p??0,minute:h??0,second:y??0,millisecond:f??0},K=a?{calendar:a}:{},L={overflow:"reject"},T;try{d!==void 0?T=N.ZonedDateTime.from({year:m,month:c,day:l,...j,...K,timeZone:d},L):E&&z?T=N.PlainDateTime.from({year:m,month:c,day:l,...j,...K},L):E?T=N.PlainDate.from({year:m,month:c,day:l,...K},L):T=N.PlainTime.from(j,L)}catch(w){throw new Error(`temporal-fmt: "${n}" doesn't describe a valid date/time for format "${e}": ${w.message}`)}if(g!==void 0){let w=T.dayOfWeek;if(w!==g){let b=v(r);throw new Error(`temporal-fmt: "${H}" doesn't match the actual weekday (${b.weekdayLong[w-1]}) for the parsed date.`)}}return T}export{de as format,xe as parse,ne as setTemporal};
1
+ var G,W=[];function J(e){W.push(e)}function ae(e){G=e;for(let n of W)n()}function ie(){return G??globalThis.Temporal}function A(){let e=ie();if(!e)throw new Error("temporal-fmt: parse() needs a Temporal implementation to construct its result. Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal (native on Node 26+, or a polyfill like temporal-polyfill).");return e}function F(e){try{return new Intl.Locale(e.replace(/_/g,"-")).toString().toLowerCase()}catch{return e}}var P=new Map,se=500;function v(e,n,t){let r=e.formatToParts(n),o=r.findIndex(p=>p.type===t);if(o===-1)throw new Error(`temporal-fmt: locale produced no "${t}" part while building match vocabulary.`);let a=r[o].value,i=r[o-1],s=r[o+1];return i?.type==="literal"&&!/\s/.test(i.value)&&(a=i.value+a),s?.type==="literal"&&!/\s/.test(s.value)&&(a=a+s.value),a}function _(e,n,t){let r=new Map;for(let o=0;o<e.length;o++){let a=r.get(e[o]);if(a!==void 0)throw new Error(`temporal-fmt: locale "${t}" renders ${n} index ${a} and ${o} identically ("${e[o]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);r.set(e[o],o)}}function M(e){let n=F(e),t=P.get(n);if(t)return t;let r=new Intl.DateTimeFormat(e,{month:"long",timeZone:"UTC"}),o=new Intl.DateTimeFormat(e,{month:"short",timeZone:"UTC"}),a=[],i=[];for(let u=0;u<12;u++){let k=new Date(Date.UTC(2020,u,1));a.push(v(r,k,"month")),i.push(v(o,k,"month"))}_(a,"MMMM month",e),_(i,"MMM month",e);let s=new Intl.DateTimeFormat(e,{weekday:"long",timeZone:"UTC"}),p=new Intl.DateTimeFormat(e,{weekday:"short",timeZone:"UTC"}),c=[],m=[];for(let u=0;u<7;u++){let k=new Date(Date.UTC(2024,0,1+u));c.push(v(s,k,"weekday")),m.push(v(p,k,"weekday"))}_(c,"EEEE weekday",e),_(m,"EEE weekday",e);let d=new Intl.DateTimeFormat(e,{hour:"numeric",hour12:!0,timeZone:"UTC"}),f=v(d,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),w=v(d,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),h=[...new Set([f,w])],g={monthLong:a,monthShort:i,weekdayLong:c,weekdayShort:m,dayPeriod:h};if(P.size>=se){let u=P.keys().next().value;u!==void 0&&P.delete(u)}return P.set(n,g),g}function T(e,n){let t=e<0,r=String(Math.abs(e)).padStart(n,"0");return t?"-"+r:r}var Z="en-US",N=new Map,me=500;function q(e,n){let t=JSON.stringify([F(e),n]),r=N.get(t);if(r)return r;if(N.size>=me){let o=N.keys().next().value;o!==void 0&&N.delete(o)}return r=new Intl.DateTimeFormat(e,n),N.set(t,r),r}var S;J(()=>{S=void 0});function de(){if(S===void 0){S=!1;try{let e=A();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),S=!0}catch{}}return S}function R(e,n,t,r){let o=e?.calendarId,a={...t,calendar:o&&o!=="iso8601"?o:"gregory"};if(!de())return e.toLocaleString(n,a);let{toInstant:i,timeZoneId:s}=e,p=typeof i=="function"&&typeof s=="string",c=p?e.toInstant():e,m={...a,...p?{timeZone:s}:{}},f=q(n,m).formatToParts(c),w=f.findIndex(k=>k.type===r);if(w===-1)throw new Error(`temporal-fmt: locale "${n}" produced no "${r}" part for this token. This usually means the Temporal object is missing the field the token needs.`);let h=f[w].value,g=f[w-1],u=f[w+1];return g?.type==="literal"&&!/\s/.test(g.value)&&(h=g.value+h),u?.type==="literal"&&!/\s/.test(u.value)&&(h=h+u.value),h}function ue(e,n){let t=new Date(Date.UTC(1970,0,1,e)),o=q(n,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(t).find(a=>a.type==="dayPeriod");if(!o)throw new Error(`temporal-fmt: locale "${n}" produced no "dayPeriod" part for token "a".`);return o.value}var H=[["yyyy",e=>T(e.year,4),"year"],["yy",e=>{if(e.year<0)throw new Error(`temporal-fmt: token "yy" doesn't support negative years (got ${e.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`);return T(e.year%100,2)},"year"],["MMMM",(e,n)=>R(e,n,{month:"long"},"month"),"month"],["MMM",(e,n)=>R(e,n,{month:"short"},"month"),"month"],["MM",e=>T(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>T(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,n)=>R(e,n,{weekday:"long"},"weekday"),"dayOfWeek"],["EEE",(e,n)=>R(e,n,{weekday:"short"},"weekday"),"dayOfWeek"],["HH",e=>T(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>T(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>T(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>T(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSS",e=>T(e.millisecond,3),"millisecond"],["a",(e,n)=>ue(e.hour,n),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"]];var ce=H.map(([e])=>e).sort((e,n)=>n.length-e.length);function U(e){let n=[],t=0;for(;t<e.length;){let r=e[t];if(r==="'"){if(e[t+1]==="'"){j(n,"'"),t+=2;continue}let a=t+1,i="",s=!1;for(;a<e.length;){if(e[a]==="'"){if(e[a+1]==="'"){i+="'",a+=2;continue}s=!0,a+=1;break}i+=e[a],a+=1}if(!s)throw new Error(`temporal-fmt: unterminated quote in format string "${e}"`);j(n,i),t=a;continue}let o=ce.find(a=>e.startsWith(a,t));if(o){n.push({kind:"token",value:o}),t+=o.length;continue}j(n,r),t+=1}return n}function j(e,n){let t=e[e.length-1];t&&t.kind==="literal"?t.value+=n:e.push({kind:"literal",value:n})}var le=new Map(H.map(([e,n,t])=>[e,{fn:n,field:t}]));function pe(e,n,t={}){if(n.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${n.length}).`);let r=t.locale??Z,o=U(n),a="";for(let i of o){if(i.kind==="literal"){a+=i.value;continue}let s=le.get(i.value);if(!s)throw new Error(`temporal-fmt: unknown token "${i.value}"`);if(e[s.field]===void 0)throw new Error(`temporal-fmt: token "${i.value}" requires "${s.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`);a+=s.fn(e,r)}return a}function ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $(e){return`(?:${e.map(ge).join("|")})`}var fe="(?:UTC|[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?|[A-Za-z_]+(?:[+-]\\d{1,2})?(?:\\/[A-Za-z0-9_+-]+)*)";function he(){return fe}var z;function ye(){return z||(z=new Set(Intl.supportedValuesOf("timeZone")),z.add("UTC")),z}var we=/^[+-]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?$/;function B(e){return we.test(e)||ye().has(e)}var ke={yy:"\\d{2}",MM:"(?:0[1-9]|1[0-2])",M:"(?:1[0-2]|[1-9])",dd:"(?:0[1-9]|[12]\\d|3[01])",d:"(?:[12]\\d|3[01]|[1-9])",HH:"(?:[01]\\d|2[0-3])",H:"(?:1\\d|2[0-3]|[0-9])",hh:"(?:0[1-9]|1[0-2])",h:"(?:1[0-2]|[1-9])",mm:"(?:[0-5]\\d)",m:"(?:[1-5]\\d|[0-9])",ss:"(?:[0-5]\\d)",s:"(?:[1-5]\\d|[0-9])",SSS:"\\d{3}"},Te="-?\\d{4}",Ee="-?\\d{4,}",be=new Set(["yyyy","yy","MM","M","dd","d","HH","H","hh","h","mm","m","ss","s","SSS"]);function Q(e,n,t){if(e==="yyyy")return t!==void 0&&be.has(t)?Te:Ee;let r=ke[e];if(r)return r;let o=M(n);switch(e){case"MMMM":return $(o.monthLong);case"MMM":return $(o.monthShort);case"EEEE":return $(o.weekdayLong);case"EEE":return $(o.weekdayShort);case"a":return $(o.dayPeriod);case"zzz":return he();default:throw new Error(`temporal-fmt: unknown token "${e}"`)}}var ee=new Set(["M","d","H","h","m","s"]),xe={M:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],d:[{digits:1,min:1,max:9},{digits:2,min:10,max:31}],H:[{digits:1,min:0,max:9},{digits:2,min:10,max:23}],h:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],m:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}],s:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}]};function te(e,n){let t=new Map;function r(o,a){let i=`${o}:${a}`,s=t.get(i);if(s)return s;if(o===n.length){let d=a===e.length?[[]]:[];return t.set(i,d),d}let p=n[o],c=xe[p];if(!c)throw new Error(`temporal-fmt: internal error \u2014 "${p}" is not an unpadded numeric token`);let m=[];for(let{digits:d,min:f,max:w}of c){if(a+d>e.length)continue;let h=e.slice(a,a+d);if(d===2&&h[0]==="0")continue;let g=Number(h);if(!(g<f||g>w)){for(let u of r(o+1,a+d))if(m.push([g,...u]),m.length===2)break;if(m.length===2)break}}return t.set(i,m),m}return r(0,0)}function ve(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ne(e,n){let t=[],r=[],o="",a=0,i={groupNames:[],tokens:[]},s=()=>{i.tokens.length>=2&&r.push(i),i={groupNames:[],tokens:[]}};for(let[p,c]of e.entries()){if(c.kind==="literal"){o+=ve(c.value),s();continue}let m=`g${a++}`;t.push({name:m,token:c.value});let d=e[p+1],f=d?.kind==="token"?d.value:void 0;o+=`(?<${m}>${Q(c.value,n,f)})`,ee.has(c.value)?(i.groupNames.push(m),i.tokens.push(c.value)):s()}return s(),{regex:new RegExp(`^(?:${o})$`,"u"),groups:t,ambiguousRuns:r}}var C=new Map,De=500;function Pe(e,n){let t=JSON.stringify([F(n),e]),r=C.get(t);if(r)return r;if(C.size>=De){let o=C.keys().next().value;o!==void 0&&C.delete(o)}return r=ne(U(e),n),C.set(t,r),r}var D=new Map,Fe=500;function Ne(e){let n=new Intl.Locale(e).toString().toLowerCase();if(D.has(n))return D.get(n);if(D.size>=Fe){let i=D.keys().next().value;i!==void 0&&D.delete(i)}let t,r=n.split("-"),o=r.indexOf("u"),a=o===-1?-1:r.indexOf("ca",o+1);if(a!==-1&&a+1<r.length){let i=new Intl.DateTimeFormat(n).resolvedOptions().calendar;t=i==="gregory"?void 0:i}return D.set(n,t),t}function l(e,n,t){e[n]=t}function Se(e,n,t,r,o){let a=M(r);switch(n){case"yyyy":l(e,"year",Number(t));break;case"yy":l(e,"twoDigitYear",Number(t));break;case"MM":case"M":l(e,"month",Number(t));break;case"MMMM":l(e,"month",a.monthLong.indexOf(t)+1);break;case"MMM":l(e,"month",a.monthShort.indexOf(t)+1);break;case"dd":case"d":l(e,"day",Number(t));break;case"EEEE":l(e,"weekdayRaw",t),l(e,"weekdayExpected",a.weekdayLong.indexOf(t)+1);break;case"EEE":l(e,"weekdayRaw",t),l(e,"weekdayExpected",a.weekdayShort.indexOf(t)+1);break;case"HH":case"H":l(e,"hour",Number(t));break;case"hh":case"h":l(e,"hour12",Number(t));break;case"mm":case"m":l(e,"minute",Number(t));break;case"ss":case"s":l(e,"second",Number(t));break;case"SSS":l(e,"millisecond",Number(t));break;case"a":{let i=a.dayPeriod.indexOf(t);if(i<0)throw new Error(`temporal-fmt: unknown day period "${t}" for locale "${r}".`);l(e,"dayPeriodRaw",t),l(e,"isPM",i===1);break}case"zzz":l(e,"timeZoneId",t);break}}function $e(e){if(e.year!==void 0&&e.twoDigitYear!==void 0)throw new Error('temporal-fmt: format string mixes "yyyy" and "yy" year representations.');if(e.year!==void 0)return e.year;if(e.twoDigitYear!==void 0)return e.twoDigitYear<=68?2e3+e.twoDigitYear:1900+e.twoDigitYear}function Ce(e,n,t){if(e.hour!==void 0&&e.hour12!==void 0)throw new Error(`temporal-fmt: format string "${n}" mixes a 24-hour token ("HH"/"H") with a 12-hour token ("hh"/"h").`);if(e.hour!==void 0){if(e.dayPeriodRaw!==void 0){let r=M(t),o=e.hour<12?r.dayPeriod[0]:r.dayPeriod[1];if(e.dayPeriodRaw!==o)throw new Error(`temporal-fmt: format string "${n}" contains a day period that contradicts the 24-hour value.`)}return e.hour}if(e.hour12!==void 0){if(e.isPM===void 0)throw new Error(`temporal-fmt: format string "${n}" uses a 12-hour token ("hh"/"h") without an "a" token, so parse() can't tell AM from PM.`);return e.hour12%12+(e.isPM?12:0)}}function Ie(e,n,t={}){if(e.length>1e3)throw new Error(`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${e.length}).`);if(n.length>1e5)throw new Error(`temporal-fmt: input exceeds maximum length of ${1e5} characters (got ${n.length}).`);let r=t.locale??Z,o=Ne(r),a=Pe(e,r),i=a.regex.exec(n);if(!i)throw new Error("temporal-fmt: no valid pattern matches the format string and input shape");if(a.groups.length===0)throw new Error(`temporal-fmt: format string "${e}" has no tokens \u2014 nothing to parse into a value.`);for(let{name:y,token:E}of a.groups)if(E==="zzz"&&!B(i.groups[y]))throw new Error("temporal-fmt: no valid pattern matches the format string and input shape");for(let y of a.ambiguousRuns){let E=y.groupNames.map(oe=>i.groups[oe]).join(""),O=te(E,y.tokens);if(O.length>1)throw new Error(`temporal-fmt: "${E}" in format string "${e}" is ambiguous \u2014 ${O.length} different ways to read tokens "${y.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(O[0])} vs ${JSON.stringify(O[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.`)}let s={};for(let{name:y,token:E}of a.groups)Se(s,E,i.groups[y],r,e);let p=$e(s),c=Ce(s,e,r),{month:m,day:d,minute:f,second:w,millisecond:h,timeZoneId:g,weekdayExpected:u,weekdayRaw:k}=s,re=p!==void 0||m!==void 0||d!==void 0,b=p!==void 0&&m!==void 0&&d!==void 0;if(re&&!b)throw new Error(`temporal-fmt: format string "${e}" has an incomplete date \u2014 year, month, and day tokens must all be present together.`);let K=c!==void 0||f!==void 0||w!==void 0||h!==void 0;if(g!==void 0&&!(b&&K))throw new Error(`temporal-fmt: format string "${e}" has a "zzz" token but needs a full date and time to build a ZonedDateTime.`);if(u!==void 0&&!b)throw new Error(`temporal-fmt: format string "${e}" has a weekday token ("EEEE"/"EEE") but needs a full date to validate it against.`);if(!b&&!K)throw new Error(`temporal-fmt: format string "${e}" has no date or time tokens to parse.`);let I=A(),Y={hour:c??0,minute:f??0,second:w??0,millisecond:h??0},V=o?{calendar:o}:{},L={overflow:"reject"},x;try{g!==void 0?x=I.ZonedDateTime.from({year:p,month:m,day:d,...Y,...V,timeZone:g},L):b&&K?x=I.PlainDateTime.from({year:p,month:m,day:d,...Y,...V},L):b?x=I.PlainDate.from({year:p,month:m,day:d,...V},L):x=I.PlainTime.from(Y,L)}catch(y){throw new Error(`temporal-fmt: "${n}" doesn't describe a valid date/time for format "${e}": ${y.message}`)}if(u!==void 0){let y=x.dayOfWeek;if(y!==u){let E=M(r);throw new Error(`temporal-fmt: "${k}" doesn't match the actual weekday (${E.weekdayLong[y-1]}) for the parsed date.`)}}return x}export{pe as format,Ie as parse,ae as setTemporal};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/temporalProvider.ts","../src/tokens.ts","../src/tokenize.ts","../src/format.ts","../src/localeVocab.ts","../src/pattern.ts","../src/parsePattern.ts","../src/parse.ts"],"sourcesContent":["// This package's tsconfig assumes lib: [\"ESNext\"] only — no ambient\n// `Temporal` namespace type. Everywhere else in this codebase only ever\n// *reads* fields off a Temporal-like object the caller already built\n// (TemporalLike in tokens.ts). This module is the single choke point for\n// touching a *namespace*-shaped Temporal (PlainDate.from, etc.): parse()\n// uses it to construct a result, tokens.ts uses it to probe native\n// Intl<->Temporal support. Consumers can hand us an implementation via\n// setTemporal(), or we fall back to globalThis.Temporal\ninterface TemporalFactory {\n from(fields: Record<string, number | string | undefined>, options?: { overflow?: 'constrain' | 'reject' }): unknown;\n}\n\nexport interface TemporalNamespace {\n PlainDate: TemporalFactory;\n PlainTime: TemporalFactory;\n PlainDateTime: TemporalFactory;\n ZonedDateTime: TemporalFactory;\n}\n\nlet injectedTemporal: TemporalNamespace | undefined;\n\n/**\n * Explicitly hand temporal-fmt the Temporal implementation to use, instead\n * of relying on a global `Temporal`. Call this once, before your first\n * `format()`/`parse()`\n *\n * Call with no argument (or `undefined`) to clear the override and fall\n * back to `globalThis.Temporal` again.\n *\n * @example\n * import { Temporal } from 'temporal-polyfill';\n * import { setTemporal } from 'temporal-fmt';\n * setTemporal(Temporal);\n */\nexport function setTemporal(temporal?: TemporalNamespace): void {\n injectedTemporal = temporal;\n}\n\nfunction resolveTemporal(): TemporalNamespace | undefined {\n return injectedTemporal ?? (globalThis as unknown as { Temporal?: TemporalNamespace }).Temporal;\n}\n\nexport function getTemporal(): TemporalNamespace {\n const temporal = resolveTemporal();\n if (!temporal) {\n throw new Error(\n 'temporal-fmt: parse() needs a Temporal implementation to construct its result. ' +\n 'Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal ' +\n '(native on Node 26+, or a polyfill like temporal-polyfill).'\n );\n }\n return temporal;\n}\n","import { getTemporal } from './temporalProvider.js';\n\nexport function pad(n: number, len: number): string {\n // padStart pads the whole string, sign included, so pad(-45, 4) used to\n // come out \"0-45\" instead of \"-045\" — split the sign off first.\n const negative = n < 0;\n const digits = String(Math.abs(n)).padStart(len, '0');\n return negative ? '-' + digits : digits;\n}\n\n// Not every field exists on every Temporal type (PlainDate has no .hour,\n// etc). Callers check for undefined before formatting a token.\nexport interface TemporalLike {\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n timeZoneId?: string;\n dayOfWeek?: number; // 1=Mon, 7=Sun, per Temporal spec\n calendarId?: string;\n toInstant?: () => unknown;\n toLocaleString?: (locale: string, options: Intl.DateTimeFormatOptions) => string;\n}\n\nexport interface FormatOptions {\n /** BCP 47 locale tag, e.g. 'en-US', 'fr-FR', 'ar-EG'. Defaults to 'en-US'. */\n locale?: string;\n}\n\nexport const DEFAULT_LOCALE = 'en-US';\n\n// Intl.DateTimeFormat is expensive to construct and format() can run in a\n// loop (rendering a table of dates), so cache by (locale, options).\nconst formatterCache = new Map<string, Intl.DateTimeFormat>();\nconst MAX_CACHE_SIZE = 500;\n\nfunction getFormatter(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = JSON.stringify([locale, options]);\n let formatter = formatterCache.get(key);\n if (formatter) {\n return formatter;\n }\n if (formatterCache.size >= MAX_CACHE_SIZE) {\n // not real LRU, just evicts oldest insertion — fine for this key space\n const oldestKey = formatterCache.keys().next().value;\n if (oldestKey !== undefined) formatterCache.delete(oldestKey);\n }\n formatter = new Intl.DateTimeFormat(locale, options);\n formatterCache.set(key, formatter);\n return formatter;\n}\n\n// Passing a Temporal object straight into `new Intl.DateTimeFormat().formatToParts()`\n// only works when the engine's Intl implementation has special-cased support for\n// *native* Temporal instances (checked via internal slots and/or gated behind a V8 flag,\n// not tied to a specific Node version).\n//\n// A Temporal polyfill's instances don't have those slots, so the engine falls back to ToNumber() -> .valueOf(),\n// which the polyfill deliberately throws on (\"Cannot use valueOf\").\n// Probed once and memoized and only from intlPart(), so it never\n// runs unless a format string actually uses a locale-aware token.\nlet nativeSupport: boolean | undefined;\nfunction intlSupportsNativeTemporal(): boolean {\n if (nativeSupport === undefined) {\n nativeSupport = false;\n try {\n const temporal = getTemporal();\n new Intl.DateTimeFormat('en-US', { day: 'numeric' })\n .formatToParts(temporal.PlainDate.from({ year: 1970, month: 1, day: 1 }) as Date);\n nativeSupport = true;\n } catch {\n // native Temporal absent, or present but not recognized by Intl — fall back\n }\n }\n return nativeSupport;\n}\n\nfunction intlPart(\n temporal: TemporalLike,\n locale: string,\n options: Intl.DateTimeFormatOptions,\n partType: Intl.DateTimeFormatPartTypes\n): string {\n // Intl throws \"Mismatching Calendars\" if the formatter's calendar doesn't\n // match the object's own (e.g. en-US formatter defaults to gregory, but\n // a hebrew/islamic PlainDate needs its own calendar passed through).\n //\n // skip this for iso8601 specifically — passing `calendar: 'iso8601'`\n // explicitly alongside a single-field options object makes formatToParts()\n // come back empty for some reason.\n const calendar = temporal?.calendarId;\n const formatterOptions: Intl.DateTimeFormatOptions = {\n ...options,\n ...(calendar && calendar !== 'iso8601' ? { calendar } : {}),\n };\n\n // Temporal.prototype.toLocaleString() is part of the Temporal spec itself:\n // polyfills implement the ICU formatting internally without needing the\n // engine to recognize the object, so it works without native Intl support.\n if (!intlSupportsNativeTemporal()) {\n return temporal.toLocaleString!(locale, formatterOptions);\n }\n\n // formatToParts() throws on ZonedDateTime directly (per spec), so convert\n // to Instant and pass the zone via `timeZone` instead. Don't convert to\n // PlainDateTime — that drops the zone, which breaks 'MMMM' + 'zzz' combos.\n const { toInstant, timeZoneId } = temporal;\n const isZoned = typeof toInstant === 'function' && typeof timeZoneId === 'string';\n // has to be called as temporal.toInstant() because destructuring it off breaks\n // the receiver and throws\n const intlSafeTemporal = isZoned ? temporal.toInstant!() : temporal;\n const nativeOptions: Intl.DateTimeFormatOptions = {\n ...formatterOptions,\n ...(isZoned ? { timeZone: timeZoneId } : {}),\n };\n\n const formatter = getFormatter(locale, nativeOptions);\n const parts = formatter.formatToParts(intlSafeTemporal as Date | number);\n const index = parts.findIndex((p) => p.type === partType);\n if (index === -1) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" produced no \"${partType}\" part for this token. ` +\n `This usually means the Temporal object is missing the field the token needs.`\n );\n }\n // some locales (ja-JP) split a field across two parts — e.g. month \"8\"\n // plus a counter suffix \"月\" as a separate sibling literal part. Merge in\n // an adjacent literal only if it has no whitespace, so a genuine suffix\n // gets folded in but an ordinary separator (the space before \"AM\") stays\n // a separator. Mirrors partValue() in localeVocab.ts, which builds the\n // vocab this token's output needs to match for parse() to round-trip.\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Temporal.prototype.toLocaleString() can't isolate a single field the way\n// formatToParts() can — asking for `hour` + `dayPeriod` together returns one\n// joined string (e.g. \"3 in the afternoon\"), and `dayPeriod` alone resolves\n// against a different, non-hour-anchored set of periods (\"in the\n// afternoon\"/\"昼\" instead of \"PM\"/\"午後\"). Day period only depends on the\n// hour anyway, so route it through a plain UTC Date and Intl.DateTimeFormat\n// instead — that's worked the same on every engine regardless of whether\n// Temporal itself is native or polyfilled.\nfunction dayPeriodPart(hour: number, locale: string): string {\n const date = new Date(Date.UTC(1970, 0, 1, hour));\n const formatter = getFormatter(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const part = formatter.formatToParts(date).find((p) => p.type === 'dayPeriod');\n if (!part) {\n throw new Error(`temporal-fmt: locale \"${locale}\" produced no \"dayPeriod\" part for token \"a\".`);\n }\n return part.value;\n}\n\ntype TokenHandler = (t: TemporalLike, locale: string) => string;\n\n// Longest-first — tokenizer is greedy, \"yyyy\" has to be tried before \"yy\".\n//\n// Numeric tokens always render in ASCII digits, never locale-native\n// (Arabic-Indic, Devanagari, etc). Padding non-ASCII digits isn't as simple\n// as padding \"3\", and most consumers parsing these back out want plain\n// digits anyway.\nexport const TOKENS: Array<[string, TokenHandler, keyof TemporalLike]> = [\n ['yyyy', (t) => pad(t.year!, 4), 'year'],\n ['yy', (t) => {\n // -45 % 100 === -45, so truncating negative years to 2 digits doesn't\n // work and Math.abs() would make 45 CE and 45 BCE render the same.\n if (t.year! < 0) {\n throw new Error(\n `temporal-fmt: token \"yy\" doesn't support negative years (got ${t.year}), ` +\n `since truncating to 2 digits would make it indistinguishable from a ` +\n `positive year. Use \"yyyy\" instead.`\n );\n }\n return pad(t.year! % 100, 2);\n }, 'year'],\n ['MMMM', (t, locale) => intlPart(t, locale, { month: 'long' }, 'month'), 'month'],\n ['MMM', (t, locale) => intlPart(t, locale, { month: 'short' }, 'month'), 'month'],\n ['MM', (t) => pad(t.month!, 2), 'month'],\n ['M', (t) => String(t.month!), 'month'],\n ['dd', (t) => pad(t.day!, 2), 'day'],\n ['d', (t) => String(t.day!), 'day'],\n ['EEEE', (t, locale) => intlPart(t, locale, { weekday: 'long' }, 'weekday'), 'dayOfWeek'],\n ['EEE', (t, locale) => intlPart(t, locale, { weekday: 'short' }, 'weekday'), 'dayOfWeek'],\n ['HH', (t) => pad(t.hour!, 2), 'hour'],\n ['H', (t) => String(t.hour!), 'hour'],\n ['hh', (t) => pad(t.hour! % 12 || 12, 2), 'hour'],\n ['h', (t) => String(t.hour! % 12 || 12), 'hour'],\n ['mm', (t) => pad(t.minute!, 2), 'minute'],\n ['m', (t) => String(t.minute!), 'minute'],\n ['ss', (t) => pad(t.second!, 2), 'second'],\n ['s', (t) => String(t.second!), 'second'],\n ['SSS', (t) => pad(t.millisecond!, 3), 'millisecond'],\n // dayPeriod text is locale-specific (AM/PM in en-US, م/ص in ar-EG) but\n // still needs .hour on the input to compute which period it is\n ['a', (t, locale) => dayPeriodPart(t.hour!, locale), 'hour'],\n ['zzz', (t) => t.timeZoneId!, 'timeZoneId'],\n];","import { TOKENS } from './tokens.js';\n\nexport type Piece =\n | { kind: 'token'; value: string }\n | { kind: 'literal'; value: string };\n\n// longest-first so the greedy scan never matches \"M\" when \"MMMM\" was there\nconst SORTED_TOKEN_STRINGS = TOKENS.map(([tok]) => tok).sort((a, b) => b.length - a.length);\n\n/**\n * Splits a format string like `\"yyyy-MM-dd 'at' HH:mm\"` into token/literal\n * pieces. Text in single quotes is always literal (e.g. write 'rd' in\n * \"3rd\" so it's not read as the day token). A doubled quote ('') means a\n * literal quote character, both inside a quoted span and standalone.\n */\nexport function tokenize(format: string): Piece[] {\n const pieces: Piece[] = [];\n let i = 0;\n\n while (i < format.length) {\n const ch = format[i];\n\n if (ch === \"'\") {\n // check doubled-quote first or \"''best''\" parses wrong\n if (format[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < format.length) {\n if (format[j] === \"'\") {\n if (format[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += format[j];\n j += 1;\n }\n\n if (!closed) {\n throw new Error(`temporal-fmt: unterminated quote in format string \"${format}\"`);\n }\n\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n\n const match = SORTED_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n\n // not a token or quote — pass through as-is\n appendLiteral(pieces, ch);\n i += 1;\n }\n\n return pieces;\n}\n\n// merges into the previous piece if it's also a literal, so \"---\" is one\n// piece instead of three\nfunction appendLiteral(pieces: Piece[], value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n}\n","import { TOKENS, DEFAULT_LOCALE, type TemporalLike, type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\n\nconst HANDLER_BY_TOKEN = new Map(TOKENS.map(([tok, fn, field]) => [tok, { fn, field }]));\n\n/**\n * Format a Temporal.PlainDate, PlainTime, PlainDateTime, or ZonedDateTime\n * using a date-fns-style token string.\n *\n * @example\n * format(Temporal.Now.plainDateISO(), 'yyyy-MM-dd') // \"2026-08-04\"\n * format(zdt, \"MMM d, yyyy 'at' h:mm a\") // \"Aug 4, 2026 at 3:45 PM\"\n * format(zdt, 'MMMM d, yyyy', { locale: 'fr-FR' }) // \"août 4, 2026\"\n *\n * Throws on a token the input type doesn't support (e.g. 'HH' on a PlainDate).\n */\nexport function format(temporal: TemporalLike, formatStr: string, options: FormatOptions = {}): string {\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 const locale = options.locale ?? DEFAULT_LOCALE;\n const pieces = tokenize(formatStr);\n let result = '';\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n\n const handler = HANDLER_BY_TOKEN.get(piece.value);\n if (!handler) {\n // shouldn't happen — tokenize() only emits tokens from TOKENS\n throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n }\n\n if (temporal[handler.field] === undefined) {\n throw new Error(\n `temporal-fmt: token \"${piece.value}\" requires \"${handler.field}\", ` +\n `which this Temporal object doesn't have. ` +\n `(e.g. PlainDate has no time fields, PlainTime has no date fields)`\n );\n }\n\n result += handler.fn(temporal, locale);\n }\n\n return result;\n}\n","// Name lists for the locale-aware tokens (MMMM, MMM, EEEE, EEE, a). Each\n// list is small and fixed (12 months, 7 weekdays, 2 day periods), so we\n// generate the real Intl strings for a locale once and cache them.\n\nexport interface LocaleVocab {\n monthLong: string[]; // index 0 = January\n monthShort: string[];\n weekdayLong: string[]; // index 0 = Monday, per Temporal's dayOfWeek numbering\n weekdayShort: string[];\n dayPeriod: string[]; // typically [AM-ish, PM-ish], deduped\n}\n\nconst vocabCache = new Map<string, LocaleVocab>();\nconst MAX_VOCAB_CACHE_SIZE = 500;\n\n// Some locales (ja-JP) split a field across two parts — month \"8\" plus a\n// counter suffix \"月\" as a separate sibling \"literal\" — while format()'s\n// tokens go through toLocaleString(), which concatenates everything into\n// \"8月\". Reading only the type-tagged part used to drop that suffix, so\n// this locale's vocab never matched what format() actually produced.\n// Only merges *adjacent* literals, not the whole string, since the\n// dayPeriod/weekday formatters below carry an extra hour part that a\n// join-everything approach would wrongly absorb.\nfunction partValue(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {\n const parts = formatter.formatToParts(date);\n const index = parts.findIndex((p) => p.type === type);\n if (index === -1) {\n throw new Error(`temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`);\n }\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n // skip whitespace literals (the separator before \"AM\") — only a\n // no-space suffix like ja-JP's \"月\" should get folded in\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Two entries rendering identically means parse()'s reverse lookup\n// (indexOf) can never tell them apart. Weekday collisions already surface\n// via parse()'s dayOfWeek cross-check, but with a confusing same-string\n// error; months have no equivalent cross-check, so a collision there would\n// otherwise resolve silently to the wrong month. Catching both here, once\n// at build time, gives one clear error instead.\nfunction assertNoCollision(names: string[], label: string, locale: string): void {\n const seen = new Map<string, number>();\n for (let i = 0; i < names.length; i++) {\n const prior = seen.get(names[i]!);\n if (prior !== undefined) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" renders ${label} index ${prior} and ${i} identically ` +\n `(\"${names[i]}\"). parse() can't reliably tell these apart for this locale/token, so this ` +\n `combination isn't supported.`\n );\n }\n seen.set(names[i]!, i);\n }\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n const cached = vocabCache.get(locale);\n if (cached) {\n return cached;\n }\n\n const monthLongFmt = new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' });\n const monthLong: string[] = [];\n const monthShort: string[] = [];\n for (let m = 0; m < 12; m++) {\n const date = new Date(Date.UTC(2020, m, 1));\n monthLong.push(partValue(monthLongFmt, date, 'month'));\n monthShort.push(partValue(monthShortFmt, date, 'month'));\n }\n assertNoCollision(monthLong, 'MMMM month', locale);\n assertNoCollision(monthShort, 'MMM month', locale);\n\n const weekdayLongFmt = new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' });\n const weekdayLong: string[] = [];\n const weekdayShort: string[] = [];\n // 2024-01-01 is a Monday (UTC) — walk 7 days from there for weekday names\n for (let d = 0; d < 7; d++) {\n const date = new Date(Date.UTC(2024, 0, 1 + d));\n weekdayLong.push(partValue(weekdayLongFmt, date, 'weekday'));\n weekdayShort.push(partValue(weekdayShortFmt, date, 'weekday'));\n }\n // redundant with parse()'s dayOfWeek cross-check, but gives a clearer error\n assertNoCollision(weekdayLong, 'EEEE weekday', locale);\n assertNoCollision(weekdayShort, 'EEE weekday', locale);\n\n const dayPeriodFmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), 'dayPeriod');\n const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), 'dayPeriod');\n const dayPeriod = [...new Set([am, pm])];\n\n const vocab: LocaleVocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };\n if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {\n const oldestKey = vocabCache.keys().next().value;\n if (oldestKey !== undefined) vocabCache.delete(oldestKey);\n }\n vocabCache.set(locale, vocab);\n return vocab;\n}","import { getLocaleVocab } from './localeVocab.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction alternation(values: string[]): string {\n return `(?:${values.map(escapeRegExp).join('|')})`;\n}\n\nlet timeZoneFragment: string | undefined;\n\nfunction getTimeZoneFragment(): string {\n if (timeZoneFragment) {\n return timeZoneFragment;\n }\n\n const supportedZones = Intl.supportedValuesOf('timeZone');\n const escapedZones = supportedZones.map(escapeRegExp);\n const offsetPattern = '[+-]\\\\d{2}:\\\\d{2}(?::\\\\d{2}(?:\\\\.\\\\d{1,9})?)?';\n timeZoneFragment = `(?:UTC|${offsetPattern}|${alternation(escapedZones)})`;\n return timeZoneFragment;\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 yyyy: '\\\\d{4}',\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 SSS: '\\\\d{3}',\n};\n\nexport function tokenFragment(token: string, locale: string): string {\n const numeric = NUMERIC_FRAGMENTS[token];\n if (numeric) {\n return numeric;\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 'a': return alternation(vocab.dayPeriod);\n case 'zzz': return getTimeZoneFragment();\n default:\n throw new Error(`temporal-fmt: unknown token \"${token}\"`);\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 if (!ranges) {\n throw new Error(`temporal-fmt: internal error — \"${token}\" is not an unpadded numeric token`);\n }\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}\n","import type { Piece } from './tokenize.js';\nimport { tokenFragment, UNPADDED_NUMERIC_TOKENS } from './pattern.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\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\", \"Hm\") — these need a split-ambiguity\n // check at match time, since a single fixed regex can't distinguish\n // \"the only valid split\" from \"one of several valid splits taken\n // arbitrarily\". Empty for the overwhelmingly common case (no such runs).\n ambiguousRuns: Array<{ 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<{ groupNames: string[]; tokens: string[] }> = [];\n let source = '';\n let i = 0;\n\n // tracks the group names/tokens of the current run of adjacent unpadded\n // numeric token pieces (no literal piece has broken it yet)\n let currentRun: { groupNames: string[]; tokens: string[] } = { groupNames: [], tokens: [] };\n const flushRun = () => {\n if (currentRun.tokens.length >= 2) {\n ambiguousRuns.push(currentRun);\n }\n currentRun = { groupNames: [], tokens: [] };\n };\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n source += escapeRegExp(piece.value);\n flushRun(); // a literal (even a single character) breaks adjacency\n continue;\n }\n const name = `g${i++}`;\n groups.push({ name, token: piece.value });\n source += `(?<${name}>${tokenFragment(piece.value, locale)})`;\n\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n currentRun.groupNames.push(name);\n currentRun.tokens.push(piece.value);\n } else {\n flushRun(); // a non-unpadded-numeric token (padded, locale-aware, zzz) also breaks adjacency\n }\n }\n flushRun();\n\n return { regex: new RegExp(`^(?:${source})$`, 'u'), 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 } from './pattern.js';\nimport { getLocaleVocab } from './localeVocab.js';\nimport { getTemporal } from './temporalProvider.js';\nimport { MAX_FORMAT_LENGTH, MAX_INPUT_LENGTH } from './constants.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([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 if (calendarCache.has(locale)) {\n return calendarCache.get(locale);\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 canonicalLocale = new Intl.Locale(locale).toString().toLowerCase();\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(locale, 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 timeZoneId?: string;\n weekdayExpected?: number;\n weekdayRaw?: string;\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 'SSS':\n assignField(fields, 'millisecond', Number(raw));\n break;\n case 'a': {\n const periodIndex = vocab.dayPeriod.indexOf(raw);\n if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period \"${raw}\" for locale \"${locale}\".`);\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 }\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 !== expected) {\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: FormatOptions = {}): 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 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 // 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 and throw if\n // more than one split is actually valid for the substring this call\n // matched — the input itself is what's ambiguous, not a fixable\n // property of the pattern.\n for (const run of pattern.ambiguousRuns) {\n const runDigits = run.groupNames.map((name) => match.groups![name]!).join('');\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length > 1) {\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 );\n }\n }\n\n const fields: Fields = {};\n for (const { name, token } of pattern.groups) {\n applyGroup(fields, token, match.groups![name]!, locale, formatStr);\n }\n\n const year = resolveYear(fields);\n const hour = resolveHour(fields, formatStr, locale);\n const { month, day, minute, second, millisecond, timeZoneId, weekdayExpected, weekdayRaw } = 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 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 = { hour: hour ?? 0, minute: minute ?? 0, second: second ?? 0, millisecond: millisecond ?? 0 };\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 result = temporal.ZonedDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField, timeZone: timeZoneId }, 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 return result;\n}\n"],"mappings":"AAmBA,IAAIA,EAeG,SAASC,GAAYC,EAAoC,CAC9DF,EAAmBE,CACrB,CAEA,SAASC,IAAiD,CACxD,OAAOH,GAAqB,WAA2D,QACzF,CAEO,SAASI,GAAiC,CAC/C,IAAMF,EAAWC,GAAgB,EACjC,GAAI,CAACD,EACH,MAAM,IAAI,MACR,6NAGF,EAEF,OAAOA,CACT,CClDO,SAASG,EAAIC,EAAWC,EAAqB,CAGlD,IAAMC,EAAWF,EAAI,EACfG,EAAS,OAAO,KAAK,IAAIH,CAAC,CAAC,EAAE,SAASC,EAAK,GAAG,EACpD,OAAOC,EAAW,IAAMC,EAASA,CACnC,CAwBO,IAAMC,EAAiB,QAIxBC,EAAiB,IAAI,IACrBC,GAAiB,IAEvB,SAASC,EAAaC,EAA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","DEFAULT_LOCALE","formatterCache","MAX_CACHE_SIZE","getFormatter","locale","options","key","formatter","oldestKey","nativeSupport","intlSupportsNativeTemporal","temporal","getTemporal","intlPart","partType","calendar","formatterOptions","toInstant","timeZoneId","isZoned","intlSafeTemporal","nativeOptions","parts","index","p","value","prev","next","dayPeriodPart","hour","date","part","TOKENS","t","SORTED_TOKEN_STRINGS","TOKENS","tok","a","b","tokenize","format","pieces","i","ch","appendLiteral","j","literal","closed","match","value","last","HANDLER_BY_TOKEN","TOKENS","tok","fn","field","format","temporal","formatStr","options","locale","DEFAULT_LOCALE","pieces","tokenize","result","piece","handler","vocabCache","MAX_VOCAB_CACHE_SIZE","partValue","formatter","date","type","parts","index","p","value","prev","next","assertNoCollision","names","label","locale","seen","i","prior","getLocaleVocab","cached","monthLongFmt","monthShortFmt","monthLong","monthShort","m","weekdayLongFmt","weekdayShortFmt","weekdayLong","weekdayShort","dayPeriodFmt","am","pm","dayPeriod","vocab","oldestKey","escapeRegExp","literal","alternation","values","timeZoneFragment","getTimeZoneFragment","escapedZones","NUMERIC_FRAGMENTS","tokenFragment","token","locale","numeric","vocab","getLocaleVocab","UNPADDED_NUMERIC_TOKENS","UNPADDED_NUMERIC_RANGES","enumerateValidSplits","digits","tokens","memo","solve","tokenIndex","offset","key","cached","result","ranges","results","width","min","max","piece","value","restSplit","escapeRegExp","literal","buildCapturingPattern","pieces","locale","groups","ambiguousRuns","source","i","currentRun","flushRun","piece","name","tokenFragment","UNPADDED_NUMERIC_TOKENS","patternCache","MAX_CACHE_SIZE","getPattern","formatStr","locale","key","pattern","oldestKey","buildCapturingPattern","tokenize","calendarCache","MAX_CALENDAR_CACHE_SIZE","resolveCalendar","calendar","canonicalLocale","parts","extensionIndex","calendarKeyIndex","resolved","assignField","fields","value","applyGroup","token","raw","vocab","getLocaleVocab","periodIndex","resolveYear","resolveHour","expected","parse","input","options","DEFAULT_LOCALE","match","run","runDigits","name","splits","enumerateValidSplits","year","hour","month","day","minute","second","millisecond","timeZoneId","weekdayExpected","weekdayRaw","hasAnyDatePart","hasFullDate","hasTime","temporal","getTemporal","timeFields","calendarField","reject","result","err","actual"]}
1
+ {"version":3,"sources":["../src/temporalProvider.ts","../src/localeVocab.ts","../src/tokens.ts","../src/tokenize.ts","../src/format.ts","../src/pattern.ts","../src/parsePattern.ts","../src/parse.ts"],"sourcesContent":["// This package's tsconfig assumes lib: [\"ESNext\"] only — no ambient\n// `Temporal` namespace type. Everywhere else in this codebase only ever\n// *reads* fields off a Temporal-like object the caller already built\n// (TemporalLike in tokens.ts). This module is the single choke point for\n// touching a *namespace*-shaped Temporal (PlainDate.from, etc.): parse()\n// uses it to construct a result, tokens.ts uses it to probe native\n// Intl<->Temporal support. Consumers can hand us an implementation via\n// setTemporal(), or we fall back to globalThis.Temporal\ninterface TemporalFactory {\n from(fields: Record<string, number | string | undefined>, options?: { overflow?: 'constrain' | 'reject' }): unknown;\n}\n\nexport interface TemporalNamespace {\n PlainDate: TemporalFactory;\n PlainTime: TemporalFactory;\n PlainDateTime: TemporalFactory;\n ZonedDateTime: TemporalFactory;\n}\n\nlet injectedTemporal: TemporalNamespace | undefined;\n\n// Anything that caches a result derived from *which* Temporal\n// implementation is active (right now: tokens.ts's native-Intl-support\n// probe) registers here so it gets invalidated whenever setTemporal()\n// swaps the implementation — see the comment on setTemporal() below for\n// why that matters. A plain array instead of an event-emitter-style API\n// since this only ever needs \"call every listener, in registration order,\n// with no payload\" — nothing here needs unsubscribe or payload data.\nconst onTemporalChanged: Array<() => void> = [];\n\nexport function subscribeToTemporalChanges(listener: () => void): void {\n onTemporalChanged.push(listener);\n}\n\n/**\n * Explicitly hand temporal-fmt the Temporal implementation to use, instead\n * of relying on a global `Temporal`. Call this once, before your first\n * `format()`/`parse()`\n *\n * Call with no argument (or `undefined`) to clear the override and fall\n * back to `globalThis.Temporal` again.\n *\n * @example\n * import { Temporal } from 'temporal-polyfill';\n * import { setTemporal } from 'temporal-fmt';\n * setTemporal(Temporal);\n */\nexport function setTemporal(temporal?: TemporalNamespace): void {\n injectedTemporal = temporal;\n // tokens.ts's native-Intl-support probe is keyed on whichever Temporal\n // implementation was active the first time a locale-aware format() ran —\n // if that implementation changes later (native -> polyfill or back), the\n // memoized probe result can go stale and disagree with what's now\n // actually active. Resetting it here means the next locale-aware format()\n // after any setTemporal() call re-probes against the implementation\n // that's active *now*, at the (small, one-time-per-switch) cost of\n // re-running the probe.\n for (const listener of onTemporalChanged) listener();\n}\n\nfunction resolveTemporal(): TemporalNamespace | undefined {\n return injectedTemporal ?? (globalThis as unknown as { Temporal?: TemporalNamespace }).Temporal;\n}\n\nexport function getTemporal(): TemporalNamespace {\n const temporal = resolveTemporal();\n if (!temporal) {\n throw new Error(\n 'temporal-fmt: parse() needs a Temporal implementation to construct its result. ' +\n 'Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal ' +\n '(native on Node 26+, or a polyfill like temporal-polyfill).'\n );\n }\n return temporal;\n}","// Name lists for the locale-aware tokens (MMMM, MMM, EEEE, EEE, a). Each\n// list is small and fixed (12 months, 7 weekdays, 2 day periods), so we\n// generate the real Intl strings for a locale once and cache them.\n\nexport interface LocaleVocab {\n monthLong: string[]; // index 0 = January\n monthShort: string[];\n weekdayLong: string[]; // index 0 = Monday, per Temporal's dayOfWeek numbering\n weekdayShort: string[];\n dayPeriod: string[]; // typically [AM-ish, PM-ish], deduped\n}\n\n// Every locale-keyed cache in this library (this one, formatterCache in\n// tokens.ts, patternCache/calendarCache in parse.ts) used to key on the\n// exact locale string a caller passed in. Intl treats spelling variants of\n// the same locale as equivalent ('en-US' / 'en-us' / 'en_US' all resolve\n// the same way), but a plain string-keyed Map doesn't — so callers mixing\n// spellings for what's really one locale would silently fragment across\n// separate cache entries instead of sharing one, making the bounded\n// eviction limits (MAX_*_CACHE_SIZE) less effective than they look. This\n// doesn't change any cache's *correctness* (each entry is still built from\n// -- and valid for -- whatever locale string produced it), only how many\n// distinct entries equivalent spellings end up costing. Falls back to the\n// original string on a malformed/unrecognized tag rather than throwing —\n// cache-key normalization shouldn't be where a bad locale first surfaces\n// as an error; whatever actually calls `new Intl.DateTimeFormat(locale)`\n// downstream is the right place for that.\nexport function canonicalCacheKey(locale: string): string {\n try {\n // Intl.Locale requires BCP-47 hyphens and rejects underscore-separated\n // tags like 'en_US' outright (RangeError), rather than normalizing\n // them — so without this replace, that spelling would just fall\n // through to the catch below and never fold with 'en-US'.\n return new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n return locale;\n }\n}\n\nconst vocabCache = new Map<string, LocaleVocab>();\nconst MAX_VOCAB_CACHE_SIZE = 500;\n\n// Some locales (ja-JP) split a field across two parts — month \"8\" plus a\n// counter suffix \"月\" as a separate sibling \"literal\" — while format()'s\n// tokens go through toLocaleString(), which concatenates everything into\n// \"8月\". Reading only the type-tagged part used to drop that suffix, so\n// this locale's vocab never matched what format() actually produced.\n// Only merges *adjacent* literals, not the whole string, since the\n// dayPeriod/weekday formatters below carry an extra hour part that a\n// join-everything approach would wrongly absorb.\nfunction partValue(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {\n const parts = formatter.formatToParts(date);\n const index = parts.findIndex((p) => p.type === type);\n if (index === -1) {\n throw new Error(`temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`);\n }\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n // skip whitespace literals (the separator before \"AM\") — only a\n // no-space suffix like ja-JP's \"月\" should get folded in\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Two entries rendering identically means parse()'s reverse lookup\n// (indexOf) can never tell them apart. Weekday collisions already surface\n// via parse()'s dayOfWeek cross-check, but with a confusing same-string\n// error; months have no equivalent cross-check, so a collision there would\n// otherwise resolve silently to the wrong month. Catching both here, once\n// at build time, gives one clear error instead.\nfunction assertNoCollision(names: string[], label: string, locale: string): void {\n const seen = new Map<string, number>();\n for (let i = 0; i < names.length; i++) {\n const prior = seen.get(names[i]!);\n if (prior !== undefined) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" renders ${label} index ${prior} and ${i} identically ` +\n `(\"${names[i]}\"). parse() can't reliably tell these apart for this locale/token, so this ` +\n `combination isn't supported.`\n );\n }\n seen.set(names[i]!, i);\n }\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n const cacheKey = canonicalCacheKey(locale);\n const cached = vocabCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const monthLongFmt = new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' });\n const monthLong: string[] = [];\n const monthShort: string[] = [];\n for (let m = 0; m < 12; m++) {\n const date = new Date(Date.UTC(2020, m, 1));\n monthLong.push(partValue(monthLongFmt, date, 'month'));\n monthShort.push(partValue(monthShortFmt, date, 'month'));\n }\n assertNoCollision(monthLong, 'MMMM month', locale);\n assertNoCollision(monthShort, 'MMM month', locale);\n\n const weekdayLongFmt = new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' });\n const weekdayLong: string[] = [];\n const weekdayShort: string[] = [];\n // 2024-01-01 is a Monday (UTC) — walk 7 days from there for weekday names\n for (let d = 0; d < 7; d++) {\n const date = new Date(Date.UTC(2024, 0, 1 + d));\n weekdayLong.push(partValue(weekdayLongFmt, date, 'weekday'));\n weekdayShort.push(partValue(weekdayShortFmt, date, 'weekday'));\n }\n // redundant with parse()'s dayOfWeek cross-check, but gives a clearer error\n assertNoCollision(weekdayLong, 'EEEE weekday', locale);\n assertNoCollision(weekdayShort, 'EEE weekday', locale);\n\n const dayPeriodFmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), 'dayPeriod');\n const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), 'dayPeriod');\n const dayPeriod = [...new Set([am, pm])];\n\n const vocab: LocaleVocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };\n if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {\n const oldestKey = vocabCache.keys().next().value;\n if (oldestKey !== undefined) vocabCache.delete(oldestKey);\n }\n vocabCache.set(cacheKey, vocab);\n return vocab;\n}","import { getTemporal, subscribeToTemporalChanges } from './temporalProvider.js';\nimport { canonicalCacheKey } from './localeVocab.js';\n\nexport function pad(n: number, len: number): string {\n // padStart pads the whole string, sign included, so pad(-45, 4) used to\n // come out \"0-45\" instead of \"-045\" — split the sign off first.\n const negative = n < 0;\n const digits = String(Math.abs(n)).padStart(len, '0');\n return negative ? '-' + digits : digits;\n}\n\n// Not every field exists on every Temporal type (PlainDate has no .hour,\n// etc). Callers check for undefined before formatting a token.\nexport interface TemporalLike {\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n timeZoneId?: string;\n dayOfWeek?: number; // 1=Mon, 7=Sun, per Temporal spec\n calendarId?: string;\n toInstant?: () => unknown;\n toLocaleString?: (locale: string, options: Intl.DateTimeFormatOptions) => string;\n}\n\nexport interface FormatOptions {\n /** BCP 47 locale tag, e.g. 'en-US', 'fr-FR', 'ar-EG'. Defaults to 'en-US'. */\n locale?: string;\n}\n\nexport const DEFAULT_LOCALE = 'en-US';\n\n// Intl.DateTimeFormat is expensive to construct and format() can run in a\n// loop (rendering a table of dates), so cache by (locale, options).\nconst formatterCache = new Map<string, Intl.DateTimeFormat>();\nconst MAX_CACHE_SIZE = 500;\n\nfunction getFormatter(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = JSON.stringify([canonicalCacheKey(locale), options]);\n let formatter = formatterCache.get(key);\n if (formatter) {\n return formatter;\n }\n if (formatterCache.size >= MAX_CACHE_SIZE) {\n // not real LRU, just evicts oldest insertion — fine for this key space\n const oldestKey = formatterCache.keys().next().value;\n if (oldestKey !== undefined) formatterCache.delete(oldestKey);\n }\n formatter = new Intl.DateTimeFormat(locale, options);\n formatterCache.set(key, formatter);\n return formatter;\n}\n\n// Passing a Temporal object straight into `new Intl.DateTimeFormat().formatToParts()`\n// only works when the engine's Intl implementation has special-cased support for\n// *native* Temporal instances (checked via internal slots and/or gated behind a V8 flag,\n// not tied to a specific Node version).\n//\n// A Temporal polyfill's instances don't have those slots, so the engine falls back to ToNumber() -> .valueOf(),\n// which the polyfill deliberately throws on (\"Cannot use valueOf\").\n// Probed once and memoized and only from intlPart(), so it never\n// runs unless a format string actually uses a locale-aware token.\nlet nativeSupport: boolean | undefined;\n// Invalidate the memoized probe whenever setTemporal() swaps the active\n// implementation — otherwise a probe result from \"is native Temporal\n// supported\" could keep being used after the active implementation is\n// no longer the one that was probed. See setTemporal() in\n// temporalProvider.ts for the other half of this.\nsubscribeToTemporalChanges(() => { nativeSupport = undefined; });\n\nfunction intlSupportsNativeTemporal(): boolean {\n if (nativeSupport === undefined) {\n nativeSupport = false;\n try {\n const temporal = getTemporal();\n new Intl.DateTimeFormat('en-US', { day: 'numeric' })\n .formatToParts(temporal.PlainDate.from({ year: 1970, month: 1, day: 1 }) as Date);\n nativeSupport = true;\n } catch {\n // native Temporal absent, or present but not recognized by Intl — fall back\n }\n }\n return nativeSupport;\n}\n\nfunction intlPart(\n temporal: TemporalLike,\n locale: string,\n options: Intl.DateTimeFormatOptions,\n partType: Intl.DateTimeFormatPartTypes\n): string {\n // Intl throws \"Mismatching Calendars\" if the formatter's calendar doesn't\n // match the object's own (e.g. en-US formatter defaults to gregory, but\n // a hebrew/islamic PlainDate needs its own calendar passed through).\n //\n // For iso8601 specifically, force 'gregory' rather than leaving calendar\n // unset: numeric fields (yyyy/dd, see tokens' pad()-based handlers) are\n // always pulled straight off the object's own ISO fields — so if the\n // *locale* carries a `-u-ca-*` extension (e.g. 'en-u-ca-hebrew') and this\n // step left calendar unset, the formatter would resolve its own default\n // calendar from the locale and format MMMM/EEEE in that calendar while\n // yyyy/dd stay ISO, producing a date that looks internally consistent\n // (a real Hebrew month name next to a real-looking day/year) but names a\n // completely different day than the object actually represents. Forcing\n // 'gregory' here keeps every field of an ISO object's output anchored to\n // the same (ISO/Gregorian) calendar — a locale's calendar extension only\n // takes effect when the object itself already carries a non-ISO calendar\n // (via `.withCalendar()`), matching what the README documents.\n //\n // 'gregory' specifically, not 'iso8601' — passing `calendar: 'iso8601'`\n // explicitly alongside a single-field options object makes\n // formatToParts() come back empty for some reason, but 'gregory' doesn't\n // have that problem and Temporal's iso8601 calendar is Gregorian-shaped\n // (proleptic Gregorian throughout, no Julian cutover) so the two agree\n // on every numeric field this library ever reads.\n const calendar = temporal?.calendarId;\n const formatterOptions: Intl.DateTimeFormatOptions = {\n ...options,\n calendar: calendar && calendar !== 'iso8601' ? calendar : 'gregory',\n };\n\n // Temporal.prototype.toLocaleString() is part of the Temporal spec itself:\n // polyfills implement the ICU formatting internally without needing the\n // engine to recognize the object, so it works without native Intl support.\n if (!intlSupportsNativeTemporal()) {\n return temporal.toLocaleString!(locale, formatterOptions);\n }\n\n // formatToParts() throws on ZonedDateTime directly (per spec), so convert\n // to Instant and pass the zone via `timeZone` instead. Don't convert to\n // PlainDateTime — that drops the zone, which breaks 'MMMM' + 'zzz' combos.\n const { toInstant, timeZoneId } = temporal;\n const isZoned = typeof toInstant === 'function' && typeof timeZoneId === 'string';\n // has to be called as temporal.toInstant() because destructuring it off breaks\n // the receiver and throws\n const intlSafeTemporal = isZoned ? temporal.toInstant!() : temporal;\n const nativeOptions: Intl.DateTimeFormatOptions = {\n ...formatterOptions,\n ...(isZoned ? { timeZone: timeZoneId } : {}),\n };\n\n const formatter = getFormatter(locale, nativeOptions);\n const parts = formatter.formatToParts(intlSafeTemporal as Date | number);\n const index = parts.findIndex((p) => p.type === partType);\n if (index === -1) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" produced no \"${partType}\" part for this token. ` +\n `This usually means the Temporal object is missing the field the token needs.`\n );\n }\n // some locales (ja-JP) split a field across two parts — e.g. month \"8\"\n // plus a counter suffix \"月\" as a separate sibling literal part. Merge in\n // an adjacent literal only if it has no whitespace, so a genuine suffix\n // gets folded in but an ordinary separator (the space before \"AM\") stays\n // a separator. Mirrors partValue() in localeVocab.ts, which builds the\n // vocab this token's output needs to match for parse() to round-trip.\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Temporal.prototype.toLocaleString() can't isolate a single field the way\n// formatToParts() can — asking for `hour` + `dayPeriod` together returns one\n// joined string (e.g. \"3 in the afternoon\"), and `dayPeriod` alone resolves\n// against a different, non-hour-anchored set of periods (\"in the\n// afternoon\"/\"昼\" instead of \"PM\"/\"午後\"). Day period only depends on the\n// hour anyway, so route it through a plain UTC Date and Intl.DateTimeFormat\n// instead — that's worked the same on every engine regardless of whether\n// Temporal itself is native or polyfilled.\nfunction dayPeriodPart(hour: number, locale: string): string {\n const date = new Date(Date.UTC(1970, 0, 1, hour));\n const formatter = getFormatter(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const part = formatter.formatToParts(date).find((p) => p.type === 'dayPeriod');\n if (!part) {\n throw new Error(`temporal-fmt: locale \"${locale}\" produced no \"dayPeriod\" part for token \"a\".`);\n }\n return part.value;\n}\n\ntype TokenHandler = (t: TemporalLike, locale: string) => string;\n\n// Longest-first — tokenizer is greedy, \"yyyy\" has to be tried before \"yy\".\n//\n// Numeric tokens always render in ASCII digits, never locale-native\n// (Arabic-Indic, Devanagari, etc). Padding non-ASCII digits isn't as simple\n// as padding \"3\", and most consumers parsing these back out want plain\n// digits anyway.\nexport const TOKENS: Array<[string, TokenHandler, keyof TemporalLike]> = [\n ['yyyy', (t) => pad(t.year!, 4), 'year'],\n ['yy', (t) => {\n // -45 % 100 === -45, so truncating negative years to 2 digits doesn't\n // work and Math.abs() would make 45 CE and 45 BCE render the same.\n if (t.year! < 0) {\n throw new Error(\n `temporal-fmt: token \"yy\" doesn't support negative years (got ${t.year}), ` +\n `since truncating to 2 digits would make it indistinguishable from a ` +\n `positive year. Use \"yyyy\" instead.`\n );\n }\n return pad(t.year! % 100, 2);\n }, 'year'],\n ['MMMM', (t, locale) => intlPart(t, locale, { month: 'long' }, 'month'), 'month'],\n ['MMM', (t, locale) => intlPart(t, locale, { month: 'short' }, 'month'), 'month'],\n ['MM', (t) => pad(t.month!, 2), 'month'],\n ['M', (t) => String(t.month!), 'month'],\n ['dd', (t) => pad(t.day!, 2), 'day'],\n ['d', (t) => String(t.day!), 'day'],\n ['EEEE', (t, locale) => intlPart(t, locale, { weekday: 'long' }, 'weekday'), 'dayOfWeek'],\n ['EEE', (t, locale) => intlPart(t, locale, { weekday: 'short' }, 'weekday'), 'dayOfWeek'],\n ['HH', (t) => pad(t.hour!, 2), 'hour'],\n ['H', (t) => String(t.hour!), 'hour'],\n ['hh', (t) => pad(t.hour! % 12 || 12, 2), 'hour'],\n ['h', (t) => String(t.hour! % 12 || 12), 'hour'],\n ['mm', (t) => pad(t.minute!, 2), 'minute'],\n ['m', (t) => String(t.minute!), 'minute'],\n ['ss', (t) => pad(t.second!, 2), 'second'],\n ['s', (t) => String(t.second!), 'second'],\n ['SSS', (t) => pad(t.millisecond!, 3), 'millisecond'],\n // dayPeriod text is locale-specific (AM/PM in en-US, م/ص in ar-EG) but\n // still needs .hour on the input to compute which period it is\n ['a', (t, locale) => dayPeriodPart(t.hour!, locale), 'hour'],\n ['zzz', (t) => t.timeZoneId!, 'timeZoneId'],\n];","import { TOKENS } from './tokens.js';\n\nexport type Piece =\n | { kind: 'token'; value: string }\n | { kind: 'literal'; value: string };\n\n// longest-first so the greedy scan never matches \"M\" when \"MMMM\" was there\nconst SORTED_TOKEN_STRINGS = TOKENS.map(([tok]) => tok).sort((a, b) => b.length - a.length);\n\n/**\n * Splits a format string like `\"yyyy-MM-dd 'at' HH:mm\"` into token/literal\n * pieces. Text in single quotes is always literal (e.g. write 'rd' in\n * \"3rd\" so it's not read as the day token). A doubled quote ('') means a\n * literal quote character, both inside a quoted span and standalone.\n */\nexport function tokenize(format: string): Piece[] {\n const pieces: Piece[] = [];\n let i = 0;\n\n while (i < format.length) {\n const ch = format[i];\n\n if (ch === \"'\") {\n // check doubled-quote first or \"''best''\" parses wrong\n if (format[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < format.length) {\n if (format[j] === \"'\") {\n if (format[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += format[j];\n j += 1;\n }\n\n if (!closed) {\n throw new Error(`temporal-fmt: unterminated quote in format string \"${format}\"`);\n }\n\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n\n const match = SORTED_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n\n // not a token or quote — pass through as-is\n appendLiteral(pieces, ch);\n i += 1;\n }\n\n return pieces;\n}\n\n// merges into the previous piece if it's also a literal, so \"---\" is one\n// piece instead of three\nfunction appendLiteral(pieces: Piece[], value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n}\n","import { TOKENS, DEFAULT_LOCALE, type TemporalLike, type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\n\nconst HANDLER_BY_TOKEN = new Map(TOKENS.map(([tok, fn, field]) => [tok, { fn, field }]));\n\n/**\n * Format a Temporal.PlainDate, PlainTime, PlainDateTime, or ZonedDateTime\n * using a date-fns-style token string.\n *\n * @example\n * format(Temporal.Now.plainDateISO(), 'yyyy-MM-dd') // \"2026-08-04\"\n * format(zdt, \"MMM d, yyyy 'at' h:mm a\") // \"Aug 4, 2026 at 3:45 PM\"\n * format(zdt, 'MMMM d, yyyy', { locale: 'fr-FR' }) // \"août 4, 2026\"\n *\n * Throws on a token the input type doesn't support (e.g. 'HH' on a PlainDate).\n */\nexport function format(temporal: TemporalLike, formatStr: string, options: FormatOptions = {}): string {\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 const locale = options.locale ?? DEFAULT_LOCALE;\n const pieces = tokenize(formatStr);\n let result = '';\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n\n const handler = HANDLER_BY_TOKEN.get(piece.value);\n if (!handler) {\n // shouldn't happen — tokenize() only emits tokens from TOKENS\n throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n }\n\n if (temporal[handler.field] === undefined) {\n throw new Error(\n `temporal-fmt: token \"${piece.value}\" requires \"${handler.field}\", ` +\n `which this Temporal object doesn't have. ` +\n `(e.g. PlainDate has no time fields, PlainTime has no date fields)`\n );\n }\n\n result += handler.fn(temporal, locale);\n }\n\n return result;\n}\n","import { getLocaleVocab } from './localeVocab.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction alternation(values: string[]): string {\n return `(?:${values.map(escapeRegExp).join('|')})`;\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\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 SSS: '\\\\d{3}',\n};\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.\nconst DIGIT_LEADING_TOKENS = new Set([\n 'yyyy', 'yy', 'MM', 'M', 'dd', 'd', 'HH', 'H', 'hh', 'h', 'mm', 'm', 'ss', 's', 'SSS',\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 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 'a': return alternation(vocab.dayPeriod);\n case 'zzz': return getTimeZoneFragment();\n default:\n throw new Error(`temporal-fmt: unknown token \"${token}\"`);\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 if (!ranges) {\n throw new Error(`temporal-fmt: internal error — \"${token}\" is not an unpadded numeric token`);\n }\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 } from './pattern.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\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\", \"Hm\") — these need a split-ambiguity\n // check at match time, since a single fixed regex can't distinguish\n // \"the only valid split\" from \"one of several valid splits taken\n // arbitrarily\". Empty for the overwhelmingly common case (no such runs).\n ambiguousRuns: Array<{ 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<{ groupNames: string[]; tokens: string[] }> = [];\n let source = '';\n let i = 0;\n\n // tracks the group names/tokens of the current run of adjacent unpadded\n // numeric token pieces (no literal piece has broken it yet)\n let currentRun: { groupNames: string[]; tokens: string[] } = { groupNames: [], tokens: [] };\n const flushRun = () => {\n if (currentRun.tokens.length >= 2) {\n ambiguousRuns.push(currentRun);\n }\n currentRun = { groupNames: [], tokens: [] };\n };\n\n for (const [idx, piece] of pieces.entries()) {\n if (piece.kind === 'literal') {\n source += escapeRegExp(piece.value);\n flushRun(); // a literal (even a single character) breaks adjacency\n continue;\n }\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 source += `(?<${name}>${tokenFragment(piece.value, locale, nextToken)})`;\n\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n currentRun.groupNames.push(name);\n currentRun.tokens.push(piece.value);\n } else {\n flushRun(); // a non-unpadded-numeric token (padded, locale-aware, zzz) also breaks adjacency\n }\n }\n flushRun();\n\n return { regex: new RegExp(`^(?:${source})$`, 'u'), groups, ambiguousRuns };\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';\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 timeZoneId?: string;\n weekdayExpected?: number;\n weekdayRaw?: string;\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 'SSS':\n assignField(fields, 'millisecond', Number(raw));\n break;\n case 'a': {\n const periodIndex = vocab.dayPeriod.indexOf(raw);\n if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period \"${raw}\" for locale \"${locale}\".`);\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 }\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 !== expected) {\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: FormatOptions = {}): 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 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 // each captured zzz group against the actual zone list here. Kept as the\n // same \"no valid pattern matches\" error the inline-alternation version\n // used to throw, since from the caller's perspective this is still the\n // regex rejecting the input, just checked in two steps instead of one.\n for (const { name, token } of pattern.groups) {\n if (token === 'zzz' && !isValidTimeZone(match.groups![name]!)) {\n throw new Error(`temporal-fmt: no valid pattern matches the format string and input shape`);\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 and throw if\n // more than one split is actually valid for the substring this call\n // matched — the input itself is what's ambiguous, not a fixable\n // property of the pattern.\n for (const run of pattern.ambiguousRuns) {\n const runDigits = run.groupNames.map((name) => match.groups![name]!).join('');\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length > 1) {\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 );\n }\n }\n\n const fields: Fields = {};\n for (const { name, token } of pattern.groups) {\n applyGroup(fields, token, match.groups![name]!, locale, formatStr);\n }\n\n const year = resolveYear(fields);\n const hour = resolveHour(fields, formatStr, locale);\n const { month, day, minute, second, millisecond, timeZoneId, weekdayExpected, weekdayRaw } = 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 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 = { hour: hour ?? 0, minute: minute ?? 0, second: second ?? 0, millisecond: millisecond ?? 0 };\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 result = temporal.ZonedDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField, timeZone: timeZoneId }, 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 return result;\n}"],"mappings":"AAmBA,IAAIA,EASEC,EAAuC,CAAC,EAEvC,SAASC,EAA2BC,EAA4B,CACrEF,EAAkB,KAAKE,CAAQ,CACjC,CAeO,SAASC,GAAYC,EAAoC,CAC9DL,EAAmBK,EASnB,QAAWF,KAAYF,EAAmBE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R,kBAAkBgD,CAAU,uCAAuC1B,EAAM,YAAYqC,EAAS,CAAC,CAAC,wBAElG,CACF,CACF,CAEA,OAAOF,CACT","names":["injectedTemporal","onTemporalChanged","subscribeToTemporalChanges","listener","setTemporal","temporal","resolveTemporal","getTemporal","canonicalCacheKey","locale","vocabCache","MAX_VOCAB_CACHE_SIZE","partValue","formatter","date","type","parts","index","value","prev","next","assertNoCollision","names","label","seen","i","prior","getLocaleVocab","cacheKey","cached","monthLongFmt","monthShortFmt","monthLong","monthShort","m","weekdayLongFmt","weekdayShortFmt","weekdayLong","weekdayShort","d","dayPeriodFmt","am","pm","dayPeriod","vocab","oldestKey","pad","n","len","negative","digits","DEFAULT_LOCALE","formatterCache","MAX_CACHE_SIZE","getFormatter","locale","options","key","canonicalCacheKey","formatter","oldestKey","nativeSupport","subscribeToTemporalChanges","intlSupportsNativeTemporal","temporal","getTemporal","intlPart","partType","calendar","formatterOptions","toInstant","timeZoneId","isZoned","intlSafeTemporal","nativeOptions","parts","index","p","value","prev","next","dayPeriodPart","hour","date","part","TOKENS","t","SORTED_TOKEN_STRINGS","TOKENS","tok","a","b","tokenize","format","pieces","i","ch","appendLiteral","j","literal","closed","match","value","last","HANDLER_BY_TOKEN","TOKENS","tok","fn","field","format","temporal","formatStr","options","locale","DEFAULT_LOCALE","pieces","tokenize","result","piece","handler","escapeRegExp","literal","alternation","values","TIME_ZONE_SHAPE","getTimeZoneFragment","validZoneSet","getValidZoneSet","FIXED_OFFSET_RE","isValidTimeZone","raw","NUMERIC_FRAGMENTS","YYYY_EXACT","YYYY_EXTENDED","DIGIT_LEADING_TOKENS","tokenFragment","token","locale","nextToken","numeric","vocab","getLocaleVocab","UNPADDED_NUMERIC_TOKENS","UNPADDED_NUMERIC_RANGES","enumerateValidSplits","digits","tokens","memo","solve","tokenIndex","offset","key","cached","result","ranges","results","width","min","max","piece","value","restSplit","escapeRegExp","literal","buildCapturingPattern","pieces","locale","groups","ambiguousRuns","source","i","currentRun","flushRun","idx","piece","name","nextPiece","nextToken","tokenFragment","UNPADDED_NUMERIC_TOKENS","patternCache","MAX_CACHE_SIZE","getPattern","formatStr","locale","key","canonicalCacheKey","pattern","oldestKey","buildCapturingPattern","tokenize","calendarCache","MAX_CALENDAR_CACHE_SIZE","resolveCalendar","canonicalLocale","calendar","parts","extensionIndex","calendarKeyIndex","resolved","assignField","fields","value","applyGroup","token","raw","vocab","getLocaleVocab","periodIndex","resolveYear","resolveHour","expected","parse","input","options","DEFAULT_LOCALE","match","name","isValidTimeZone","run","runDigits","splits","enumerateValidSplits","year","hour","month","day","minute","second","millisecond","timeZoneId","weekdayExpected","weekdayRaw","hasAnyDatePart","hasFullDate","hasTime","temporal","getTemporal","timeFields","calendarField","reject","result","err","actual"]}
@@ -0,0 +1,9 @@
1
+ export interface LocaleVocab {
2
+ monthLong: string[];
3
+ monthShort: string[];
4
+ weekdayLong: string[];
5
+ weekdayShort: string[];
6
+ dayPeriod: string[];
7
+ }
8
+ export declare function canonicalCacheKey(locale: string): string;
9
+ export declare function getLocaleVocab(locale: string): LocaleVocab;
@@ -5,4 +5,5 @@ export interface LocaleVocab {
5
5
  weekdayShort: string[];
6
6
  dayPeriod: string[];
7
7
  }
8
+ export declare function canonicalCacheKey(locale: string): string;
8
9
  export declare function getLocaleVocab(locale: string): LocaleVocab;
@@ -0,0 +1,24 @@
1
+ import { type FormatOptions } from './tokens.cjs';
2
+ /**
3
+ * Parses `input` against `formatStr` and builds the real Temporal value it
4
+ * describes: a `Temporal.PlainDate`, `PlainTime`, `PlainDateTime`, or
5
+ * `ZonedDateTime` depending on which tokens are present.
6
+ *
7
+ * Returns `unknown` — this package has no ambient `Temporal` types to return
8
+ * a real one against.
9
+ *
10
+ * `options.locale` picks the calendar the result is built in. Pass a locale
11
+ * tag with a `-u-ca-` extension (e.g. `'en-u-ca-hebrew'`) to parse into a
12
+ * non-Gregorian calendar.
13
+ *
14
+ * @throws if `input` doesn't match `formatStr`'s shape at all
15
+ * @throws if it matches the shape but describes an impossible date (e.g. Feb
16
+ * 30) or self-contradictory data (e.g. a weekday name that doesn't match the
17
+ * actual date)
18
+ *
19
+ * @example
20
+ * parse('yyyy-MM-dd HH:mm', '2026-08-04 15:45') // Temporal.PlainDateTime
21
+ * parse('yyyy-MM', '2026-08-04T15:45:30') // throws — shape doesn't match
22
+ * parse('yyyy-MM-dd', '2026-02-30') // throws — not a real date
23
+ */
24
+ export declare function parse(formatStr: string, input: string, options?: FormatOptions): unknown | undefined;
@@ -0,0 +1,19 @@
1
+ import type { Piece } from './tokenize.cjs';
2
+ export interface CapturingPattern {
3
+ regex: RegExp;
4
+ groups: Array<{
5
+ name: string;
6
+ token: string;
7
+ }>;
8
+ ambiguousRuns: Array<{
9
+ groupNames: string[];
10
+ tokens: string[];
11
+ }>;
12
+ }
13
+ /**
14
+ * Same walk as buildPatternSource() in pattern.ts, but each token piece
15
+ * gets its own named capture group (positionally named so the same token,
16
+ * e.g. "yyyy", could in theory appear twice) so a caller can pull the
17
+ * matched substring for each token back out after a successful match.
18
+ */
19
+ export declare function buildCapturingPattern(pieces: Piece[], locale: string): CapturingPattern;
@@ -0,0 +1,28 @@
1
+ export declare function isValidTimeZone(raw: string): boolean;
2
+ export declare function tokenFragment(token: string, locale: string, nextToken?: string): string;
3
+ export declare const UNPADDED_NUMERIC_TOKENS: Set<string>;
4
+ export declare const UNPADDED_NUMERIC_RANGES: Record<string, Array<{
5
+ digits: 1 | 2;
6
+ min: number;
7
+ max: number;
8
+ }>>;
9
+ /**
10
+ * Given the literal digit string a run of N adjacent unpadded-numeric
11
+ * tokens matched as a whole (e.g. "112" for a 2-token run), enumerates
12
+ * every way to split it into N pieces (one per token, each piece 1-2
13
+ * digits per that token's own width rule) and returns every split where
14
+ * every piece is independently valid for its token. Length 0 means the
15
+ * run's regex match shouldn't have been possible in the first place
16
+ * (shouldn't happen — the caller only invokes this after the whole
17
+ * pattern already matched, meaning at least one split exists: the one the
18
+ * regex actually took). Length 1 means the reading is unambiguous.
19
+ * Length 2+ means true ambiguity — the caller should throw rather than
20
+ * pick one.
21
+ *
22
+ * Recursive over token count rather than hardcoded to 2, so a 3+ token
23
+ * unseparated run (e.g. "Hms") is covered by the same logic without a
24
+ * special case — those are rarer in practice but not impossible, and a
25
+ * partial fix that only covered pairs would leave the identical bug for
26
+ * anyone writing a 3-token glued run.
27
+ */
28
+ export declare function enumerateValidSplits(digits: string, tokens: string[]): number[][];
package/dist/pattern.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export declare function tokenFragment(token: string, locale: string): string;
1
+ export declare function isValidTimeZone(raw: string): boolean;
2
+ export declare function tokenFragment(token: string, locale: string, nextToken?: string): string;
2
3
  export declare const UNPADDED_NUMERIC_TOKENS: Set<string>;
3
4
  export declare const UNPADDED_NUMERIC_RANGES: Record<string, Array<{
4
5
  digits: 1 | 2;
@@ -0,0 +1,28 @@
1
+ interface TemporalFactory {
2
+ from(fields: Record<string, number | string | undefined>, options?: {
3
+ overflow?: 'constrain' | 'reject';
4
+ }): unknown;
5
+ }
6
+ export interface TemporalNamespace {
7
+ PlainDate: TemporalFactory;
8
+ PlainTime: TemporalFactory;
9
+ PlainDateTime: TemporalFactory;
10
+ ZonedDateTime: TemporalFactory;
11
+ }
12
+ export declare function subscribeToTemporalChanges(listener: () => void): void;
13
+ /**
14
+ * Explicitly hand temporal-fmt the Temporal implementation to use, instead
15
+ * of relying on a global `Temporal`. Call this once, before your first
16
+ * `format()`/`parse()`
17
+ *
18
+ * Call with no argument (or `undefined`) to clear the override and fall
19
+ * back to `globalThis.Temporal` again.
20
+ *
21
+ * @example
22
+ * import { Temporal } from 'temporal-polyfill';
23
+ * import { setTemporal } from 'temporal-fmt';
24
+ * setTemporal(Temporal);
25
+ */
26
+ export declare function setTemporal(temporal?: TemporalNamespace): void;
27
+ export declare function getTemporal(): TemporalNamespace;
28
+ export {};
@@ -9,6 +9,7 @@ export interface TemporalNamespace {
9
9
  PlainDateTime: TemporalFactory;
10
10
  ZonedDateTime: TemporalFactory;
11
11
  }
12
+ export declare function subscribeToTemporalChanges(listener: () => void): void;
12
13
  /**
13
14
  * Explicitly hand temporal-fmt the Temporal implementation to use, instead
14
15
  * of relying on a global `Temporal`. Call this once, before your first
@@ -0,0 +1,14 @@
1
+ export type Piece = {
2
+ kind: 'token';
3
+ value: string;
4
+ } | {
5
+ kind: 'literal';
6
+ value: string;
7
+ };
8
+ /**
9
+ * Splits a format string like `"yyyy-MM-dd 'at' HH:mm"` into token/literal
10
+ * pieces. Text in single quotes is always literal (e.g. write 'rd' in
11
+ * "3rd" so it's not read as the day token). A doubled quote ('') means a
12
+ * literal quote character, both inside a quoted span and standalone.
13
+ */
14
+ export declare function tokenize(format: string): Piece[];
@@ -0,0 +1,23 @@
1
+ export declare function pad(n: number, len: number): string;
2
+ export interface TemporalLike {
3
+ year?: number;
4
+ month?: number;
5
+ day?: number;
6
+ hour?: number;
7
+ minute?: number;
8
+ second?: number;
9
+ millisecond?: number;
10
+ timeZoneId?: string;
11
+ dayOfWeek?: number;
12
+ calendarId?: string;
13
+ toInstant?: () => unknown;
14
+ toLocaleString?: (locale: string, options: Intl.DateTimeFormatOptions) => string;
15
+ }
16
+ export interface FormatOptions {
17
+ /** BCP 47 locale tag, e.g. 'en-US', 'fr-FR', 'ar-EG'. Defaults to 'en-US'. */
18
+ locale?: string;
19
+ }
20
+ export declare const DEFAULT_LOCALE = "en-US";
21
+ type TokenHandler = (t: TemporalLike, locale: string) => string;
22
+ export declare const TOKENS: Array<[string, TokenHandler, keyof TemporalLike]>;
23
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "temporal-fmt",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Format Temporal.PlainDate/PlainDateTime/PlainTime/ZonedDateTime objects using date-fns-style token strings.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -8,9 +8,14 @@
8
8
  "types": "./dist/index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
14
19
  }
15
20
  },
16
21
  "files": [
@@ -18,13 +23,14 @@
18
23
  ],
19
24
  "sideEffects": false,
20
25
  "scripts": {
21
- "build": "tsup && tsc --declaration --emitDeclarationOnly",
26
+ "build": "tsup && tsc --declaration --emitDeclarationOnly && node scripts/emit-cjs-types.mjs",
22
27
  "dev": "tsup --watch",
23
- "test": "node --test test/*.test.js",
28
+ "test": "node --test test/*.test.js test/*.test.cjs",
24
29
  "test:unit": "vitest run",
25
30
  "test:unit:watch": "vitest",
26
31
  "test:types": "vitest run --typecheck",
27
- "test:all": "npm run build && npm test && npm run test:unit && npm run test:types",
32
+ "test:pack": "attw --pack .",
33
+ "test:all": "npm run build && npm test && npm run test:unit && npm run test:types && npm run test:pack",
28
34
  "prepublishOnly": "npm run build && npm test"
29
35
  },
30
36
  "keywords": [
@@ -48,7 +54,7 @@
48
54
  },
49
55
  "homepage": "https://github.com/DirazCoder/temporal-fmt#readme",
50
56
  "devDependencies": {
51
- "@typescript/native-preview": "^7.0.0-dev.20260707.2",
57
+ "@arethetypeswrong/cli": "^0.18.5",
52
58
  "temporal-polyfill": "^1.0.4",
53
59
  "tsup": "^8.5.1",
54
60
  "typescript": "^7.0.2",