@webority/web-core 0.146.2 → 0.148.0

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.
@@ -1 +1 @@
1
- import{ACCESS_TOKEN_KEY as e,REFRESH_TOKEN_KEY as t,clearSession as n,getToken as r,storeToken as i}from"../auth/authStore.js";import{Logger as a}from"../logger/logger.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d,f,p=e=>{d=e},m=e=>{f=e},h=null,g=[],_=(e,t=null)=>{g.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),g=[]},v=()=>{h=null,_(/* @__PURE__ */ Error(`[@webority/web-core] Session ended`))},y=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,b=()=>{if(!d||!f)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:d,auth:f}},x=()=>f?.accountId,S=()=>f?.refresh.path,C=async()=>{let e=b();await e.store.dispatch(e.auth.logout())},w=async(e,t,r)=>{await n(e,{code:t,detail:r}),await C()},T=e=>{let t=e&&typeof e==`object`?e.code:void 0;return t===`session_revoked`||t===`session_expired`?t:null},E=e=>{let t=e&&typeof e==`object`?e.detail:void 0;return typeof t==`string`&&t!==``&&T(e)!==null?t:null},D=e=>{if(!c.isAxiosError(e)||!e.response)return null;let t=e.response.data,n=t&&typeof t==`object`?t.code:void 0;return typeof n==`string`&&f?.endSessionOn?.includes(n)?n:null},O=()=>h!==null,k=0,A=Promise.resolve(),j=null,M=()=>{k===0&&(A=new Promise(e=>{j=e})),k+=1;let e=!1;return()=>{e||(e=!0,--k,k===0&&(j?.(),j=null))}},N=()=>k===0?Promise.resolve():A,P=async n=>{let r;try{r=(f?.refresh.readTokens??H)(n)}catch(e){a.error(`A session-replacing response carried no tokens:`,y(e));return}await i(e,r.accessToken,r.accessTokenExpiry),await i(t,r.refreshToken,r.refreshTokenExpiry)},F=async e=>{let t=(await r(`accessToken`))?.token??null;return t!==null&&t!==e?t:null},I=()=>new Promise((e,t)=>{g.push({resolve:e,reject:t})}),L=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},R=e=>e instanceof L||c.isAxiosError(e)&&(e.response?.status===400||e.response?.status===401),z=e=>!c.isAxiosError(e)||e.response?.status!==401?null:T(e.response.data),B=e=>!c.isAxiosError(e)||e.response?.status!==401?null:E(e.response.data),V=(e,t)=>{if(typeof e!=`string`||e===``)throw Error(`The refresh response has no "${t}".`);return e},H=e=>{let t=e??{};return{accessToken:V(t.accessToken,`accessToken`),accessTokenExpiry:V(t.accessTokenExpiration,`accessTokenExpiration`),refreshToken:V(t.refreshToken,`refreshToken`),refreshTokenExpiry:V(t.refreshTokenExpiration,`refreshTokenExpiration`)}},U=async n=>{await N();let o=await r(t);if(!o?.token)throw new L(`No refresh token available`);if(Date.parse(o.expiry)<=Date.now())throw new L(`Refresh token expired`);let c={accessToken:(await r(`accessToken`))?.token??null,refreshToken:o.token},l=n.body?await n.body(c):c,u=n.headers?await n.headers():void 0;a.info(`Refreshing the access token`);let{data:d}=await s.post(n.path,l,u?{headers:u}:void 0),f=(n.readTokens??H)(d);await N();let p=(await r(`refreshToken`))?.token===o.token?null:await r(e);return p?.token?(a.info(`Keeping the session that replaced this one during the refresh`),p.token):(await i(e,f.accessToken,f.accessTokenExpiry),await i(t,f.refreshToken,f.refreshTokenExpiry),a.info(`Access token refreshed`),f.accessToken)},W=3e4,G=async(t,n)=>{let i=await r(e);return i?.token&&i.token!==n&&Date.parse(i.expiry)>Date.now()+W?(a.info(`Adopting the access token another tab refreshed`),i.token):U(t)},K=()=>{if(h)return h;let e=(async()=>{let e=null;try{let{refresh:t}=b().auth;e=(await r(`accessToken`))?.token??null;let n=await o(()=>G(t,e));return _(null,n),n}catch(t){if(R(t)){await N();let t=await F(e);if(t)return a.info(`The session was replaced during the refresh; continuing with the new one`),_(null,t),t}let n=D(t);if(n!==null)throw _(t,null),await w(`terminated`,n,E(c.isAxiosError(t)?t.response?.data:void 0)),t;let r=c.isAxiosError(t)?t.response?.data:void 0;throw a.error(`Token refresh failed:`,r??y(t)),_(t,null),R(t)&&await w(`rejected`,z(t),B(t)),t}})().finally(()=>{h===e&&(h=null)});return h=e,e};export{u as SESSION_EXPIRED_CODE,l as SESSION_REVOKED_CODE,M as beginSessionReplacement,F as currentTokenIfReplaced,C as dispatchLogout,w as endSessionAndLogout,D as endSessionCodeOf,x as getAccountIdProvider,y as getErrorMessage,S as getRefreshPath,p as injectStore,m as injectUserAuth,O as isRefreshInFlight,I as queueBehindRefresh,K as refreshAccessToken,v as resetRefreshState,T as sessionCodeOf,E as sessionDetailOf,P as storeReplacementSession,N as waitForSessionReplacement};
1
+ import{ACCESS_TOKEN_KEY as e,REFRESH_TOKEN_KEY as t,clearSession as n,getToken as r,storeToken as i}from"../auth/authStore.js";import{Logger as a}from"../logger/logger.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},f,p,m=e=>{f=e},h=e=>{p=e},g=null,_=[],v=(e,t=null)=>{_.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),_=[]},y=()=>{g=null,v(new d(`[@webority/web-core] Session ended`))},b=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,x=()=>{if(!f||!p)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:f,auth:p}},S=()=>p?.accountId,C=()=>p?.refresh.path,w=async()=>{let e=x();await e.store.dispatch(e.auth.logout())},T=async(e,t,r)=>{await n(e,{code:t,detail:r}),await w()},E=e=>{let t=e&&typeof e==`object`?e.code:void 0;return t===`session_revoked`||t===`session_expired`?t:null},D=e=>{let t=e&&typeof e==`object`?e.detail:void 0;return typeof t==`string`&&t!==``&&E(e)!==null?t:null},O=e=>{if(!c.isAxiosError(e)||!e.response)return null;let t=e.response.data,n=t&&typeof t==`object`?t.code:void 0;return typeof n==`string`&&p?.endSessionOn?.includes(n)?n:null},k=()=>g!==null,A=0,j=Promise.resolve(),M=null,N=()=>{A===0&&(j=new Promise(e=>{M=e})),A+=1;let e=!1;return()=>{e||(e=!0,--A,A===0&&(M?.(),M=null))}},P=()=>A===0?Promise.resolve():j,F=class e extends Error{constructor(t){super(`A session-replacing response carried no tokens: ${t}`),this.name=`ReplacementTokensMissingError`,Object.setPrototypeOf(this,e.prototype)}},I=async n=>{let r;try{r=(p?.refresh.readTokens??G)(n)}catch(e){throw new F(b(e))}await i(e,r.accessToken,r.accessTokenExpiry),await i(t,r.refreshToken,r.refreshTokenExpiry)},L=async e=>{let t=(await r(`accessToken`))?.token??null;return t!==null&&t!==e?t:null},R=()=>new Promise((e,t)=>{_.push({resolve:e,reject:t})}),z=e=>e instanceof d||c.isAxiosError(e)&&(e.response?.status===400||e.response?.status===401),B=e=>!c.isAxiosError(e)||e.response?.status!==401?null:E(e.response.data),V=e=>!c.isAxiosError(e)||e.response?.status!==401?null:D(e.response.data),H=e=>z(e)||O(e)!==null,U=e=>c.isAxiosError(e)?E(e.response?.data)??`status ${e.response?.status}`:b(e),W=(e,t)=>{if(typeof e!=`string`||e===``)throw Error(`The refresh response has no "${t}".`);return e},G=e=>{let t=e??{};return{accessToken:W(t.accessToken,`accessToken`),accessTokenExpiry:W(t.accessTokenExpiration,`accessTokenExpiration`),refreshToken:W(t.refreshToken,`refreshToken`),refreshTokenExpiry:W(t.refreshTokenExpiration,`refreshTokenExpiration`)}},K=async n=>{await P();let o=await r(t);if(!o?.token)throw new d(`No refresh token available`);if(Date.parse(o.expiry)<=Date.now())throw new d(`Refresh token expired`);let c={accessToken:(await r(`accessToken`))?.token??null,refreshToken:o.token},l=n.body?await n.body(c):c,u=n.headers?await n.headers():void 0;a.info(`Refreshing the access token`);let{data:f}=await s.post(n.path,l,{...u?{headers:u}:{},skipErrorLog:!0}),p=(n.readTokens??G)(f);await P();let m=(await r(`refreshToken`))?.token===o.token?null:await r(e);return m?.token?(a.info(`Keeping the session that replaced this one during the refresh`),m.token):(await i(e,p.accessToken,p.accessTokenExpiry),await i(t,p.refreshToken,p.refreshTokenExpiry),a.info(`Access token refreshed`),p.accessToken)},q=3e4,J=async(t,n)=>{let i=await r(e);return i?.token&&i.token!==n&&Date.parse(i.expiry)>Date.now()+q?(a.info(`Adopting the access token another tab refreshed`),i.token):K(t)},Y=()=>{if(g)return g;let e=(async()=>{let e=null;try{let{refresh:t}=x().auth;e=(await r(`accessToken`))?.token??null;let n=await o(()=>J(t,e));return v(null,n),n}catch(t){if(z(t)){await P();let t=await L(e);if(t)return a.info(`The session was replaced during the refresh; continuing with the new one`),v(null,t),t}let n=O(t);if(n!==null)throw a.info(`Session ended, the refresh was refused: ${n}`),v(t,null),await T(`terminated`,n,D(c.isAxiosError(t)?t.response?.data:void 0)),t;let r=z(t);if(r)a.info(`Session ended, the refresh was refused:`,U(t));else{let e=c.isAxiosError(t)?t.response?.data:void 0;a.error(`Token refresh failed:`,e??b(t))}throw v(t,null),r&&await T(`rejected`,B(t),V(t)),t}})().finally(()=>{g===e&&(g=null)});return g=e,e};export{u as SESSION_EXPIRED_CODE,l as SESSION_REVOKED_CODE,d as SessionEndedError,N as beginSessionReplacement,L as currentTokenIfReplaced,w as dispatchLogout,T as endSessionAndLogout,O as endSessionCodeOf,S as getAccountIdProvider,b as getErrorMessage,C as getRefreshPath,m as injectStore,h as injectUserAuth,k as isRefreshInFlight,H as isSessionEnd,R as queueBehindRefresh,Y as refreshAccessToken,y as resetRefreshState,E as sessionCodeOf,D as sessionDetailOf,I as storeReplacementSession,P as waitForSessionReplacement};
@@ -1 +1 @@
1
- import{ACCESS_TOKEN_KEY as e,getToken as t}from"../auth/authStore.js";import{Logger as n}from"../logger/logger.js";import{getLastKnownNetworkStatus as r}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as i}from"./baseUrl.js";import{applyClientHeaders as a,readAccountId as o,stampAccountId as s}from"./clientHeaders.js";import{applyDesignSample as c}from"./designSample.js";import{readMinAppVersion as l}from"./minAppVersion.js";import{sendFormDataAsMultipart as u}from"./multipart.js";import{applyRequestDefaults as d}from"./requestDefaults.js";import{responseBodyText as f}from"./responseBodyText.js";import{attachRetry as p}from"./retry.js";import{SESSION_EXPIRED_CODE as m,SESSION_REVOKED_CODE as h,beginSessionReplacement as g,currentTokenIfReplaced as _,endSessionAndLogout as v,endSessionCodeOf as y,getAccountIdProvider as b,getErrorMessage as x,getRefreshPath as S,injectStore as C,injectUserAuth as w,isRefreshInFlight as T,queueBehindRefresh as E,refreshAccessToken as D,resetRefreshState as O,sessionCodeOf as k,sessionDetailOf as A,storeReplacementSession as j,waitForSessionReplacement as M}from"./tokenRefresh.js";import{WorkspaceChangedError as N,isWorkspaceChangedResponse as P,workspaceChangedFromResponse as F}from"./workspaceChanged.js";import I,{AxiosHeaders as L}from"axios";var R=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},z=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},B=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},V=e=>{let t=e.headers instanceof L?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},H=I.create({headers:{"Content-Type":`application/json`}});l(H),p(H);var U=(e,t)=>{e.headers instanceof L?e.headers.set(`Authorization`,`Bearer ${t}`):e.headers=L.from({...e.headers,Authorization:`Bearer ${t}`})},W=e=>{let t=S();return!!t&&!!e?.includes(t)};i(H),d(H),u(H),a(H),c(H),H.interceptors.request.use(async i=>{if(B(i),(await r()).isConnected===!1)return n.warn(`Request blocked: browser is offline. URL: ${i.url}`),Promise.reject(new R);try{if(W(i.url))return i;await s(i,b());let r=await t(e);if(!r?.token)throw new z;let a=Date.now();return Date.parse(r.expiry)<=a+3e4?(n.info(`Access token expired or about to expire, refreshing before request`),U(i,await D())):U(i,r.token),i.replacesSession&&(i._endReplacement=g()),i}catch(e){return e instanceof z?n.info(`Request not sent: signed out. URL: ${i.url}`):n.error(`Failed to attach token:`,x(e)),Promise.reject(e)}},e=>(n.error(`Request error:`,x(e)),Promise.reject(e))),H.interceptors.response.use(async e=>{let t=e.config;if(t._endReplacement)try{await j(e.data)}finally{B(t)}return e},async e=>{if(B(e?.config),I.isCancel(e)||e instanceof R||e instanceof z||e instanceof N)return Promise.reject(e);if(!I.isAxiosError(e))return n.error(`Non-axios error in response interceptor: ${x(e)}`),Promise.reject(e);let t=e,r=t.config;if(!t.response)return r?.skipErrorLog||n.error(`Network error or no response from server: ${t.message}, URL: ${r?.url}`),Promise.reject(e);if(P(t))return n.info(`Request refused: the workspace changed after it was made. URL: ${r?.url}`),Promise.reject(F(t));if(t.response.status===401&&r&&!r._replayedWithCurrentToken&&!r.replacesSession&&!W(r.url)&&(await M(),await _(V(r))))return(r._accountId??null)===await o(b())?(n.info(`Session changed while the request was in flight; sending it again. URL: ${r.url}`),r._replayedWithCurrentToken=!0,H(r)):(n.info(`Session moved to another workspace while the request was in flight; not sending it again. URL: ${r.url}`),Promise.reject(new N(void 0,{config:r,cause:e})));let i=W(r?.url)?null:y(t);if(i!==null)return n.warn(`Session ended by ${i}, logging out. URL: ${r?.url}`),O(),await v(`terminated`,i,A(t.response?.data)),Promise.reject(e);if(t.response.status===401&&r&&!r._retry){if(W(r.url))return Promise.reject(e);let i=k(t.response.data);if(i!==null)return n.warn(`Session ${i}, logging out without refresh. URL: ${r.url}`),O(),await v(`terminated`,i,A(t.response.data)),Promise.reject(e);if(n.warn(`Unauthorized URL: ${r.url}`),r._retry=!0,T())return E().then(e=>(n.info(`Retrying request after token refresh:`,r.url),U(r,e),H(r))).catch(e=>(e instanceof N||n.error(`Failed to retry request after token refresh:`,x(e)),Promise.reject(e)));try{return U(r,await D()),H(r)}catch(e){return Promise.reject(e)}}if(!r?.skipErrorLog){let e=`Response error: ${f(t.response?.data,t.message)}, URL: ${r?.url}, Status: ${t.response.status}`;r?.expectedStatuses?.includes(t.response.status)?n.debug(e):n.error(e)}return Promise.reject(e)});export{R as RequestOfflineError,m as SESSION_EXPIRED_CODE,h as SESSION_REVOKED_CODE,H as default,C as injectStore,w as injectUserAuth,O as resetRefreshState};
1
+ import{ACCESS_TOKEN_KEY as e,getToken as t}from"../auth/authStore.js";import{Logger as n}from"../logger/logger.js";import{getLastKnownNetworkStatus as r}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as i}from"./baseUrl.js";import{applyClientHeaders as a,readAccountId as o,stampAccountId as s}from"./clientHeaders.js";import{applyDesignSample as c}from"./designSample.js";import{readMinAppVersion as l}from"./minAppVersion.js";import{sendFormDataAsMultipart as u}from"./multipart.js";import{applyRequestDefaults as d}from"./requestDefaults.js";import{responseBodyText as f}from"./responseBodyText.js";import{attachRetry as p}from"./retry.js";import{SESSION_EXPIRED_CODE as m,SESSION_REVOKED_CODE as h,SessionEndedError as g,beginSessionReplacement as _,currentTokenIfReplaced as v,endSessionAndLogout as y,endSessionCodeOf as b,getAccountIdProvider as x,getErrorMessage as S,getRefreshPath as C,injectStore as w,injectUserAuth as T,isRefreshInFlight as E,isSessionEnd as D,queueBehindRefresh as O,refreshAccessToken as k,resetRefreshState as A,sessionCodeOf as j,sessionDetailOf as M,storeReplacementSession as N,waitForSessionReplacement as P}from"./tokenRefresh.js";import{WorkspaceChangedError as F,isWorkspaceChangedResponse as I,workspaceChangedFromResponse as L}from"./workspaceChanged.js";import R,{AxiosHeaders as z}from"axios";var B=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},V=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},H=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},U=e=>{let t=e.headers instanceof z?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},W=R.create({headers:{"Content-Type":`application/json`}});l(W),p(W);var G=(e,t)=>{e.headers instanceof z?e.headers.set(`Authorization`,`Bearer ${t}`):e.headers=z.from({...e.headers,Authorization:`Bearer ${t}`})},K=e=>{let t=C();return!!t&&!!e?.includes(t)};i(W),d(W),u(W),a(W),c(W),W.interceptors.request.use(async i=>{if(H(i),(await r()).isConnected===!1)return n.warn(`Request blocked: browser is offline. URL: ${i.url}`),Promise.reject(new B);try{if(K(i.url))return i;await s(i,x());let r=await t(e);if(!r?.token)throw new V;let a=Date.now();return Date.parse(r.expiry)<=a+3e4?(n.info(`Access token expired or about to expire, refreshing before request`),G(i,await k())):G(i,r.token),i.replacesSession&&(i._endReplacement=_()),i}catch(e){return e instanceof V?n.info(`Request not sent: signed out. URL: ${i.url}`):D(e)||n.error(`Failed to attach token:`,S(e)),Promise.reject(e)}},e=>(n.error(`Request error:`,S(e)),Promise.reject(e))),W.interceptors.response.use(async e=>{let t=e.config;if(t._endReplacement)try{await N(e.data)}finally{H(t)}return e},async e=>{if(H(e?.config),R.isCancel(e)||e instanceof B||e instanceof V||e instanceof g||e instanceof F)return Promise.reject(e);if(!R.isAxiosError(e))return n.error(`Non-axios error in response interceptor: ${S(e)}`),Promise.reject(e);let t=e,r=t.config;if(!t.response)return r?.skipErrorLog||n.error(`Network error or no response from server: ${t.message}, URL: ${r?.url}`),Promise.reject(e);if(I(t))return n.info(`Request refused: the workspace changed after it was made. URL: ${r?.url}`),Promise.reject(L(t));if(K(r?.url))return Promise.reject(e);if(t.response.status===401&&r&&!r._replayedWithCurrentToken&&!r.replacesSession&&(await P(),await v(U(r))))return(r._accountId??null)===await o(x())?(n.info(`Session changed while the request was in flight; sending it again. URL: ${r.url}`),r._replayedWithCurrentToken=!0,W(r)):(n.info(`Session moved to another workspace while the request was in flight; not sending it again. URL: ${r.url}`),Promise.reject(new F(void 0,{config:r,cause:e})));let i=b(t);if(i!==null)return n.warn(`Session ended by ${i}, logging out. URL: ${r?.url}`),A(),await y(`terminated`,i,M(t.response?.data)),Promise.reject(e);if(t.response.status===401&&r&&!r._retry){let i=j(t.response.data);if(i!==null)return n.warn(`Session ${i}, logging out without refresh. URL: ${r.url}`),A(),await y(`terminated`,i,M(t.response.data)),Promise.reject(e);if(n.warn(`Unauthorized URL: ${r.url}`),r._retry=!0,E())return O().then(e=>(n.info(`Retrying request after token refresh:`,r.url),G(r,e),W(r))).catch(e=>(!D(e)&&!(e instanceof F)&&n.error(`Failed to retry request after token refresh:`,S(e)),Promise.reject(e)));try{return G(r,await k()),W(r)}catch(e){return Promise.reject(e)}}if(!r?.skipErrorLog){let e=`Response error: ${f(t.response?.data,t.message)}, URL: ${r?.url}, Status: ${t.response.status}`;r?.expectedStatuses?.includes(t.response.status)?n.debug(e):n.error(e)}return Promise.reject(e)});export{B as RequestOfflineError,m as SESSION_EXPIRED_CODE,h as SESSION_REVOKED_CODE,W as default,w as injectStore,T as injectUserAuth,A as resetRefreshState};
@@ -1 +1 @@
1
- import{Logger as e}from"../logger/logger.js";import{getJWTExpiry as t}from"./jwt.js";var n=`accessToken`,r=`refreshToken`,i=`sessionUser`,a=2592e6,o=/* @__PURE__ */ new Set([n,r,i]),s=null,c=()=>globalThis.localStorage,l=()=>globalThis.sessionStorage,u=(e,t)=>{try{return e().getItem(t)}catch{return null}},d=(e,t)=>{try{e().removeItem(t)}catch{}},f=()=>s===null?u(c,`refreshToken`)!==null||u(c,`accessToken`)!==null:s,p=()=>f()?c:l,m=()=>f()?l:c,h=t=>{s=t;let n=p(),r=m();for(let t of o){let i=u(r,t);if(i!==null)try{n().setItem(t,i),d(r,t)}catch(n){e.error(`[authStore] could not move "${t}" to the chosen store`,n)}}},g=/* @__PURE__ */ new Set,_=`sessionEnded`,v=()=>u(l,_)!==null,y=(t,n)=>{try{l().setItem(_,t)}catch{}for(let r of[...g])try{r(t,n)}catch(t){e.error(`[authStore] a session-ended listener threw`,t)}},b=e=>{if(e.storageArea!==c())return;let t=e.key===`refreshToken`&&e.oldValue!==null&&e.newValue===null;(e.key===null||t)&&u(l,`refreshToken`)===null&&y(`otherTab`,{code:null,detail:null})},x=e=>(g.size===0&&typeof window<`u`&&window.addEventListener(`storage`,b),g.add(e),()=>{g.delete(e),g.size===0&&typeof window<`u`&&window.removeEventListener(`storage`,b)}),S=async(t,n,r)=>{try{p()().setItem(t,JSON.stringify({token:n,expiry:r})),d(m(),t),d(l,_)}catch(n){throw e.error(`Error storing token for key: ${t}`,n),n}},C=e=>{try{let t=JSON.parse(e);return t&&typeof t==`object`&&typeof t.token==`string`&&typeof t.expiry==`string`?t:null}catch{return null}},w=e=>u(l,e)??u(c,e),T=async t=>{let n=w(t);return n===null&&j(t)&&L()&&(n=w(t)),n===null?null:C(n)||(e.warn(`Stored credentials for key "${t}" are not a valid token; clearing them.`),j(t)?await R(`corrupt`,!0):await D(t),null)},E=()=>{w(`refreshToken`)===null&&w(`accessToken`)===null&&L();let e=w(r);if(e!==null&&C(e)!==null)return!0;let t=w(n),i=t===null?null:C(t);if(i===null)return!1;let a=Date.parse(i.expiry);return Number.isNaN(a)||a>Date.now()},D=async e=>{d(c,e),d(l,e)},O=async t=>{try{p()().setItem(i,JSON.stringify(t)),d(m(),i)}catch(t){throw e.error(`Error storing the session user`,t),t}},k=async()=>{let t=w(i);if(t===null)return null;try{return JSON.parse(t)}catch{return e.warn(`The stored session user is not valid JSON; clearing it.`),await A(),null}},A=async()=>{d(c,i),d(l,i)},j=e=>e===`accessToken`||e===`refreshToken`,M=null,N=!1,P=e=>{M=e,N=!1},F=e=>{let t=C(e);if(t)return t;let n=e;try{let t=JSON.parse(e);typeof t==`string`&&(n=t)}catch{}return n.trim()===``?null:{token:n,expiry:null}},I=e=>e.split(`.`).length===3?t(e)?.toISOString()??null:null,L=()=>{if(!M||N)return!1;N=!0;let t=M,a=[c,l].every(e=>u(e,`accessToken`)===null&&u(e,`refreshToken`)===null),o=!1;for(let s of[c,l]){let l=u(s,t.accessToken),f=u(s,t.refreshToken),p=t.sessionUser?u(s,t.sessionUser):null;if(a&&!o&&(l!==null||f!==null))try{let t=l===null?null:F(l),a=f===null?null:F(f);if(t){let e=t.expiry??I(t.token)??(/* @__PURE__ */ new Date()).toISOString();s().setItem(n,JSON.stringify({token:t.token,expiry:e}))}if(a){let e=a.expiry??I(a.token)??new Date(Date.now()+2592e6).toISOString();s().setItem(r,JSON.stringify({token:a.token,expiry:e}))}p!==null&&s().setItem(i,p),o=t!==null||a!==null,o&&e.breadcrumb(`[authStore] moved a session from the legacy token keys`,{store:s===c?`localStorage`:`sessionStorage`})}catch(t){e.error(`[authStore] could not move the session from the legacy token keys`,t)}for(let e of[t.accessToken,t.refreshToken,t.sessionUser])e&&d(s,e)}return o},R=async(e,t,i=null,a=null)=>{let o=t||await T(`accessToken`)!==null||await T(`refreshToken`)!==null;await D(n),await D(r),await A(),s=null,(o||t)&&y(e,{code:i,detail:a})},z=async(e=`signedOut`,t={})=>R(e,!1,t.code??null,t.detail??null);export{n as ACCESS_TOKEN_KEY,a as LEGACY_REFRESH_TOKEN_LIFETIME_MS,r as REFRESH_TOKEN_KEY,i as SESSION_USER_KEY,x as addSessionEndedListener,z as clearSession,f as getKeepSignedIn,k as getSessionUser,T as getToken,E as hasSession,v as hasSessionEndedInTab,A as removeSessionUser,D as removeToken,h as setKeepSignedIn,P as setLegacyTokenKeys,O as storeSessionUser,S as storeToken};
1
+ import{Logger as e}from"../logger/logger.js";import{getJWTExpiry as t}from"./jwt.js";var n=`accessToken`,r=`refreshToken`,i=`sessionUser`,a=2592e6,o=/* @__PURE__ */ new Set([n,r,i]),s=null,c=()=>globalThis.localStorage,l=()=>globalThis.sessionStorage,u=(e,t)=>{try{return e().getItem(t)}catch{return null}},d=(e,t)=>{try{e().removeItem(t)}catch{}},f=()=>s===null?u(c,`refreshToken`)!==null||u(c,`accessToken`)!==null:s,p=()=>f()?c:l,m=()=>f()?l:c,h=t=>{let n=s;s=t;let r=p(),i=m();for(let t of o){let a=u(i,t);if(a!==null)try{r().setItem(t,a),d(i,t)}catch(r){throw s=n,e.error(`[authStore] could not move "${t}" to the chosen store`,r),r}}},g=/* @__PURE__ */ new Set,_=`sessionEnded`,v=()=>u(l,_)!==null,y=(t,n)=>{try{l().setItem(_,t)}catch{}for(let r of[...g])try{r(t,n)}catch(t){e.error(`[authStore] a session-ended listener threw`,t)}},b=e=>{if(e.storageArea!==c())return;let t=e.key===`refreshToken`&&e.oldValue!==null&&e.newValue===null;(e.key===null||t)&&u(l,`refreshToken`)===null&&y(`otherTab`,{code:null,detail:null})},x=e=>(g.size===0&&typeof window<`u`&&window.addEventListener(`storage`,b),g.add(e),()=>{g.delete(e),g.size===0&&typeof window<`u`&&window.removeEventListener(`storage`,b)}),S=async(t,n,r)=>{try{p()().setItem(t,JSON.stringify({token:n,expiry:r})),d(m(),t),d(l,_)}catch(n){throw e.error(`Error storing token for key: ${t}`,n),n}},C=e=>{try{let t=JSON.parse(e);return t&&typeof t==`object`&&typeof t.token==`string`&&typeof t.expiry==`string`?t:null}catch{return null}},w=e=>u(l,e)??u(c,e),T=async t=>{let n=w(t);return n===null&&j(t)&&L()&&(n=w(t)),n===null?null:C(n)||(e.warn(`Stored credentials for key "${t}" are not a valid token; clearing them.`),j(t)?await R(`corrupt`,!0):await D(t),null)},E=()=>{w(`refreshToken`)===null&&w(`accessToken`)===null&&L();let e=w(r);if(e!==null&&C(e)!==null)return!0;let t=w(n),i=t===null?null:C(t);if(i===null)return!1;let a=Date.parse(i.expiry);return Number.isNaN(a)||a>Date.now()},D=async e=>{d(c,e),d(l,e)},O=async t=>{try{p()().setItem(i,JSON.stringify(t)),d(m(),i)}catch(t){throw e.error(`Error storing the session user`,t),t}},k=async()=>{let t=w(i);if(t===null)return null;try{return JSON.parse(t)}catch{return e.warn(`The stored session user is not valid JSON; clearing it.`),await A(),null}},A=async()=>{d(c,i),d(l,i)},j=e=>e===`accessToken`||e===`refreshToken`,M=null,N=!1,P=e=>{M=e,N=!1},F=e=>{let t=C(e);if(t)return t;let n=e;try{let t=JSON.parse(e);typeof t==`string`&&(n=t)}catch{}return n.trim()===``?null:{token:n,expiry:null}},I=e=>e.split(`.`).length===3?t(e)?.toISOString()??null:null,L=()=>{if(!M||N)return!1;N=!0;let t=M,a=[c,l].every(e=>u(e,`accessToken`)===null&&u(e,`refreshToken`)===null),o=!1;for(let s of[c,l]){let l=u(s,t.accessToken),f=u(s,t.refreshToken),p=t.sessionUser?u(s,t.sessionUser):null,m=!1;if(a&&!o&&(l!==null||f!==null))try{let t=l===null?null:F(l),a=f===null?null:F(f);if(t){let e=t.expiry??I(t.token)??(/* @__PURE__ */ new Date()).toISOString();s().setItem(n,JSON.stringify({token:t.token,expiry:e}))}if(a){let e=a.expiry??I(a.token)??new Date(Date.now()+2592e6).toISOString();s().setItem(r,JSON.stringify({token:a.token,expiry:e}))}p!==null&&s().setItem(i,p),o=t!==null||a!==null,o&&e.breadcrumb(`[authStore] moved a session from the legacy token keys`,{store:s===c?`localStorage`:`sessionStorage`})}catch(t){m=!0,d(s,n),d(s,r),e.error(`[authStore] could not move the session from the legacy token keys`,t)}if(!m)for(let e of[t.accessToken,t.refreshToken,t.sessionUser])e&&d(s,e)}return o},R=async(e,t,i=null,a=null)=>{let o=t||await T(`accessToken`)!==null||await T(`refreshToken`)!==null;await D(n),await D(r),await A(),s=null,(o||t)&&y(e,{code:i,detail:a})},z=async(e=`signedOut`,t={})=>R(e,!1,t.code??null,t.detail??null);export{n as ACCESS_TOKEN_KEY,a as LEGACY_REFRESH_TOKEN_LIFETIME_MS,r as REFRESH_TOKEN_KEY,i as SESSION_USER_KEY,x as addSessionEndedListener,z as clearSession,f as getKeepSignedIn,k as getSessionUser,T as getToken,E as hasSession,v as hasSessionEndedInTab,A as removeSessionUser,D as removeToken,h as setKeepSignedIn,P as setLegacyTokenKeys,O as storeSessionUser,S as storeToken};
@@ -1,2 +1,2 @@
1
1
  var e=`Something went wrong on our side. Please try again in a moment.`,t=`You appear to be offline. Check your connection and try again.`,n=`We couldn't reach the server. Check your connection and try again.`,r=`That took too long to respond. Check your connection and try again.`,i=`Something went wrong. Please try again.`,a=`request_canceled`,o=`contract_error`,s=`timeout`,c=`network`,l=`offline`,u=e=>`Request failed (${e})`,d={401:{code:`unauthorized`,sentence:`Please sign in to continue.`},403:{code:`forbidden`,sentence:`You do not have access to this.`}},f=e=>typeof e==`object`&&!!e&&!Array.isArray(e),p=e=>typeof e==`string`&&e.trim().length>0?e:null,m=(e,t)=>{let n=d[e];if(n===void 0||t===null||t.code!==n.code)return null;let r=p(t.detail);return r===null||r===n.sentence?n.sentence:null},h=e=>e.length>300||/^\s*</.test(e)||e.includes(`
2
- at `)||/\b(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),g=e=>{let t=p(e);return t!==null&&!h(t)?t:null},_=e=>e.replace(/^\$\.?/,``).split(`.`).map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(`.`),v=e=>{if(Array.isArray(e)){for(let t of e){let e=p(t);if(e!==null)return e}return null}return p(e)},y=(e,t,n)=>{let r=_(t);r===``?e.form??=n:r in e.fields||(e.fields[r]=n)},b=e=>{let t={fields:{},form:null};if(Array.isArray(e)){for(let n of e){if(!f(n))continue;let e=p(n.message);e!==null&&y(t,typeof n.field==`string`?n.field:``,e)}return t}if(!f(e))return t;for(let[n,r]of Object.entries(e)){let e=v(r);e!==null&&y(t,n,e)}return t},x=e=>f(e)&&typeof e.message==`string`&&typeof e.status==`number`&&typeof e.offline==`boolean`&&f(e.fieldErrors),S=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),C=()=>typeof navigator<`u`&&navigator.onLine===!1,w=e=>{let t=f(e.config)?e.config.headers:void 0;if(!f(t))return null;let n=typeof t.get==`function`?t.get(`traceparent`):t.traceparent??t.Traceparent,r=typeof n==`string`?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null;return r?r[1]:null},T=e=>{let o=p(e.code),u=p(e.name),d=p(e.message),f=w(e);return u===`CanceledError`||o===`ERR_CANCELED`?S({code:a,message:i,traceId:f,diagnostic:d}):o===`ECONNABORTED`||o===`ETIMEDOUT`?S({code:s,message:r,offline:!0,traceId:f,diagnostic:d}):u===`RequestOfflineError`||o===`ERR_NETWORK`||d===`Network Error`?C()?S({code:l,message:t,offline:!0,traceId:f,diagnostic:d}):S({code:c,message:n,offline:!0,traceId:f,diagnostic:d}):S({message:i,traceId:f,diagnostic:d})};function E(e){if(x(e))return e;if(typeof e==`string`)return S({message:g(e)??`Something went wrong. Please try again.`,diagnostic:e||null});if(!f(e))return S({message:i,diagnostic:e==null?null:String(e)});if(e.isContractError===!0)return S({code:o,message:g(e.message)??`Something went wrong. Please try again.`,diagnostic:p(e.message)});let t=f(e.response)?e.response:null,n=typeof t?.status==`number`?t.status:typeof e.status==`number`?e.status:0,r=t?t.data:e.body;if(n===0&&r==null)return T(e);let a=f(r)?r:null,{fields:s,form:c}=b(a?.errors),l=p(a?.code),d=p(a?.traceId)??w(e),h=p(a?.detail)??p(a?.title)??p(r)??p(e.message),_;return _=n>=500?(l!==null&&l!==`internal_error`?g(a?.detail):null)??`Something went wrong on our side. Please try again in a moment.`:m(n,a)??g(Object.values(s)[0])??g(c)??g(a?.detail)??g(a?.title)??g(r)??(n?u(n):`Something went wrong. Please try again.`),S({code:l,message:_,fieldErrors:s,status:n,traceId:d,diagnostic:h})}var D=e=>E(e).offline;function O(e,t){let n=E(e);return n.offline||t!==null&&!t||n.status>=500&&n.message!==`Something went wrong on our side. Please try again in a moment.`?n.message:n.status>=500||n.code===`request_canceled`||n.message===`Something went wrong. Please try again.`||n.message===u(n.status)?t??null:n.message}export{o as CONTRACT_ERROR_CODE,c as NETWORK_CODE,l as OFFLINE_CODE,t as OFFLINE_MESSAGE,a as REQUEST_CANCELED_CODE,e as SERVER_FAILURE_MESSAGE,s as TIMEOUT_CODE,r as TIMEOUT_MESSAGE,i as UNEXPECTED_MESSAGE,n as UNREACHABLE_MESSAGE,O as apiErrorMessage,E as extractApiError,x as isApiError,D as isNoResponse,_ as toFieldPath};
2
+ at `)||/\b(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),g=e=>{let t=p(e);return t!==null&&!h(t)?t:null},_=e=>e.replace(/^\$\.?/,``).split(`.`).map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(`.`),v=e=>{if(Array.isArray(e)){for(let t of e){let e=p(t);if(e!==null)return e}return null}return p(e)},y=(e,t,n)=>{let r=_(t);r===``?e.form??=n:r in e.fields||(e.fields[r]=n)},b=e=>{let t={fields:{},form:null};if(Array.isArray(e)){for(let n of e){if(!f(n))continue;let e=p(n.message);e!==null&&y(t,typeof n.field==`string`?n.field:``,e)}return t}if(!f(e))return t;for(let[n,r]of Object.entries(e)){let e=v(r);e!==null&&y(t,n,e)}return t},x=e=>f(e)&&typeof e.message==`string`&&typeof e.status==`number`&&typeof e.offline==`boolean`&&f(e.fieldErrors),S=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),C=()=>typeof navigator<`u`&&navigator.onLine===!1,w=e=>{let t=f(e.config)?e.config.headers:void 0;if(!f(t))return null;let n=typeof t.get==`function`?t.get(`traceparent`):t.traceparent??t.Traceparent,r=typeof n==`string`?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null;if(r===null)return null;let i=r[1];if(i===void 0)throw Error(`A matched traceparent always carries its trace id group.`);return i},T=e=>{let o=p(e.code),u=p(e.name),d=p(e.message),f=w(e);return u===`CanceledError`||o===`ERR_CANCELED`?S({code:a,message:i,traceId:f,diagnostic:d}):o===`ECONNABORTED`||o===`ETIMEDOUT`?S({code:s,message:r,offline:!0,traceId:f,diagnostic:d}):u===`RequestOfflineError`||o===`ERR_NETWORK`||d===`Network Error`?C()?S({code:l,message:t,offline:!0,traceId:f,diagnostic:d}):S({code:c,message:n,offline:!0,traceId:f,diagnostic:d}):S({message:i,traceId:f,diagnostic:d})};function E(e){if(x(e))return e;if(typeof e==`string`)return S({message:g(e)??`Something went wrong. Please try again.`,diagnostic:e||null});if(!f(e))return S({message:i,diagnostic:e==null?null:String(e)});if(e.isContractError===!0)return S({code:o,message:g(e.message)??`Something went wrong. Please try again.`,diagnostic:p(e.message)});let t=f(e.response)?e.response:null,n=typeof t?.status==`number`?t.status:typeof e.status==`number`?e.status:0,r=t?t.data:e.body;if(n===0&&r==null)return T(e);let a=f(r)?r:null,{fields:s,form:c}=b(a?.errors),l=p(a?.code),d=p(a?.traceId)??w(e),h=p(a?.detail)??p(a?.title)??p(r)??p(e.message),_;return _=n>=500?(l!==null&&l!==`internal_error`?g(a?.detail):null)??`Something went wrong on our side. Please try again in a moment.`:m(n,a)??g(Object.values(s)[0])??g(c)??g(a?.detail)??g(a?.title)??g(r)??(n?u(n):`Something went wrong. Please try again.`),S({code:l,message:_,fieldErrors:s,status:n,traceId:d,diagnostic:h})}var D=e=>E(e).offline;function O(e,t){let n=E(e);return n.offline||t!==null&&!t||n.status>=500&&n.message!==`Something went wrong on our side. Please try again in a moment.`?n.message:n.status>=500||n.code===`request_canceled`||n.message===`Something went wrong. Please try again.`||n.message===u(n.status)?t??null:n.message}export{o as CONTRACT_ERROR_CODE,c as NETWORK_CODE,l as OFFLINE_CODE,t as OFFLINE_MESSAGE,a as REQUEST_CANCELED_CODE,e as SERVER_FAILURE_MESSAGE,s as TIMEOUT_CODE,r as TIMEOUT_MESSAGE,i as UNEXPECTED_MESSAGE,n as UNREACHABLE_MESSAGE,O as apiErrorMessage,E as extractApiError,x as isApiError,D as isNoResponse,_ as toFieldPath};
@@ -1 +1 @@
1
- var e={zone:`IST`,locale:`en-IN`,empty:`-`},t={PointWithCommaGroups:{decimal:`.`,group:`,`},CommaWithPointGroups:{decimal:`,`,group:`.`},CommaWithSpaceGroups:{decimal:`,`,group:`\xA0`},PointWithSpaceGroups:{decimal:`.`,group:`\xA0`}},n=[`DayMonthNameYear`,`DayMonthYear`,`MonthDayYear`,`YearMonthDay`],r={...e},i=/* @__PURE__ */ new Set,a=a=>{if(a===void 0)r={...e},i=/* @__PURE__ */ new Set;else{if(a.numberStyle!==void 0&&!Object.hasOwn(t,a.numberStyle))throw RangeError(`Unknown number style "${a.numberStyle}"; expected one of ${Object.keys(t).join(`, `)}.`);if(a.dateOrder!==void 0&&!n.includes(a.dateOrder))throw RangeError(`Unknown date order "${a.dateOrder}"; expected one of ${n.join(`, `)}.`);for(let e of Object.keys(a)){let t=a[e];t!==void 0&&(r={...r,[e]:t},i.add(e))}}},o=()=>({...r}),s=e=>i.has(e),c=()=>i.has(`locale`)?r.locale:null,l=e=>/-IN(?:-|$)/i.test(e)?`indian`:`international`,u=()=>r.numberStyle===void 0?null:t[r.numberStyle],d=/* @__PURE__ */ new Map,f=e=>{let t=new Intl.NumberFormat(e,{useGrouping:!1}),n=/* @__PURE__ */ new Set;for(let e=0;e<=9;e++)n.add(t.format(e));return n},p=(e,t)=>{let n=[],r=[],i=!1;for(let a of e)t.has(a)?(r.length>0&&(n.push(r),r=[]),i=!0):i&&r.push(a);return n},m=e=>{let t=d.get(e);if(t!==void 0)return t;let n=f(e),r=new Intl.NumberFormat(e,{useGrouping:!0,minimumFractionDigits:1,maximumFractionDigits:1}).format(11111.5),i=p(Array.from(r),n),a={digits:n,decimal:i.length>=1?i[i.length-1]:null,group:i.length>=2?i[0]:null};return d.set(e,a),a},h=(e,t,n)=>t>=0&&t<e.length&&n.has(e[t]),g=(e,t,n)=>{let r=Array.from(e),i=``,a=0;for(;a<r.length;){let e=n.find(({mark:e})=>h(r,a-1,t)&&e.every((e,t)=>r[a+t]===e)&&h(r,a+e.length,t));e===void 0?(i+=r[a],a+=1):(i+=e.to,a+=e.mark.length)}return i},_=(e,t)=>{let n=u();if(n===null)return e.format(t);let{digits:r,decimal:i,group:a}=m(e.resolvedOptions().locale),o=[];return i!==null&&o.push({mark:i,to:n.decimal}),a!==null&&o.push({mark:a,to:n.group}),g(e.format(t),r,o)};export{a as configureFormatters,c as configuredLocale,o as getFormatterConfig,l as groupingForLocale,s as isFormatterConfigured,u as numberSeparators,_ as styledNumber};
1
+ var e={zone:`IST`,locale:`en-IN`,empty:`-`},t={PointWithCommaGroups:{decimal:`.`,group:`,`},CommaWithPointGroups:{decimal:`,`,group:`.`},CommaWithSpaceGroups:{decimal:`,`,group:`\xA0`},PointWithSpaceGroups:{decimal:`.`,group:`\xA0`}},n=[`DayMonthNameYear`,`DayMonthYear`,`MonthDayYear`,`YearMonthDay`],r={...e},i=/* @__PURE__ */ new Set,a=a=>{if(a===void 0)r={...e},i=/* @__PURE__ */ new Set;else{if(a.numberStyle!==void 0&&!Object.hasOwn(t,a.numberStyle))throw RangeError(`Unknown number style "${a.numberStyle}"; expected one of ${Object.keys(t).join(`, `)}.`);if(a.dateOrder!==void 0&&!n.includes(a.dateOrder))throw RangeError(`Unknown date order "${a.dateOrder}"; expected one of ${n.join(`, `)}.`);for(let e of Object.keys(a)){let t=a[e];t!==void 0&&(r={...r,[e]:t},i.add(e))}}},o=()=>({...r}),s=e=>i.has(e),c=()=>i.has(`locale`)?r.locale:null,l=e=>/-IN(?:-|$)/i.test(e)?`indian`:`international`,u=()=>r.numberStyle===void 0?null:t[r.numberStyle],d=/* @__PURE__ */ new Map,f=e=>{let t=new Intl.NumberFormat(e,{useGrouping:!1}),n=/* @__PURE__ */ new Set;for(let e=0;e<=9;e++)n.add(t.format(e));return n},p=(e,t)=>{let n=[],r=[],i=!1;for(let a of e)t.has(a)?(r.length>0&&(n.push(r),r=[]),i=!0):i&&r.push(a);return n},m=e=>{let t=d.get(e);if(t!==void 0)return t;let n=f(e),r=new Intl.NumberFormat(e,{useGrouping:!0,minimumFractionDigits:1,maximumFractionDigits:1}).format(11111.5),i=p(Array.from(r),n),a={digits:n,decimal:i.at(-1)??null,group:i.length>=2?i.at(0)??null:null};return d.set(e,a),a},h=(e,t,n)=>{let r=t>=0?e.at(t):void 0;return r!==void 0&&n.has(r)},g=(e,t,n)=>{let r=Array.from(e),i=``,a=0;for(;a<r.length;){let e=n.find(({mark:e})=>h(r,a-1,t)&&e.every((e,t)=>r[a+t]===e)&&h(r,a+e.length,t));e===void 0?(i+=r[a],a+=1):(i+=e.to,a+=e.mark.length)}return i},_=(e,t)=>{let n=u();if(n===null)return e.format(t);let{digits:r,decimal:i,group:a}=m(e.resolvedOptions().locale),o=[];return i!==null&&o.push({mark:i,to:n.decimal}),a!==null&&o.push({mark:a,to:n.group}),g(e.format(t),r,o)};export{a as configureFormatters,c as configuredLocale,o as getFormatterConfig,l as groupingForLocale,s as isFormatterConfigured,u as numberSeparators,_ as styledNumber};
@@ -1 +1 @@
1
- import{withoutSpaces as e}from"./text.js";var t=/^[2-9][0-9]{11}$/,n=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],r=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],i=e=>{let t=0;for(let i=0;i<e.length;i+=1){let a=Number(e.charAt(e.length-1-i));t=n[t][r[i%8][a]]}return t===0},a=t=>{let n=e(t);return n===null?null:n.replace(/-/g,``).trim()},o=e=>{let n=a(e);return n!==null&&t.test(n)&&i(n)?n:null},s=e=>o(e)!==null,c=e=>{let t=o(e);return t===null?null:`XXXX XXXX ${t.slice(-4)}`},l=e=>{let t=o(e);return t===null?null:t.slice(-4)};export{l as aadhaarLastFour,s as isAadhaar,c as maskAadhaar,a as normalizeAadhaar};
1
+ import{withoutSpaces as e}from"./text.js";var t=/^[2-9][0-9]{11}$/,n=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],r=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],i=e=>{let t=0;for(let i=0;i<e.length;i+=1){let a=Number(e.charAt(e.length-1-i)),o=r[i%8],s=n[t];if(o===void 0||s===void 0)throw Error(`Verhoeff lookup is out of range.`);let c=o[a],l=c===void 0?void 0:s[c];if(l===void 0)throw Error(`Aadhaar digits must be 0 to 9.`);t=l}return t===0},a=t=>{let n=e(t);return n===null?null:n.replace(/-/g,``).trim()},o=e=>{let n=a(e);return n!==null&&t.test(n)&&i(n)?n:null},s=e=>o(e)!==null,c=e=>{let t=o(e);return t===null?null:`XXXX XXXX ${t.slice(-4)}`},l=e=>{let t=o(e);return t===null?null:t.slice(-4)};export{l as aadhaarLastFour,s as isAadhaar,c as maskAadhaar,a as normalizeAadhaar};
@@ -1 +1 @@
1
- import{istDateOf as e}from"./indiaTime.js";var t=9998,n=e=>String(e%100).padStart(2,`0`),r=e=>String(e).padStart(4,`0`),i=e=>`${e}-${n(e+1)}`,a=e=>{let t=i(e);return{startYear:e,label:t,displayLabel:`FY ${t}`,assessmentYearLabel:i(e+1),startDate:`${r(e)}-04-01`,endDate:`${r(e+1)}-03-31`}},o=t=>{let[n,r]=e(t).split(`-`).map(Number);return a(r>=4?n:n-1)},s=(e=/* @__PURE__ */ new Date)=>o(e),c=e=>{if(typeof e!=`string`)return null;let r=e.trim();/^fy/i.test(r)&&(r=r.slice(2).trimStart());let i=r.indexOf(`-`),o=(i<0?r:r.slice(0,i)).trimEnd();if(!/^\d{4}$/.test(o))return null;let s=Number(o);if(s<1||s>t)return null;if(i<0)return a(s);let c=r.slice(i+1).trimStart(),l=s+1;return c===n(l)||c===String(l)?a(s):null},l=(e,t=/* @__PURE__ */ new Date)=>{if(!Number.isInteger(e)||e<1)throw RangeError(`A count of recent financial years must be a whole number of at least 1, got ${e}.`);let n=s(t).startYear;return Array.from({length:e},(e,t)=>a(n-t))};export{s as currentFinancialYear,i as financialYearLabel,o as financialYearOf,c as parseFinancialYear,l as recentFinancialYears};
1
+ import{istDateOf as e}from"./indiaTime.js";var t=9998,n=e=>String(e%100).padStart(2,`0`),r=e=>String(e).padStart(4,`0`),i=e=>`${e}-${n(e+1)}`,a=e=>{let t=i(e);return{startYear:e,label:t,displayLabel:`FY ${t}`,assessmentYearLabel:i(e+1),startDate:`${r(e)}-04-01`,endDate:`${r(e+1)}-03-31`}},o=t=>{let[n,r]=e(t).split(`-`).map(Number);if(n===void 0||r===void 0)throw Error(`istDateOf returns a yyyy-MM-dd date.`);return a(r>=4?n:n-1)},s=(e=/* @__PURE__ */ new Date)=>o(e),c=e=>{if(typeof e!=`string`)return null;let r=e.trim();/^fy/i.test(r)&&(r=r.slice(2).trimStart());let i=r.indexOf(`-`),o=(i<0?r:r.slice(0,i)).trimEnd();if(!/^\d{4}$/.test(o))return null;let s=Number(o);if(s<1||s>t)return null;if(i<0)return a(s);let c=r.slice(i+1).trimStart(),l=s+1;return c===n(l)||c===String(l)?a(s):null},l=(e,t=/* @__PURE__ */ new Date)=>{if(!Number.isInteger(e)||e<1)throw RangeError(`A count of recent financial years must be a whole number of at least 1, got ${e}.`);let n=s(t).startYear;return Array.from({length:e},(e,t)=>a(n-t))};export{s as currentFinancialYear,i as financialYearLabel,o as financialYearOf,c as parseFinancialYear,l as recentFinancialYears};
@@ -19,6 +19,10 @@ export declare const SESSION_EXPIRED_CODE = "session_expired";
19
19
  export interface RefreshableStore {
20
20
  dispatch: (action: unknown) => unknown;
21
21
  }
22
+ /** A failure that proves the session is over, as opposed to one worth retrying later. */
23
+ export declare class SessionEndedError extends Error {
24
+ constructor(message: string);
25
+ }
22
26
  export declare const injectStore: <S>(_store: S) => void;
23
27
  export declare const injectUserAuth: (options: UserAuthOptions) => void;
24
28
  /**
@@ -57,7 +61,7 @@ export declare const waitForSessionReplacement: () => Promise<void>;
57
61
  /**
58
62
  * Stores the session a flagged request's response carries, read the way refresh responses are, before
59
63
  * the replacement window closes, so a request waiting on the window retries with the new token.
60
- * A body without tokens is logged and left to the caller.
64
+ * A body without tokens rejects, so the request that carried it fails instead of resolving with a session nobody stored.
61
65
  */
62
66
  export declare const storeReplacementSession: (data: unknown) => Promise<void>;
63
67
  /**
@@ -68,6 +72,8 @@ export declare const storeReplacementSession: (data: unknown) => Promise<void>;
68
72
  export declare const currentTokenIfReplaced: (sentToken: string | null) => Promise<string | null>;
69
73
  /** Wait for the in-flight refresh without joining it: resolved or rejected by processQueue. */
70
74
  export declare const queueBehindRefresh: () => Promise<string>;
75
+ /** True when a failure from the refresh proves the session is over (refreshAccessToken has already logged it once), as opposed to a fault worth an error line. */
76
+ export declare const isSessionEnd: (error: unknown) => boolean;
71
77
  /**
72
78
  * Refresh the access token, joining a refresh already in flight rather than
73
79
  * starting a second one. Every request queued behind it is replayed on success
@@ -57,7 +57,9 @@ export declare const getKeepSignedIn: () => boolean;
57
57
  * Web only. Choose where the session is kept: `true` for "keep me signed in"
58
58
  * (localStorage), `false` for this tab only (sessionStorage). Call it at sign-in,
59
59
  * before `storeToken`. A session already stored moves to the chosen store, so
60
- * the refresh flow keeps writing where the session started.
60
+ * the refresh flow keeps writing where the session started. Throws when a stored
61
+ * key cannot be moved to the chosen store, and keeps the previous choice, so the
62
+ * sign-in flow can report it instead of leaving the session where the person did not choose.
61
63
  */
62
64
  export declare const setKeepSignedIn: (keep: boolean) => void;
63
65
  /**
@@ -30,6 +30,7 @@ export interface FormatCurrencyOptions extends Omit<Intl.NumberFormatOptions, "s
30
30
  * its group sizes and symbol placement ("₹1.50.000,50" for `'CommaWithPointGroups'`).
31
31
  * A numeric string reads as its number. For money the API carries in minor units (paise),
32
32
  * use `formatMinor`.
33
+ * The code is not checked against the ISO 4217 list: a well-formed three-letter code the engine does not know prints as the code itself ("XYZ 1,234.00"), and only a malformed code or locale throws a RangeError.
33
34
  *
34
35
  * @example
35
36
  * formatCurrency(150000, { currency: 'INR' }) // ₹1,50,000
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"node:fs";import{basename as n,dirname as r,join as i,resolve as a}from"node:path";var o=`virtual:webority-static-assets`,s=`\0${o}`,c=i(`.webority`,`infra`,`deployables.json`),l=/^https:\/\/[a-z0-9.-]+(:\d+)?$/,u=/^[0-9a-f]{64}$/,d=12,f=`export default null;`;function p(e,t){let n=t?.trim();if(!n)return null;if(n!==`/`&&!l.test(n))throw Error(`weborityStatic: ${e} must be "/" or an https origin with no path and no trailing slash, got "${n}".`);return n}function m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function h(t){let n=i(t,c);if(e(n))return n;let a=r(t);return a===t?null:h(a)}function g(e){let n;try{n=JSON.parse(t(e,`utf8`))}catch(t){throw Error(`weborityStatic: cannot read ${e}: ${t instanceof Error?t.message:String(t)}`)}let r=m(n)?n.deployables:void 0;if(!m(r))throw Error(`weborityStatic: ${e} has no "deployables" object.`);let i=Object.entries(r).filter(([,e])=>m(e)&&`staticAssets`in e);if(i.length===0)return null;if(i.length>1)throw Error(`weborityStatic: ${e} must have exactly one deployable with "staticAssets"; it has ${i.length}.`);let[[a,o]]=i,s=o.staticAssets,c=m(s)?s.assets:void 0;if(!m(c))throw Error(`weborityStatic: ${e}: deployable '${a}' has no "staticAssets.assets" object.`);let l={};for(let[t,n]of Object.entries(c)){let r=n?.sha256;if(typeof r!=`string`||!u.test(r))throw Error(`weborityStatic: ${e} asset "${t}" needs a sha256 of 64 lowercase hex characters.`);l[t]=r.slice(0,d)}return{carrier:a,versions:l}}function _(e={}){let t=p(`authoredOrigin`,e.authoredOrigin),r=p(`buildOrigin`,e.buildOrigin),i=``,o=f;return{name:`webority-static`,enforce:`pre`,config(e,t){if(r===null||t.command!==`build`)return;let n=r===`/`?``:r;return{experimental:{renderBuiltUrl:(e,t)=>t.type===`public`?void 0:`${n}/_static/${i}/${e.replace(/^\/+/,``)}`}}},configResolved(s){let c=a(s.root);if(i=n(c).toLowerCase().replaceAll(`.`,`-`),r!==null&&i===``)throw Error(`weborityStatic: cannot name the head from the Vite root "${c}".`);let l=e.manifest?a(c,e.manifest):h(c),u=l===null?null:g(l);if(u===null){if(t!==null)throw Error(`weborityStatic: authoredOrigin is set but ${l??`no .webority/infra/deployables.json above the Vite root`} has no deployable carrying "staticAssets".`);o=f}else{if(t===null)throw Error(`weborityStatic: ${l} has a deployable carrying staticAssets, so authoredOrigin is required ("/" or an https origin).`);o=`export default ${JSON.stringify({authoredOrigin:t,versions:u.versions})};`}},resolveId(e){return e===`virtual:webority-static-assets`?s:null},load(e){return e===s?o:null}}}export{o as STATIC_ASSETS_MODULE_ID,_ as weborityStatic};
1
+ import{existsSync as e,readFileSync as t}from"node:fs";import{basename as n,dirname as r,join as i,resolve as a}from"node:path";var o=`virtual:webority-static-assets`,s=`\0${o}`,c=i(`.webority`,`infra`,`deployables.json`),l=/^https:\/\/[a-z0-9.-]+(:\d+)?$/,u=/^[0-9a-f]{64}$/,d=12,f=`export default null;`;function p(e,t){let n=t?.trim();if(!n)return null;if(n!==`/`&&!l.test(n))throw Error(`weborityStatic: ${e} must be "/" or an https origin with no path and no trailing slash, got "${n}".`);return n}function m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function h(t){let n=i(t,c);if(e(n))return n;let a=r(t);return a===t?null:h(a)}function g(e){let n;try{n=JSON.parse(t(e,`utf8`))}catch(t){throw Error(`weborityStatic: cannot read ${e}: ${t instanceof Error?t.message:String(t)}`)}let r=m(n)?n.deployables:void 0;if(!m(r))throw Error(`weborityStatic: ${e} has no "deployables" object.`);let i=Object.entries(r).filter(([,e])=>m(e)&&`staticAssets`in e);if(i.length===0)return null;if(i.length>1)throw Error(`weborityStatic: ${e} must have exactly one deployable with "staticAssets"; it has ${i.length}.`);let[a]=i;if(a===void 0)throw Error(`weborityStatic: ${e} lost its carrier deployable.`);let[o,s]=a,c=s.staticAssets,l=m(c)?c.assets:void 0;if(!m(l))throw Error(`weborityStatic: ${e}: deployable '${o}' has no "staticAssets.assets" object.`);let f={};for(let[t,n]of Object.entries(l)){let r=n?.sha256;if(typeof r!=`string`||!u.test(r))throw Error(`weborityStatic: ${e} asset "${t}" needs a sha256 of 64 lowercase hex characters.`);f[t]=r.slice(0,d)}return{carrier:o,versions:f}}function _(e={}){let t=p(`authoredOrigin`,e.authoredOrigin),r=p(`buildOrigin`,e.buildOrigin),i=``,o=f;return{name:`webority-static`,enforce:`pre`,config(e,t){if(r===null||t.command!==`build`)return;let n=r===`/`?``:r;return{experimental:{renderBuiltUrl:(e,t)=>t.type===`public`?void 0:`${n}/_static/${i}/${e.replace(/^\/+/,``)}`}}},configResolved(s){let c=a(s.root);if(i=n(c).toLowerCase().replaceAll(`.`,`-`),r!==null&&i===``)throw Error(`weborityStatic: cannot name the head from the Vite root "${c}".`);let l=e.manifest?a(c,e.manifest):h(c),u=l===null?null:g(l);if(u===null){if(t!==null)throw Error(`weborityStatic: authoredOrigin is set but ${l??`no .webority/infra/deployables.json above the Vite root`} has no deployable carrying "staticAssets".`);o=f}else{if(t===null)throw Error(`weborityStatic: ${l} has a deployable carrying staticAssets, so authoredOrigin is required ("/" or an https origin).`);o=`export default ${JSON.stringify({authoredOrigin:t,versions:u.versions})};`}},resolveId(e){return e===`virtual:webority-static-assets`?s:null},load(e){return e===s?o:null}}}export{o as STATIC_ASSETS_MODULE_ID,_ as weborityStatic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/web-core",
3
- "version": "0.146.2",
3
+ "version": "0.148.0",
4
4
  "description": "Platform layer for Webority React web portals: HTTP clients with single-flight token refresh, auth store, API error extraction, RTK Query base query, logger, formatters, storage, version check and route guards. No UI.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -101,19 +101,19 @@
101
101
  "react-router": "^7.16.0"
102
102
  },
103
103
  "devDependencies": {
104
- "@reduxjs/toolkit": "^2.12.0",
104
+ "@reduxjs/toolkit": "^2.14.0",
105
105
  "@testing-library/react": "^16.3.0",
106
106
  "@types/react": "^19.2.17",
107
- "@vitest/coverage-v8": "5.0.1",
107
+ "@vitest/coverage-v8": "5.1.0",
108
108
  "axios": "^1.18.0",
109
109
  "jsdom": "30.1.1",
110
- "react": "^19.2.6",
111
- "react-dom": "^19.2.6",
110
+ "react": "^19.3.1",
111
+ "react-dom": "^19.3.1",
112
112
  "react-redux": "^9.3.0",
113
113
  "react-router": "^7.16.0",
114
114
  "typescript": "^7.0.2",
115
- "vite": "^8.0.12",
116
- "vitest": "5.0.1"
115
+ "vite": "^8.3.6",
116
+ "vitest": "5.1.0"
117
117
  },
118
118
  "scripts": {
119
119
  "build": "vite build && tsc -p tsconfig.json",