@nocios/crudify-ui 4.0.94 → 4.0.96

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocios/crudify-ui",
3
- "version": "4.0.94",
3
+ "version": "4.0.96",
4
4
  "description": "Biblioteca de componentes UI para Crudify",
5
5
  "author": "Nocios",
6
6
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "prepublishOnly": "npm run build"
37
37
  },
38
38
  "dependencies": {
39
- "@nocios/crudify-browser": "^4.0.4",
39
+ "@nocios/crudify-browser": "^4.0.6",
40
40
  "crypto-js": "^4.2.0",
41
41
  "dompurify": "^3.2.7",
42
42
  "uuid": "^13.0.0"
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var a=class a{static setStorageType(e){a.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(e).toString()}static getEncryptionKey(){if(a.encryptionKey)return a.encryptionKey;let e=window.localStorage;if(!e)return a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey;try{let t=e.getItem(a.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=a.generateEncryptionKey(),e.setItem(a.ENCRYPTION_KEY_STORAGE,t)),a.encryptionKey=t,t}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch (e3){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(console.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=a.getEncryptionKey();return _cryptojs2.default.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=a.getEncryptionKey();return _cryptojs2.default.AES.decrypt(e,t).toString(_cryptojs2.default.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=a.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},i=a.encrypt(JSON.stringify(r));t.setItem(a.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let r=a.decrypt(t),i=JSON.parse(r);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),a.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),a.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),a.clearTokens(),null}}static clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{a.clearTokens(),a.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(a.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return a.getTokens()!==null}static getExpirationInfo(){let e=a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static updateAccessToken(e,t){let r=a.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}a.saveTokens({...r,accessToken:e,expiresAt:t})}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.encryptionKey=null,a.storageType="localStorage";var g=a;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var P=class o{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await _crudifybrowser2.default.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let i={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(i)]),{success:!0,tokens:i,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),g.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _5 => _5.config, 'access', _6 => _6.onLogout, 'optionalCall', _7 => _7()])}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(i)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(e)]),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=_crudifybrowser2.default.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await _crudifybrowser2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.showNotification, 'optionalCall', _16 => _16(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionExpired, 'optionalCall', _19 => _19()]),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),_optionalChain([this, 'access', _20 => _20.config, 'access', _21 => _21.showNotification, 'optionalCall', _22 => _22(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _23 => _23.config, 'access', _24 => _24.onSessionExpired, 'optionalCall', _25 => _25()]),!1}}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),_optionalChain([this, 'access', _26 => _26.config, 'access', _27 => _27.showNotification, 'optionalCall', _28 => _28(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.onSessionExpired, 'optionalCall', _31 => _31()]),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),_optionalChain([this, 'access', _32 => _32.config, 'access', _33 => _33.onSessionExpired, 'optionalCall', _34 => _34()]))):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),_optionalChain([this, 'access', _35 => _35.config, 'access', _36 => _36.showNotification, 'optionalCall', _37 => _37(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _38 => _38.config, 'access', _39 => _39.onSessionExpired, 'optionalCall', _40 => _40()]))}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(i=>i.errorType==="Unauthorized"||_optionalChain([i, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Unauthorized")])||_optionalChain([i, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("Not Authorized")])||_optionalChain([i, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Token")])||_optionalChain([i, 'access', _50 => _50.extensions, 'optionalAccess', _51 => _51.code])==="UNAUTHENTICATED"||_optionalChain([i, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("NOT_AUTHORIZED")]))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(u=>typeof u=="string"&&u.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&_optionalChain([e, 'access', _55 => _55.data, 'optionalAccess', _56 => _56.response, 'optionalAccess', _57 => _57.status])==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&_optionalChain([e, 'access', _58 => _58.data, 'optionalAccess', _59 => _59.response, 'optionalAccess', _60 => _60.data]))try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch (e4){}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity(),t=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let r=900*1e3,i=300*1e3,u=300*1e3;return e>r?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):e<i&&t.expiresIn<u&&t.expiresIn>0?(this.log(`User active recently (${Math.floor(e/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk6EBMA4HZjs.b.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,...t){this.config.enableLogging&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function j(o={}){let[e,t]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=P.getInstance(),i=_react.useCallback.call(void 0, async()=>{try{t(s=>({...s,isLoading:!0,error:null}));let l={autoRestore:_nullishCoalesce(o.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(o.enableLogging, () => (!1)),showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([o, 'access', _61 => _61.onSessionExpired, 'optionalCall', _62 => _62()])},onSessionRestored:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null})),_optionalChain([o, 'access', _63 => _63.onSessionRestored, 'optionalCall', _64 => _64(s)])},onLoginSuccess:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(l),r.setupResponseInterceptor();let n=r.isAuthenticated(),c=r.getTokenInfo();t(s=>({...s,isAuthenticated:n,isInitialized:!0,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}catch(l){let n=l instanceof Error?l.message:"Initialization failed";t(c=>({...c,isLoading:!1,isInitialized:!0,error:n}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=_react.useCallback.call(void 0, async(l,n)=>{t(c=>({...c,isLoading:!0,error:null}));try{let c=await r.login(l,n);return c.success&&c.tokens?t(s=>({...s,isAuthenticated:!0,tokens:c.tokens,isLoading:!1,error:null})):t(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),c}catch(c){let s=c instanceof Error?c.message:"Login failed",d=s.includes("INVALID_CREDENTIALS")||s.includes("Invalid email")||s.includes("Invalid password")||s.includes("credentials");return t(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:s})),{success:!1,error:s}}},[r]),v=_react.useCallback.call(void 0, async()=>{t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),p=_react.useCallback.call(void 0, async()=>{try{let l=await r.refreshTokens();if(l){let n=r.getTokenInfo();t(c=>({...c,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(n=>({...n,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(n=>({...n,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),x=_react.useCallback.call(void 0, ()=>{t(l=>({...l,error:null}))},[]),k=_react.useCallback.call(void 0, ()=>r.getTokenInfo(),[r]);_react.useEffect.call(void 0, ()=>{i()},[i]),_react.useEffect.call(void 0, ()=>{if(!e.isAuthenticated||!e.tokens)return;let l=()=>{r.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")};window.addEventListener("popstate",l);let n=window.history.pushState,c=window.history.replaceState;window.history.pushState=function(...d){let T=n.apply(this,d);return l(),T},window.history.replaceState=function(...d){let T=c.apply(this,d);return l(),T};let s=setInterval(async()=>{let d=r.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await v();else if(d==="refresh"&&(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),await r.refreshTokens())){let h=r.getTokenInfo();t(b=>({...b,tokens:h.crudifyTokens.accessToken?{accessToken:h.crudifyTokens.accessToken,refreshToken:h.crudifyTokens.refreshToken,expiresAt:h.crudifyTokens.expiresAt,refreshExpiresAt:h.crudifyTokens.refreshExpiresAt}:null}))}},120*1e3);return()=>{clearInterval(s),window.removeEventListener("popstate",l),window.history.pushState=n,window.history.replaceState=c}},[e.isAuthenticated,e.tokens,r,o.enableLogging,v]);let S=_react.useCallback.call(void 0, ()=>{r.updateLastActivity()},[r]);return{...e,login:u,logout:v,refreshTokens:p,clearError:x,getTokenInfo:k,updateActivity:S,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var B=_react.createContext.call(void 0, null),ue=o=>_dompurify2.default.sanitize(o,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),J= exports.d =({children:o,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[v,p]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (n,c="info",s)=>{if(!i)return"";if(!n||typeof n!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";n.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),n=n.substring(0,1e3)+"...");let d=_uuid.v4.call(void 0, ),T={id:d,message:n,severity:c,autoHideDuration:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _65 => _65.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _66 => _66.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _67 => _67.allowHtml]), () => (u))};return p(h=>[...h.length>=e?h.slice(-(e-1)):h,T]),d},[e,t,i,u]),k=_react.useCallback.call(void 0, n=>{p(c=>c.filter(s=>s.id!==n))},[]),S=_react.useCallback.call(void 0, ()=>{p([])},[]),l={showNotification:x,hideNotification:k,clearAllNotifications:S};return _jsxruntime.jsxs.call(void 0, B.Provider,{value:l,children:[o,i&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(n=>_jsxruntime.jsx.call(void 0, fe,{notification:n,onClose:()=>k(n.id)},n.id))})})]})},fe=({notification:o,onClose:e})=>{let[t,r]=_react.useState.call(void 0, !0),i=_react.useCallback.call(void 0, (u,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:o.message})})})},_= exports.e =()=>{let o=_react.useContext.call(void 0, B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};var X=_react.createContext.call(void 0, void 0);function ye({children:o,options:e={},config:t,showNotifications:r=!1,notificationOptions:i={}}){let u;try{let{showNotification:n}=_();u=n}catch (e5){}let v=_react2.default.useMemo(()=>({...e,showNotification:u,onSessionExpired:()=>{_optionalChain([e, 'access', _68 => _68.onSessionExpired, 'optionalCall', _69 => _69()])}}),[e,u]),p=j(v),x=_react.useMemo.call(void 0, ()=>{let n,c,s,d,T,h="unknown";if(_optionalChain([t, 'optionalAccess', _70 => _70.publicApiKey])&&(n=t.publicApiKey,h="props"),_optionalChain([t, 'optionalAccess', _71 => _71.env])&&(c=t.env),_optionalChain([t, 'optionalAccess', _72 => _72.appName])&&(s=t.appName),_optionalChain([t, 'optionalAccess', _73 => _73.loginActions])&&(d=t.loginActions),_optionalChain([t, 'optionalAccess', _74 => _74.logo])&&(T=t.logo),!n){let b=_chunk6EBMA4HZjs.a.call(void 0, "publicApiKey"),N=_chunk6EBMA4HZjs.a.call(void 0, "environment"),R=_chunk6EBMA4HZjs.a.call(void 0, "appName"),E=_chunk6EBMA4HZjs.a.call(void 0, "loginActions"),f=_chunk6EBMA4HZjs.a.call(void 0, "logo");b&&(n=b,h="cookies"),N&&["dev","stg","prod"].includes(N)&&(c=N),R&&(s=decodeURIComponent(R)),E&&(d=decodeURIComponent(E).split(",").map(L=>L.trim()).filter(Boolean)),f&&(T=decodeURIComponent(f))}return{publicApiKey:n,env:c,appName:s,loginActions:d,logo:T}},[t]),k=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([p, 'access', _75 => _75.tokens, 'optionalAccess', _76 => _76.accessToken])||!p.isAuthenticated)return null;try{let n=_chunk6EBMA4HZjs.f.call(void 0, p.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let c={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(s=>{["sub","email","subscriber"].includes(s)||(c[s]=n[s])}),c}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([p, 'access', _77 => _77.tokens, 'optionalAccess', _78 => _78.accessToken]),p.isAuthenticated]),S={...p,sessionData:k,config:x},l={enabled:r,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, X.Provider,{value:S,children:o})}function Be(o){let e={enabled:o.showNotifications,maxNotifications:_optionalChain([o, 'access', _79 => _79.notificationOptions, 'optionalAccess', _80 => _80.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([o, 'access', _81 => _81.notificationOptions, 'optionalAccess', _82 => _82.defaultAutoHideDuration])||6e3,position:_optionalChain([o, 'access', _83 => _83.notificationOptions, 'optionalAccess', _84 => _84.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([o, 'access', _85 => _85.notificationOptions, 'optionalAccess', _86 => _86.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, J,{...e,children:_jsxruntime.jsx.call(void 0, ye,{...o})})}function Z(){let o=_react.useContext.call(void 0, X);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function Je({children:o,fallback:e=_jsxruntime.jsx.call(void 0, "div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:i,isInitialized:u}=Z();return!u||i?_jsxruntime.jsx.call(void 0, "div",{children:"Loading..."}):r?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):t?(t(),null):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function _e(){let o=Z();return o.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var et=(o={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=o,[i,u]=_react.useState.call(void 0, null),[v,p]=_react.useState.call(void 0, !1),[x,k]=_react.useState.call(void 0, null),[S,l]=_react.useState.call(void 0, {}),n=_react.useRef.call(void 0, null),c=_react.useRef.call(void 0, !0),s=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),T=_react.useCallback.call(void 0, ()=>{u(null),k(null),p(!1),l({})},[]),h=_react.useCallback.call(void 0, async()=>{let b=_chunk6EBMA4HZjs.g.call(void 0, );if(!b){c.current&&(k("No user email available"),p(!1));return}n.current&&n.current.abort();let N=new AbortController;n.current=N;let R=++s.current;try{c.current&&(p(!0),k(null));let E=await _crudifybrowser2.default.readItems("users",{filter:{email:b},pagination:{limit:1}});if(R===s.current&&c.current&&!N.signal.aborted)if(E.success&&E.data&&E.data.length>0){let f=E.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,z)=>({...L,[z]:f[z]}),{})}};l(H),k(null),d.current=0}else k("User profile not found"),u(null),l({})}catch(E){if(R===s.current&&c.current){let f=E;if(f.name==="AbortError")return;t&&d.current<r&&(_optionalChain([f, 'access', _87 => _87.message, 'optionalAccess', _88 => _88.includes, 'call', _89 => _89("Network Error")])||_optionalChain([f, 'access', _90 => _90.message, 'optionalAccess', _91 => _91.includes, 'call', _92 => _92("Failed to fetch")]))?(d.current++,setTimeout(()=>{c.current&&h()},1e3*d.current)):(k("Failed to load user profile"),u(null),l({}))}}finally{R===s.current&&c.current&&p(!1),n.current===N&&(n.current=null)}},[t,r]);return _react.useEffect.call(void 0, ()=>{e&&h()},[e,h]),_react.useEffect.call(void 0, ()=>(c.current=!0,()=>{c.current=!1,n.current&&(n.current.abort(),n.current=null)}),[]),{userProfile:i,loading:v,error:x,extendedData:S,refreshProfile:h,clearProfile:T}};exports.a = g; exports.b = P; exports.c = j; exports.d = J; exports.e = _; exports.f = Be; exports.g = Z; exports.h = Je; exports.i = _e; exports.j = et;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var m=e=>{let n=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return n?n[2]:null};var R=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],T={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},f={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function l(e,n){let{translateFn:r,currentLanguage:t,enableDebug:a}=n;a&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${t||"unknown"})`);let i=e.toUpperCase(),d=T[i],c=R.map(o=>o.replace("{category}",d||"general").replace("{code}",i));a&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",c);for(let o of c){let s=r(o);if(a&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${o}" -> result: "${s}" (same as key: ${s===o})`),s&&s!==o)return a&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${o} = "${s}"`),s}let g=f[i];if(g)return a&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${g}"`),g;let u=i.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return a&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${u}"`),u}function I(e,n){return e.map(r=>l(r,n))}function N(e,n){let{enableDebug:r}=n;r&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let t=l(e.code,n);return t!==e.code.toUpperCase()&&t!==e.code?(r&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${t}"`),e.field?`${e.field}: ${t}`:t):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(r&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(r&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${t}"`),e.field?`${e.field}: ${t}`:t)}function O(e,n={}){let r={translateFn:e,currentLanguage:n.currentLanguage,enableDebug:n.enableDebug||!1};return{translateErrorCode:t=>l(t,r),translateErrorCodes:t=>I(t,r),translateError:t=>N(t,r),translateApiError:t=>_optionalChain([t, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.status])?l(t.data.response.status,r):_optionalChain([t, 'optionalAccess', _4 => _4.status])?l(t.status,r):_optionalChain([t, 'optionalAccess', _5 => _5.code])?l(t.code,r):"Unknown error"}}var E=e=>{try{let n=e.split(".");if(n.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let r=n[1],t=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(t))}catch(n){return console.warn("Failed to decode JWT token:",n),null}},y= exports.g =()=>{try{let e=null;if(e=sessionStorage.getItem("authToken"),console.log("\u{1F50D} getCurrentUserEmail - authToken:",e?`${e.substring(0,20)}...`:null),e||(e=sessionStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - token:",e?`${e.substring(0,20)}...`:null)),e||(e=localStorage.getItem("authToken")||localStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - localStorage:",e?`${e.substring(0,20)}...`:null)),!e)return console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage"),null;let n=E(e);if(!n)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let r=n.email||n["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",r),r}catch(e){return console.warn("Failed to get current user email:",e),null}},A= exports.h =e=>{try{let n=E(e);if(!n||!n.exp)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<r}catch (e2){return!0}};exports.a = m; exports.b = l; exports.c = I; exports.d = N; exports.e = O; exports.f = E; exports.g = y; exports.h = A;
@@ -1 +0,0 @@
1
- import{a as D,b as F,f as G,g as Y}from"./chunk-YS3C7YG5.mjs";import C from"crypto-js";var a=class a{static setStorageType(e){a.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return C.SHA256(e).toString()}static getEncryptionKey(){if(a.encryptionKey)return a.encryptionKey;let e=window.localStorage;if(!e)return a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey;try{let t=e.getItem(a.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=a.generateEncryptionKey(),e.setItem(a.ENCRYPTION_KEY_STORAGE,t)),a.encryptionKey=t,t}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(console.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=a.getEncryptionKey();return C.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=a.getEncryptionKey();return C.AES.decrypt(e,t).toString(C.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=a.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},i=a.encrypt(JSON.stringify(r));t.setItem(a.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let r=a.decrypt(t),i=JSON.parse(r);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),a.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),a.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),a.clearTokens(),null}}static clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{a.clearTokens(),a.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(a.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return a.getTokens()!==null}static getExpirationInfo(){let e=a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static updateAccessToken(e,t){let r=a.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}a.saveTokens({...r,accessToken:e,expiresAt:t})}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.encryptionKey=null,a.storageType="localStorage";var g=a;import m from"@nocios/crudify-browser";var P=class o{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await m.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let i={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),this.config.onLoginSuccess?.(i),{success:!0,tokens:i,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await m.logout(),g.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(m.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),m.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&this.config.onSessionRestored?.(i),!0}return g.clearTokens(),await m.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(e),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await m.logout(),!1}}isAuthenticated(){return m.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=m.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await m.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}setupResponseInterceptor(){m.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),this.config.onSessionExpired?.())):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.())}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(i=>i.errorType==="Unauthorized"||i.message?.includes("Unauthorized")||i.message?.includes("Not Authorized")||i.message?.includes("Token")||i.extensions?.code==="UNAUTHENTICATED"||i.message?.includes("NOT_AUTHORIZED"))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(u=>typeof u=="string"&&u.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&e.data?.response?.status==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&e.data?.response?.data)try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch{}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity(),t=m.getTokenData();if(this.lastActivityTime===0)return"none";let r=900*1e3,i=300*1e3,u=300*1e3;return e>r?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):e<i&&t.expiresIn<u&&t.expiresIn>0?(this.log(`User active recently (${Math.floor(e/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),m.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?F("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,...t){this.config.enableLogging&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as ee,useEffect as V,useCallback as w}from"react";function j(o={}){let[e,t]=ee({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=P.getInstance(),i=w(async()=>{try{t(s=>({...s,isLoading:!0,error:null}));let l={autoRestore:o.autoRestore??!0,enableLogging:o.enableLogging??!1,showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),o.onSessionExpired?.()},onSessionRestored:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null})),o.onSessionRestored?.(s)},onLoginSuccess:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(l),r.setupResponseInterceptor();let n=r.isAuthenticated(),c=r.getTokenInfo();t(s=>({...s,isAuthenticated:n,isInitialized:!0,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}catch(l){let n=l instanceof Error?l.message:"Initialization failed";t(c=>({...c,isLoading:!1,isInitialized:!0,error:n}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=w(async(l,n)=>{t(c=>({...c,isLoading:!0,error:null}));try{let c=await r.login(l,n);return c.success&&c.tokens?t(s=>({...s,isAuthenticated:!0,tokens:c.tokens,isLoading:!1,error:null})):t(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),c}catch(c){let s=c instanceof Error?c.message:"Login failed",d=s.includes("INVALID_CREDENTIALS")||s.includes("Invalid email")||s.includes("Invalid password")||s.includes("credentials");return t(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:s})),{success:!1,error:s}}},[r]),v=w(async()=>{t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),p=w(async()=>{try{let l=await r.refreshTokens();if(l){let n=r.getTokenInfo();t(c=>({...c,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(n=>({...n,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(n=>({...n,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),x=w(()=>{t(l=>({...l,error:null}))},[]),k=w(()=>r.getTokenInfo(),[r]);V(()=>{i()},[i]),V(()=>{if(!e.isAuthenticated||!e.tokens)return;let l=()=>{r.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")};window.addEventListener("popstate",l);let n=window.history.pushState,c=window.history.replaceState;window.history.pushState=function(...d){let T=n.apply(this,d);return l(),T},window.history.replaceState=function(...d){let T=c.apply(this,d);return l(),T};let s=setInterval(async()=>{let d=r.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await v();else if(d==="refresh"&&(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),await r.refreshTokens())){let h=r.getTokenInfo();t(b=>({...b,tokens:h.crudifyTokens.accessToken?{accessToken:h.crudifyTokens.accessToken,refreshToken:h.crudifyTokens.refreshToken,expiresAt:h.crudifyTokens.expiresAt,refreshExpiresAt:h.crudifyTokens.refreshExpiresAt}:null}))}},120*1e3);return()=>{clearInterval(s),window.removeEventListener("popstate",l),window.history.pushState=n,window.history.replaceState=c}},[e.isAuthenticated,e.tokens,r,o.enableLogging,v]);let S=w(()=>{r.updateLastActivity()},[r]);return{...e,login:u,logout:v,refreshTokens:p,clearError:x,getTokenInfo:k,updateActivity:S,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}import{useState as W,createContext as te,useContext as re,useCallback as O,useEffect as oe}from"react";import{Snackbar as ne,Alert as ie,Box as se,Portal as ae}from"@mui/material";import{v4 as ce}from"uuid";import le from"dompurify";import{jsx as I,jsxs as de}from"react/jsx-runtime";var B=te(null),ue=o=>le.sanitize(o,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),J=({children:o,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[v,p]=W([]),x=O((n,c="info",s)=>{if(!i)return"";if(!n||typeof n!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";n.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),n=n.substring(0,1e3)+"...");let d=ce(),T={id:d,message:n,severity:c,autoHideDuration:s?.autoHideDuration??t,persistent:s?.persistent??!1,allowHtml:s?.allowHtml??u};return p(h=>[...h.length>=e?h.slice(-(e-1)):h,T]),d},[e,t,i,u]),k=O(n=>{p(c=>c.filter(s=>s.id!==n))},[]),S=O(()=>{p([])},[]),l={showNotification:x,hideNotification:k,clearAllNotifications:S};return de(B.Provider,{value:l,children:[o,i&&I(ae,{children:I(se,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(n=>I(fe,{notification:n,onClose:()=>k(n.id)},n.id))})})]})},fe=({notification:o,onClose:e})=>{let[t,r]=W(!0),i=O((u,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return oe(()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),I(ne,{open:t,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:I(ie,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?I("span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):I("span",{children:o.message})})})},_=()=>{let o=re(B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};import ge,{createContext as pe,useContext as he,useMemo as $}from"react";import{Fragment as M,jsx as y,jsxs as A}from"react/jsx-runtime";var X=pe(void 0);function ye({children:o,options:e={},config:t,showNotifications:r=!1,notificationOptions:i={}}){let u;try{let{showNotification:n}=_();u=n}catch{}let v=ge.useMemo(()=>({...e,showNotification:u,onSessionExpired:()=>{e.onSessionExpired?.()}}),[e,u]),p=j(v),x=$(()=>{let n,c,s,d,T,h="unknown";if(t?.publicApiKey&&(n=t.publicApiKey,h="props"),t?.env&&(c=t.env),t?.appName&&(s=t.appName),t?.loginActions&&(d=t.loginActions),t?.logo&&(T=t.logo),!n){let b=D("publicApiKey"),N=D("environment"),R=D("appName"),E=D("loginActions"),f=D("logo");b&&(n=b,h="cookies"),N&&["dev","stg","prod"].includes(N)&&(c=N),R&&(s=decodeURIComponent(R)),E&&(d=decodeURIComponent(E).split(",").map(L=>L.trim()).filter(Boolean)),f&&(T=decodeURIComponent(f))}return{publicApiKey:n,env:c,appName:s,loginActions:d,logo:T}},[t]),k=$(()=>{if(!p.tokens?.accessToken||!p.isAuthenticated)return null;try{let n=G(p.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let c={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(s=>{["sub","email","subscriber"].includes(s)||(c[s]=n[s])}),c}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[p.tokens?.accessToken,p.isAuthenticated]),S={...p,sessionData:k,config:x},l={enabled:r,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return y(X.Provider,{value:S,children:o})}function Be(o){let e={enabled:o.showNotifications,maxNotifications:o.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:o.notificationOptions?.defaultAutoHideDuration||6e3,position:o.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:o.notificationOptions?.allowHtml||!1};return y(J,{...e,children:y(ye,{...o})})}function Z(){let o=he(X);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function Je({children:o,fallback:e=y("div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:i,isInitialized:u}=Z();return!u||i?y("div",{children:"Loading..."}):r?y(M,{children:o}):t?(t(),null):y(M,{children:e})}function _e(){let o=Z();return o.isInitialized?A("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[y("h4",{children:"Session Debug Info"}),A("div",{children:[y("strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),A("div",{children:[y("strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),A("div",{children:[y("strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&A(M,{children:[A("div",{children:[y("strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),A("div",{children:[y("strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),A("div",{children:[y("strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),A("div",{children:[y("strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),A("div",{children:[y("strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):y("div",{children:"Session not initialized"})}import{useState as U,useEffect as q,useCallback as Q,useRef as K}from"react";import Te from"@nocios/crudify-browser";var et=(o={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=o,[i,u]=U(null),[v,p]=U(!1),[x,k]=U(null),[S,l]=U({}),n=K(null),c=K(!0),s=K(0),d=K(0),T=Q(()=>{u(null),k(null),p(!1),l({})},[]),h=Q(async()=>{let b=Y();if(!b){c.current&&(k("No user email available"),p(!1));return}n.current&&n.current.abort();let N=new AbortController;n.current=N;let R=++s.current;try{c.current&&(p(!0),k(null));let E=await Te.readItems("users",{filter:{email:b},pagination:{limit:1}});if(R===s.current&&c.current&&!N.signal.aborted)if(E.success&&E.data&&E.data.length>0){let f=E.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,z)=>({...L,[z]:f[z]}),{})}};l(H),k(null),d.current=0}else k("User profile not found"),u(null),l({})}catch(E){if(R===s.current&&c.current){let f=E;if(f.name==="AbortError")return;t&&d.current<r&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{c.current&&h()},1e3*d.current)):(k("Failed to load user profile"),u(null),l({}))}}finally{R===s.current&&c.current&&p(!1),n.current===N&&(n.current=null)}},[t,r]);return q(()=>{e&&h()},[e,h]),q(()=>(c.current=!0,()=>{c.current=!1,n.current&&(n.current.abort(),n.current=null)}),[]),{userProfile:i,loading:v,error:x,extendedData:S,refreshProfile:h,clearProfile:T}};export{g as a,P as b,j as c,J as d,_ as e,Be as f,Z as g,Je as h,_e as i,et as j};
@@ -1 +0,0 @@
1
- var m=e=>{let n=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return n?n[2]:null};var R=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],T={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},f={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function l(e,n){let{translateFn:r,currentLanguage:t,enableDebug:a}=n;a&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${t||"unknown"})`);let i=e.toUpperCase(),d=T[i],c=R.map(o=>o.replace("{category}",d||"general").replace("{code}",i));a&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",c);for(let o of c){let s=r(o);if(a&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${o}" -> result: "${s}" (same as key: ${s===o})`),s&&s!==o)return a&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${o} = "${s}"`),s}let g=f[i];if(g)return a&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${g}"`),g;let u=i.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return a&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${u}"`),u}function I(e,n){return e.map(r=>l(r,n))}function N(e,n){let{enableDebug:r}=n;r&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let t=l(e.code,n);return t!==e.code.toUpperCase()&&t!==e.code?(r&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${t}"`),e.field?`${e.field}: ${t}`:t):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(r&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(r&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${t}"`),e.field?`${e.field}: ${t}`:t)}function O(e,n={}){let r={translateFn:e,currentLanguage:n.currentLanguage,enableDebug:n.enableDebug||!1};return{translateErrorCode:t=>l(t,r),translateErrorCodes:t=>I(t,r),translateError:t=>N(t,r),translateApiError:t=>t?.data?.response?.status?l(t.data.response.status,r):t?.status?l(t.status,r):t?.code?l(t.code,r):"Unknown error"}}var E=e=>{try{let n=e.split(".");if(n.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let r=n[1],t=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(t))}catch(n){return console.warn("Failed to decode JWT token:",n),null}},y=()=>{try{let e=null;if(e=sessionStorage.getItem("authToken"),console.log("\u{1F50D} getCurrentUserEmail - authToken:",e?`${e.substring(0,20)}...`:null),e||(e=sessionStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - token:",e?`${e.substring(0,20)}...`:null)),e||(e=localStorage.getItem("authToken")||localStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - localStorage:",e?`${e.substring(0,20)}...`:null)),!e)return console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage"),null;let n=E(e);if(!n)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let r=n.email||n["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",r),r}catch(e){return console.warn("Failed to get current user email:",e),null}},A=e=>{try{let n=E(e);if(!n||!n.exp)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<r}catch{return!0}};export{m as a,l as b,I as c,N as d,O as e,E as f,y as g,A as h};