temporal-fmt 0.9.1 → 0.9.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.
- package/dist/chunk-2JHEV7ZF.js +7 -0
- package/dist/chunk-2JHEV7ZF.js.map +1 -0
- package/dist/{chunk-DXLBLPLQ.js → chunk-4JWGUR4O.js} +2 -2
- package/dist/{chunk-H52AMABK.js → chunk-5U5WJ465.js} +6 -6
- package/dist/chunk-5U5WJ465.js.map +1 -0
- package/dist/chunk-C5YESWFT.js +2 -0
- package/dist/chunk-C5YESWFT.js.map +1 -0
- package/dist/chunk-F4RGUDA3.js +2 -0
- package/dist/chunk-F4RGUDA3.js.map +1 -0
- package/dist/chunk-NBXF7V5B.js +2 -0
- package/dist/chunk-NBXF7V5B.js.map +1 -0
- package/dist/{chunk-M5WL5VGW.js → chunk-R52YOKI3.js} +2 -2
- package/dist/chunk-UJR6DHXY.js +2 -0
- package/dist/chunk-UJR6DHXY.js.map +1 -0
- package/dist/{chunk-6UNSCZPL.js → chunk-XH46JNPK.js} +2 -2
- package/dist/chunk-XH46JNPK.js.map +1 -0
- package/dist/chunk-YB6YAG7E.js +35 -0
- package/dist/chunk-YB6YAG7E.js.map +1 -0
- package/dist/chunk-ZGMTY52O.js +2 -0
- package/dist/chunk-ZGMTY52O.js.map +1 -0
- package/dist/duration.cjs +4 -10
- package/dist/duration.cjs.map +1 -1
- package/dist/duration.js +1 -1
- package/dist/format.cjs +6 -6
- package/dist/format.cjs.map +1 -1
- package/dist/format.js +1 -1
- package/dist/formatDuration.d.cts +6 -0
- package/dist/formatDuration.d.ts +6 -0
- package/dist/index.cjs +37 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/dist/interval.cjs +6 -6
- package/dist/interval.cjs.map +1 -1
- package/dist/interval.js +1 -1
- package/dist/localeRegistry.cjs +4 -4
- package/dist/localeRegistry.cjs.map +1 -1
- package/dist/localeRegistry.js +1 -1
- package/dist/localeVocab.d.cts +3 -0
- package/dist/localeVocab.d.ts +3 -0
- package/dist/parse.cjs +9 -9
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.js +1 -1
- package/dist/parsePattern.d.cts +1 -0
- package/dist/parsePattern.d.ts +1 -0
- package/dist/pattern.d.cts +1 -0
- package/dist/pattern.d.ts +1 -0
- package/dist/recurrence.cjs +4 -4
- package/dist/recurrence.cjs.map +1 -1
- package/dist/recurrence.js +1 -1
- package/dist/relativeTime.cjs +24 -1
- package/dist/relativeTime.cjs.map +1 -1
- package/dist/relativeTime.js +1 -1
- package/dist/rounding.d.cts +1 -0
- package/dist/rounding.d.ts +1 -0
- package/dist/serialization.d.cts +1 -1
- package/dist/serialization.d.ts +1 -1
- package/dist/typeGuards.d.cts +9 -9
- package/dist/typeGuards.d.ts +9 -9
- package/package.json +1 -1
- package/dist/chunk-6JAWE65A.js +0 -2
- package/dist/chunk-6JAWE65A.js.map +0 -1
- package/dist/chunk-6UNSCZPL.js.map +0 -1
- package/dist/chunk-CUTVOO4Y.js +0 -35
- package/dist/chunk-CUTVOO4Y.js.map +0 -1
- package/dist/chunk-H52AMABK.js.map +0 -1
- package/dist/chunk-ILXRFTAE.js +0 -13
- package/dist/chunk-ILXRFTAE.js.map +0 -1
- package/dist/chunk-LYWOLBMV.js +0 -2
- package/dist/chunk-LYWOLBMV.js.map +0 -1
- package/dist/chunk-QASXSTBN.js +0 -2
- package/dist/chunk-QASXSTBN.js.map +0 -1
- package/dist/chunk-YAVXHM4W.js +0 -2
- package/dist/chunk-YAVXHM4W.js.map +0 -1
- package/dist/chunk-ZYVMZRMR.js +0 -2
- package/dist/chunk-ZYVMZRMR.js.map +0 -1
- /package/dist/{chunk-DXLBLPLQ.js.map → chunk-4JWGUR4O.js.map} +0 -0
- /package/dist/{chunk-M5WL5VGW.js.map → chunk-R52YOKI3.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{b as F,k as I,l as k,p as U,q as S}from"./chunk-5U5WJ465.js";import{n as v}from"./chunk-EHLRZULM.js";var h={day:864e5,hour:36e5,minute:6e4,second:1e3,millisecond:1};function E(n,t,e){let o=n<0?-1:1,i=Math.abs(n)/e,s;switch(t){case"nearest":s=Math.round(i);break;case"floor":s=Math.floor(i);break;case"ceil":s=Math.ceil(i);break;case"trunc":s=Math.trunc(i);break}return o*s*e}function A(n){let t=n.year,e=n.month,o=n.day,r=e<=2?t-1:t,i=Math.floor((r>=0?r:r-399)/400),s=r-i*400,a=e>2?e-3:e+9,u=Math.floor((153*a+2)/5)+o-1,c=s*365+Math.floor(s/4)-Math.floor(s/100)+u;return(i*146097+c-719468)*h.day+(n.hour??0)*h.hour+(n.minute??0)*h.minute+(n.second??0)*h.second+(n.millisecond??0)}function V(n,t){let e=h.day,o=Math.floor(n/e),r=n-o*e;r<0&&(r+=e);let i=Math.floor(r/h.hour),s=Math.floor(r%h.hour/h.minute),a=Math.floor(r%h.minute/h.second),u=r%h.second,c=o+719468,l=Math.floor((c>=0?c:c-146096)/146097),m=c-l*146097,d=Math.floor((m-Math.floor(m/1460)+Math.floor(m/36524)-Math.floor(m/146096))/365),D=d+l*400,g=m-(365*d+Math.floor(d/4)-Math.floor(d/100)),y=Math.floor((5*g+2)/153),f=g-Math.floor((153*y+2)/5)+1,p=y<10?y+3:y-9,_=p<=2?D+1:D;return{...t,year:_,month:p,day:f,hour:i,minute:s,second:a,millisecond:u}}function P(n,t){let e=v(n),o=t.mode??"nearest",r=(t.roundingIncrement??1)*h[t.unit];if(r<=0)throw new Error(`temporal-fmt: round() requires a positive roundingIncrement (got ${t.roundingIncrement}).`);let i=A(e),s=E(i,o,r);return V(s,e)}function J(n,t,e=1){return P(n,{unit:t,mode:"floor",roundingIncrement:e})}function Q(n,t,e=1){return P(n,{unit:t,mode:"ceil",roundingIncrement:e})}function nn(n,t,e=1){return P(n,{unit:t,mode:"trunc",roundingIncrement:e})}function b(n,t,e){if(Number.isInteger(n))return BigInt(n)*t;let o=n*Number(t);if(Number.isSafeInteger(o))return BigInt(o);throw new k({reason:`field "${e}" (${n}) cannot be converted to nanoseconds exactly \u2014 the value is too large for a fractional unit; use smaller units`})}var M={years:0n,months:0n,weeks:0n,days:86400n*1000000000n,hours:3600n*1000000000n,minutes:60n*1000000000n,seconds:1000000000n,milliseconds:1000000n,microseconds:1000n,nanoseconds:1n};function j(n){return n==="years"||n==="months"||n==="weeks"}function z(n,t){let e=t.mode??"nearest",o=BigInt(t.roundingIncrement??1);if(o<=0n)throw new Error(`temporal-fmt: roundDuration() requires a positive roundingIncrement (got ${t.roundingIncrement}).`);if(j(t.unit))throw new Error(`temporal-fmt: roundDuration() to "${t.unit}" requires a Temporal.Duration with a relativeTo \u2014 this helper operates on plain field bags without calendar context. Use Temporal.Duration.prototype.round() directly.`);let r=0n;for(let f of["days","hours","minutes","seconds","milliseconds","microseconds","nanoseconds"]){let p=n[f]??0;r+=b(p,M[f],f)}let i=o*M[t.unit],s=r<0n?-1n:1n,a=r<0n?-r:r,u=a/i,c=a%i,l;switch(e){case"nearest":l=c*2n>=i?u+1n:u;break;case"floor":l=u;break;case"ceil":l=c>0n?u+1n:u;break;case"trunc":l=u;break}let m=s*l*i,d={...n},D=m,g=["days","hours","minutes","seconds","milliseconds","microseconds","nanoseconds"],y=g.indexOf(t.unit);for(let f=y+1;f<g.length;f++)d[g[f]]=0;for(let f=0;f<=y;f++){let p=g[f],_=M[p];if(_===0n)continue;let T=D/_;D-=T*_,d[p]=Number(T)}return d}var $={y:{longSingular:"year",longPlural:"years",shortSingular:"yr",shortPlural:"yrs",field:"years",intlUnit:"year"},o:{longSingular:"month",longPlural:"months",shortSingular:"mo",shortPlural:"mos",field:"months",intlUnit:"month"},w:{longSingular:"week",longPlural:"weeks",shortSingular:"wk",shortPlural:"wks",field:"weeks",intlUnit:"week"},d:{longSingular:"day",longPlural:"days",shortSingular:"d",shortPlural:"d",field:"days",intlUnit:"day"},h:{longSingular:"hour",longPlural:"hours",shortSingular:"h",shortPlural:"h",field:"hours",intlUnit:"hour"},m:{longSingular:"minute",longPlural:"minutes",shortSingular:"m",shortPlural:"m",field:"minutes",intlUnit:"minute"},s:{longSingular:"second",longPlural:"seconds",shortSingular:"s",shortPlural:"s",field:"seconds",intlUnit:"second"},S:{longSingular:"millisecond",longPlural:"milliseconds",shortSingular:"ms",shortPlural:"ms",field:"milliseconds",intlUnit:"millisecond"}},L=Object.keys($).flatMap(n=>[n+n+n,n+n,n]).sort((n,t)=>t.length-n.length);function q(n){let t=[],e=0;for(;e<n.length;){let o=n[e];if(o==="'"){if(n[e+1]==="'"){N(t,"'"),e+=2;continue}let i=e+1,s="",a=!1;for(;i<n.length;){if(n[i]==="'"){if(n[i+1]==="'"){s+="'",i+=2;continue}a=!0,i+=1;break}s+=n[i],i+=1}if(!a)throw new Error(`temporal-fmt: unterminated quote in duration format string "${n}"`);N(t,s),e=i;continue}let r=L.find(i=>n.startsWith(i,e));if(r){let i=r[0],s=r.length===1?"numeric":r.length===2?"short":"long";t.push({kind:"token",value:r,unit:i,form:s}),e+=r.length;continue}N(t,o),e+=1}return t}function N(n,t){let e=n[n.length-1];e&&e.kind==="literal"?e.value+=t:n.push({kind:"literal",value:t})}function C(n,t){let e=n[t];if(e==null)return 0;if(typeof e=="number"&&Number.isFinite(e))return e;let o=Number(e);if(!Number.isFinite(o))throw new Error(`temporal-fmt: duration field "${t}" is not a finite number (got ${String(e)}).`);return o}var w=new Map,H=200;function W(n,t,e){let o=`${S(n)}|${t}|${e}`,r=w.get(o);if(r)return r;if(w.size>=H){let s=w.keys().next().value;s!==void 0&&w.delete(s)}let i;try{i=new Intl.NumberFormat(U(n),{style:"unit",unit:t,unitDisplay:e})}catch(s){throw new I({actual:n,reason:s.message})}return w.set(o,i),i}function rn(n,t,e={}){return x(n,t,e).map(o=>o.value).join("")}function x(n,t,e={}){if(t.length>1e3)throw new Error(`temporal-fmt: duration format string exceeds maximum length of ${1e3} characters (got ${t.length}).`);let o=e.showZeroValues===!0,r=e.locale,i=r!==void 0,s=q(t),a=[];for(let u of s){if(u.kind==="literal"){a.push({kind:"literal",value:u.value});continue}let c=$[u.unit];if(!c)throw new Error(`temporal-fmt: unknown duration token "${u.value}"`);let l=C(n,c.field);if(l===0&&!o){a.push({kind:"token",value:"",token:u.value});continue}if(u.form==="numeric"){a.push({kind:"token",value:String(l),token:u.value});continue}if(i){let m=u.form==="short"?"short":"long",d=W(r,c.intlUnit,m);a.push({kind:"token",value:d.format(l),token:u.value});continue}u.form==="short"?a.push({kind:"token",value:l+(l===1||l===-1?c.shortSingular:c.shortPlural),token:u.value}):a.push({kind:"token",value:l+" "+(l===1||l===-1?c.longSingular:c.longPlural),token:u.value})}return a}function dn(n,t,e={}){return x(n,t,e).map(o=>o.kind==="token"?{type:"token",value:o.value,token:o.token}:{type:"literal",value:o.value})}function mn(n){let e=/^P(?:(?:(\d+(?:\.\d+)?)Y)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)W)?(?:(\d+(?:\.\d+)?)D)?)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/.exec(n);if(!e)throw new k({input:n,reason:"does not match ISO 8601 duration grammar (P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S)"});if(e.slice(1).every(r=>r===void 0))throw new k({input:n,reason:'duration has no fields (use "P0D" for zero duration)'});let o=r=>r===void 0?0:Number(r);return{years:o(e[1]),months:o(e[2]),weeks:o(e[3]),days:o(e[4]),hours:o(e[5]),minutes:o(e[6]),seconds:o(e[7])}}function fn(n){let t=["P"],e=n.years??0,o=n.months??0,r=n.weeks??0,i=n.days??0,s=n.hours??0,a=n.minutes??0,u=n.seconds??0;return e&&t.push(`${e}Y`),o&&t.push(`${o}M`),r&&t.push(`${r}W`),i&&t.push(`${i}D`),(s||a||u)&&(t.push("T"),s&&t.push(`${s}H`),a&&t.push(`${a}M`),u&&t.push(`${u}S`)),t.length===1&&t.push("0D"),t.join("")}function B(n){let t=["y","o","w","d","h","m","s","S"].flatMap(r=>[r+r+r,r+r,r]).sort((r,i)=>i.length-r.length),e=[],o=0;for(;o<n.length;){let r=n[o];if(r==="'"){if(n[o+1]==="'"){R(e,"'"),o+=2;continue}let s=o+1,a="",u=!1;for(;s<n.length;){if(n[s]==="'"){if(n[s+1]==="'"){a+="'",s+=2;continue}u=!0,s+=1;break}a+=n[s],s+=1}if(!u)throw new F({format:n,reason:"unterminated quote"});R(e,a),o=s;continue}let i=t.find(s=>n.startsWith(s,o));if(i){e.push({kind:"token",value:i,unit:i[0]}),o+=i.length;continue}R(e,r),o+=1}return e}function R(n,t){let e=n[n.length-1];e&&e.kind==="literal"?e.value+=t:n.push({kind:"literal",value:t})}function hn(n,t,e={}){let o=B(t),r={},i=[],s="";for(let c of o)if(c.kind==="literal")s+=c.value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");else{let l=c.unit,m=c.value.length===1?"numeric":c.value.length===2?"short":"long";/* c8 ignore start @preserve -- the final `: null` branch, and the
|
|
2
|
+
`if (key === null)` throw it feeds, are both unreachable: tok.unit
|
|
3
|
+
is always one of the 8 letters in DURATION_TOKEN_STRINGS (the same
|
|
4
|
+
source set this ternary checks against), so `null` can't be
|
|
5
|
+
produced by any token the tokenizer emits. Kept as a guard against
|
|
6
|
+
a future letter being added to one set without the other. */let d=l==="y"?"years":l==="o"?"months":l==="w"?"weeks":l==="d"?"days":l==="h"?"hours":l==="m"?"minutes":l==="s"?"seconds":l==="S"?"milliseconds":null;if(d===null)throw new F({format:t,token:c.value,reason:"unknown duration token"});/* c8 ignore stop @preserve */m==="numeric"?s+="(-?\\d+)":s+="(\\d+)\\s*\\w*",i.push({unit:d,form:m})}let u=new RegExp(`^${s}$`,"u").exec(n);if(!u)throw new F({input:n,format:t,reason:"does not match duration format"});return i.forEach((c,l)=>{let m=u[l+1],d=Number(m);if(!Number.isFinite(d))throw new k({input:n,reason:`token for ${c.unit} matched "${m}" but isn't a finite number`});r[c.unit]=d}),r}function gn(n){let t=[["days",86400n*1000000000n],["hours",3600n*1000000000n],["minutes",60n*1000000000n],["seconds",1000000000n],["milliseconds",1000000n],["microseconds",1000n],["nanoseconds",1n]],e=0n;for(let[i,s]of t){let a=n[i];typeof a=="number"&&(e+=b(a,s,i))}let o={...n},r=e;for(let[i,s]of t){let a=r/s;r-=a*s,o[i]=Number(a)}return o}function yn(n,t){let e={days:86400n*1000000000n,hours:3600n*1000000000n,minutes:60n*1000000000n,seconds:1000000000n,milliseconds:1000000n,microseconds:1000n,nanoseconds:1n},o=0n;for(let i of Object.keys(e)){let s=n[i];typeof s=="number"&&(o+=b(s,e[i],i))}let r=e[t];if(!r)throw new k({reason:`totalDuration() does not support unit "${t}" (calendar-bound units need a relativeTo)`});return Number(o)/Number(r)}function pn(n,t){let e=O(n),o=O(t);return e<o?-1:e>o?1:0}function O(n){let t={days:86400n*1000000000n,hours:3600n*1000000000n,minutes:60n*1000000000n,seconds:1000000000n,milliseconds:1000000n,microseconds:1000n,nanoseconds:1n},e=0n;for(let o of Object.keys(t)){let r=n[o];typeof r=="number"&&(e+=b(r,t[o],o))}return e}function Y(n,t){let e=["years","months","weeks","days","hours","minutes","seconds","milliseconds","microseconds","nanoseconds"],o={};for(let r of e)o[r]=(n[r]??0)+(t[r]??0);return o}function kn(n,t){return Y(n,Z(t))}function Z(n){let t={};for(let e of Object.keys(n))t[e]=-(n[e]??0);return t}export{P as a,J as b,Q as c,nn as d,z as e,rn as f,dn as g,mn as h,fn as i,hn as j,gn as k,yn as l,pn as m,Y as n,kn as o};
|
|
7
|
+
//# sourceMappingURL=chunk-2JHEV7ZF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/rounding.ts","../src/formatDuration.ts","../src/duration.ts"],"sourcesContent":["// Rounding helpers. Pure functions over field bags,\n// same convention as arithmetic.ts/calendarUtils.ts.\n\nimport { asDateFieldView, type DateFieldView } from './calendarUtils.js';\nimport { InvalidDurationError } from './errors.js';\n\ntype RoundingUnit = 'day' | 'hour' | 'minute' | 'second' | 'millisecond';\ntype RoundingMode = 'nearest' | 'floor' | 'ceil' | 'trunc';\n\ninterface DateTimeFieldView extends DateFieldView {\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n}\n\n// Ms-per-unit table. Used by round() to convert a field bag to ms,\n// apply the rounding mode, and convert back. Mirrors how add() in\n// arithmetic.ts handles sub-day arithmetic.\nconst MS_PER_UNIT: Record<RoundingUnit, number> = {\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n second: 1_000,\n millisecond: 1,\n};\n\nfunction applyMode(ms: number, mode: RoundingMode, increment: number): number {\n // All four modes operate on absolute value then re-apply the sign,\n // so negative values round symmetrically (floor of -1.5 → -2, not -1).\n // Matches Math.round semantics for 'nearest' and Temporal's rounding\n // for the other three.\n const sign = ms < 0 ? -1 : 1;\n const abs = Math.abs(ms);\n const stepped = abs / increment;\n let rounded: number;\n switch (mode) {\n case 'nearest': rounded = Math.round(stepped); break;\n case 'floor': rounded = Math.floor(stepped); break;\n case 'ceil': rounded = Math.ceil(stepped); break;\n case 'trunc': rounded = Math.trunc(stepped); break;\n }\n return sign * rounded * increment;\n}\n\nfunction toMs(v: DateTimeFieldView): number {\n // Returns ms-since-(Howard Hinnant epoch). Used internally — the\n // absolute value is meaningful only relative to the same epoch used\n // by fromMs.\n const y = v.year!, m = v.month!, d = v.day!;\n const y2 = m <= 2 ? y - 1 : y;\n const era = Math.floor((y2 >= 0 ? y2 : y2 - 399) / 400);\n const yoe = y2 - era * 400;\n const m2 = m > 2 ? m - 3 : m + 9;\n const doy = Math.floor((153 * m2 + 2) / 5) + d - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n const days = era * 146097 + doe - 719468;\n return days * MS_PER_UNIT.day\n + (v.hour ?? 0) * MS_PER_UNIT.hour\n + (v.minute ?? 0) * MS_PER_UNIT.minute\n + (v.second ?? 0) * MS_PER_UNIT.second\n + (v.millisecond ?? 0);\n}\n\nfunction fromMs(ms: number, base: DateTimeFieldView): DateTimeFieldView {\n // Convert absolute ms (on the same epoch as toMs) back to a field bag.\n // Walks the Howard Hinnant days_from_civil inverse inline.\n const MS_PER_DAY = MS_PER_UNIT.day;\n const totalDays = Math.floor(ms / MS_PER_DAY);\n let withinDay = ms - totalDays * MS_PER_DAY; // ms since midnight\n // Defensive floating-point guard: given totalDays = Math.floor(ms /\n // MS_PER_DAY), withinDay = ms - totalDays * MS_PER_DAY is\n // mathematically guaranteed non-negative (that's what Math.floor\n // division gives you), verified against extreme values including\n // Number.MIN_SAFE_INTEGER and sub-ms fractional noise near day\n // boundaries. Kept in case a future change to how ms is computed\n // upstream breaks that guarantee.\n /* c8 ignore next */\n if (withinDay < 0) withinDay += MS_PER_DAY;\n const hour = Math.floor(withinDay / MS_PER_UNIT.hour);\n const minute = Math.floor((withinDay % MS_PER_UNIT.hour) / MS_PER_UNIT.minute);\n const second = Math.floor((withinDay % MS_PER_UNIT.minute) / MS_PER_UNIT.second);\n const millisecond = withinDay % MS_PER_UNIT.second;\n // Convert totalDays back to year/month/day via Howard Hinnant's\n // civil_from_days. Same algorithm as arithmetic.ts's shiftDays.\n const z = totalDays + 719468;\n const era = Math.floor((z >= 0 ? z : z - 146096) / 146097);\n const doe = z - era * 146097;\n const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);\n const y2 = yoe + era * 400;\n const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));\n const mp = Math.floor((5 * doy + 2) / 153);\n const d = doy - Math.floor((153 * mp + 2) / 5) + 1;\n const m = mp < 10 ? mp + 3 : mp - 9;\n const year = m <= 2 ? y2 + 1 : y2;\n return { ...base, year, month: m, day: d, hour, minute, second, millisecond };\n}\n\nfunction shiftDays(v: DateTimeFieldView, days: number): DateTimeFieldView {\n const y = v.year!, m = v.month!, d = v.day!;\n const y2 = m <= 2 ? y - 1 : y;\n const era = Math.floor((y2 >= 0 ? y2 : y2 - 399) / 400);\n const yoe = y2 - era * 400;\n const m2 = m > 2 ? m - 3 : m + 9;\n const doy = Math.floor((153 * m2 + 2) / 5) + d - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n const totalDays = era * 146097 + doe - 719468 + days;\n const z = totalDays + 719468;\n const era2 = Math.floor((z >= 0 ? z : z - 146096) / 146097);\n const doe2 = z - era2 * 146097;\n const yoe2 = Math.floor((doe2 - Math.floor(doe2 / 1460) + Math.floor(doe2 / 36524) - Math.floor(doe2 / 146096)) / 365);\n const y2out = yoe2 + era2 * 400;\n const doy2 = doe2 - (365 * yoe2 + Math.floor(yoe2 / 4) - Math.floor(yoe2 / 100));\n const mp = Math.floor((5 * doy2 + 2) / 153);\n const d2 = doy2 - Math.floor((153 * mp + 2) / 5) + 1;\n const m2out = mp < 10 ? mp + 3 : mp - 9;\n const yOut = m2out <= 2 ? y2out + 1 : y2out;\n return { ...v, year: yOut, month: m2out, day: d2 };\n}\n\nexport interface RoundOptions {\n unit: RoundingUnit;\n mode?: RoundingMode;\n roundingIncrement?: number;\n}\n\nexport function round(value: unknown, options: RoundOptions): DateTimeFieldView {\n const base = asDateFieldView(value) as DateTimeFieldView;\n const mode = options.mode ?? 'nearest';\n const increment = (options.roundingIncrement ?? 1) * MS_PER_UNIT[options.unit];\n if (increment <= 0) {\n throw new Error(`temporal-fmt: round() requires a positive roundingIncrement (got ${options.roundingIncrement}).`);\n }\n const ms = toMs(base);\n const rounded = applyMode(ms, mode, increment);\n return fromMs(rounded, base);\n}\n\nexport function floor(value: unknown, unit: RoundingUnit, roundingIncrement: number = 1): DateTimeFieldView {\n return round(value, { unit, mode: 'floor', roundingIncrement });\n}\n\nexport function ceil(value: unknown, unit: RoundingUnit, roundingIncrement: number = 1): DateTimeFieldView {\n return round(value, { unit, mode: 'ceil', roundingIncrement });\n}\n\nexport function truncate(value: unknown, unit: RoundingUnit, roundingIncrement: number = 1): DateTimeFieldView {\n return round(value, { unit, mode: 'trunc', roundingIncrement });\n}\n\n// Duration rounding. Takes a duration field bag and rounds it to the\n// requested unit. Operates on the duration's own fields (years/months\n// for calendar-bound units, days/hours/minutes/seconds/ms/µs/ns for\n// absolute units). Mirrors Temporal.Duration.prototype.round's surface\n// — but operates on plain field bags rather than real Temporal.Duration\n// instances, same convention as the rest of this module set.\nexport interface DurationFields {\n years?: number;\n months?: number;\n weeks?: number;\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n microseconds?: number;\n nanoseconds?: number;\n}\n\n// Converts one absolute-unit field to nanoseconds, exactly. Integer\n// values keep the exact BigInt path (arbitrary magnitude). Fractional\n// values — which parseISODuration legitimately produces (\"P1.5D\") —\n// scale in floating point and are accepted only when the product is a\n// safe integer, so P1.5D balances to exactly 1 day + 12 hours. A\n// fractional value whose product can't be represented exactly (large\n// fractional day counts) throws the typed InvalidDurationError instead\n// of the opaque \"TypeError: Cannot convert 1.5 to a BigInt\" the old\n// BigInt(v) call produced. Shared by roundDuration (here) and the\n// duration.ts arithmetic helpers — duration.ts already imports from\n// this module, so exporting keeps the dependency direction acyclic.\nexport function fieldToNs(v: number, nsPer: bigint, field: string): bigint {\n if (Number.isInteger(v)) return BigInt(v) * nsPer;\n const scaled = v * Number(nsPer);\n if (Number.isSafeInteger(scaled)) return BigInt(scaled);\n throw new InvalidDurationError({\n reason: `field \"${field}\" (${v}) cannot be converted to nanoseconds exactly — the value is too large for a fractional unit; use smaller units`,\n });\n}\n\ntype DurationUnit = 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' | 'microseconds' | 'nanoseconds';\n\nconst DURATION_UNIT_TO_NS: Record<DurationUnit, bigint> = {\n years: 0n, // calendar-bound, can't convert without relativeTo\n months: 0n, // same\n weeks: 0n, // same\n days: 86_400n * 1_000_000_000n,\n hours: 3_600n * 1_000_000_000n,\n minutes: 60n * 1_000_000_000n,\n seconds: 1_000_000_000n,\n milliseconds: 1_000_000n,\n microseconds: 1_000n,\n nanoseconds: 1n,\n};\n\n// Absolute units (days and below) can be rounded without a relativeTo\n// because their length is fixed in nanoseconds. Calendar-bound units\n// (years/months/weeks) can't — would need a Temporal.Duration round()\n// call with a relativeTo. This helper throws if the caller tries to\n// round to/from a calendar-bound unit, rather than silently producing\n// a wrong result.\nfunction isCalendarBound(unit: DurationUnit): boolean {\n return unit === 'years' || unit === 'months' || unit === 'weeks';\n}\n\nexport function roundDuration(duration: DurationFields, options: {\n unit: DurationUnit;\n mode?: RoundingMode;\n roundingIncrement?: number;\n}): DurationFields {\n const mode = options.mode ?? 'nearest';\n const increment = BigInt(options.roundingIncrement ?? 1);\n if (increment <= 0n) {\n throw new Error(`temporal-fmt: roundDuration() requires a positive roundingIncrement (got ${options.roundingIncrement}).`);\n }\n if (isCalendarBound(options.unit)) {\n throw new Error(\n `temporal-fmt: roundDuration() to \"${options.unit}\" requires a Temporal.Duration with a relativeTo — ` +\n `this helper operates on plain field bags without calendar context. Use Temporal.Duration.prototype.round() directly.`\n );\n }\n\n // Sum all absolute-unit contributions into total nanoseconds.\n let totalNs = 0n;\n for (const u of ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'] as DurationUnit[]) {\n const v = duration[u] ?? 0;\n totalNs += fieldToNs(v, DURATION_UNIT_TO_NS[u], u);\n }\n\n // Apply rounding on the absolute value, preserving sign (same as round()).\n const stepNs = increment * DURATION_UNIT_TO_NS[options.unit];\n const sign = totalNs < 0n ? -1n : 1n;\n const abs = totalNs < 0n ? -totalNs : totalNs;\n const stepped = abs / stepNs;\n const remainder = abs % stepNs;\n let rounded: bigint;\n switch (mode) {\n case 'nearest':\n // Banker's rounding would be the Temporal spec, but Math.round-style\n // half-up is what callers typically expect from a \"round\" function.\n // Going with half-up to match round() above and avoid surprising anyone\n // who reads the output.\n rounded = remainder * 2n >= stepNs ? stepped + 1n : stepped;\n break;\n case 'floor': rounded = stepped; break;\n case 'ceil': rounded = remainder > 0n ? stepped + 1n : stepped; break;\n case 'trunc': rounded = stepped; break;\n }\n const newTotalNs = sign * rounded * stepNs;\n\n // Distribute back into the largest unit ≤ the requested unit. This\n // produces a balanced duration (e.g. rounding 90s to minutes gives\n // 1m30s in the minute field, not 90s).\n const result: DurationFields = { ...duration };\n let remaining = newTotalNs;\n // Clear all absolute units, then re-populate from largest to smallest so\n // the balanced output has all its value concentrated at the target unit\n // and below.\n const unitsInOrder: DurationUnit[] = ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'];\n const startIdx = unitsInOrder.indexOf(options.unit);\n // Units finer than the rounding target are zeroed: all their value was\n // folded into `remaining` above, and whatever survives rounding now\n // lives at the target unit and above. (Units coarser than the target\n // are re-written by the distribution loop below — their value is\n // already inside `remaining`, so the spread copy is overwritten with\n // the same number.)\n for (let i = startIdx + 1; i < unitsInOrder.length; i++) {\n result[unitsInOrder[i]!] = 0;\n }\n // Re-populate from the largest absolute unit down to the target, so the\n // result has all its value concentrated at the target unit and above.\n for (let i = 0; i <= startIdx; i++) {\n const u = unitsInOrder[i]!;\n const unitNs = DURATION_UNIT_TO_NS[u];\n // Dead by construction: unitsInOrder only lists days/hours/minutes/\n // seconds/milliseconds/microseconds/nanoseconds, none of which are\n // 0n in DURATION_UNIT_TO_NS (only years/months/weeks are, and those\n // never appear in this array). Kept in case unitsInOrder grows to\n // include a calendar-bound unit later.\n /* c8 ignore next */\n if (unitNs === 0n) continue;\n const count = remaining / unitNs;\n remaining -= count * unitNs;\n // Assign unconditionally (zero counts write 0): the units at and above\n // the target are fully re-derived from the rounded total, so any\n // original spread-copied value must be overwritten either way —\n // conditionally skipping zero counts would leave the caller's stale\n // value sitting in the field.\n result[u] = Number(count);\n }\n return result;\n}","import { type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\nimport { canonicalCacheKey, normalizeLocaleTag } from './localeVocab.js';\nimport { InvalidLocaleError } from './errors.js';\n\n// A Temporal.Duration doesn't sit on a calendar — it has no year/month/day\n// position the way a PlainDate does — so the date/time token set in\n// tokens.ts doesn't apply. This is a separate token table for the same\n// reason parseRelative() lives in its own module: a different surface\n// deserves its own grammar, not a bolt-on to the existing one.\n//\n// Token design: each unit has three forms, in increasing verbosity.\n// `y` — numeric value, no unit text (\"2\")\n// `yy` — short unit suffix, plural-aware (\"2y\", or \"1y\" — see below)\n// `yyy` — full unit word, plural-aware (\"2 years\", \"1 year\")\n// Same for months (`o`/`oo`/`ooo` — `o` not `M` because the duration's\n// own field name in Temporal is \"months\" and the long-form output should\n// read \"month\"/\"months\", but the *token* letter is arbitrary; `o` is\n// chosen so it doesn't visually collide with `m` (minutes) or `M`\n// (months in date format) when a reader skims both tables side by side).\n//\n// Locale-aware rendering: when a `locale` is passed, the short/long\n// forms delegate to `Intl.NumberFormat` with `style: 'unit'`. That gives\n// us pluralization, native unit names, and the locale's preferred\n// spacing for free, matching the same \"delegate to Intl\" approach\n// `formatDistance` already uses. Without a `locale`, the original\n// English-only hardcoded table is used so existing default output stays\n// byte-identical — this is an additive locale option, not a rewrite of\n// the default rendering path.\n\ntype UnitKey = 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds';\n\ninterface UnitForms {\n // singular and plural suffixes for the long form (e.g. \"year\", \"years\")\n longSingular: string;\n longPlural: string;\n // singular and plural suffixes for the short form (e.g. \"yr\", \"yrs\")\n shortSingular: string;\n shortPlural: string;\n // the property on Temporal.Duration to read for this unit\n field: UnitKey;\n // Intl.NumberFormat unit identifier (used only on the locale-aware path).\n // Confirmed against the current Intl spec — including `millisecond`, which\n // is in fact supported by every engine we target (Node 20+, modern ICU).\n // The task brief flagged this as a possible gap; empirically it isn't.\n intlUnit: string;\n}\n\nconst DURATION_UNITS: Record<string, UnitForms> = {\n y: { longSingular: 'year', longPlural: 'years', shortSingular: 'yr', shortPlural: 'yrs', field: 'years', intlUnit: 'year' },\n o: { longSingular: 'month', longPlural: 'months', shortSingular: 'mo', shortPlural: 'mos', field: 'months', intlUnit: 'month' },\n w: { longSingular: 'week', longPlural: 'weeks', shortSingular: 'wk', shortPlural: 'wks', field: 'weeks', intlUnit: 'week' },\n d: { longSingular: 'day', longPlural: 'days', shortSingular: 'd', shortPlural: 'd', field: 'days', intlUnit: 'day' },\n h: { longSingular: 'hour', longPlural: 'hours', shortSingular: 'h', shortPlural: 'h', field: 'hours', intlUnit: 'hour' },\n m: { longSingular: 'minute', longPlural: 'minutes', shortSingular: 'm', shortPlural: 'm', field: 'minutes', intlUnit: 'minute' },\n s: { longSingular: 'second', longPlural: 'seconds', shortSingular: 's', shortPlural: 's', field: 'seconds', intlUnit: 'second' },\n S: { longSingular: 'millisecond', longPlural: 'milliseconds', shortSingular: 'ms', shortPlural: 'ms', field: 'milliseconds', intlUnit: 'millisecond' },\n};\n\n// Token strings this module recognizes, longest-first for the greedy\n// tokenizer. tokenize() in tokenize.ts already does longest-first via\n// SORTED_TOKEN_STRINGS, but it operates on the *date/time* TOKENS table —\n// not this one. Rather than teach tokenize() about two tables, this\n// module uses its own equivalent scan over DURATION_UNITS keys.\nconst DURATION_TOKEN_STRINGS = Object.keys(DURATION_UNITS)\n .flatMap((single) => [single + single + single, single + single, single])\n .sort((a, b) => b.length - a.length);\n\ntype Piece =\n | { kind: 'token'; value: string; unit: string; form: 'numeric' | 'short' | 'long' }\n | { kind: 'literal'; value: string };\n\n// Same greedy-match shape as tokenize() in tokenize.ts, but with this\n// module's own token set. Quoted-literal handling is identical so the\n// same documented escaping rules carry over: 'at' is a literal, '' is a\n// literal quote.\nfunction tokenizeDuration(format: string): Piece[] {\n const pieces: Piece[] = [];\n let i = 0;\n while (i < format.length) {\n const ch = format[i];\n if (ch === \"'\") {\n if (format[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\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 if (!closed) {\n throw new Error(`temporal-fmt: unterminated quote in duration format string \"${format}\"`);\n }\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n const match = DURATION_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));\n if (match) {\n // single letter = numeric, double = short, triple = long\n const unit = match[0]!;\n const form = match.length === 1 ? 'numeric' : match.length === 2 ? 'short' : 'long';\n pieces.push({ kind: 'token', value: match, unit, form });\n i += match.length;\n continue;\n }\n appendLiteral(pieces, ch);\n i += 1;\n }\n return pieces;\n}\n\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\n// Reads a unit value off the duration in a way that works for both real\n// Temporal.Duration objects and field bags ({ hours: 2, minutes: 30 }).\n// Temporal.Duration values are numbers, possibly negative for\n// backwards durations; a field bag the caller passes might leave fields\n// off entirely (undefined → treated as 0 for this unit).\nfunction readUnit(duration: Record<string, unknown>, field: UnitKey): number {\n const value = duration[field];\n if (value === undefined || value === null) return 0;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n // Temporal.Duration values are always numbers, but a hand-built field\n // bag could end up with a string here. Coerce; throw on garbage rather\n // than silently formatting NaN.\n const coerced = Number(value);\n if (!Number.isFinite(coerced)) {\n throw new Error(\n `temporal-fmt: duration field \"${field}\" is not a finite number (got ${String(value)}).`\n );\n }\n return coerced;\n}\n\n// Intl.NumberFormat is expensive to construct, and a typical duration\n// render walks 2-4 units — so a tight loop on the same (locale, unit,\n// display) triple would otherwise rebuild the formatter for every token\n// of every row. Cache by canonical-locale + unit + display, same\n// eviction shape as the other locale-keyed caches in this library\n// (formatterCache in tokens.ts, rtfCache in formatDistance.ts).\nconst unitFormatterCache = new Map<string, Intl.NumberFormat>();\nconst MAX_UNIT_FORMATTER_CACHE_SIZE = 200;\n\nfunction getUnitFormatter(locale: string, intlUnit: string, unitDisplay: 'short' | 'long'): Intl.NumberFormat {\n const key = `${canonicalCacheKey(locale)}|${intlUnit}|${unitDisplay}`;\n const cached = unitFormatterCache.get(key);\n if (cached) return cached;\n if (unitFormatterCache.size >= MAX_UNIT_FORMATTER_CACHE_SIZE) {\n const oldestKey = unitFormatterCache.keys().next().value;\n if (oldestKey !== undefined) unitFormatterCache.delete(oldestKey);\n }\n let formatter: Intl.NumberFormat;\n try {\n formatter = new Intl.NumberFormat(normalizeLocaleTag(locale), {\n style: 'unit',\n unit: intlUnit,\n unitDisplay,\n });\n } catch (err) {\n // Malformed locale tags reach Intl as a bare RangeError; surface the\n // library's typed error instead. (Every failure mode of these\n // constructors with a string locale is a RangeError, so converting\n // unconditionally loses nothing — the original message is preserved\n // in `reason` either way.)\n throw new InvalidLocaleError({ actual: locale, reason: (err as Error).message });\n }\n unitFormatterCache.set(key, formatter);\n return formatter;\n}\n\nexport interface DurationFormatOptions extends FormatOptions {\n /**\n * When true, units whose value is zero are still emitted in the output\n * (e.g. \"0 hours, 30 minutes\" instead of \"30 minutes\"). Default is\n * false: zero-value units are omitted, matching how date-fns's\n * formatDuration works and how most callers rendering a duration to\n * a human would want it.\n */\n showZeroValues?: boolean;\n}\n\n/**\n * Format a Temporal.Duration (or a plain field bag { years, months, ...\n * }) using a duration-specific token string. Token grammar is documented\n * in the README under \"Duration formatting\" — it does NOT reuse the\n * date/time token table, since a duration has no calendar position.\n *\n * Zero-value units are omitted by default; pass { showZeroValues: true }\n * to force them to appear.\n *\n * Unit-name localization: without a `locale`, output is the original\n * English hardcoded singular/plural forms (byte-identical to previous\n * versions). With a `locale`, the short/long forms delegate to\n * `Intl.NumberFormat`'s `style: 'unit'` — same approach `formatDistance`\n * already uses for `Intl.RelativeTimeFormat`. Numeric-only tokens\n * (`y`, `o`, `w`, ...) are not affected by `locale`; they remain ASCII\n * digits, matching the rest of this library's \"numbers stay Western\"\n * convention.\n *\n * @example\n * formatDuration(Temporal.Duration.from({ years: 2, months: 1 }), 'yyy ooo')\n * // \"2 years 1 month\"\n * formatDuration({ hours: 2, minutes: 30 }, 'hhh mmm', { locale: 'fr-FR' })\n * // \"2 heures 30 minutes\"\n */\nexport function formatDuration(\n duration: Record<string, unknown>,\n formatStr: string,\n options: DurationFormatOptions = {},\n): string {\n return renderDurationPieces(duration, formatStr, options).map((p) => p.value).join('');\n}\n\n// One rendered piece of a duration format string: either literal text or\n// a token with its already-rendered value (empty string for a\n// zero-suppressed token, matching formatDurationToParts' documented\n// contract of emitting an empty token part rather than dropping it).\nexport interface RenderedDurationPiece {\n kind: 'literal' | 'token';\n value: string;\n token?: string;\n}\n\n// Shared renderer behind both formatDuration() (joins the pieces) and\n// formatDurationToParts() (returns them). Single source of truth, so the\n// joined string and the parts can never disagree — the old\n// formatDurationToParts re-derived part boundaries by searching the\n// rendered string with indexOf and mis-sliced whenever a literal's text\n// also occurred inside an earlier token's rendered value.\nexport function renderDurationPieces(\n duration: Record<string, unknown>,\n formatStr: string,\n options: DurationFormatOptions = {},\n): RenderedDurationPiece[] {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: duration format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n\n const showZeroes = options.showZeroValues === true;\n // Undefined locale → keep the original hardcoded English path so\n // existing default output is byte-identical. Any locale string passed\n // (including 'en-US') takes the Intl.NumberFormat path — so an\n // explicit `locale: 'en-US'` will produce Intl's spacing/word choices\n // rather than the hand-rolled English table. That's intentional: the\n // locale-aware path delegates to Intl, the default path doesn't.\n const locale = options.locale;\n const useIntl = locale !== undefined;\n\n const pieces = tokenizeDuration(formatStr);\n const out: RenderedDurationPiece[] = [];\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n out.push({ kind: 'literal', value: piece.value });\n continue;\n }\n\n const unit = DURATION_UNITS[piece.unit];\n // Dead by construction: piece.unit always comes from match[0] where\n // match is a member of DURATION_TOKEN_STRINGS, itself built\n // exhaustively from DURATION_UNITS' own keys — so this lookup can\n // never miss. Kept in case tokenizeDuration's token construction\n // ever diverges from DURATION_UNITS.\n /* c8 ignore start */\n if (!unit) {\n throw new Error(`temporal-fmt: unknown duration token \"${piece.value}\"`);\n }\n /* c8 ignore stop */\n\n const value = readUnit(duration, unit.field);\n if (value === 0 && !showZeroes) {\n // Omit zero-value units entirely. The token's contribution to the\n // output is empty — but this can leave a dangling separator literal\n // (e.g. \"2 hours, \" with nothing after). Callers who want clean\n // output should structure their format string to not put a\n // separator after a unit that might be zero, or use showZeroValues.\n out.push({ kind: 'token', value: '', token: piece.value });\n continue;\n }\n\n if (piece.form === 'numeric') {\n out.push({ kind: 'token', value: String(value), token: piece.value });\n continue;\n }\n\n if (useIntl) {\n // Intl.NumberFormat handles pluralization, native unit names, and\n // locale-appropriate spacing all in one call — no point replicating\n // that here. We pass the value as-is so negative durations\n // (`-1 hour`) round-trip the sign the way Intl expects.\n const unitDisplay = piece.form === 'short' ? 'short' : 'long';\n const formatter = getUnitFormatter(locale!, unit.intlUnit, unitDisplay);\n out.push({ kind: 'token', value: formatter.format(value), token: piece.value });\n continue;\n }\n\n // Default-path English. Plural rule based on absolute value matches\n // what Intl does for unit style on en-US — only |value| === 1 is\n // singular, including for negatives like \"-1 hour\" (which is what\n // Intl produces for en-US too).\n if (piece.form === 'short') {\n out.push({ kind: 'token', value: value + (value === 1 || value === -1 ? unit.shortSingular : unit.shortPlural), token: piece.value });\n } else {\n out.push({ kind: 'token', value: value + ' ' + (value === 1 || value === -1 ? unit.longSingular : unit.longPlural), token: piece.value });\n }\n }\n\n return out;\n}","// Duration extensions. The existing formatDuration()\n// in formatDuration.ts stays as-is; this module adds the rest of the\n// duration surface: parseDuration, parseISODuration, formatISODuration,\n// formatDurationToParts, balanceDuration, roundDuration (re-exported\n// from rounding.ts), totalDuration, compareDuration, addDuration,\n// subtractDuration.\n//\n// All operate on plain field bags ({ years, months, weeks, days, hours,\n// minutes, seconds, milliseconds, microseconds, nanoseconds }) rather\n// than Temporal.Duration instances — same convention as the rest of\n// this module set, so callers can use these without committing to a\n// Temporal implementation. addDuration/subtractDuration produce a new\n// field bag; totalDuration produces a number; compareDuration produces\n// -1/0/1.\n\nimport { roundDuration, fieldToNs, type DurationFields } from './rounding.js';\nimport { formatDuration, renderDurationPieces } from './formatDuration.js';\nimport { InvalidDurationError, FormatSyntaxError } from './errors.js';\n\n// Re-export roundDuration here so callers can import everything duration-\n// related from one place.\nexport { roundDuration };\nexport type { DurationFields };\n\n// Mirrors formatToParts in format.ts. Returns the same piece list\n// formatDuration() would consume, but split into parts instead of\n// joined. Useful for callers building custom UIs (one DOM node per\n// unit) or doing their own unit suppression logic.\n\nimport type { Piece } from './tokenize.js';\n\nexport interface DurationPart {\n type: 'literal' | 'token';\n value: string;\n token?: string;\n}\n\n// Delegates to formatDuration()'s own piece renderer, so the joined\n// string and the parts can never disagree. (This used to re-tokenize the\n// format string and re-derive part boundaries by searching the rendered\n// string with indexOf — which mis-sliced whenever a literal's text also\n// occurred inside an earlier token's rendered value, e.g. a \"s\"\n// separator against \"5 seconds\".) Zero-suppressed tokens emit an empty\n// token part and their neighboring literals are kept, matching the\n// documented formatDurationToParts contract.\nexport function formatDurationToParts(\n duration: Record<string, unknown>,\n formatStr: string,\n options: Parameters<typeof formatDuration>[2] = {},\n): DurationPart[] {\n return renderDurationPieces(duration, formatStr, options).map((p) =>\n p.kind === 'token' ? { type: 'token' as const, value: p.value, token: p.token } : { type: 'literal' as const, value: p.value },\n );\n}\n\n// ISO 8601 duration format: P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S\n// e.g. \"P3Y6M4DT12H30M5S\", \"PT1H30M\", \"P1W\", \"P0D\".\n// Parsed into a DurationFields bag.\nexport function parseISODuration(input: string): DurationFields {\n // Loose grammar: P [years Y] [months M] [weeks W] [days D] [T [hours H] [minutes M] [seconds S]]\n // Weeks is an ISO 8601-2 extension; widely supported.\n const re = /^P(?:(?:(\\d+(?:\\.\\d+)?)Y)?(?:(\\d+(?:\\.\\d+)?)M)?(?:(\\d+(?:\\.\\d+)?)W)?(?:(\\d+(?:\\.\\d+)?)D)?)?(?:T(?:(\\d+(?:\\.\\d+)?)H)?(?:(\\d+(?:\\.\\d+)?)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/;\n const m = re.exec(input);\n if (!m) {\n throw new InvalidDurationError({ input, reason: 'does not match ISO 8601 duration grammar (P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S)' });\n }\n // All-zero / empty: P0D is valid ISO for zero duration.\n if (m.slice(1).every((g) => g === undefined)) {\n throw new InvalidDurationError({ input, reason: 'duration has no fields (use \"P0D\" for zero duration)' });\n }\n const toNum = (s: string | undefined): number => s === undefined ? 0 : Number(s);\n return {\n years: toNum(m[1]),\n months: toNum(m[2]),\n weeks: toNum(m[3]),\n days: toNum(m[4]),\n hours: toNum(m[5]),\n minutes: toNum(m[6]),\n seconds: toNum(m[7]),\n };\n}\n\nexport function formatISODuration(duration: DurationFields): string {\n const parts: string[] = ['P'];\n const years = duration.years ?? 0;\n const months = duration.months ?? 0;\n const weeks = duration.weeks ?? 0;\n const days = duration.days ?? 0;\n const hours = duration.hours ?? 0;\n const minutes = duration.minutes ?? 0;\n const seconds = duration.seconds ?? 0;\n if (years) parts.push(`${years}Y`);\n if (months) parts.push(`${months}M`);\n if (weeks) parts.push(`${weeks}W`);\n if (days) parts.push(`${days}D`);\n if (hours || minutes || seconds) {\n parts.push('T');\n if (hours) parts.push(`${hours}H`);\n if (minutes) parts.push(`${minutes}M`);\n if (seconds) parts.push(`${seconds}S`);\n }\n // parts is just ['P'] when every field is zero -- ISO has no empty\n // duration, so fall back to P0D.\n if (parts.length === 1) parts.push('0D');\n return parts.join('');\n}\n\n// Minimal tokenizer for the duration format string. Reuses the same\n// quoted-literal and greedy-match logic as tokenize.ts.\nfunction tokenizeDurationFormat(formatStr: string): Array<Piece & { unit?: string }> {\n const DURATION_TOKEN_STRINGS = ['y', 'o', 'w', 'd', 'h', 'm', 's', 'S']\n .flatMap((single) => [single + single + single, single + single, single])\n .sort((a, b) => b.length - a.length);\n const pieces: Array<Piece & { unit?: string }> = [];\n let i = 0;\n while (i < formatStr.length) {\n const ch = formatStr[i];\n if (ch === \"'\") {\n if (formatStr[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < formatStr.length) {\n if (formatStr[j] === \"'\") {\n if (formatStr[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += formatStr[j]!;\n j += 1;\n }\n if (!closed) throw new FormatSyntaxError({ format: formatStr, reason: 'unterminated quote' });\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n const match = DURATION_TOKEN_STRINGS.find((tok) => formatStr.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match, unit: match[0] });\n i += match.length;\n continue;\n }\n appendLiteral(pieces, ch);\n i += 1;\n }\n return pieces;\n}\n\nfunction appendLiteral(pieces: Array<Piece & { unit?: string }>, 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\nfunction findNextLiteralStart(\n tokens: Array<Piece & { unit?: string }>,\n _currentTok: Piece & { unit?: string },\n full: string,\n pos: number,\n): number {\n // Find the position in `full` where the next literal after the\n // current token starts. For now, just return the end of `full` —\n // formatDurationToParts is best-effort for the common case where\n // tokens are separated by literals, and degrades gracefully when\n // they aren't.\n // A more precise implementation would walk the tokens array from\n // the current position and use the next literal piece's text to\n // find the boundary in `full`. Doing it correctly requires handling\n // zero-value unit suppression, which is why this helper exists.\n // For now, we use the next literal piece's value as a search anchor.\n const idx = tokens.indexOf(_currentTok);\n for (let j = idx + 1; j < tokens.length; j++) {\n const t = tokens[j]!;\n if (t.kind === 'literal') {\n const found = full.indexOf(t.value, pos);\n if (found >= 0) return found;\n }\n }\n return full.length;\n}\n\n// ISO 8601 duration format: P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S\n// Parses a duration-format string (the tokenized format formatDuration\n// accepts) into a DurationFields bag. Inverse of formatDuration().\nexport function parseDuration(input: string, formatStr: string, options: { locale?: string } = {}): DurationFields {\n // Build a capturing regex from the format string. Each token\n // captures a number; literals are matched literally.\n const tokens = tokenizeDurationFormat(formatStr);\n const fields: DurationFields = {};\n const groupSpecs: Array<{ unit: keyof DurationFields; form: 'numeric' | 'short' | 'long' }> = [];\n let regex = '';\n for (const tok of tokens) {\n if (tok.kind === 'literal') {\n regex += tok.value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n } else {\n const unit = tok.unit!;\n const form = tok.value.length === 1 ? 'numeric' : tok.value.length === 2 ? 'short' : 'long';\n // Map token letter to DurationFields key.\n /* c8 ignore start @preserve -- the final `: null` branch, and the\n `if (key === null)` throw it feeds, are both unreachable: tok.unit\n is always one of the 8 letters in DURATION_TOKEN_STRINGS (the same\n source set this ternary checks against), so `null` can't be\n produced by any token the tokenizer emits. Kept as a guard against\n a future letter being added to one set without the other. */\n const key: keyof DurationFields | null = (\n unit === 'y' ? 'years'\n : unit === 'o' ? 'months'\n : unit === 'w' ? 'weeks'\n : unit === 'd' ? 'days'\n : unit === 'h' ? 'hours'\n : unit === 'm' ? 'minutes'\n : unit === 's' ? 'seconds'\n : unit === 'S' ? 'milliseconds'\n : null\n );\n if (key === null) {\n throw new FormatSyntaxError({ format: formatStr, token: tok.value, reason: 'unknown duration token' });\n }\n /* c8 ignore stop @preserve */\n // Numeric form: capture digits (and optional sign).\n // Short/long form: capture digits followed by optional unit text.\n // We'll handle unit-text stripping after the match.\n if (form === 'numeric') {\n regex += '(-?\\\\d+)';\n } else {\n // Short form like \"2y\" or \"2yrs\"; long form like \"2 years\" or \"2 year\".\n // Capture the number; unit text is matched but not captured.\n regex += '(\\\\d+)\\\\s*\\\\w*';\n }\n groupSpecs.push({ unit: key, form });\n }\n }\n const re = new RegExp(`^${regex}$`, 'u');\n const m = re.exec(input);\n if (!m) {\n throw new FormatSyntaxError({ input, format: formatStr, reason: 'does not match duration format' });\n }\n groupSpecs.forEach((spec, i) => {\n const raw = m[i + 1]!;\n const value = Number(raw);\n if (!Number.isFinite(value)) {\n throw new InvalidDurationError({ input, reason: `token for ${spec.unit} matched \"${raw}\" but isn't a finite number` });\n }\n fields[spec.unit] = value;\n });\n return fields;\n}\n\n// Balances a duration's absolute fields (days/hours/minutes/seconds/ms/µs/ns)\n// so each carries its natural range and excess carries into the next\n// larger unit. Doesn't touch calendar-bound fields (years/months/weeks)\n// since those need a relativeTo to balance correctly.\nexport function balanceDuration(duration: DurationFields): DurationFields {\n const NS_PER: Array<[keyof DurationFields, bigint]> = [\n ['days', 86_400n * 1_000_000_000n],\n ['hours', 3_600n * 1_000_000_000n],\n ['minutes', 60n * 1_000_000_000n],\n ['seconds', 1_000_000_000n],\n ['milliseconds', 1_000_000n],\n ['microseconds', 1_000n],\n ['nanoseconds', 1n],\n ];\n // Sum everything from days down to ns.\n let totalNs = 0n;\n for (const [k, nsPer] of NS_PER) {\n const v = duration[k];\n if (typeof v === 'number') totalNs += fieldToNs(v, nsPer, k);\n }\n // Re-distribute.\n const result: DurationFields = { ...duration };\n let remaining = totalNs;\n for (const [k, nsPer] of NS_PER) {\n const count = remaining / nsPer;\n remaining -= count * nsPer;\n result[k] = Number(count);\n }\n return result;\n}\n\n// Sums all absolute fields into a single number expressed in the\n// requested unit. Throws for calendar-bound target units (years/months/\n// weeks) since those need a relativeTo.\nexport function totalDuration(duration: DurationFields, unit: 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' | 'microseconds' | 'nanoseconds'): number {\n const NS_PER: Record<string, bigint> = {\n days: 86_400n * 1_000_000_000n,\n hours: 3_600n * 1_000_000_000n,\n minutes: 60n * 1_000_000_000n,\n seconds: 1_000_000_000n,\n milliseconds: 1_000_000n,\n microseconds: 1_000n,\n nanoseconds: 1n,\n };\n let totalNs = 0n;\n for (const k of Object.keys(NS_PER) as Array<keyof typeof NS_PER>) {\n const v = duration[k as keyof DurationFields];\n if (typeof v === 'number') totalNs += fieldToNs(v, NS_PER[k]!, k);\n }\n const divisor = NS_PER[unit];\n if (!divisor) {\n throw new InvalidDurationError({ reason: `totalDuration() does not support unit \"${unit}\" (calendar-bound units need a relativeTo)` });\n }\n return Number(totalNs) / Number(divisor);\n}\n\n// Compares two durations by their total absolute length. Returns -1/0/1.\nexport function compareDuration(a: DurationFields, b: DurationFields): number {\n const aNs = totalDurationNs(a);\n const bNs = totalDurationNs(b);\n if (aNs < bNs) return -1;\n if (aNs > bNs) return 1;\n return 0;\n}\n\nfunction totalDurationNs(d: DurationFields): bigint {\n const NS_PER: Record<string, bigint> = {\n days: 86_400n * 1_000_000_000n,\n hours: 3_600n * 1_000_000_000n,\n minutes: 60n * 1_000_000_000n,\n seconds: 1_000_000_000n,\n milliseconds: 1_000_000n,\n microseconds: 1_000n,\n nanoseconds: 1n,\n };\n let total = 0n;\n for (const k of Object.keys(NS_PER)) {\n const v = d[k as keyof DurationFields];\n if (typeof v === 'number') total += fieldToNs(v, NS_PER[k]!, k);\n }\n return total;\n}\n\n// Adds two durations field-by-field. Doesn't balance — call\n// balanceDuration() afterwards if you want a balanced result.\nexport function addDuration(a: DurationFields, b: DurationFields): DurationFields {\n const keys: Array<keyof DurationFields> = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'];\n const result: DurationFields = {};\n for (const k of keys) {\n result[k] = (a[k] ?? 0) + (b[k] ?? 0);\n }\n return result;\n}\n\nexport function subtractDuration(a: DurationFields, b: DurationFields): DurationFields {\n return addDuration(a, negateDuration(b));\n}\n\nfunction negateDuration(d: DurationFields): DurationFields {\n const result: DurationFields = {};\n for (const k of Object.keys(d) as Array<keyof DurationFields>) {\n result[k] = -(d[k] ?? 0);\n }\n return result;\n}\n"],"mappings":"4GAmBA,IAAMA,EAA4C,CAChD,IAAK,MACL,KAAM,KACN,OAAQ,IACR,OAAQ,IACR,YAAa,CACf,EAEA,SAASC,EAAUC,EAAYC,EAAoBC,EAA2B,CAK5E,IAAMC,EAAOH,EAAK,EAAI,GAAK,EAErBI,EADM,KAAK,IAAIJ,CAAE,EACDE,EAClBG,EACJ,OAAQJ,EAAM,CACZ,IAAK,UAAWI,EAAU,KAAK,MAAMD,CAAO,EAAG,MAC/C,IAAK,QAASC,EAAU,KAAK,MAAMD,CAAO,EAAG,MAC7C,IAAK,OAAQC,EAAU,KAAK,KAAKD,CAAO,EAAG,MAC3C,IAAK,QAASC,EAAU,KAAK,MAAMD,CAAO,EAAG,KAC/C,CACA,OAAOD,EAAOE,EAAUH,CAC1B,CAEA,SAASI,EAAKC,EAA8B,CAI1C,IAAMC,EAAID,EAAE,KAAOE,EAAIF,EAAE,MAAQG,EAAIH,EAAE,IACjCI,EAAKF,GAAK,EAAID,EAAI,EAAIA,EACtBI,EAAM,KAAK,OAAOD,GAAM,EAAIA,EAAKA,EAAK,KAAO,GAAG,EAChDE,EAAMF,EAAKC,EAAM,IACjBE,EAAKL,EAAI,EAAIA,EAAI,EAAIA,EAAI,EACzBM,EAAM,KAAK,OAAO,IAAMD,EAAK,GAAK,CAAC,EAAIJ,EAAI,EAC3CM,EAAMH,EAAM,IAAM,KAAK,MAAMA,EAAM,CAAC,EAAI,KAAK,MAAMA,EAAM,GAAG,EAAIE,EAEtE,OADaH,EAAM,OAASI,EAAM,QACpBlB,EAAY,KACrBS,EAAE,MAAQ,GAAKT,EAAY,MAC3BS,EAAE,QAAU,GAAKT,EAAY,QAC7BS,EAAE,QAAU,GAAKT,EAAY,QAC7BS,EAAE,aAAe,EACxB,CAEA,SAASU,EAAOjB,EAAYkB,EAA4C,CAGtE,IAAMC,EAAar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","era","yoe","m2","doy","doe","fromMs","base","MS_PER_DAY","totalDays","withinDay","hour","minute","second","millisecond","z","mp","year","round","value","options","base","asDateFieldView","mode","increment","MS_PER_UNIT","ms","toMs","rounded","applyMode","fromMs","floor","unit","roundingIncrement","ceil","truncate","fieldToNs","v","nsPer","field","scaled","InvalidDurationError","DURATION_UNIT_TO_NS","isCalendarBound","roundDuration","duration","totalNs","u","stepNs","sign","abs","stepped","remainder","newTotalNs","result","remaining","unitsInOrder","startIdx","i","unitNs","count","DURATION_UNITS","DURATION_TOKEN_STRINGS","single","a","b","tokenizeDuration","format","pieces","i","ch","appendLiteral","j","literal","closed","match","tok","unit","form","value","last","readUnit","duration","field","coerced","unitFormatterCache","MAX_UNIT_FORMATTER_CACHE_SIZE","getUnitFormatter","locale","intlUnit","unitDisplay","key","canonicalCacheKey","cached","oldestKey","formatter","normalizeLocaleTag","err","InvalidLocaleError","formatDuration","formatStr","options","renderDurationPieces","p","showZeroes","useIntl","out","piece","formatDurationToParts","duration","formatStr","options","renderDurationPieces","p","parseISODuration","input","m","InvalidDurationError","g","toNum","s","formatISODuration","parts","years","months","weeks","days","hours","minutes","seconds","tokenizeDurationFormat","DURATION_TOKEN_STRINGS","single","a","b","pieces","i","ch","appendLiteral","j","literal","closed","FormatSyntaxError","match","tok","value","last","parseDuration","input","formatStr","options","tokens","tokenizeDurationFormat","fields","groupSpecs","regex","tok","unit","form","key","FormatSyntaxError","m","spec","i","raw","value","InvalidDurationError","balanceDuration","duration","NS_PER","totalNs","k","nsPer","v","fieldToNs","result","remaining","count","totalDuration","divisor","compareDuration","a","b","aNs","totalDurationNs","bNs","d","total","addDuration","keys","subtractDuration","negateDuration"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as v,e as c}from"./chunk-
|
|
1
|
+
import{a as v,e as c}from"./chunk-R52YOKI3.js";import{a as f,b as k}from"./chunk-C5YESWFT.js";import{b as r,c as u}from"./chunk-5U5WJ465.js";var d=new Map(k.map(([t,n,i])=>[t,{fn:n,field:i}])),p=new Map,w=500;function h(t){let n=p.get(t);if(n)return n;if(p.size>=w){let i=p.keys().next().value;i!==void 0&&p.delete(i)}return n=v(t),p.set(t,n),n}function $(t,n,i={}){if(n.length>1e3)throw new r({format:n,message:`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${n.length}).`});let l=i.locale??f,s=h(n),o="";for(let e of s){if(e.kind==="literal"){o+=e.value;continue}let a=d.get(e.value);/* c8 ignore start @preserve -- unreachable: tokenize() only ever emits
|
|
2
2
|
tokens present in TOKENS, and HANDLER_BY_TOKEN is built from that
|
|
3
3
|
same list, so every token piece.value can hold already has an entry
|
|
4
4
|
here. Same defensive-guard category as the twin checks in
|
|
@@ -8,4 +8,4 @@ import{a as v,e as c}from"./chunk-M5WL5VGW.js";import{a as f,b as k}from"./chunk
|
|
|
8
8
|
two 'literal' pieces never sit back-to-back in the array this
|
|
9
9
|
loop walks. Kept as defense-in-depth in case that invariant ever
|
|
10
10
|
changes upstream. */if(m&&m.type==="literal")m.value+=e.value;else{/* c8 ignore stop @preserve */o.push({type:"literal",value:e.value})}continue}let a=d.get(e.value);/* c8 ignore start @preserve -- unreachable, see the note in format() above */if(!a)throw new u({token:e.value,format:n,message:`temporal-fmt: unknown token "${e.value}"`});/* c8 ignore stop @preserve */if(t[a.field]===void 0)throw new r({format:n,token:e.value,message:`temporal-fmt: token "${e.value}" requires "${a.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`});o.push({type:"token",value:c(a.fn(t,l),i),token:e.value})}return o}function L(t){if(t.length>1e3)throw new r({format:t,message:`temporal-fmt: format string exceeds maximum length of ${1e3} characters (got ${t.length}).`});let n=h(t);return{formatStr:t,pieces:n,format(i,l={}){let s=l.locale??f,o="";for(let e of n){if(e.kind==="literal"){o+=e.value;continue}let a=d.get(e.value);if(!a)throw new u({token:e.value,format:t,message:`temporal-fmt: unknown token "${e.value}"`});if(i[a.field]===void 0)throw new r({format:t,token:e.value,message:`temporal-fmt: token "${e.value}" requires "${a.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`});o+=a.fn(i,s)}return c(o,l)},formatToParts(i,l={}){let s=l.locale??f,o=[];for(let e of n){if(e.kind==="literal"){let m=o[o.length-1];m&&m.type==="literal"?m.value+=e.value:o.push({type:"literal",value:e.value});continue}let a=d.get(e.value);if(!a)throw new u({token:e.value,format:t,message:`temporal-fmt: unknown token "${e.value}"`});if(i[a.field]===void 0)throw new r({format:t,token:e.value,message:`temporal-fmt: token "${e.value}" requires "${a.field}", which this Temporal object doesn't have. (e.g. PlainDate has no time fields, PlainTime has no date fields)`});o.push({type:"token",value:c(a.fn(i,s),l),token:e.value})}return o}}}function N(t){return h(t)}function O(t){return d.get(t)}export{$ as a,x as b,L as c,N as d,O as e};
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
11
|
+
//# sourceMappingURL=chunk-4JWGUR4O.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=class extends Error{code;input;format;token;position;expected;actual;reason;constructor(e,t){super(e),this.name="TemporalFmtError",this.code=t.code,this.input=t.input,this.format=t.format,this.token=t.token,this.position=t.position,this.expected=t.expected,this.actual=t.actual,this.reason=t.reason;let o=Error.captureStackTrace;typeof o=="function"&&o(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,input:this.input,format:this.format,token:this.token,position:this.position,expected:this.expected,actual:this.actual,reason:this.reason}}},T=class extends s{constructor(e){let{message:t,...o}=e;super(t??`format string "${e.format??""}" has a syntax error${e.reason?`: ${e.reason}`:""}.`,{code:"FORMAT_SYNTAX_ERROR",...o}),this.name="FormatSyntaxError"}},$=class extends s{constructor(e){let{message:t,...o}=e;super(t??`token "${e.token??""}" is not a recognized temporal-fmt token${e.format?` in format string "${e.format}"`:""}.`,{code:"UNKNOWN_TOKEN",...o}),this.name="UnknownTokenError"}},w=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" does not match format "${e.format??""}"${e.reason?`: ${e.reason}`:""}.`,{code:"PARSE_MISMATCH",...o}),this.name="ParseMismatchError"}},k=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" does not describe a valid date${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_DATE",...o}),this.name="InvalidDateError"}};/* c8 ignore start @preserve -- InvalidTimeError is part of the public
|
|
2
2
|
error-class surface (exported from index.ts, code 'INVALID_TIME')
|
|
3
3
|
but nothing in this package constructs one. Investigated wiring it
|
|
4
4
|
in the same way InvalidTimeZoneError was just wired (see parse.ts's
|
|
@@ -10,7 +10,7 @@ var i=class extends Error{code;input;format;token;position;expected;actual;reaso
|
|
|
10
10
|
is rejected as a plain shape mismatch before any semantic check
|
|
11
11
|
could run. There's no live gap to hook this into without inventing a
|
|
12
12
|
redundant check purely to give this class a body. Left unconstructed
|
|
13
|
-
until the library actually has a real invalid-time case to report. */var
|
|
13
|
+
until the library actually has a real invalid-time case to report. */var _=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" does not describe a valid time${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_TIME",...o}),this.name="InvalidTimeError"}};/* c8 ignore stop @preserve */var A=class extends s{constructor(e){let{message:t,...o}=e;super(t??`offset "${e.actual??""}" is invalid${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_OFFSET",...o}),this.name="InvalidOffsetError"}},b=class extends s{constructor(e){let{message:t,...o}=e;super(t??`time zone "${e.actual??""}" is not a recognized IANA time zone or fixed offset${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_TIME_ZONE",...o}),this.name="InvalidTimeZoneError"}};/* c8 ignore start @preserve -- InvalidCalendarError is part of the
|
|
14
14
|
public error-class surface (exported from index.ts, code
|
|
15
15
|
'INVALID_CALENDAR') but nothing in this package constructs one.
|
|
16
16
|
Checked for a wiring opportunity the same way InvalidTimeZoneError
|
|
@@ -20,8 +20,8 @@ var i=class extends Error{code;input;format;token;position;expected;actual;reaso
|
|
|
20
20
|
of the locale string — it's never handed an arbitrary "calendar"
|
|
21
21
|
value a caller could get wrong. There's no live input to reject.
|
|
22
22
|
Left unconstructed until the library actually accepts a calendar
|
|
23
|
-
parameter that could be invalid. */var
|
|
24
|
-
see rationale above */function
|
|
23
|
+
parameter that could be invalid. */var M=class extends s{constructor(e){let{message:t,...o}=e;super(t??`calendar "${e.actual??""}" is not supported${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_CALENDAR",...o}),this.name="InvalidCalendarError"}};/* c8 ignore stop @preserve */var I=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" is ambiguous${e.reason?`: ${e.reason}`:""}.`,{code:"AMBIGUOUS_INPUT",...o}),this.name="AmbiguousInputError"}},u=class extends s{constructor(e){let{message:t,...o}=e;super(t??`locale "${e.actual??""}" is not a valid BCP-47 tag${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_LOCALE",...o}),this.name="InvalidLocaleError"}},C=class extends s{constructor(e){let{message:t,...o}=e;super(t??`duration is invalid${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_DURATION",...o}),this.name="InvalidDurationError"}};/* c8 ignore start @preserve -- unreachable from the current test suite,
|
|
24
|
+
see rationale above */function H(r,e){let t=r.message;if(/unknown token|isn't a recognized token/.test(t))return new $({input:e.input,format:e.format,reason:t});if(/ambiguous/i.test(t))return new I({input:e.input,format:e.format,reason:t});if(/offset/.test(t)&&/out of range|exceeds|doesn't match the shape/i.test(t))return new A({input:e.input,format:e.format,reason:t});if(/no valid pattern matches/i.test(t))return new w({input:e.input,format:e.format,reason:t});if(/doesn't describe a valid date\/time|incomplete date|weekday token|quarter token/.test(t))return new k({input:e.input,format:e.format,reason:t});let o=t.toLowerCase();return o.includes("locale")&&(o.includes("produced no")||o.includes("not a valid"))||o.includes("cutoffs must be")?new u({input:e.input,format:e.format,reason:t}):/format string exceeds maximum length|input exceeds maximum length|unterminated quote|isn't a recognized token/i.test(t)?new T({input:e.input,format:e.format,reason:t}):new w({input:e.input,format:e.format,reason:t})}/* c8 ignore stop @preserve */var y=new Map,N=500,D=256,O=256;function Z(r,e){let t=[{key:"monthLong",length:12,label:"long month names"},{key:"monthShort",length:12,label:"short month names"},{key:"weekdayLong",length:7,label:"long weekday names"},{key:"weekdayShort",length:7,label:"short weekday names"},{key:"dayPeriod",length:2,label:"day period markers (AM/PM-equivalent)"}];for(let{key:o,length:n,label:a}of t){let i=r[o];if(i===void 0)throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}" is missing required field "${o}" (${a}).`);if(!Array.isArray(i))throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}" must be an array, got ${typeof i}.`);if(i.length!==n)throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}" must have exactly ${n} entries (got ${i.length}) \u2014 ${a}.`);i.forEach((m,g)=>{if(typeof m!="string"||m.length===0)throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}[${g}]" must be a non-empty string, got ${String(m)}.`);if(m.length>O)throw new RangeError(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}[${g}]" is too long (maximum ${O} characters).`)})}if(d(r.monthLong,"MMMM month",e),d(r.monthShort,"MMM month",e),d(r.weekdayLong,"EEEE weekday",e),d(r.weekdayShort,"EEE weekday",e),r.dayPeriod[0]===r.dayPeriod[1])throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": dayPeriod entries must differ (both are "${r.dayPeriod[0]}"); otherwise parse() can't tell AM from PM.`)}var S=[];function W(r){S.push(r)}function J(r,e){if(typeof r!="string"||r.length===0)throw new Error(`temporal-fmt: registerLocaleVocab requires a non-empty locale string, got ${String(r)}.`);if(r.length>D)throw new RangeError(`temporal-fmt: registerLocaleVocab locale is too long (maximum ${D} characters).`);Z(e,r);let t=F(r);if(!y.has(t)&&y.size>=N)throw new RangeError(`temporal-fmt: registerLocaleVocab reached the ${N}-locale limit.`);y.set(t,{monthLong:[...e.monthLong],monthShort:[...e.monthShort],weekdayLong:[...e.weekdayLong],weekdayShort:[...e.weekdayShort],dayPeriod:[...e.dayPeriod]}),p.delete(t);for(let o of S)o()}function P(r){return r.replace(/_/g,"-")}var f=new Map,B=500;function F(r){let e=f.get(r);if(e!==void 0)return e;let t;try{t=new Intl.Locale(r.replace(/_/g,"-")).toString().toLowerCase()}catch{t=r}if(f.size>=B){let o=f.keys().next().value;o!==void 0&&f.delete(o)}return f.set(r,t),t}function X(r){try{new Intl.Locale(P(r))}catch{throw new u({actual:r,reason:"not a valid BCP-47 locale tag"})}}var p=new Map,q=500;function l(r,e,t){let o=r.formatToParts(e),n=o.findIndex(g=>g.type===t);/* c8 ignore start @preserve -- defensive guard against a real but
|
|
25
25
|
unreproducible failure mode: an Intl implementation that omits the
|
|
26
26
|
requested part type entirely for some locale. Checked every locale
|
|
27
27
|
with unusual dayPeriod/weekday/month rendering available in this
|
|
@@ -32,5 +32,5 @@ var i=class extends Error{code;input;format;token;position;expected;actual;reaso
|
|
|
32
32
|
produced a false "gap" during investigation). None omit their part
|
|
33
33
|
on this runtime. A different ICU version or a non-Node Intl
|
|
34
34
|
implementation could plausibly behave differently, so this stays a
|
|
35
|
-
real check rather than an assertion. *//* c8 ignore start @preserve */if(n===-1)throw new
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
35
|
+
real check rather than an assertion. *//* c8 ignore start @preserve */if(n===-1)throw new u({message:`temporal-fmt: locale produced no "${t}" part while building match vocabulary.`});/* c8 ignore stop @preserve */let a=o[n].value,i=o[n-1],m=o[n+1];return i?.type==="literal"&&!/\s/.test(i.value)&&(a=i.value+a),m?.type==="literal"&&!/\s/.test(m.value)&&(a=a+m.value),a}function d(r,e,t){let o=new Map;for(let n=0;n<r.length;n++){let a=o.get(r[n]);if(a!==void 0)throw new Error(`temporal-fmt: locale "${t}" renders ${e} index ${a} and ${n} identically ("${r[n]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);o.set(r[n],n)}}function j(r){let e=F(r);return y.get(e)}function Q(r){X(r);let e=F(r),t=y.get(e);if(t)return t;let o=p.get(e);if(o)return o;let n=P(r),a=new Intl.DateTimeFormat(n,{month:"long",timeZone:"UTC"}),i=new Intl.DateTimeFormat(n,{month:"short",timeZone:"UTC"}),m=[],g=[];for(let c=0;c<12;c++){let h=new Date(Date.UTC(2020,c,1));m.push(l(a,h,"month")),g.push(l(i,h,"month"))}d(m,"MMMM month",r),d(g,"MMM month",r);let v=new Intl.DateTimeFormat(n,{weekday:"long",timeZone:"UTC"}),U=new Intl.DateTimeFormat(n,{weekday:"short",timeZone:"UTC"}),E=[],L=[];for(let c=0;c<7;c++){let h=new Date(Date.UTC(2024,0,1+c));E.push(l(v,h,"weekday")),L.push(l(U,h,"weekday"))}d(E,"EEEE weekday",r),d(L,"EEE weekday",r);let V=new Intl.DateTimeFormat(n,{hour:"numeric",hour12:!0,timeZone:"UTC"}),R=l(V,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),K=l(V,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),z=[...new Set([R,K])],x={monthLong:m,monthShort:g,weekdayLong:E,weekdayShort:L,dayPeriod:z};if(p.size>=q){let c=p.keys().next().value;c!==void 0&&p.delete(c)}return p.set(e,x),x}export{s as a,T as b,$ as c,w as d,k as e,_ as f,A as g,b as h,M as i,I as j,u as k,C as l,H as m,W as n,J as o,P as p,F as q,X as r,j as s,Q as t};
|
|
36
|
+
//# sourceMappingURL=chunk-5U5WJ465.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/localeVocab.ts"],"sourcesContent":["// Structured error classes for parse()/format() failures.\n//\n// As of 0.9.0, every throw site on the parse/format data path —\n// tokenize.ts, pattern.ts, format.ts, parse.ts (parse/safeParse/tryParse/\n// parseToParts/compileParser), and the two data-path throws in\n// localeVocab.ts (partValue/assertNoCollision on the getLocaleVocab side)\n// — throws these typed classes directly instead of plain\n// `new Error(message)`. Every migrated site kept its exact pre-0.9.0\n// message text — subclasses of TemporalFmtError still satisfy\n// `instanceof Error` and message-matching regexes (e.g.\n// `/token \"HH\" requires/`), so this was safe to do without a semver-major\n// bump for either check. What *is* a breaking change for 0.9.0: code that\n// specifically checked `err.constructor === Error` or `err.name ===\n// 'Error'` will see a different name now (e.g. 'FormatSyntaxError'). See\n// the 0.9.0 changelog entry.\n//\n// Not migrated, on purpose:\n// - localeVocab.ts's registration-time throws (assertValidVocab,\n// registerLocaleVocab itself) — these are config-time API-misuse\n// errors on data the developer supplies once at startup, not runtime\n// parse/format failures, so they don't fit this module's\n// TemporalFmtErrorCode taxonomy as-is. assertNoCollision is shared\n// between the registration path and the data path (getLocaleVocab), so\n// its throw stays plain `Error` for both until that split is done —\n// see the tracking note at its call site.\n//\n// wrapUntypedError() below still exists for localeVocab.ts's registration\n// throws and for anything a caller passes into safeParse()/tryParse() from\n// outside this package. On the data path, safeParse's `if (err instanceof\n// TemporalFmtError) return { ok: false, error: err }` now catches every\n// throw before it would reach the classifier, so the regex branches here\n// are effectively dead for parse/format/tokenize/pattern — left in place\n// as the fallback for anything not yet on a typed throw site.\n\nexport type TemporalFmtErrorCode =\n | 'FORMAT_SYNTAX_ERROR'\n | 'UNKNOWN_TOKEN'\n | 'PARSE_MISMATCH'\n | 'INVALID_DATE'\n | 'INVALID_TIME'\n | 'INVALID_OFFSET'\n | 'INVALID_TIME_ZONE'\n | 'INVALID_CALENDAR'\n | 'AMBIGUOUS_INPUT'\n | 'INVALID_LOCALE'\n | 'INVALID_DURATION';\n\nexport interface TemporalFmtErrorFields {\n code: TemporalFmtErrorCode;\n input?: string;\n format?: string;\n token?: string;\n position?: number;\n expected?: string;\n actual?: string;\n reason?: string;\n}\n\n// Base class. `message` is the human-readable summary; the structured\n// fields are the machine-readable parts a linter or codemod reports on.\n// `Error.captureStackTrace` is called manually (where available) so\n// the stack points at the call site, not at this constructor — same\n// pattern Node uses for its own error classes.\nexport class TemporalFmtError extends Error {\n readonly code: TemporalFmtErrorCode;\n readonly input?: string;\n readonly format?: string;\n readonly token?: string;\n readonly position?: number;\n readonly expected?: string;\n readonly actual?: string;\n readonly reason?: string;\n\n constructor(message: string, fields: TemporalFmtErrorFields) {\n super(message);\n this.name = 'TemporalFmtError';\n this.code = fields.code;\n this.input = fields.input;\n this.format = fields.format;\n this.token = fields.token;\n this.position = fields.position;\n this.expected = fields.expected;\n this.actual = fields.actual;\n this.reason = fields.reason;\n // Avoid setting the stack to point at this constructor — keeps it\n // useful. captureStackTrace is V8-only; on other engines the\n // default stack (this constructor line) is what callers get.\n const capture = (Error as unknown as { captureStackTrace?: (target: Error, ctor?: Function) => void }).captureStackTrace;\n if (typeof capture === 'function') {\n capture(this, this.constructor);\n }\n }\n\n // Lets callers do `err.toJSON()` for logging. Plain `Error` doesn't\n // serialize its non-enumerable fields; this picks them up explicitly.\n toJSON(): TemporalFmtErrorFields & { name: string; message: string } {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n input: this.input,\n format: this.format,\n token: this.token,\n position: this.position,\n expected: this.expected,\n actual: this.actual,\n reason: this.reason,\n };\n }\n}\n\n// Each subclass fixes `code` so callers can switch on it without\n// re-checking message text. The constructor takes only the fields\n// that vary per call; `code` and a default `message` template are\n// provided by the subclass.\n\nexport class FormatSyntaxError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `format string \"${fields.format ?? ''}\" has a syntax error${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'FORMAT_SYNTAX_ERROR', ...rest },\n );\n this.name = 'FormatSyntaxError';\n }\n}\n\nexport class UnknownTokenError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `token \"${fields.token ?? ''}\" is not a recognized temporal-fmt token${fields.format ? ` in format string \"${fields.format}\"` : ''}.`,\n { code: 'UNKNOWN_TOKEN', ...rest },\n );\n this.name = 'UnknownTokenError';\n }\n}\n\nexport class ParseMismatchError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" does not match format \"${fields.format ?? ''}\"${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'PARSE_MISMATCH', ...rest },\n );\n this.name = 'ParseMismatchError';\n }\n}\n\nexport class InvalidDateError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" does not describe a valid date${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_DATE', ...rest },\n );\n this.name = 'InvalidDateError';\n }\n}\n\n/* c8 ignore start @preserve -- InvalidTimeError is part of the public\n error-class surface (exported from index.ts, code 'INVALID_TIME')\n but nothing in this package constructs one. Investigated wiring it\n in the same way InvalidTimeZoneError was just wired (see parse.ts's\n zzz-validation loop): checked whether hour/minute/second have a\n post-match semantic range check the way zone ids do. They don't —\n pattern.ts's regex fragments for HH/H/hh/h/mm/m/ss/s already enforce\n their valid ranges at the regex level (e.g. HH is '(?:[01]\\d|2[0-3])',\n which can't match \"99\" in the first place), so an out-of-range time\n is rejected as a plain shape mismatch before any semantic check\n could run. There's no live gap to hook this into without inventing a\n redundant check purely to give this class a body. Left unconstructed\n until the library actually has a real invalid-time case to report. */\nexport class InvalidTimeError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" does not describe a valid time${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_TIME', ...rest },\n );\n this.name = 'InvalidTimeError';\n }\n}\n/* c8 ignore stop @preserve */\n\nexport class InvalidOffsetError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `offset \"${fields.actual ?? ''}\" is invalid${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_OFFSET', ...rest },\n );\n this.name = 'InvalidOffsetError';\n }\n}\n\nexport class InvalidTimeZoneError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `time zone \"${fields.actual ?? ''}\" is not a recognized IANA time zone or fixed offset${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_TIME_ZONE', ...rest },\n );\n this.name = 'InvalidTimeZoneError';\n }\n}\n\n/* c8 ignore start @preserve -- InvalidCalendarError is part of the\n public error-class surface (exported from index.ts, code\n 'INVALID_CALENDAR') but nothing in this package constructs one.\n Checked for a wiring opportunity the same way InvalidTimeZoneError\n got one: there's no user-supplied calendar identifier anywhere in\n the library to validate against a supported list. resolveCalendar()\n in parse.ts derives the calendar entirely from Intl's own resolution\n of the locale string — it's never handed an arbitrary \"calendar\"\n value a caller could get wrong. There's no live input to reject.\n Left unconstructed until the library actually accepts a calendar\n parameter that could be invalid. */\nexport class InvalidCalendarError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `calendar \"${fields.actual ?? ''}\" is not supported${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_CALENDAR', ...rest },\n );\n this.name = 'InvalidCalendarError';\n }\n}\n/* c8 ignore stop @preserve */\n\nexport class AmbiguousInputError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" is ambiguous${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'AMBIGUOUS_INPUT', ...rest },\n );\n this.name = 'AmbiguousInputError';\n }\n}\n\nexport class InvalidLocaleError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `locale \"${fields.actual ?? ''}\" is not a valid BCP-47 tag${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_LOCALE', ...rest },\n );\n this.name = 'InvalidLocaleError';\n }\n}\n\nexport class InvalidDurationError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `duration is invalid${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_DURATION', ...rest },\n );\n this.name = 'InvalidDurationError';\n }\n}\n\n// Wraps a plain Error thrown from a code path that hasn't been\n// migrated to typed errors yet. Carries the original message in\n// `reason` so callers reading the typed surface still see what\n// failed. Used by safeParse() in parse.ts.\n//\n// As of the 0.9.0 migration, every throw site on the parse/format data\n// path throws a TemporalFmtError directly, so safeParse's `instanceof\n// TemporalFmtError` check always passes before this function would be\n// called — nothing in the current test suite reaches any branch below.\n// Kept as the safety net for wrapping a future unmigrated throw site\n// (see the c8-ignored call in parse.ts's safeParse), same reasoning as\n// that call site: removing this would silently drop the \"safeParse\n// always returns a TemporalFmtError\" contract the moment anyone adds a\n// throw new Error(...) without wiring a typed class for it.\n/* c8 ignore start @preserve -- unreachable from the current test suite,\n see rationale above */\nexport function wrapUntypedError(err: Error, context: { input?: string; format?: string }): TemporalFmtError {\n // Try to classify by inspecting the message — covers the existing\n // parse()/format() throw sites without modifying them. Anything\n // that doesn't match a known pattern falls through to a generic\n // ParseMismatchError, which still has the structured fields.\n const msg = err.message;\n if (/unknown token|isn't a recognized token/.test(msg)) {\n return new UnknownTokenError({ input: context.input, format: context.format, reason: msg });\n }\n if (/ambiguous/i.test(msg)) {\n return new AmbiguousInputError({ input: context.input, format: context.format, reason: msg });\n }\n if (/offset/.test(msg) && /out of range|exceeds|doesn't match the shape/i.test(msg)) {\n return new InvalidOffsetError({ input: context.input, format: context.format, reason: msg });\n }\n if (/no valid pattern matches/i.test(msg)) {\n return new ParseMismatchError({ input: context.input, format: context.format, reason: msg });\n }\n if (/doesn't describe a valid date\\/time|incomplete date|weekday token|quarter token/.test(msg)) {\n return new InvalidDateError({ input: context.input, format: context.format, reason: msg });\n }\n const lowerMsg = msg.toLowerCase();\n const mentionsLocale = lowerMsg.includes('locale');\n if (\n (mentionsLocale && (lowerMsg.includes('produced no') || lowerMsg.includes('not a valid'))) ||\n lowerMsg.includes('cutoffs must be')\n ) {\n return new InvalidLocaleError({ input: context.input, format: context.format, reason: msg });\n }\n if (/format string exceeds maximum length|input exceeds maximum length|unterminated quote|isn't a recognized token/i.test(msg)) {\n return new FormatSyntaxError({ input: context.input, format: context.format, reason: msg });\n }\n return new ParseMismatchError({ input: context.input, format: context.format, reason: msg });\n}\n/* c8 ignore stop @preserve */","// 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\nimport { InvalidLocaleError } from './errors.js';\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// Custom vocabs registered by callers for locales Intl doesn't cover well\n// (e.g. a 13-month Hebrew leap year, where Intl's 12-month vocabulary\n// silently loses a whole month). Keyed by canonical cache key so the\n// same locale string spelling variants fold together — same convention\n// as the Intl-derived vocab cache above.\nconst customVocabs = new Map<string, LocaleVocab>();\nconst MAX_CUSTOM_VOCABS = 500;\nconst MAX_LOCALE_TAG_LENGTH = 256;\nconst MAX_VOCAB_ENTRY_LENGTH = 256;\n\nfunction assertValidVocab(vocab: Partial<LocaleVocab>, locale: string): void {\n // Strict shape validation at registration time, not lazily on first\n // use — the README's promise is that a malformed registration throws\n // descriptively here, rather than failing later inside format()/parse()\n // with a confusing \"no month part\" or wrong-month error the caller\n // can't trace back to the bad registration.\n const required: Array<{ key: keyof LocaleVocab; length: number; label: string }> = [\n { key: 'monthLong', length: 12, label: 'long month names' },\n { key: 'monthShort', length: 12, label: 'short month names' },\n { key: 'weekdayLong', length: 7, label: 'long weekday names' },\n { key: 'weekdayShort', length: 7, label: 'short weekday names' },\n { key: 'dayPeriod', length: 2, label: 'day period markers (AM/PM-equivalent)' },\n ];\n\n for (const { key, length, label } of required) {\n const value = vocab[key];\n if (value === undefined) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\" is missing required field \"${key}\" (${label}).`\n );\n }\n if (!Array.isArray(value)) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}\" must be an array, got ${typeof value}.`\n );\n }\n if (value.length !== length) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}\" must have exactly ${length} entries (got ${value.length}) — ${label}.`\n );\n }\n value.forEach((entry, i) => {\n if (typeof entry !== 'string' || entry.length === 0) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}[${i}]\" must be a non-empty string, got ${String(entry)}.`\n );\n }\n if (entry.length > MAX_VOCAB_ENTRY_LENGTH) {\n throw new RangeError(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}[${i}]\" is too long (maximum ${MAX_VOCAB_ENTRY_LENGTH} characters).`\n );\n }\n });\n }\n\n // Reuse the same collision check the Intl-derived path uses — a\n // duplicate month name is just as ambiguous when supplied by a caller\n // as when produced by Intl.\n assertNoCollision(vocab.monthLong!, 'MMMM month', locale);\n assertNoCollision(vocab.monthShort!, 'MMM month', locale);\n assertNoCollision(vocab.weekdayLong!, 'EEEE weekday', locale);\n assertNoCollision(vocab.weekdayShort!, 'EEE weekday', locale);\n\n // dayPeriod entries must differ from each other, or parse()'s\n // isPM check (raw === vocab.dayPeriod[1]) can never return true and\n // every 12-hour parse silently resolves to AM. The Intl-derived path\n // dedupes a same-AM/PM collision to length 1, but a caller passing\n // both entries identical is a real bug to surface — not something to\n // dedupe around.\n if (vocab.dayPeriod![0] === vocab.dayPeriod![1]) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": dayPeriod entries must differ ` +\n `(both are \"${vocab.dayPeriod![0]}\"); otherwise parse() can't tell AM from PM.`\n );\n }\n}\n\n// Anything that caches a result derived from *which* vocabulary is\n// active for a locale (right now: parse.ts's compiled pattern cache,\n// whose MMMM/MMM/EEEE/EEE/a fragments embed the vocab's alternations)\n// subscribes here so it gets invalidated when a registration swaps the\n// vocab — mirrors temporalProvider.ts's subscribeToTemporalChanges.\nconst onVocabChanged: Array<() => void> = [];\n\nexport function subscribeToVocabChanges(listener: () => void): void {\n onVocabChanged.push(listener);\n}\n\n/**\n * Supply a custom month/weekday/day-period vocabulary for a locale key,\n * overriding the Intl-derived vocab this library would otherwise build\n * for that key. Useful for locales Intl doesn't cover well — the README's\n * known-limitations section calls out the Hebrew leap-month gap as a\n * specific case this addresses.\n *\n * Throws descriptively on malformed input (wrong array lengths, empty\n * strings, duplicate entries, missing fields) rather than failing later\n * during format/parse.\n *\n * Registered vocab takes precedence over the Intl-derived vocab for that\n * locale key, including for already-cached entries — registering\n * invalidates the prior cache entry for that locale so the next call\n * picks up the new vocab.\n *\n * @example\n * registerLocaleVocab('en-u-ca-hebrew-leap', {\n * monthLong: ['Nisan','Iyar','Sivan','Tammuz','Av','Elul','Tishrei','Marcheshvan','Kislev','Tevet','Shevat','Adar I','Adar II'],\n * monthShort: ['Nis','Iyy','Siv','Tam','Av','Elu','Tish','Chesh','Kis','Tev','Shv','Ad1','Ad2'],\n * weekdayLong: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],\n * weekdayShort: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],\n * dayPeriod: ['AM','PM'],\n * });\n */\nexport function registerLocaleVocab(locale: string, vocab: Partial<LocaleVocab>): void {\n if (typeof locale !== 'string' || locale.length === 0) {\n throw new Error(`temporal-fmt: registerLocaleVocab requires a non-empty locale string, got ${String(locale)}.`);\n }\n if (locale.length > MAX_LOCALE_TAG_LENGTH) {\n throw new RangeError(`temporal-fmt: registerLocaleVocab locale is too long (maximum ${MAX_LOCALE_TAG_LENGTH} characters).`);\n }\n assertValidVocab(vocab, locale);\n\n const cacheKey = canonicalCacheKey(locale);\n if (!customVocabs.has(cacheKey) && customVocabs.size >= MAX_CUSTOM_VOCABS) {\n throw new RangeError(`temporal-fmt: registerLocaleVocab reached the ${MAX_CUSTOM_VOCABS}-locale limit.`);\n }\n customVocabs.set(cacheKey, {\n monthLong: [...vocab.monthLong!],\n monthShort: [...vocab.monthShort!],\n weekdayLong: [...vocab.weekdayLong!],\n weekdayShort: [...vocab.weekdayShort!],\n dayPeriod: [...vocab.dayPeriod!],\n });\n // Invalidate the Intl-derived cache entry so any prior format/parse\n // result cached for this locale is rebuilt against the new vocab. Not\n // strictly necessary (getLocaleVocab checks customVocabs first), but\n // cheap and keeps the two caches from drifting out of sync.\n vocabCache.delete(cacheKey);\n // Also invalidate downstream caches that baked the previous vocab in\n // at build time (parse.ts's pattern cache is the one that matters:\n // without this, a cached pattern would keep matching the OLD month /\n // weekday names while format() renders the new ones, so the library's\n // own format() output would fail to parse back).\n for (const listener of onVocabChanged) listener();\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.\n// Intl constructors (DateTimeFormat/NumberFormat/RelativeTimeFormat)\n// reject underscore-separated tags like 'en_US' outright, while\n// canonicalCacheKey and every locale-parsing path in this library\n// tolerates them by normalizing to BCP-47 hyphens. Centralize that\n// normalization so every `new Intl.*(locale)` construction site\n// accepts the same spellings the cache keys do. Genuinely malformed\n// tags still throw downstream, unchanged.\nexport function normalizeLocaleTag(locale: string): string {\n return locale.replace(/_/g, '-');\n}\n\n// Memoized so hot paths (parse()'s resolveCalendar keys off this on\n// every call, and every locale-keyed cache re-derives it) don't build a\n// fresh Intl.Locale per invocation — construction is comparatively\n// expensive. Bounded like every other cache in this library.\nconst canonicalKeyCache = new Map<string, string>();\nconst MAX_CANONICAL_KEY_CACHE = 500;\n\nexport function canonicalCacheKey(locale: string): string {\n const hit = canonicalKeyCache.get(locale);\n if (hit !== undefined) return hit;\n let key: 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 key = new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n // Malformed tag: key on the raw string. Callers that must reject\n // malformed tags do it via assertValidLocaleTag() before/instead of\n // relying on this function — cache-key normalization isn't where a\n // bad locale should surface as an error (unchanged behavior).\n key = locale;\n }\n if (canonicalKeyCache.size >= MAX_CANONICAL_KEY_CACHE) {\n const oldestKey = canonicalKeyCache.keys().next().value;\n if (oldestKey !== undefined) canonicalKeyCache.delete(oldestKey);\n }\n canonicalKeyCache.set(locale, key);\n return key;\n}\n\n// Single validation choke point for locale tags at public boundaries.\n// Intl constructors reject malformed tags with a bare engine RangeError\n// (\"Incorrect locale information provided\") that carries none of the\n// library's structured error context; this rethrows as the typed\n// InvalidLocaleError with the offending tag in its fields. Accepts the\n// same spellings as canonicalCacheKey (underscore tags normalized).\nexport function assertValidLocaleTag(locale: string): void {\n try {\n new Intl.Locale(normalizeLocaleTag(locale));\n } catch {\n throw new InvalidLocaleError({\n actual: locale,\n reason: 'not a valid BCP-47 locale tag',\n });\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 /* c8 ignore start @preserve -- defensive guard against a real but\n unreproducible failure mode: an Intl implementation that omits the\n requested part type entirely for some locale. Checked every locale\n with unusual dayPeriod/weekday/month rendering available in this\n runtime's ICU data (ja-JP, zh-CN, th-TH, he-IL, ar-SA, ko-KR, fa-IR)\n against the exact formatter options getLocaleVocab uses (notably\n hour12: true for the dayPeriod formatter, which is what makes every\n locale here actually emit a dayPeriod part — omitting it is what\n produced a false \"gap\" during investigation). None omit their part\n on this runtime. A different ICU version or a non-Node Intl\n implementation could plausibly behave differently, so this stays a\n real check rather than an assertion. */\n /* c8 ignore start @preserve */\n if (index === -1) {\n throw new InvalidLocaleError({\n message: `temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`,\n });\n }\n /* c8 ignore stop @preserve */\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 // Not migrated to a typed error: this function is shared between\n // getLocaleVocab's Intl-derived path (data-path error, would be a\n // good InvalidLocaleError candidate) and assertValidVocab's\n // registration-time check (out of scope for this pass — see the\n // localeVocab.ts registration-error follow-up). Splitting this into\n // two near-duplicate functions just to route error types\n // differently isn't worth it for one throw; revisit together with\n // the registration-error work instead.\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\n// Exposed for tokens.ts: when a custom vocab is registered for this\n// locale, format()'s locale-aware tokens (MMMM/MMM/EEEE/EEE/a) read\n// straight from the registered array instead of going through\n// Intl.DateTimeFormat. Without this override, format() would silently\n// keep producing Intl's strings while parse() matched against the\n// registered vocab — the two would round-trip-fail.\nexport function getCustomVocab(locale: string): LocaleVocab | undefined {\n const cacheKey = canonicalCacheKey(locale);\n return customVocabs.get(cacheKey);\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n // Validate before building vocab: a malformed tag used to surface as a\n // raw RangeError from the first new Intl.DateTimeFormat below.\n assertValidLocaleTag(locale);\n const cacheKey = canonicalCacheKey(locale);\n // Registered vocabs take precedence over the Intl-derived one — this\n // is the override mechanism registerLocaleVocab() promises. Checking\n // here, before the Intl cache lookup, means a registration that\n // happens *after* the first Intl-derived vocab was built still takes\n // effect on the next call.\n const custom = customVocabs.get(cacheKey);\n if (custom) {\n return custom;\n }\n const cached = vocabCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const intlLocale = normalizeLocaleTag(locale);\n const monthLongFmt = new Intl.DateTimeFormat(intlLocale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(intlLocale, { 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(intlLocale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(intlLocale, { 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(intlLocale, { 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}"],"mappings":"AA+DO,IAAMA,EAAN,cAA+B,KAAM,CACjC,KACA,MACA,OACA,MACA,SACA,SACA,OACA,OAET,YAAYC,EAAiBC,EAAgC,CAC3D,MAAMD,CAAO,EACb,KAAK,KAAO,mBACZ,KAAK,KAAOC,EAAO,KACnB,KAAK,MAAQA,EAAO,MACpB,KAAK,OAASA,EAAO,OACrB,KAAK,MAAQA,EAAO,MACpB,KAAK,SAAWA,EAAO,SACvB,KAAK,SAAWA,EAAO,SACvB,KAAK,OAASA,EAAO,OACrB,KAAK,OAASA,EAAO,OAIrB,IAAMC,EAAW,MAAsF,kBACnG,OAAOA,GAAY,YACrBA,EAAQ,KAAM,KAAK,WAAW,CAElC,CAIA,QAAqE,CACnE,MAAO,CACL,KAAM,KAAK,KACX,QAAS,KAAK,QACd,KAAM,KAAK,KACX,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,MAAO,KAAK,MACZ,SAAU,KAAK,SACf,SAAU,KAAK,SACf,OAAQ,KAAK,OACb,OAAQ,KAAK,MACf,CACF,CACF,EAOaC,EAAN,cAAgCJ,CAAiB,CACtD,YAAYE,EAAqE,CAC/E,GAAM,CAAE,QAAAD,EAAS,GAAGI,CAAK,EAAIH,EAC7B,MACED,GAAW,kBAAkBC,EAAO,QAAU,EAAE,uBAAuBA,EAAO,OAAS,KAAKA,EAAO,MAAM,GAAK,EAAE,IAChH,CAAE,KAAM,sBAAuB,GAAGG,CAAK,CACzC,EACA,KAAK,KAAO,mBACd,CACF,EAEaC,EAAN,cAAgCN,CAAiB,CACtD,YAAYE,EAAqE,CAC/E,GAAM,CAAE,QAAAD,EAAS,GAAGI,CAAK,EAAIH,EAC7B,MACED,GAAW,UAAUC,EAAO,OAAS,EAAE,2CAA2CA,EAAO,OAAS,sBAAsBA,EAAO,M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C,IAAMH,EAAYL,EAAW,KAAK,EAAE,KAAK,EAAE,MACvCK,IAAc,QAAWL,EAAW,OAAOK,CAAS,CAC1D,CACA,OAAAL,EAAW,IAAIF,EAAUd,CAAK,EACvBA,CACT","names":["TemporalFmtError","message","fields","capture","FormatSyntaxError","rest","UnknownTokenError","ParseMismatchError","InvalidDateError","InvalidTimeError","InvalidOffsetError","InvalidTimeZoneError","InvalidCalendarError","AmbiguousInputError","InvalidLocaleError","InvalidDurationError","wrapUntypedError","err","context","msg","lowerMsg","customVocabs","MAX_CUSTOM_VOCABS","MAX_LOCALE_TAG_LENGTH","MAX_VOCAB_ENTRY_LENGTH","assertValidVocab","vocab","locale","required","key","length","label","value","entry","i","assertNoCollision","onVocabChanged","subscribeToVocabChanges","listener","registerLocaleVocab","cacheKey","canonicalCacheKey","vocabCache","normalizeLocaleTag","canonicalKeyCache","MAX_CANONICAL_KEY_CACHE","hit","oldestKey","assertValidLocaleTag","InvalidLocaleError","MAX_VOCAB_CACHE_SIZE","partValue","formatter","date","type","parts","index","p","prev","next","names","seen","prior","getCustomVocab","getLocaleVocab","custom","cached","intlLocale","monthLongFmt","monthShortFmt","monthLong","monthShort","m","weekdayLongFmt","weekdayShortFmt","weekdayLong","weekdayShort","d","dayPeriodFmt","am","pm","dayPeriod"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as I,c as L}from"./chunk-3MZLTVP3.js";import{k as D,p as O,q as b,s}from"./chunk-5U5WJ465.js";import{b as p,c as w}from"./chunk-C6ZZ62ET.js";function r(e,t){let n=e<0,o=String(Math.abs(e)).padStart(t,"0");return n?"-"+o:o}r.fraction=function(t,n){let o=t.millisecond*1e6+(t.microsecond??0)*1e3+(t.nanosecond??0);return r(o,9).slice(0,n)};var G="en-US",l=new Map,$=500;function F(e,t){let n=JSON.stringify([b(e),t]),o=l.get(n);if(o)return o;if(l.size>=$){let a=l.keys().next().value;a!==void 0&&l.delete(a)}try{o=new Intl.DateTimeFormat(O(e),t)}catch(a){throw new D({actual:e,reason:a.message})}return l.set(n,o),o}var y;I(()=>{y=void 0});function M(){if(y===void 0){y=!1;try{let e=L();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),y=!0}catch{}}return y}function h(e,t,n,o){let a=e?.calendarId,i={...n,calendar:a&&a!=="iso8601"?a:"gregory"},d=e.toLocaleString;if(typeof d!="function"||d===Object.prototype.toLocaleString)throw new Error(`temporal-fmt: locale-aware part "${o}" needs a value that implements toLocaleString (a real Temporal object). A plain field bag cannot render locale-aware names \u2014 pass a Temporal.PlainDate/PlainDateTime/ZonedDateTime.`);if(!M())try{return d.call(e,O(t),i)}catch(u){throw u instanceof RangeError?new D({actual:t,reason:u.message}):u}let{toInstant:E,timeZoneId:X}=e,x=typeof E=="function"&&typeof X=="string",Z=x?e.toInstant():e,P={...i,...x?{timeZone:X}:{}},S=F(t,P).formatToParts(Z),g=S.findIndex(u=>u.type===o);if(g===-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 f=S[g].value,T=S[g-1],k=S[g+1];return T?.type==="literal"&&!/\s/.test(T.value)&&(f=T.value+f),k?.type==="literal"&&!/\s/.test(k.value)&&(f=f+k.value),f}function W(e,t){let n=s(t);if(n)return e<12?n.dayPeriod[0]:n.dayPeriod[1];let o=new Date(Date.UTC(1970,0,1,e)),i=F(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(o).find(d=>d.type==="dayPeriod");if(!i)throw new Error(`temporal-fmt: locale "${t}" produced no "dayPeriod" part for token "a".`);return i.value}function m(e,t,n,o,a,i){return a&&i!==void 0&&i>=0&&i<a.length?a[i]:h(e,t,n,o)}function c(e,t){if(e==="+00:00"&&(t==="X"||t==="XX"||t==="XXX"))return"Z";let n=e[0],o=e.slice(1,3),a=e.slice(4,6);switch(t){case"X":case"x":return a==="00"?`${n}${o}`:`${n}${o}${a}`;case"XX":case"xx":return`${n}${o}${a}`;case"XXX":case"xxx":return`${n}${o}:${a}`}}var H=[["yyyy",e=>r(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 r(e.year%100,2)},"year"],["MMMM",(e,t)=>{let n=s(t);return m(e,t,{month:"long"},"month",n?.monthLong,e.month-1)},"month"],["MMM",(e,t)=>{let n=s(t);return m(e,t,{month:"short"},"month",n?.monthShort,e.month-1)},"month"],["MM",e=>r(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>r(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,t)=>{let n=s(t);return m(e,t,{weekday:"long"},"weekday",n?.weekdayLong,e.dayOfWeek-1)},"dayOfWeek"],["EEE",(e,t)=>{let n=s(t);return m(e,t,{weekday:"short"},"weekday",n?.weekdayShort,e.dayOfWeek-1)},"dayOfWeek"],["HH",e=>r(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>r(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>r(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>r(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSSSSSSSS",e=>r.fraction(e,9),"millisecond"],["SSSSSSSS",e=>r.fraction(e,8),"millisecond"],["SSSSSSS",e=>r.fraction(e,7),"millisecond"],["SSSSSS",e=>r.fraction(e,6),"millisecond"],["SSSSS",e=>r.fraction(e,5),"millisecond"],["SSSS",e=>r.fraction(e,4),"millisecond"],["SSS",e=>r.fraction(e,3),"millisecond"],["SS",e=>r.fraction(e,2),"millisecond"],["S",e=>r.fraction(e,1),"millisecond"],["a",(e,t)=>W(e.hour,t),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"],["xxx",e=>c(e.offset,"xxx"),"offset"],["xx",e=>c(e.offset,"xx"),"offset"],["X",e=>c(e.offset,"X"),"offset"],["XX",e=>c(e.offset,"XX"),"offset"],["XXX",e=>c(e.offset,"XXX"),"offset"],["x",e=>c(e.offset,"x"),"offset"],["do",e=>{let t=e.day,n=t%10,o=t%100;return o>=11&&o<=13?t+"th":n===1?t+"st":n===2?t+"nd":n===3?t+"rd":t+"th"},"day"],["Q",e=>String(Math.ceil(e.month/3)),"month"],["QQQ",e=>"Q"+Math.ceil(e.month/3),"month"],["ww",e=>{let{week:t}=w(e.year,e.month,e.day,e.dayOfWeek);return r(t,2)},"dayOfWeek"],["RRRR",e=>{let{isoYear:t}=w(e.year,e.month,e.day,e.dayOfWeek);return r(t,4)},"dayOfWeek"],["D",e=>String(p(e.year,e.month,e.day)),"day"],["DD",e=>r(p(e.year,e.month,e.day),2),"day"],["DDD",e=>r(p(e.year,e.month,e.day),3),"day"],["LLLL",(e,t)=>{let n=s(t);return m(e,t,{month:"long"},"month",n?.monthLong,e.month-1)},"month"],["LLL",(e,t)=>{let n=s(t);return m(e,t,{month:"short"},"month",n?.monthShort,e.month-1)},"month"],["cccc",(e,t)=>{let n=s(t);return m(e,t,{weekday:"long"},"weekday",n?.weekdayLong,e.dayOfWeek-1)},"dayOfWeek"],["ccc",(e,t)=>{let n=s(t);return m(e,t,{weekday:"short"},"weekday",n?.weekdayShort,e.dayOfWeek-1)},"dayOfWeek"],["GGGG",(e,t)=>h(e,t,{era:"long"},"era"),"year"],["G",(e,t)=>h(e,t,{era:"short"},"era"),"year"],["zzzz",(e,t)=>h(e,t,{timeZoneName:"longGeneric"},"timeZoneName"),"timeZoneId"],["z",(e,t)=>h(e,t,{timeZoneName:"short"},"timeZoneName"),"timeZoneId"]];export{G as a,H as b};
|
|
2
|
+
//# sourceMappingURL=chunk-C5YESWFT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tokens.ts"],"sourcesContent":["import { getTemporal, subscribeToTemporalChanges } from './temporalProvider.js';\nimport { canonicalCacheKey, getCustomVocab, normalizeLocaleTag } from './localeVocab.js';\nimport { InvalidLocaleError } from './errors.js';\nimport { isoWeekYearAndWeek, dayOfYear } from './isoWeek.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// Combines the three sub-second fields Temporal exposes into one 9-digit\n// nanosecond-of-second value, then truncates (never rounds) to the\n// requested width. Truncating matches what every digit-width token in\n// this library already does elsewhere (yy, MM, dd, ...) — the token\n// asked for N digits of precision, not a rounded N-digit approximation.\n// A caller asking for SSS on a value with nanosecond precision gets the\n// leading 3 digits of it, same as they'd get the leading 3 digits of any\n// other multi-digit field this library formats.\n//\n// Attached to pad() rather than declared standalone: the bundler's\n// per-function coverage instrumentation attributes hits to each of the\n// 9 fraction-token arrow functions individually but not to a shared\n// helper they all close over, so a correctly-exercised helper still\n// shows as 0 hits under c8. pad() itself is called directly all over\n// this file and is reliably attributed — routing through it here keeps\n// the coverage numbers honest without duplicating the slice logic\n// across every token entry below.\npad.fraction = function formatFraction(t: TemporalLike, width: number): string {\n const nanoOfSecond = t.millisecond! * 1_000_000 + (t.microsecond ?? 0) * 1_000 + (t.nanosecond ?? 0);\n return pad(nanoOfSecond, 9).slice(0, width);\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 microsecond?: number;\n nanosecond?: number;\n timeZoneId?: string;\n // ZonedDateTime.prototype.offset — always `±HH:MM` (6 chars) for any\n // modern date. Historical LMT offsets with seconds exist in IANA but\n // aren't reachable through this Temporal field, so format-side offset\n // tokens can assume the canonical 6-char shape. Parse-side writes a\n // canonicalized `+HH:MM` here before handing it to\n // Temporal.ZonedDateTime.from as the `timeZone` value.\n offset?: 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 * When set on parse(), opts into the lenient split heuristic for ambiguous\n * glued numeric runs (e.g. \"121\" against \"Md\"). Default (false) keeps\n * parse()'s strict behavior — throw on ambiguity rather than guess.\n * See README \"Lenient parse mode\" for the heuristic and why it's opt-in.\n */\n lenient?: boolean;\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 try {\n formatter = new Intl.DateTimeFormat(normalizeLocaleTag(locale), options);\n } catch (err) {\n // Malformed locale tags reach Intl as a bare RangeError; surface the\n // library's typed error instead (reached via dayPeriodPart — the\n // 'a' token — on any runtime, and the native-Intl path for the rest).\n // Every failure mode of this constructor with a string locale is a\n // RangeError, so converting unconditionally preserves the original\n // message in `reason` either way.\n throw new InvalidLocaleError({ actual: locale, reason: (err as Error).message });\n }\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 // Version-gated, not dead — see the matching note on the\n // !intlSupportsNativeTemporal() branch in intlPart() below for\n // why this can't be exercised from this environment.\n /* c8 ignore next */\n nativeSupport = true;\n /* c8 ignore start */\n } catch {\n // native Temporal absent, or present but not recognized by Intl — fall back.\n // Version-gated, not dead: this catch only fires on runtimes where the\n // probe above throws (no native Temporal, or Intl doesn't recognize it).\n // On a runtime with full native support (e.g. Node builds where Intl\n // accepts native Temporal instances directly) the try succeeds and this\n // branch is unreachable — mirror case of the block below.\n }\n /* c8 ignore stop */\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 // Field-bag guard: a plain { year, month, day } object only has\n // Object.prototype.toLocaleString, which ignores both arguments and\n // returns \"[object Object]\". On engines without native Temporal\n // support in Intl this used to be caught below, but on engines where\n // Intl *does* recognize native Temporal instances (Node 26+), a bag\n // skips that branch entirely and reaches formatToParts() directly —\n // which doesn't throw \"[object Object]\", it throws a bare\n // \"RangeError: Invalid time value\" once the bag fails ToNumber()\n // coercion. Neither failure mode is useful to a caller, so check for\n // a real toLocaleString up front, before branching on native support,\n // so the descriptive error fires on every engine.\n const ls = temporal.toLocaleString;\n if (typeof ls !== 'function' || ls === Object.prototype.toLocaleString) {\n throw new Error(\n `temporal-fmt: locale-aware part \"${partType}\" needs a value that implements ` +\n `toLocaleString (a real Temporal object). A plain field bag cannot render ` +\n `locale-aware names — pass a Temporal.PlainDate/PlainDateTime/ZonedDateTime.`\n );\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 //\n // Everything from here to the end of this function is genuinely\n // reachable — NOT dead code — but only on a Node build where a global\n // `Temporal` exists AND Intl.DateTimeFormat.formatToParts() recognizes\n // native Temporal instances directly (this is real, observed to vary\n // across Node versions: absent on the Node 22/24 builds this suite has\n // been run against, present on at least one Node 26 build). This\n // environment has no native Temporal (`typeof globalThis.Temporal ===\n // 'undefined'`), so intlSupportsNativeTemporal() always returns false\n // here and this branch can't be exercised from this test suite without\n // faking native-instance recognition, which turned out to be\n // impractical (Intl's native-Temporal detection isn't spoofable via a\n // Proxy or valueOf() shim — see the M-02 regression test in\n // temporalProvider.test.js for the same conclusion reached about the\n // sibling probe function). Coverage numbers for this block will differ\n // between Node versions for that reason; that's expected, not a\n // regression.\n /* c8 ignore start */\n if (!intlSupportsNativeTemporal()) {\n // normalizeLocaleTag: the active Temporal implementation's\n // toLocaleString forwards the locale to Intl.DateTimeFormat, which\n // (unlike this library's cache keys) rejects underscore-separated\n // tags like 'en_US' outright.\n // (Field-bag guard now runs unconditionally above, before this\n // native-support branch, so it's not repeated here.)\n try {\n return ls.call(temporal, normalizeLocaleTag(locale), formatterOptions);\n } catch (err) {\n // The active Temporal implementation forwards the tag to Intl, which\n // throws a bare RangeError for a malformed one — rethrow typed.\n if (err instanceof RangeError) {\n throw new InvalidLocaleError({ actual: locale, reason: err.message });\n }\n throw err;\n }\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/* c8 ignore stop */\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 // Custom vocab (when registered) takes precedence over Intl — same\n // contract as the other locale-aware tokens. Intl won't know about a\n // caller-supplied AM/PM string for a made-up locale key, so going\n // through Intl would produce something other than what the caller\n // registered.\n const custom = getCustomVocab(locale);\n if (custom) {\n return hour < 12 ? custom.dayPeriod[0]! : custom.dayPeriod[1]!;\n }\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 // Defensive guard, confirmed unreachable on this ICU build: forcing\n // hour12: true (as this call always does) produces a dayPeriod part\n // for every locale checked, including 24-hour-clock locales (ja-JP,\n // zh-CN, th-TH, he-IL) and a wide sweep of less-common tags (dz-BT,\n // bo-CN, am-ET, etc.). Same finding as partValue()'s twin guard in\n // localeVocab.ts. Kept in case a future ICU/locale-data update\n // produces a locale that genuinely omits it.\n /* c8 ignore start */\n if (!part) {\n throw new Error(`temporal-fmt: locale \"${locale}\" produced no \"dayPeriod\" part for token \"a\".`);\n }\n /* c8 ignore stop */\n return part.value;\n}\n\n// Resolves a locale-aware month/weekday name from the registered custom\n// vocab when one exists for this locale, falling through to Intl otherwise.\n// Without this, format() would silently keep producing Intl's strings while\n// parse() matched against the registered vocab — the two would round-trip-fail\n// against each other.\nfunction localeAwareName(\n temporal: TemporalLike,\n locale: string,\n options: Intl.DateTimeFormatOptions,\n partType: Intl.DateTimeFormatPartTypes,\n customArray: string[] | undefined,\n customIndex: number | undefined,\n): string {\n if (customArray && customIndex !== undefined && customIndex >= 0 && customIndex < customArray.length) {\n return customArray[customIndex]!;\n }\n return intlPart(temporal, locale, options, partType);\n}\n\n// Formats a `±HH:MM` offset string (the shape Temporal exposes on\n// ZonedDateTime.prototype.offset) into one of the six offset-token widths.\n// Width and Z-handling come from the variant letter+case:\n//\n// X / x — short form: minutes omitted when zero, no colon otherwise\n// XX / xx — hours + minutes, no colon\n// XXX / xxx — hours + minutes, with colon\n//\n// Uppercase (X) collapses +00:00 to \"Z\"; lowercase (x) always emits a\n// numeric offset, even for UTC. Mirrors the date-fns/Unicode-LDML offset\n// family — see README for the full variant table.\nfunction formatOffset(offset: string, variant: 'X' | 'XX' | 'XXX' | 'x' | 'xx' | 'xxx'): string {\n if (offset === '+00:00' && (variant === 'X' || variant === 'XX' || variant === 'XXX')) {\n return 'Z';\n }\n // offset is always 6 chars: sign + HH + ':' + MM\n const sign = offset[0]!;\n const hours = offset.slice(1, 3);\n const minutes = offset.slice(4, 6);\n switch (variant) {\n case 'X': case 'x':\n // minutes only matter when they're non-zero — otherwise drop them\n // entirely. Matches LDML: \"With a single X, the hours field is\n // required. The minutes field is optional, but only if the\n // minutes value is 0.\"\n return minutes === '00' ? `${sign}${hours}` : `${sign}${hours}${minutes}`;\n case 'XX': case 'xx':\n return `${sign}${hours}${minutes}`;\n case 'XXX': case 'xxx':\n return `${sign}${hours}:${minutes}`;\n }\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) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { month: 'long' }, 'month', custom?.monthLong, t.month! - 1);\n }, 'month'],\n ['MMM', (t, locale) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { month: 'short' }, 'month', custom?.monthShort, t.month! - 1);\n }, '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) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { weekday: 'long' }, 'weekday', custom?.weekdayLong, t.dayOfWeek! - 1);\n }, 'dayOfWeek'],\n ['EEE', (t, locale) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { weekday: 'short' }, 'weekday', custom?.weekdayShort, t.dayOfWeek! - 1);\n }, '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 // Fractional-second tokens, S through SSSSSSSSS (1-9 digits). Each token\n // formats a slice of the same underlying nanosecond-of-second value —\n // combining millisecond/microsecond/nanosecond into one 9-digit number\n // and truncating to the token's width — so \"SSS\" keeps meaning exactly\n // what it always meant (3-digit milliseconds) while wider tokens expose\n // the precision Temporal actually carries. formatFraction below is the\n // shared implementation; see its comment for the truncate-not-round\n // rule and why.\n ['SSSSSSSSS', (t) => pad.fraction(t, 9), 'millisecond'],\n ['SSSSSSSS', (t) => pad.fraction(t, 8), 'millisecond'],\n ['SSSSSSS', (t) => pad.fraction(t, 7), 'millisecond'],\n ['SSSSSS', (t) => pad.fraction(t, 6), 'millisecond'],\n ['SSSSS', (t) => pad.fraction(t, 5), 'millisecond'],\n ['SSSS', (t) => pad.fraction(t, 4), 'millisecond'],\n ['SSS', (t) => pad.fraction(t, 3), 'millisecond'],\n ['SS', (t) => pad.fraction(t, 2), 'millisecond'],\n ['S', (t) => pad.fraction(t, 1), '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 // Numeric UTC offset tokens (date-fns/Unicode-LDML family). Only\n // ZonedDateTime carries an offset, so the field check in format() throws\n // the same \"requires offset, which this Temporal object doesn't have\"\n // error zzz throws on PlainDate/PlainTime/PlainDateTime — same\n // validation path, just a different field name. See formatOffset above\n // for the per-variant width and Z/numeric distinction.\n ['xxx', (t) => formatOffset(t.offset!, 'xxx'), 'offset'],\n ['xx', (t) => formatOffset(t.offset!, 'xx'), 'offset'],\n ['X', (t) => formatOffset(t.offset!, 'X'), 'offset'],\n ['XX', (t) => formatOffset(t.offset!, 'XX'), 'offset'],\n ['XXX', (t) => formatOffset(t.offset!, 'XXX'), 'offset'],\n ['x', (t) => formatOffset(t.offset!, 'x'), 'offset'],\n\n // Ordinal day (1st, 2nd, 3rd, ... 21st). English suffix rules only —\n // locale-aware ordinals (\"2.\" in de-DE, \"2日\" in ja-JP) are out of scope,\n // since the rest of this library routes locale-specific names through\n // Intl.DateTimeFormat, and Intl has no part type for ordinals. Format-only:\n // the suffix isn't structurally distinguishable from a literal in a parse\n // context (a \"st\"/\"nd\"/\"rd\"/\"th\" suffix isn't a digit and would collide\n // with any adjacent literal text), so there's no good way to read it back.\n ['do', (t) => {\n const day = t.day!;\n const lastDigit = day % 10;\n // 11, 12, 13 are the exception — they'd otherwise match the 1/2/3 rule\n // and produce \"11st\"/\"12nd\"/\"13rd\", which is wrong. They always take \"th\".\n const lastTwoDigits = day % 100;\n if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {\n return day + 'th';\n }\n if (lastDigit === 1) return day + 'st';\n if (lastDigit === 2) return day + 'nd';\n if (lastDigit === 3) return day + 'rd';\n return day + 'th';\n }, 'day'],\n\n // Quarter computed from month: 1-3=Q1, 4-6=Q2, 7-9=Q3, 10-12=Q4.\n // `Q` is plain numeric, `QQQ` renders as \"Q3\" — same convention as\n // date-fns's `Q` and `QQQ` for parity with the most common prior art.\n // Both format and parse; parse() cross-checks Q/QQQ against the parsed\n // month in the same spirit as the EEEE-vs-date cross-check.\n ['Q', (t) => String(Math.ceil(t.month! / 3)), 'month'],\n ['QQQ', (t) => 'Q' + Math.ceil(t.month! / 3), 'month'],\n\n // ISO 8601 week and week-numbering year. Both are format-only — parsing\n // \"ww\"/\"RRRR\" back into a real date requires resolving an ISO week + a\n // weekday (or some other disambiguator) to a specific date, which is a\n // different parsing surface than the token-based parse() here. The\n // ISO-week year (RRRR) can differ from the calendar year at the boundary:\n // Dec 29-31 often belong to week 1 of the *next* year; Jan 1-3 often\n // belong to week 52/53 of the *previous* year. See isoWeekYearAndWeek().\n ['ww', (t) => {\n const { week } = isoWeekYearAndWeek(t.year!, t.month!, t.day!, t.dayOfWeek!);\n return pad(week, 2);\n }, 'dayOfWeek'],\n ['RRRR', (t) => {\n const { isoYear } = isoWeekYearAndWeek(t.year!, t.month!, t.day!, t.dayOfWeek!);\n return pad(isoYear, 4);\n }, 'dayOfWeek'],\n\n // Day of year — number of days since Jan 1 (1-366). Three widths:\n // D — unpadded (1, 2, 366)\n // DD — 2-digit minimum (zero-padded if <100)\n // DDD — 3-digit zero-padded (001, 002, 366)\n // Format-only — parsing day-of-year requires resolving against a year,\n // which is a different shape from the token-based parse() surface.\n // The dayOfYearHelper() in calendarUtils.ts covers the same field for\n // callers who need the numeric value.\n ['D', (t) => String(dayOfYear(t.year!, t.month!, t.day!)), 'day'],\n ['DD', (t) => pad(dayOfYear(t.year!, t.month!, t.day!), 2), 'day'],\n ['DDD', (t) => pad(dayOfYear(t.year!, t.month!, t.day!), 3), 'day'],\n\n // Stand-alone month — uses Intl's stand-alone form. In most locales\n // (en, fr, de, es) this is identical to MMMM/MMM. In Slavic/Baltic\n // locales (cs, sk, pl, ru) the stand-alone form differs from the\n // format form (nominative vs genitive case). LLLL = long, LLL = short.\n ['LLLL', (t, locale) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { month: 'long' }, 'month', custom?.monthLong, t.month! - 1);\n }, 'month'],\n ['LLL', (t, locale) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { month: 'short' }, 'month', custom?.monthShort, t.month! - 1);\n }, 'month'],\n\n // Stand-alone weekday — same pattern as stand-alone month but for\n // weekday names. cccc = long, ccc = short.\n ['cccc', (t, locale) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { weekday: 'long' }, 'weekday', custom?.weekdayLong, t.dayOfWeek! - 1);\n }, 'dayOfWeek'],\n ['ccc', (t, locale) => {\n const custom = getCustomVocab(locale);\n return localeAwareName(t, locale, { weekday: 'short' }, 'weekday', custom?.weekdayShort, t.dayOfWeek! - 1);\n }, 'dayOfWeek'],\n\n // Era — locale-aware (\"AD\"/\"BC\" in en, \"ap. J.-C.\"/\"av. J.-C.\" in fr).\n // GGGG = long, G = short. Format-only.\n ['GGGG', (t, locale) => {\n return intlPart(t, locale, { era: 'long' }, 'era');\n }, 'year'],\n ['G', (t, locale) => {\n return intlPart(t, locale, { era: 'short' }, 'era');\n }, 'year'],\n\n // Localized timezone name — uses Intl's longLocalized/short timezone\n // name option. Format-only — these names are locale-dependent and\n // vary by season (EST vs EDT), so parsing them back requires a\n // lookup table that isn't practical to ship.\n ['zzzz', (t, locale) => {\n return intlPart(t, locale, { timeZoneName: 'longGeneric' as Intl.DateTimeFormatOptions['timeZoneName'] }, 'timeZoneName' as Intl.DateTimeFormatPartTypes);\n }, 'timeZoneId'],\n ['z', (t, locale) => {\n return intlPart(t, locale, { timeZoneName: 'short' as Intl.DateTimeFormatOptions['timeZoneName'] }, 'timeZoneName' as Intl.DateTimeFormatPartTypes);\n }, 'timeZoneId'],\n\n];"],"mappings":"sJAKO,SAASA,EAAIC,EAAWC,EAAqB,CAGlD,IAAMC,EAAWF,EAAI,EACfG,EAAS,OAAO,KAAK,IAAIH,CAAC,CAAC,EAAE,SAASC,EAAK,GAAG,EACpD,OAAOC,EAAW,IAAMC,EAASA,CACnC,CAmBAJ,EAAI,SAAW,SAAwB,EAAiBK,EAAuB,CAC7E,IAAMC,EAAe,EAAE,YAAe,KAAa,EAAE,aAAe,GAAK,KAAS,EAAE,YAAc,GAClG,OAAON,EAAIM,EAAc,CAAC,EAAE,MAAM,EAAGD,CAAK,CAC5C,EAwCO,IAAME,EAAiB,QAIxBC,EAAiB,IAAI,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AQ,UAAWc,EAAE,MAAS,CAAC,CAC/F,EAAG,OAAO,EACV,CAAC,MAAO,CAACA,EAAG9C,IAAW,CACrB,IAAMgC,EAASC,EAAejC,CAAM,EACpC,OAAOoC,EAAgBU,EAAG9C,EAAQ,CAAE,MAAO,OAAQ,EAAG,QAASgC,GAAQ,WAAYc,EAAE,MAAS,CAAC,CACjG,EAAG,OAAO,EAIV,CAAC,OAAQ,CAACA,EAAG9C,IAAW,CACtB,IAAMgC,EAASC,EAAejC,CAAM,EACpC,OAAOoC,EAAgBU,EAAG9C,EAAQ,CAAE,QAAS,MAAO,EAAG,UAAWgC,GAAQ,YAAac,EAAE,UAAa,CAAC,CACzG,EAAG,WAAW,EACd,CAAC,MAAO,CAACA,EAAG9C,IAAW,CACrB,IAAMgC,EAASC,EAAejC,CAAM,EACpC,OAAOoC,EAAgBU,EAAG9C,EAAQ,CAAE,QAAS,OAAQ,EAAG,UAAWgC,GAAQ,aAAcc,EAAE,UAAa,CAAC,CAC3G,EAAG,WAAW,EAId,CAAC,OAAQ,CAACA,EAAG9C,IACJc,EAASgC,EAAG9C,EAAQ,CAAE,IAAK,MAAO,EAAG,KAAK,EAChD,MAAM,EACT,CAAC,IAAK,CAAC8C,EAAG9C,IACDc,EAASgC,EAAG9C,EAAQ,CAAE,IAAK,OAAQ,EAAG,KAAK,EACjD,MAAM,EAMT,CAAC,OAAQ,CAAC8C,EAAG9C,IACJc,EAASgC,EAAG9C,EAAQ,CAAE,aAAc,aAA4D,EAAG,cAA8C,EACvJ,YAAY,EACf,CAAC,IAAK,CAAC8C,EAAG9C,IACDc,EAASgC,EAAG9C,EAAQ,CAAE,aAAc,OAAsD,EAAG,cAA8C,EACjJ,YAAY,CAEjB","names":["pad","n","len","negative","digits","width","nanoOfSecond","DEFAULT_LOCALE","formatterCache","MAX_CACHE_SIZE","getFormatter","locale","options","key","canonicalCacheKey","formatter","oldestKey","normalizeLocaleTag","err","InvalidLocaleError","nativeSupport","subscribeToTemporalChanges","intlSupportsNativeTemporal","temporal","getTemporal","intlPart","partType","calendar","formatterOptions","ls","toInstant","timeZoneId","isZoned","intlSafeTemporal","nativeOptions","parts","index","p","value","prev","next","dayPeriodPart","hour","custom","getCustomVocab","date","part","localeAwareName","customArray","customIndex","formatOffset","offset","variant","sign","hours","minutes","TOKENS","t","day","lastDigit","lastTwoDigits","week","isoWeekYearAndWeek","isoYear","dayOfYear"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as p,b as h}from"./chunk-4JWGUR4O.js";import{p as b}from"./chunk-5U5WJ465.js";import{a}from"./chunk-UJR6DHXY.js";import{n as f}from"./chunk-EHLRZULM.js";function x(t,n,o="closed"){if(a(t,n)>0)throw new Error("temporal-fmt: interval start must be \u2264 end (got start > end). Pass them in chronological order.");return{start:t,end:n,bounds:o}}function F(t,n){let o=a(n,t.start),r=a(n,t.end),e=t.bounds==="open"||t.bounds==="half-open-end"?o>0:o>=0,s=t.bounds==="open"||t.bounds==="half-open-start"?r<0:r<=0;return e&&s}function E(t,n){return m(t,n)}function m(t,n){return!(a(t.end,n.start)<0||a(t.start,n.end)>0)}function S(t,n){return a(t.end,n.start)<0}function T(t,n){return a(t.start,n.end)>0}function B(t,n){if(!m(t,n))return null;let o=a(t.start,n.start)>=0?t.start:n.start,r=a(t.end,n.end)<=0?t.end:n.end,e=t.bounds==="open"||t.bounds==="half-open-end"||n.bounds==="open"||n.bounds==="half-open-end",s=t.bounds==="open"||t.bounds==="half-open-start"||n.bounds==="open"||n.bounds==="half-open-start";return{start:o,end:r,bounds:e&&s?"open":e?"half-open-end":s?"half-open-start":"closed"}}function R(t,n){if(!m(t,n))return null;let o=a(t.start,n.start)<=0?t.start:n.start,r=a(t.end,n.end)>=0?t.end:n.end,e=(t.bounds==="open"||t.bounds==="half-open-end")&&(n.bounds==="open"||n.bounds==="half-open-end"),s=(t.bounds==="open"||t.bounds==="half-open-start")&&(n.bounds==="open"||n.bounds==="half-open-start");return{start:o,end:r,bounds:e&&s?"open":e?"half-open-end":s?"half-open-start":"closed"}}function v(t,n){if(!m(t,n))return[t];let o=[],r=t.bounds==="closed"||t.bounds==="half-open-end",e=t.bounds==="closed"||t.bounds==="half-open-start";return a(t.start,n.start)<0&&o.push({start:t.start,end:n.start,bounds:r?"half-open-end":"open"}),a(t.end,n.end)>0&&o.push({start:n.end,end:t.end,bounds:e?"half-open-start":"open"}),o}var A=v;function O(t){if(t.length===0)return[];let n=[...t].sort((r,e)=>a(r.start,e.start)),o=[{...n[0]}];for(let r=1;r<n.length;r++){let e=n[r],s=o[o.length-1];m(s,e)||a(s.end,e.start)===0?a(e.end,s.end)>0&&(s.end=e.end):o.push(e)}return o}var I=864e13;function k(t,n){if(n<=0)throw new Error(`temporal-fmt: splitInterval requires n > 0 (got ${n}).`);if(n===1)return[t];let o=f(t.start),r=f(t.end),e=y(o),s=y(r);if(Math.abs(e)>I||Math.abs(s)>I)throw new RangeError("temporal-fmt: splitInterval() endpoints are outside the representable Date range (approximately \xB1275,760 years). Split the interval into smaller ranges first.");let l=(s-e)/n,d=[];for(let u=0;u<n;u++){let c=e+u*l,i=u===n-1?s:c+l;d.push({start:w(c,o),end:w(i,r),bounds:u===0?t.bounds:"half-open-start"})}return d}function y(t){let n=t.year,o=t.month,r=t.day,e=o<=2?n-1:n,s=Math.floor((e>=0?e:e-399)/400),l=e-s*400,d=o>2?o-3:o+9,u=Math.floor((153*d+2)/5)+r-1,c=l*365+Math.floor(l/4)-Math.floor(l/100)+u;return(s*146097+c-719468)*864e5+(t.hour??0)*36e5+(t.minute??0)*6e4+(t.second??0)*1e3+(t.millisecond??0)}function w(t,n){let r=Math.floor(t/864e5),e=t%864e5;e<0&&(e+=864e5);let s=Math.floor(e/36e5),l=Math.floor(e%36e5/6e4),d=Math.floor(e%6e4/1e3),u=e%1e3,c=r*864e5,i=new Date(c);return{...n,year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),hour:s,minute:l,second:d,millisecond:u}}function V(t,n,o={}){try{let r=p(t.start,n,o),e=p(t.end,n,o);return`${r} \u2013 ${e}`}catch(r){try{let e=new Intl.DateTimeFormat(b(o.locale??"en-US"),{}),s=_(t.start),l=_(t.end);return e.formatRange(s,l)}catch{throw r}}}function C(t,n,o={}){let r=h(t.start,n,o),e=h(t.end,n,o),s=[...r];return s.push({type:"literal",value:" \u2013 "}),s.push(...e),s}function _(t){let n=t;if(typeof n?.toInstant=="function")return new Date(n.toInstant().epochMilliseconds);if(typeof n?.year=="number"&&typeof n?.month=="number"&&typeof n?.day=="number")return new Date(Date.UTC(n.year,n.month-1,n.day,n.hour??0,n.minute??0,n.second??0,n.millisecond??0));throw new Error(`temporal-fmt: formatRange() expected Temporal values with year/month/day, got ${typeof t}.`)}export{x as a,F as b,E as c,m as d,S as e,T as f,B as g,R as h,v as i,A as j,O as k,k as l,V as m,C as n};
|
|
2
|
+
//# sourceMappingURL=chunk-F4RGUDA3.js.map
|