@nocios/crudify-ui 4.4.10 → 4.4.14

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
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkG6TKY43Rjs = require('./chunk-G6TKY43R.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);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= exports.a =Y.getInstance();var _jsxruntime = require('react/jsx-runtime');var ee=_react.createContext.call(void 0, void 0),ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,c]=_react.useState.call(void 0, null),[p,y]=_react.useState.call(void 0, !1),[k,h]=_react.useState.call(void 0, ""),[x,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{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{_crudifybrowser2.default.config(r.env||"prod");let d=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(d),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.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?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:p,adminCredentials:x};return _jsxruntime.jsx.call(void 0, ee.Provider,{value:s,children:i})},te= exports.c =()=>{let r=_react.useContext.call(void 0, ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);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 _cryptojs2.default.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 (e2){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 (e3){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 _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.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;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(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkG6TKY43Rjs.f.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 _crudifybrowser2.default.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:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return f.saveTokens(c),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(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 _crudifybrowser2.default.logout(),f.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}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(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.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&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return f.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.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 _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!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(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.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"),_chunkG6TKY43Rjs.f.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"),_chunkG6TKY43Rjs.f.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"),_chunkG6TKY43Rjs.f.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=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await _crudifybrowser2.default.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"||_optionalChain([o, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([o, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([o, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([o, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([o, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([o, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([o, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([o, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([o, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.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.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.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&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.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&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.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 (e4){}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(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkG6TKY43Rjs.b.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(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"}};function re(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=F.getInstance(),o=_react.useCallback.call(void 0, 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:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(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"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(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=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),h=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{o()},[o]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let u=_chunkG6TKY43Rjs.g.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]),_react.useEffect.call(void 0, ()=>{let u=_chunkG6TKY43Rjs.f.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"),_chunkG6TKY43Rjs.f.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),_chunkG6TKY43Rjs.f.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:_optionalChain([s, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{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})),_chunkG6TKY43Rjs.f.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let x=_react.useCallback.call(void 0, ()=>{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}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var oe=_react.createContext.call(void 0, null),Ie=r=>_dompurify2.default.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}),$= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[p,y]=_react.useState.call(void 0, []),k=_react.useCallback.call(void 0, (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=_uuid.v4.call(void 0, ),m={id:d,message:s,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (c))};return y(b=>[...b.length>=i?b.slice(-(i-1)):b,m]),d},[i,e,o,c]),h=_react.useCallback.call(void 0, s=>{y(a=>a.filter(n=>n.id!==s))},[]),x=_react.useCallback.call(void 0, ()=>{y([])},[]),u={showNotification:k,hideNotification:h,clearAllNotifications:x};return _jsxruntime.jsxs.call(void 0, oe.Provider,{value:u,children:[r,o&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{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=>_jsxruntime.jsx.call(void 0, Ne,{notification:s,onClose:()=>h(s.id)},s.id))})})]})},Ne=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (c,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:Ie(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},se= exports.h =()=>{let r=_react.useContext.call(void 0, oe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var le=_react.createContext.call(void 0, 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 (e5){}let p={};try{let n=te();n.isInitialized&&n.adminCredentials&&(p=n.adminCredentials)}catch (e6){}let y=_react.useMemo.call(void 0, ()=>{let n=_chunkG6TKY43Rjs.k.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _81 => _81.env]),enableDebug:_optionalChain([i, 'optionalAccess', _82 => _82.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _83 => _83.enableLogging])]),k=_react2.default.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,publicApiKey:y.publicApiKey,env:y.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,c,p.apiEndpointAdmin,p.apiKeyEndpointAdmin,y]),h=re(k),x=_react.useMemo.call(void 0, ()=>{let n=_chunkG6TKY43Rjs.k.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),appName:_optionalChain([e, 'optionalAccess', _88 => _88.appName]),logo:_optionalChain([e, 'optionalAccess', _89 => _89.logo]),loginActions:_optionalChain([e, 'optionalAccess', _90 => _90.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([h, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!h.isAuthenticated)return null;try{let n=_chunkG6TKY43Rjs.h.call(void 0, 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},[_optionalChain([h, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.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 _jsxruntime.jsx.call(void 0, le.Provider,{value:s,children:r})}function Ii(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.allowHtml])||!1};return _optionalChain([r, 'access', _105 => _105.config, 'optionalAccess', _106 => _106.publicApiKey])?_jsxruntime.jsx.call(void 0, ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, $,{...i,children:_jsxruntime.jsx.call(void 0, ae,{...r})})}):_jsxruntime.jsx.call(void 0, $,{...i,children:_jsxruntime.jsx.call(void 0, ae,{...r})})}function we(){let r=_react.useContext.call(void 0, 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?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_react.useState.call(void 0, null),[p,y]=_react.useState.call(void 0, !1),[k,h]=_react.useState.call(void 0, null),[x,u]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),m=_react.useCallback.call(void 0, ()=>{c(null),h(null),y(!1),u({})},[]),b=_react.useCallback.call(void 0, async()=>{let S=_chunkG6TKY43Rjs.i.call(void 0, );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 _crudifybrowser2.default.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&&(_optionalChain([g, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([g, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("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 _react.useEffect.call(void 0, ()=>{i&&b()},[i,b]),_react.useEffect.call(void 0, ()=>(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}};var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:p=0,separator:y=""}=r,[k,h]=_react.useState.call(void 0, ""),[x,u]=_react.useState.call(void 0, !1),[s,a]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),d=_react.useCallback.call(void 0, T=>{let v=String(T).padStart(p,"0");return`${c}${y}${v}`},[c,p,y]),m=_react.useCallback.call(void 0, async()=>{u(!0),a(null);try{let T=await _crudifybrowser2.default.getNextSequence(c);if(T.success&&_optionalChain([T, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let v=d(T.data.value);h(v),_optionalChain([t, 'optionalCall', _115 => _115(v)])}else{let v=_optionalChain([T, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";a(v),_optionalChain([o, 'optionalCall', _119 => _119(v)])}}catch(T){let v=T instanceof Error?T.message:"Unknown error";a(v),_optionalChain([o, 'optionalCall', _120 => _120(v)])}finally{u(!1)}},[c,d,t,o]),b=_react.useCallback.call(void 0, async()=>{await m()},[m]),S=_react.useCallback.call(void 0, ()=>{a(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!k&&!n.current&&(n.current=!0,m())},[e,k,m]),{value:k,loading:x,error:s,regenerate:b,clearError:S}};exports.a = Q; exports.b = ie; exports.c = te; exports.d = f; exports.e = F; exports.f = re; exports.g = $; exports.h = se; exports.i = Ii; exports.j = we; exports.k = Ni; exports.l = Pi; exports.m = zi;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkQ7BXOIWSjs = require('./chunk-Q7BXOIWS.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);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= exports.a =Y.getInstance();var _jsxruntime = require('react/jsx-runtime');var ee=_react.createContext.call(void 0, void 0),ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,c]=_react.useState.call(void 0, null),[p,y]=_react.useState.call(void 0, !1),[k,h]=_react.useState.call(void 0, ""),[x,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{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{_crudifybrowser2.default.config(r.env||"prod");let d=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(d),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.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?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:p,adminCredentials:x};return _jsxruntime.jsx.call(void 0, ee.Provider,{value:s,children:i})},te= exports.c =()=>{let r=_react.useContext.call(void 0, ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);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 _cryptojs2.default.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 (e2){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 (e3){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 _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.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;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(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkQ7BXOIWSjs.h.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 _crudifybrowser2.default.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:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return f.saveTokens(c),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(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 _crudifybrowser2.default.logout(),f.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}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(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.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&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return f.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.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 _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!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(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.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"),_chunkQ7BXOIWSjs.h.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"),_chunkQ7BXOIWSjs.h.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"),_chunkQ7BXOIWSjs.h.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=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await _crudifybrowser2.default.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"||_optionalChain([o, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([o, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([o, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([o, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([o, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([o, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([o, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([o, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([o, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.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.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.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&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.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&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.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 (e4){}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(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkQ7BXOIWSjs.d.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(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"}};function re(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=F.getInstance(),o=_react.useCallback.call(void 0, 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:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(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"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(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=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),h=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{o()},[o]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let u=_chunkQ7BXOIWSjs.i.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]),_react.useEffect.call(void 0, ()=>{let u=_chunkQ7BXOIWSjs.h.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"),_chunkQ7BXOIWSjs.h.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),_chunkQ7BXOIWSjs.h.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:_optionalChain([s, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{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})),_chunkQ7BXOIWSjs.h.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let x=_react.useCallback.call(void 0, ()=>{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}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var oe=_react.createContext.call(void 0, null),Ie=r=>_dompurify2.default.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}),$= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[p,y]=_react.useState.call(void 0, []),k=_react.useCallback.call(void 0, (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=_uuid.v4.call(void 0, ),m={id:d,message:s,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (c))};return y(b=>[...b.length>=i?b.slice(-(i-1)):b,m]),d},[i,e,o,c]),h=_react.useCallback.call(void 0, s=>{y(a=>a.filter(n=>n.id!==s))},[]),x=_react.useCallback.call(void 0, ()=>{y([])},[]),u={showNotification:k,hideNotification:h,clearAllNotifications:x};return _jsxruntime.jsxs.call(void 0, oe.Provider,{value:u,children:[r,o&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{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=>_jsxruntime.jsx.call(void 0, Ne,{notification:s,onClose:()=>h(s.id)},s.id))})})]})},Ne=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (c,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:Ie(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},se= exports.h =()=>{let r=_react.useContext.call(void 0, oe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var le=_react.createContext.call(void 0, 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 (e5){}let p={};try{let n=te();n.isInitialized&&n.adminCredentials&&(p=n.adminCredentials)}catch (e6){}let y=_react.useMemo.call(void 0, ()=>{let n=_chunkQ7BXOIWSjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _81 => _81.env]),enableDebug:_optionalChain([i, 'optionalAccess', _82 => _82.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _83 => _83.enableLogging])]),k=_react2.default.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,publicApiKey:y.publicApiKey,env:y.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,c,p.apiEndpointAdmin,p.apiKeyEndpointAdmin,y]),h=re(k),x=_react.useMemo.call(void 0, ()=>{let n=_chunkQ7BXOIWSjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),appName:_optionalChain([e, 'optionalAccess', _88 => _88.appName]),logo:_optionalChain([e, 'optionalAccess', _89 => _89.logo]),loginActions:_optionalChain([e, 'optionalAccess', _90 => _90.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([h, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!h.isAuthenticated)return null;try{let n=_chunkQ7BXOIWSjs.j.call(void 0, 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},[_optionalChain([h, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.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 _jsxruntime.jsx.call(void 0, le.Provider,{value:s,children:r})}function Ii(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.allowHtml])||!1};return _optionalChain([r, 'access', _105 => _105.config, 'optionalAccess', _106 => _106.publicApiKey])?_jsxruntime.jsx.call(void 0, ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, $,{...i,children:_jsxruntime.jsx.call(void 0, ae,{...r})})}):_jsxruntime.jsx.call(void 0, $,{...i,children:_jsxruntime.jsx.call(void 0, ae,{...r})})}function we(){let r=_react.useContext.call(void 0, 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?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_react.useState.call(void 0, null),[p,y]=_react.useState.call(void 0, !1),[k,h]=_react.useState.call(void 0, null),[x,u]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),m=_react.useCallback.call(void 0, ()=>{c(null),h(null),y(!1),u({})},[]),b=_react.useCallback.call(void 0, async()=>{let S=_chunkQ7BXOIWSjs.k.call(void 0, );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 _crudifybrowser2.default.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&&(_optionalChain([g, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([g, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("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 _react.useEffect.call(void 0, ()=>{i&&b()},[i,b]),_react.useEffect.call(void 0, ()=>(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}};var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:p=0,separator:y=""}=r,[k,h]=_react.useState.call(void 0, ""),[x,u]=_react.useState.call(void 0, !1),[s,a]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),d=_react.useCallback.call(void 0, T=>{let v=String(T).padStart(p,"0");return`${c}${y}${v}`},[c,p,y]),m=_react.useCallback.call(void 0, async()=>{u(!0),a(null);try{let T=await _crudifybrowser2.default.getNextSequence(c);if(T.success&&_optionalChain([T, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let v=d(T.data.value);h(v),_optionalChain([t, 'optionalCall', _115 => _115(v)])}else{let v=_optionalChain([T, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";a(v),_optionalChain([o, 'optionalCall', _119 => _119(v)])}}catch(T){let v=T instanceof Error?T.message:"Unknown error";a(v),_optionalChain([o, 'optionalCall', _120 => _120(v)])}finally{u(!1)}},[c,d,t,o]),b=_react.useCallback.call(void 0, async()=>{await m()},[m]),S=_react.useCallback.call(void 0, ()=>{a(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!k&&!n.current&&(n.current=!0,m())},[e,k,m]),{value:k,loading:x,error:s,regenerate:b,clearError:S}};exports.a = Q; exports.b = ie; exports.c = te; exports.d = f; exports.e = F; exports.f = re; exports.g = $; exports.h = se; exports.i = Ii; exports.j = we; exports.k = Ni; exports.l = Pi; exports.m = zi;
@@ -1 +1 @@
1
- import{h as $,j as D}from"./chunk-QVI5TQM6.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
1
+ import{h as $,j as D}from"./chunk-6MBALWSY.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
@@ -1 +1 @@
1
- import{b as W,f as I,g as J,h as q,i as Z,k as X}from"./chunk-W44OXEQ4.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 X,d as W,h as I,i as J,j as q,k as Z}from"./chunk-O2G2ZS3U.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};