@nocios/crudify-ui 4.1.58 → 4.1.62

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 +0,0 @@
1
- import{a as N,b as B,f as b,g as $,h as j,i as J}from"./chunk-5JKS55SE.mjs";import{createContext as ce,useContext as ue,useEffect as de,useState as K}from"react";import O from"@nocios/crudify-browser";var V=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},W=V.getInstance();import{jsx as fe}from"react/jsx-runtime";var Z=ce(void 0),q=({config:r,children:i})=>{let[e,t]=K(!0),[o,c]=K(null),[y,E]=K(!1),[k,h]=K(""),[S,u]=K();de(()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),E(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===k&&y){t(!1);return}(async()=>{t(!0),c(null),E(!1);try{O.config(r.env||"prod");let d=await O.init(r.publicApiKey,"none");if(u(d),typeof O.transaction=="function"&&typeof O.login=="function")E(!0),h(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&W.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let m=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),c(m),E(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,k,y]);let s={crudify:y?O:null,isLoading:e,error:o,isInitialized:y,adminCredentials:S};return fe(Z.Provider,{value:s,children:i})},Q=()=>{let r=ue(Z);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import U from"crypto-js";var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return U.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return l.storageType==="none"?null:l.isStorageAvailable(l.storageType)?window[l.storageType]:(console.warn(`Crudify: ${l.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=l.getEncryptionKey();return U.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return U.AES.decrypt(i,e).toString(U.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=l.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var f=l;import T from"@nocios/crudify-browser";var z=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},f.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),T.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),b.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=f.getTokens();e?f.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):f.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await T.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=f.getTokens(),c={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return f.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await T.logout(),f.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),f.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=f.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),f.clearTokens(),!1;if(T.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),T.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=f.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return f.clearTokens(),await T.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await T.logout(),!1}}isAuthenticated(){return T.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=T.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await T.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return f.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),f.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){T.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),b.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(f.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),b.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),b.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=T.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";T.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await T.init(t,o);if(c.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors||"Unknown error")}`);if(!c.data&&c.success!==!0)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors||"Unknown error")}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(c=>typeof c=="string"&&(c.includes("NOT_AUTHORIZED")||c.includes("TOKEN_REFRESH_FAILED")||c.includes("TOKEN_HAS_EXPIRED")||c.includes("PLEASE_LOGIN")||c.includes("Unauthorized")||c.includes("UNAUTHENTICATED")||c.includes("SESSION_EXPIRED")||c.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity(),e=T.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,o=300*1e3,c=300*1e3;return i>t?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):i<o&&e.expiresIn<c&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(i/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){f.clearTokens(),T.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?B("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as ge,useEffect as F,useCallback as R}from"react";function ee(r={}){let[i,e]=ge({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=z.getInstance(),o=R(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",u),await t.initialize(u),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),a=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let s=u instanceof Error?u.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),c=R(async(u,s)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await t.login(u,s);return a.success&&a.tokens?e(n=>({...n,isAuthenticated:!0,tokens:a.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),a}catch(a){let n=a instanceof Error?a.message:"Login failed",d=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:n})),{success:!1,error:n}}},[t]),y=R(async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),E=R(async()=>{try{let u=await t.refreshTokens();if(u){let s=t.getTokenInfo();e(a=>({...a,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),k=R(()=>{e(u=>({...u,error:null}))},[]),h=R(()=>t.getTokenInfo(),[t]);F(()=>{o()},[o]),F(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=$.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=setInterval(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await y();else if(d==="refresh")if(r.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(g=>({...g,isLoading:!0})),await t.refreshTokens()){let g=t.getTokenInfo();e(I=>({...I,isLoading:!1,tokens:g.crudifyTokens.accessToken?{accessToken:g.crudifyTokens.accessToken,refreshToken:g.crudifyTokens.refreshToken,expiresAt:g.crudifyTokens.expiresAt,refreshExpiresAt:g.crudifyTokens.refreshExpiresAt}:null}))}else e(g=>({...g,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(n),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,y]),F(()=>{let u=b.subscribe(async s=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(a=>({...a,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(d=>({...d,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),b.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(a){r.enableLogging&&console.error("\u274C Error during token refresh:",a),b.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),F(()=>{let u=f.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),b.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let S=R(()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:y,refreshTokens:E,clearError:k,getTokenInfo:h,updateActivity:S,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as ie,createContext as pe,useContext as ye,useCallback as M,useEffect as he}from"react";import{Snackbar as Ee,Alert as me,Box as Te,Portal as ve}from"@mui/material";import{v4 as ke}from"uuid";import Ae from"dompurify";import{jsx as C,jsxs as Se}from"react/jsx-runtime";var te=pe(null),be=r=>Ae.sanitize(r,{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}),X=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[y,E]=ie([]),k=M((s,a="info",n)=>{if(!o)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=ke(),m={id:d,message:s,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??c};return E(g=>[...g.length>=i?g.slice(-(i-1)):g,m]),d},[i,e,o,c]),h=M(s=>{E(a=>a.filter(n=>n.id!==s))},[]),S=M(()=>{E([])},[]),u={showNotification:k,hideNotification:h,clearAllNotifications:S};return Se(te.Provider,{value:u,children:[r,o&&C(ve,{children:C(Te,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:y.map(s=>C(xe,{notification:s,onClose:()=>h(s.id)},s.id))})})]})},xe=({notification:r,onClose:i})=>{let[e,t]=ie(!0),o=M((c,y)=>{y!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return he(()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),C(Ee,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:C(me,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?C("span",{dangerouslySetInnerHTML:{__html:be(r.message)}}):C("span",{children:r.message})})})},re=()=>{let r=ye(te);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Ie,{createContext as Ne,useContext as Re,useMemo as Y}from"react";import{Fragment as De,jsx as v,jsxs as x}from"react/jsx-runtime";var oe=Ne(void 0);function ne({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=re();c=n}catch{}let y={};try{let n=Q();n.isInitialized&&n.adminCredentials&&(y=n.adminCredentials)}catch{}let E=Y(()=>{let n,d;if(e?.publicApiKey&&(n=e.publicApiKey),e?.env&&(d=e.env),!n){let m=N("publicApiKey"),g=N("environment");m&&(n=m),g&&["dev","stg","prod"].includes(g)&&(d=g)}return{publicApiKey:n,env:d||"stg"}},[e]),k=Ie.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:y.apiEndpointAdmin,apiKeyEndpointAdmin:y.apiKeyEndpointAdmin,publicApiKey:E.publicApiKey,env:E.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,c,y.apiEndpointAdmin,y.apiKeyEndpointAdmin,E]),h=ee(k),S=Y(()=>{let n,d,m,g,I,D="unknown";if(e?.publicApiKey&&(n=e.publicApiKey,D="props"),e?.env&&(d=e.env),e?.appName&&(m=e.appName),e?.loginActions&&(g=e.loginActions),e?.logo&&(I=e.logo),!n){let L=N("publicApiKey"),A=N("environment"),p=N("appName"),P=N("loginActions"),w=N("logo");L&&(n=L,D="cookies"),A&&["dev","stg","prod"].includes(A)&&(d=A),p&&(m=decodeURIComponent(p)),P&&(g=decodeURIComponent(P).split(",").map(le=>le.trim()).filter(Boolean)),w&&(I=decodeURIComponent(w))}return{publicApiKey:n,env:d,appName:m,loginActions:g,logo:I}},[e]),u=Y(()=>{if(!h.tokens?.accessToken||!h.isAuthenticated)return null;try{let n=j(h.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let d={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(m=>{["sub","email","subscriber"].includes(m)||(d[m]=n[m])}),d}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[h.tokens?.accessToken,h.isAuthenticated]),s={...h,sessionData:u,config:S},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return v(oe.Provider,{value:s,children:r})}function Ti(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?v(q,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:v(X,{...i,children:v(ne,{...r})})}):v(X,{...i,children:v(ne,{...r})})}function Ce(){let r=Re(oe);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function vi(){let r=Ce();return r.isInitialized?x("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[v("h4",{children:"Session Debug Info"}),x("div",{children:[v("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),x("div",{children:[v("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),x("div",{children:[v("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&x(De,{children:[x("div",{children:[v("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),x("div",{children:[v("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),x("div",{children:[v("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),x("div",{children:[v("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),x("div",{children:[v("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):v("div",{children:"Session not initialized"})}import{useState as H,useEffect as se,useCallback as ae,useRef as _}from"react";import Le from"@nocios/crudify-browser";var Ii=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=H(null),[y,E]=H(!1),[k,h]=H(null),[S,u]=H({}),s=_(null),a=_(!0),n=_(0),d=_(0),m=ae(()=>{c(null),h(null),E(!1),u({})},[]),g=ae(async()=>{let I=J();if(!I){a.current&&(h("No user email available"),E(!1));return}s.current&&s.current.abort();let D=new AbortController;s.current=D;let L=++n.current;try{a.current&&(E(!0),h(null));let A=await Le.readItems("users",{filter:{email:I},pagination:{limit:1}});if(L===n.current&&a.current&&!D.signal.aborted)if(A.success&&A.data&&A.data.length>0){let p=A.data[0];c(p);let P={fullProfile:p,totalFields:Object.keys(p).length,displayData:{id:p.id,email:p.email,username:p.username,firstName:p.firstName,lastName:p.lastName,fullName:p.fullName||`${p.firstName||""} ${p.lastName||""}`.trim(),role:p.role,permissions:p.permissions||[],isActive:p.isActive,lastLogin:p.lastLogin,createdAt:p.createdAt,updatedAt:p.updatedAt,...Object.keys(p).filter(w=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(w)).reduce((w,G)=>({...w,[G]:p[G]}),{})}};u(P),h(null),d.current=0}else h("User profile not found"),c(null),u({})}catch(A){if(L===n.current&&a.current){let p=A;if(p.name==="AbortError")return;e&&d.current<t&&(p.message?.includes("Network Error")||p.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{a.current&&g()},1e3*d.current)):(h("Failed to load user profile"),c(null),u({}))}}finally{L===n.current&&a.current&&E(!1),s.current===D&&(s.current=null)}},[e,t]);return se(()=>{i&&g()},[i,g]),se(()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:y,error:k,extendedData:S,refreshProfile:g,clearProfile:m}};export{W as a,q as b,Q as c,f as d,z as e,ee as f,X as g,re as h,Ti as i,Ce as j,vi as k,Ii as l};