@nocios/crudify-ui 4.4.8 → 4.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var u=e=>{let t=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return t?t[2]:null};var N=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],I={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"},C={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 p(e,t){let{translateFn:o,currentLanguage:n,enableDebug:s}=t;s&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${n||"unknown"})`);let c=e.toUpperCase(),E=I[c],g=N.map(r=>r.replace("{category}",E||"general").replace("{code}",c));s&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",g);for(let r of g){let a=o(r);if(s&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${r}" -> result: "${a}" (same as key: ${a===r})`),a&&a!==r)return s&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${r} = "${a}"`),a}let i=C[c];if(i)return s&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${i}"`),i;let d=c.replace(/_/g," ").toLowerCase().replace(/\b\w/g,r=>r.toUpperCase());return s&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function S(e,t){return e.map(o=>p(o,t))}function O(e,t){let{enableDebug:o}=t;o&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let n=p(e.code,t);return n!==e.code.toUpperCase()&&n!==e.code?(o&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${n}"`),e.field?`${e.field}: ${n}`:n):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(o&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(o&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${n}"`),e.field?`${e.field}: ${n}`:n)}function _(e,t={}){let o={translateFn:e,currentLanguage:t.currentLanguage,enableDebug:t.enableDebug||!1};return{translateErrorCode:n=>p(n,o),translateErrorCodes:n=>S(n,o),translateError:n=>O(n,o),translateApiError:n=>n?.data?.response?.status?p(n.data.response.status,o):n?.status?p(n.status,o):n?.code?p(n.code,o):"Unknown error"}}var y=class e{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return e.instance||(e.instance=new e),e.instance}emit(t,o){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===t&&n-this.lastErrorTime<this.DEBOUNCE_TIME){console.log(`\u{1F6AB} AuthEventBus: Ignoring duplicate ${t} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=t,console.log(`\u{1F4E2} AuthEventBus: Emitting ${t} event`,o);let s={type:t,details:o,timestamp:n};this.listeners.forEach(c=>{try{c(s)}catch(E){console.error("AuthEventBus: Error in listener",E)}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},w=y.getInstance();var l=class l{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return l.instance||(l.instance=new l),l.instance}subscribe(t){return this.listeners.add(t),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(t)}}unsubscribe(t){this.listeners.delete(t),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let t=this;window.history.pushState=function(...o){let n=t.originalPushState.apply(this,o);return t.notifyListeners(),n},window.history.replaceState=function(...o){let n=t.originalReplaceState.apply(this,o);return t.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(t=>{try{t()}catch(o){console.error("NavigationTracker: Error in navigation listener",o)}})}static reset(){l.instance?.isPatched&&l.instance.removePatches(),l.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};l.instance=null;var T=l;var A=e=>{try{let t=e.split(".");if(t.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let o=t[1],n=o+"=".repeat((4-o.length%4)%4);return JSON.parse(atob(n))}catch(t){return console.warn("Failed to decode JWT token:",t),null}},L=()=>{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 t=A(e);if(!t)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let o=t.email||t["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",o),o}catch(e){return console.warn("Failed to get current user email:",e),null}},x=e=>{try{let t=A(e);if(!t||!t.exp)return!0;let o=Math.floor(Date.now()/1e3);return t.exp<o}catch{return!0}};function b(e={}){let{publicApiKey:t,env:o,appName:n,logo:s,loginActions:c,sections:E,enableDebug:g=!1}=e,i={configSource:"none"},d=u("publicApiKey");if(d){let r=u("environment"),a=u("appName"),h=u("logo"),v=u("loginActions"),m=u("sections"),R=u("theme");return i={publicApiKey:decodeURIComponent(d),env:r&&["dev","stg","api","prod"].includes(r)?r:"prod",appName:a?decodeURIComponent(a):void 0,logo:h?decodeURIComponent(h):void 0,loginActions:v?decodeURIComponent(v).split(",").map(f=>f.trim()).filter(Boolean):void 0,sections:m?decodeURIComponent(m).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:R?(()=>{try{return JSON.parse(decodeURIComponent(R))}catch(f){console.warn("[ConfigResolver] Failed to parse theme cookie:",f);return}})():void 0,configSource:"cookies"},g&&(console.log("[ConfigResolver] \u2705 Using COOKIES config (production):",i),console.log("[ConfigResolver] Raw cookies:",{publicApiKey:d,environment:r,appName:a,logo:h,loginActions:v,sections:m,theme:R})),g&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=i),i}return t?(i={publicApiKey:t,env:o||"prod",appName:n,logo:s,loginActions:c,sections:E,configSource:"props"},g&&console.log("[ConfigResolver] \u2705 Using PROPS config (development):",i),i):(g&&console.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props available."),i)}function K(e={}){return b(e)}export{u as a,p as b,S as c,O as d,_ as e,w as f,T as g,A as h,L as i,x as j,b as k,K as l};
1
+ var u=e=>{let t=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return t?t[2]:null};var I=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],N={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"},C={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 d(e,t){let{translateFn:o,currentLanguage:n,enableDebug:i}=t;i&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${n||"unknown"})`);let c=e.toUpperCase(),p=N[c],g=I.map(r=>r.replace("{category}",p||"general").replace("{code}",c));i&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",g);for(let r of g){let l=o(r);if(i&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${r}" -> result: "${l}" (same as key: ${l===r})`),l&&l!==r)return i&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${r} = "${l}"`),l}let s=C[c];if(s)return i&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${s}"`),s;let E=c.replace(/_/g," ").toLowerCase().replace(/\b\w/g,r=>r.toUpperCase());return i&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${E}"`),E}function S(e,t){return e.map(o=>d(o,t))}function O(e,t){let{enableDebug:o}=t;o&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let n=d(e.code,t);return n!==e.code.toUpperCase()&&n!==e.code?(o&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${n}"`),e.field?`${e.field}: ${n}`:n):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(o&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(o&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${n}"`),e.field?`${e.field}: ${n}`:n)}function w(e,t={}){let o={translateFn:e,currentLanguage:t.currentLanguage,enableDebug:t.enableDebug||!1};return{translateErrorCode:n=>d(n,o),translateErrorCodes:n=>S(n,o),translateError:n=>O(n,o),translateApiError:n=>n?.data?.response?.status?d(n.data.response.status,o):n?.status?d(n.status,o):n?.code?d(n.code,o):"Unknown error"}}var h=class e{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return e.instance||(e.instance=new e),e.instance}emit(t,o){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===t&&n-this.lastErrorTime<this.DEBOUNCE_TIME){console.log(`\u{1F6AB} AuthEventBus: Ignoring duplicate ${t} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=t,console.log(`\u{1F4E2} AuthEventBus: Emitting ${t} event`,o);let i={type:t,details:o,timestamp:n};this.listeners.forEach(c=>{try{c(i)}catch(p){console.error("AuthEventBus: Error in listener",p)}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},U=h.getInstance();var a=class a{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return a.instance||(a.instance=new a),a.instance}subscribe(t){return this.listeners.add(t),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(t)}}unsubscribe(t){this.listeners.delete(t),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let t=this;window.history.pushState=function(...o){let n=t.originalPushState.apply(this,o);return t.notifyListeners(),n},window.history.replaceState=function(...o){let n=t.originalReplaceState.apply(this,o);return t.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(t=>{try{t()}catch(o){console.error("NavigationTracker: Error in navigation listener",o)}})}static reset(){a.instance?.isPatched&&a.instance.removePatches(),a.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};a.instance=null;var T=a;var A=e=>{try{let t=e.split(".");if(t.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let o=t[1],n=o+"=".repeat((4-o.length%4)%4);return JSON.parse(atob(n))}catch(t){return console.warn("Failed to decode JWT token:",t),null}},P=()=>{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 t=A(e);if(!t)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let o=t.email||t["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",o),o}catch(e){return console.warn("Failed to get current user email:",e),null}},x=e=>{try{let t=A(e);if(!t||!t.exp)return!0;let o=Math.floor(Date.now()/1e3);return t.exp<o}catch{return!0}};function b(e={}){let{publicApiKey:t,env:o,appName:n,logo:i,loginActions:c,sections:p,enableDebug:g=!1}=e,s={configSource:"none"},E=u("publicApiKey");if(E){let r=u("environment"),l=u("appName"),m=u("logo"),v=u("loginActions"),R=u("sections"),y=u("theme");return s={publicApiKey:decodeURIComponent(E),env:r&&["dev","stg","api","prod"].includes(r)?r:"prod",appName:l?decodeURIComponent(l):void 0,logo:m?decodeURIComponent(m):void 0,loginActions:v?decodeURIComponent(v).split(",").map(f=>f.trim()).filter(Boolean):void 0,sections:R?decodeURIComponent(R).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:y?(()=>{try{return JSON.parse(decodeURIComponent(y))}catch(f){g&&console.warn("[ConfigResolver] Failed to parse theme cookie:",f);return}})():void 0,configSource:"cookies"},g&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s),s}return t&&(s={publicApiKey:t,env:o||"prod",appName:n,logo:i,loginActions:c,sections:p,configSource:"props"},g&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}function K(e={}){return b(e)}export{u as a,d as b,S as c,O as d,w as e,U as f,T as g,A as h,P as i,x as j,b as k,K as l};
@@ -1 +1 @@
1
- import{b as W,f as I,g as J,h as q,i as Z,k as X}from"./chunk-AWJ3DQQT.mjs";import{createContext as fe,useContext as ge,useEffect as pe,useState as P}from"react";import K from"@nocios/crudify-browser";var Y=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}},Q=Y.getInstance();import{jsx as ye}from"react/jsx-runtime";var ee=fe(void 0),ie=({config:r,children:i})=>{let[e,t]=P(!0),[o,c]=P(null),[p,y]=P(!1),[k,h]=P(""),[x,u]=P();pe(()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),y(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===k&&p){t(!1);return}(async()=>{t(!0),c(null),y(!1);try{K.config(r.env||"prod");let d=await K.init(r.publicApiKey,"none");if(u(d),typeof K.transaction=="function"&&typeof K.login=="function")y(!0),h(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&Q.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),y(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,k,p]);let s={crudify:p?K:null,isLoading:e,error:o,isInitialized:p,adminCredentials:x};return ye(ee.Provider,{value:s,children:i})},te=()=>{let r=ge(ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import z 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 z.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 z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return z.AES.decrypt(i,e).toString(z.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 A from"@nocios/crudify-browser";var F=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(),A.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),I.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 A.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 A.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(A.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),A.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 A.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 A.logout(),!1}}isAuthenticated(){return A.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=A.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 A.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(){A.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"),I.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"),I.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"),I.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=A.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";A.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await A.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);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();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){f.clearTokens(),A.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?W("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 he,useEffect as M,useCallback as L}from"react";function re(r={}){let[i,e]=he({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=F.getInstance(),o=L(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=L(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]),p=L(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]),y=L(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=L(()=>{e(u=>({...u,error:null}))},[]),h=L(()=>t.getTokenInfo(),[t]);M(()=>{o()},[o]),M(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=J.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let S=t.getTokenInfo().crudifyTokens.expiresIn||0;return S<300*1e3?30*1e3:S<1800*1e3?60*1e3:120*1e3},d,m=()=>{let b=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),m();return}let S=t.getTokenInfo(),T=S.crudifyTokens.expiresIn||0,R=(S.crudifyTokens.expiresAt||0)-(Date.now()-T),g=R*.5;if(T>0&&T<=g){let U=Math.round(T/R*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${U}% of TTL (${Math.round(T/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(de=>({...de,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let O=t.getTimeSinceLastActivity(),w=1800*1e3;O>w?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await p()):m()},b)};return m(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,p]),M(()=>{let u=I.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"),I.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),I.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]),M(()=>{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})),I.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let x=L(()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:p,refreshTokens:y,clearError:k,getTokenInfo:h,updateActivity:x,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 ne,createContext as me,useContext as Te,useCallback as H,useEffect as Ee}from"react";import{Snackbar as ve,Alert as Ae,Box as ke,Portal as be}from"@mui/material";import{v4 as xe}from"uuid";import Se from"dompurify";import{jsx as D,jsxs as Re}from"react/jsx-runtime";var oe=me(null),Ie=r=>Se.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}),$=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[p,y]=ne([]),k=H((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=xe(),m={id:d,message:s,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??c};return y(b=>[...b.length>=i?b.slice(-(i-1)):b,m]),d},[i,e,o,c]),h=H(s=>{y(a=>a.filter(n=>n.id!==s))},[]),x=H(()=>{y([])},[]),u={showNotification:k,hideNotification:h,clearAllNotifications:x};return Re(oe.Provider,{value:u,children:[r,o&&D(be,{children:D(ke,{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:p.map(s=>D(Ne,{notification:s,onClose:()=>h(s.id)},s.id))})})]})},Ne=({notification:r,onClose:i})=>{let[e,t]=ne(!0),o=H((c,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ee(()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),D(ve,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:D(Ae,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?D("span",{dangerouslySetInnerHTML:{__html:Ie(r.message)}}):D("span",{children:r.message})})})},se=()=>{let r=Te(oe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Ce,{createContext as Le,useContext as De,useMemo as B}from"react";import{Fragment as Pe,jsx as E,jsxs as N}from"react/jsx-runtime";var le=Le(void 0);function ae({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=se();c=n}catch{}let p={};try{let n=te();n.isInitialized&&n.adminCredentials&&(p=n.adminCredentials)}catch{}let y=B(()=>{let n=X({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),k=Ce.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,publicApiKey:y.publicApiKey,env:y.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,c,p.apiEndpointAdmin,p.apiKeyEndpointAdmin,y]),h=re(k),x=B(()=>{let n=X({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),u=B(()=>{if(!h.tokens?.accessToken||!h.isAuthenticated)return null;try{let n=q(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:x},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return E(le.Provider,{value:s,children:r})}function Ii(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?E(ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:E($,{...i,children:E(ae,{...r})})}):E($,{...i,children:E(ae,{...r})})}function we(){let r=De(le);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=we();return r.isInitialized?N("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[E("h4",{children:"Session Debug Info"}),N("div",{children:[E("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),N("div",{children:[E("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),N("div",{children:[E("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&N(Pe,{children:[N("div",{children:[E("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),N("div",{children:[E("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),N("div",{children:[E("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),N("div",{children:[E("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),N("div",{children:[E("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):E("div",{children:"Session not initialized"})}import{useState as G,useEffect as ce,useCallback as ue,useRef as _}from"react";import Ke from"@nocios/crudify-browser";var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=G(null),[p,y]=G(!1),[k,h]=G(null),[x,u]=G({}),s=_(null),a=_(!0),n=_(0),d=_(0),m=ue(()=>{c(null),h(null),y(!1),u({})},[]),b=ue(async()=>{let S=Z();if(!S){a.current&&(h("No user email available"),y(!1));return}s.current&&s.current.abort();let T=new AbortController;s.current=T;let v=++n.current;try{a.current&&(y(!0),h(null));let R=await Ke.readItems("users",{filter:{email:S},pagination:{limit:1}});if(v===n.current&&a.current&&!T.signal.aborted)if(R.success&&R.data&&R.data.length>0){let g=R.data[0];c(g);let O={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(w=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(w)).reduce((w,U)=>({...w,[U]:g[U]}),{})}};u(O),h(null),d.current=0}else h("User profile not found"),c(null),u({})}catch(R){if(v===n.current&&a.current){let g=R;if(g.name==="AbortError")return;e&&d.current<t&&(g.message?.includes("Network Error")||g.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{a.current&&b()},1e3*d.current)):(h("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&y(!1),s.current===T&&(s.current=null)}},[e,t]);return ce(()=>{i&&b()},[i,b]),ce(()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:p,error:k,extendedData:x,refreshProfile:b,clearProfile:m}};import{useState as j,useEffect as Oe,useCallback as V,useRef as Ue}from"react";import ze from"@nocios/crudify-browser";var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:p=0,separator:y=""}=r,[k,h]=j(""),[x,u]=j(!1),[s,a]=j(null),n=Ue(!1),d=V(T=>{let v=String(T).padStart(p,"0");return`${c}${y}${v}`},[c,p,y]),m=V(async()=>{u(!0),a(null);try{let T=await ze.getNextSequence(c);if(T.success&&T.data?.value){let v=d(T.data.value);h(v),t?.(v)}else{let v=T.errors?._error?.[0]||"Failed to generate code";a(v),o?.(v)}}catch(T){let v=T instanceof Error?T.message:"Unknown error";a(v),o?.(v)}finally{u(!1)}},[c,d,t,o]),b=V(async()=>{await m()},[m]),S=V(()=>{a(null)},[]);return Oe(()=>{e&&!k&&!n.current&&(n.current=!0,m())},[e,k,m]),{value:k,loading:x,error:s,regenerate:b,clearError:S}};export{Q as a,ie as b,te as c,f as d,F as e,re as f,$ as g,se as h,Ii as i,we as j,Ni as k,Pi as l,zi as m};
1
+ import{b as W,f as I,g as J,h as q,i as Z,k as X}from"./chunk-BGLMR67G.mjs";import{createContext as fe,useContext as ge,useEffect as pe,useState as P}from"react";import K from"@nocios/crudify-browser";var Y=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}},Q=Y.getInstance();import{jsx as ye}from"react/jsx-runtime";var ee=fe(void 0),ie=({config:r,children:i})=>{let[e,t]=P(!0),[o,c]=P(null),[p,y]=P(!1),[k,h]=P(""),[x,u]=P();pe(()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),y(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===k&&p){t(!1);return}(async()=>{t(!0),c(null),y(!1);try{K.config(r.env||"prod");let d=await K.init(r.publicApiKey,"none");if(u(d),typeof K.transaction=="function"&&typeof K.login=="function")y(!0),h(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&Q.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),y(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,k,p]);let s={crudify:p?K:null,isLoading:e,error:o,isInitialized:p,adminCredentials:x};return ye(ee.Provider,{value:s,children:i})},te=()=>{let r=ge(ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import z 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 z.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 z.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return z.AES.decrypt(i,e).toString(z.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 A from"@nocios/crudify-browser";var F=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(),A.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),I.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 A.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 A.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(A.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),A.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 A.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 A.logout(),!1}}isAuthenticated(){return A.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=A.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 A.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(){A.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"),I.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"),I.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"),I.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=A.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";A.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await A.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);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();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){f.clearTokens(),A.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?W("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 he,useEffect as M,useCallback as L}from"react";function re(r={}){let[i,e]=he({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=F.getInstance(),o=L(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=L(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]),p=L(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]),y=L(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=L(()=>{e(u=>({...u,error:null}))},[]),h=L(()=>t.getTokenInfo(),[t]);M(()=>{o()},[o]),M(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=J.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let S=t.getTokenInfo().crudifyTokens.expiresIn||0;return S<300*1e3?30*1e3:S<1800*1e3?60*1e3:120*1e3},d,m=()=>{let b=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),m();return}let S=t.getTokenInfo(),T=S.crudifyTokens.expiresIn||0,R=(S.crudifyTokens.expiresAt||0)-(Date.now()-T),g=R*.5;if(T>0&&T<=g){let U=Math.round(T/R*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${U}% of TTL (${Math.round(T/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(de=>({...de,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let O=t.getTimeSinceLastActivity(),w=1800*1e3;O>w?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await p()):m()},b)};return m(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,p]),M(()=>{let u=I.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"),I.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),I.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]),M(()=>{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})),I.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let x=L(()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:p,refreshTokens:y,clearError:k,getTokenInfo:h,updateActivity:x,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 ne,createContext as me,useContext as Te,useCallback as H,useEffect as Ee}from"react";import{Snackbar as ve,Alert as Ae,Box as ke,Portal as be}from"@mui/material";import{v4 as xe}from"uuid";import Se from"dompurify";import{jsx as D,jsxs as Re}from"react/jsx-runtime";var oe=me(null),Ie=r=>Se.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}),$=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[p,y]=ne([]),k=H((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=xe(),m={id:d,message:s,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??c};return y(b=>[...b.length>=i?b.slice(-(i-1)):b,m]),d},[i,e,o,c]),h=H(s=>{y(a=>a.filter(n=>n.id!==s))},[]),x=H(()=>{y([])},[]),u={showNotification:k,hideNotification:h,clearAllNotifications:x};return Re(oe.Provider,{value:u,children:[r,o&&D(be,{children:D(ke,{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:p.map(s=>D(Ne,{notification:s,onClose:()=>h(s.id)},s.id))})})]})},Ne=({notification:r,onClose:i})=>{let[e,t]=ne(!0),o=H((c,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ee(()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),D(ve,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:D(Ae,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?D("span",{dangerouslySetInnerHTML:{__html:Ie(r.message)}}):D("span",{children:r.message})})})},se=()=>{let r=Te(oe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Ce,{createContext as Le,useContext as De,useMemo as B}from"react";import{Fragment as Pe,jsx as E,jsxs as N}from"react/jsx-runtime";var le=Le(void 0);function ae({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=se();c=n}catch{}let p={};try{let n=te();n.isInitialized&&n.adminCredentials&&(p=n.adminCredentials)}catch{}let y=B(()=>{let n=X({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),k=Ce.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,publicApiKey:y.publicApiKey,env:y.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,c,p.apiEndpointAdmin,p.apiKeyEndpointAdmin,y]),h=re(k),x=B(()=>{let n=X({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),u=B(()=>{if(!h.tokens?.accessToken||!h.isAuthenticated)return null;try{let n=q(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:x},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return E(le.Provider,{value:s,children:r})}function Ii(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?E(ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:E($,{...i,children:E(ae,{...r})})}):E($,{...i,children:E(ae,{...r})})}function we(){let r=De(le);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=we();return r.isInitialized?N("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[E("h4",{children:"Session Debug Info"}),N("div",{children:[E("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),N("div",{children:[E("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),N("div",{children:[E("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&N(Pe,{children:[N("div",{children:[E("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),N("div",{children:[E("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),N("div",{children:[E("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),N("div",{children:[E("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),N("div",{children:[E("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):E("div",{children:"Session not initialized"})}import{useState as G,useEffect as ce,useCallback as ue,useRef as _}from"react";import Ke from"@nocios/crudify-browser";var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=G(null),[p,y]=G(!1),[k,h]=G(null),[x,u]=G({}),s=_(null),a=_(!0),n=_(0),d=_(0),m=ue(()=>{c(null),h(null),y(!1),u({})},[]),b=ue(async()=>{let S=Z();if(!S){a.current&&(h("No user email available"),y(!1));return}s.current&&s.current.abort();let T=new AbortController;s.current=T;let v=++n.current;try{a.current&&(y(!0),h(null));let R=await Ke.readItems("users",{filter:{email:S},pagination:{limit:1}});if(v===n.current&&a.current&&!T.signal.aborted)if(R.success&&R.data&&R.data.length>0){let g=R.data[0];c(g);let O={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(w=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(w)).reduce((w,U)=>({...w,[U]:g[U]}),{})}};u(O),h(null),d.current=0}else h("User profile not found"),c(null),u({})}catch(R){if(v===n.current&&a.current){let g=R;if(g.name==="AbortError")return;e&&d.current<t&&(g.message?.includes("Network Error")||g.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{a.current&&b()},1e3*d.current)):(h("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&y(!1),s.current===T&&(s.current=null)}},[e,t]);return ce(()=>{i&&b()},[i,b]),ce(()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:p,error:k,extendedData:x,refreshProfile:b,clearProfile:m}};import{useState as j,useEffect as Oe,useCallback as V,useRef as Ue}from"react";import ze from"@nocios/crudify-browser";var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:p=0,separator:y=""}=r,[k,h]=j(""),[x,u]=j(!1),[s,a]=j(null),n=Ue(!1),d=V(T=>{let v=String(T).padStart(p,"0");return`${c}${y}${v}`},[c,p,y]),m=V(async()=>{u(!0),a(null);try{let T=await ze.getNextSequence(c);if(T.success&&T.data?.value){let v=d(T.data.value);h(v),t?.(v)}else{let v=T.errors?._error?.[0]||"Failed to generate code";a(v),o?.(v)}}catch(T){let v=T instanceof Error?T.message:"Unknown error";a(v),o?.(v)}finally{u(!1)}},[c,d,t,o]),b=V(async()=>{await m()},[m]),S=V(()=>{a(null)},[]);return Oe(()=>{e&&!k&&!n.current&&(n.current=!0,m())},[e,k,m]),{value:k,loading:x,error:s,regenerate:b,clearError:S}};export{Q as a,ie as b,te as c,f as d,F as e,re as f,$ as g,se as h,Ii as i,we as j,Ni as k,Pi as l,zi as m};
@@ -0,0 +1 @@
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 u=e=>{let t=document.cookie.match(new RegExp("(^|;)\\s*"+e+"=([^;]+)"));return t?t[2]:null};var I=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],N={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"},C={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 d(e,t){let{translateFn:o,currentLanguage:n,enableDebug:i}=t;i&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${e} (lang: ${n||"unknown"})`);let c=e.toUpperCase(),p=N[c],g=I.map(r=>r.replace("{category}",p||"general").replace("{code}",c));i&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",g);for(let r of g){let l=o(r);if(i&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${r}" -> result: "${l}" (same as key: ${l===r})`),l&&l!==r)return i&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${r} = "${l}"`),l}let s=C[c];if(s)return i&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${s}"`),s;let E=c.replace(/_/g," ").toLowerCase().replace(/\b\w/g,r=>r.toUpperCase());return i&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${E}"`),E}function S(e,t){return e.map(o=>d(o,t))}function O(e,t){let{enableDebug:o}=t;o&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",e);let n=d(e.code,t);return n!==e.code.toUpperCase()&&n!==e.code?(o&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${n}"`),e.field?`${e.field}: ${n}`:n):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(o&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(o&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${n}"`),e.field?`${e.field}: ${n}`:n)}function w(e,t={}){let o={translateFn:e,currentLanguage:t.currentLanguage,enableDebug:t.enableDebug||!1};return{translateErrorCode:n=>d(n,o),translateErrorCodes:n=>S(n,o),translateError:n=>O(n,o),translateApiError:n=>_optionalChain([n, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.status])?d(n.data.response.status,o):_optionalChain([n, 'optionalAccess', _4 => _4.status])?d(n.status,o):_optionalChain([n, 'optionalAccess', _5 => _5.code])?d(n.code,o):"Unknown error"}}var h=class e{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return e.instance||(e.instance=new e),e.instance}emit(t,o){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===t&&n-this.lastErrorTime<this.DEBOUNCE_TIME){console.log(`\u{1F6AB} AuthEventBus: Ignoring duplicate ${t} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=t,console.log(`\u{1F4E2} AuthEventBus: Emitting ${t} event`,o);let i={type:t,details:o,timestamp:n};this.listeners.forEach(c=>{try{c(i)}catch(p){console.error("AuthEventBus: Error in listener",p)}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},U= exports.f =h.getInstance();var a=class a{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return a.instance||(a.instance=new a),a.instance}subscribe(t){return this.listeners.add(t),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(t)}}unsubscribe(t){this.listeners.delete(t),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let t=this;window.history.pushState=function(...o){let n=t.originalPushState.apply(this,o);return t.notifyListeners(),n},window.history.replaceState=function(...o){let n=t.originalReplaceState.apply(this,o);return t.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(t=>{try{t()}catch(o){console.error("NavigationTracker: Error in navigation listener",o)}})}static reset(){_optionalChain([a, 'access', _6 => _6.instance, 'optionalAccess', _7 => _7.isPatched])&&a.instance.removePatches(),a.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};a.instance=null;var T=a;var A=e=>{try{let t=e.split(".");if(t.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let o=t[1],n=o+"=".repeat((4-o.length%4)%4);return JSON.parse(atob(n))}catch(t){return console.warn("Failed to decode JWT token:",t),null}},P= exports.i =()=>{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 t=A(e);if(!t)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let o=t.email||t["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",o),o}catch(e){return console.warn("Failed to get current user email:",e),null}},x= exports.j =e=>{try{let t=A(e);if(!t||!t.exp)return!0;let o=Math.floor(Date.now()/1e3);return t.exp<o}catch (e2){return!0}};function b(e={}){let{publicApiKey:t,env:o,appName:n,logo:i,loginActions:c,sections:p,enableDebug:g=!1}=e,s={configSource:"none"},E=u("publicApiKey");if(E){let r=u("environment"),l=u("appName"),m=u("logo"),v=u("loginActions"),R=u("sections"),y=u("theme");return s={publicApiKey:decodeURIComponent(E),env:r&&["dev","stg","api","prod"].includes(r)?r:"prod",appName:l?decodeURIComponent(l):void 0,logo:m?decodeURIComponent(m):void 0,loginActions:v?decodeURIComponent(v).split(",").map(f=>f.trim()).filter(Boolean):void 0,sections:R?decodeURIComponent(R).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:y?(()=>{try{return JSON.parse(decodeURIComponent(y))}catch(f){g&&console.warn("[ConfigResolver] Failed to parse theme cookie:",f);return}})():void 0,configSource:"cookies"},g&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s),s}return t&&(s={publicApiKey:t,env:o||"prod",appName:n,logo:i,loginActions:c,sections:p,configSource:"props"},g&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}function K(e={}){return b(e)}exports.a = u; exports.b = d; exports.c = S; exports.d = O; exports.e = w; exports.f = U; exports.g = T; exports.h = A; exports.i = P; exports.j = x; exports.k = b; exports.l = K;