@nocios/crudify-ui 4.4.72 → 4.4.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{a as o}from"./chunk-UJD6SL66.mjs";import a from"crypto-js";var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return a.SHA256(t).toString()}setItem(t,e,n){try{let r=a.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){o.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=a.AES.decrypt(r,this.encryptionKey).toString(a.enc.Utf8);return i||(o.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return o.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch{o.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch{return o.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y=new c("sessionStorage"),h=new c("localStorage");export{y as a,h as b};
1
+ import{a as o}from"./chunk-PK2UX3UH.mjs";import a from"crypto-js";var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return a.SHA256(t).toString()}setItem(t,e,n){try{let r=a.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){o.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=a.AES.decrypt(r,this.encryptionKey).toString(a.enc.Utf8);return i||(o.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return o.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch{o.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch{return o.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y=new c("sessionStorage"),h=new c("localStorage");export{y as a,h as b};
@@ -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 _chunkX3JFRSEAjs = require('./chunk-X3JFRSEA.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ue=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){_chunkX3JFRSEAjs.a.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(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}},j= exports.a =ue.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ae=_react.createContext.call(void 0, void 0),Ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[w,b]=_react.useState.call(void 0, ""),[T,c]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&d){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{_crudifybrowser2.default.config(r.env||"prod");let y=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(c(y),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")m(!0),b(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";_chunkX3JFRSEAjs.a.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),s(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,d]);let a={crudify:d?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:d,adminCredentials:T};return _jsxruntime.jsx.call(void 0, Ae.Provider,{value:a,children:i})},be= exports.c =()=>{let r=_react.useContext.call(void 0, Ae);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 f=class f{static setStorageType(i){f.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(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch (e2){return _chunkX3JFRSEAjs.a.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.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 f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(_chunkX3JFRSEAjs.a.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return _chunkX3JFRSEAjs.a.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return _chunkX3JFRSEAjs.a.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,o),_chunkX3JFRSEAjs.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunkX3JFRSEAjs.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(_chunkX3JFRSEAjs.a.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(_chunkX3JFRSEAjs.a.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return _chunkX3JFRSEAjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),_chunkX3JFRSEAjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkX3JFRSEAjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),_chunkX3JFRSEAjs.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunkX3JFRSEAjs.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.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=f.getTokens();if(!t){_chunkX3JFRSEAjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){_chunkX3JFRSEAjs.a.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){_chunkX3JFRSEAjs.a.debug("Crudify: Tokens updated in another tab");let o=f.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var I=f;var Q=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},I.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkX3JFRSEAjs.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=I.getTokens();e?I.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):I.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=I.getTokens(),s={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 I.saveTokens(s),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(s)]),{success:!0,tokens:s,data:t.data}}catch(t){return _chunkX3JFRSEAjs.a.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),I.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),I.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=I.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"),I.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=I.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return I.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),I.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||I.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=I.getExpirationInfo(),t=I.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:I.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),I.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 I.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),I.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"),_chunkX3JFRSEAjs.i.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(I.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkX3JFRSEAjs.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"),_chunkX3JFRSEAjs.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=_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",s=await _crudifybrowser2.default.init(t,o);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw _chunkX3JFRSEAjs.a.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(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(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.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(){I.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkX3JFRSEAjs.e.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 ke(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),o=_react.useCallback.call(void 0, async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let c={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(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=_react.useCallback.call(void 0, async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",y=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:n})),{success:!1,error:n}}},[t]),d=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),m=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),w=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),b=_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 c=_chunkX3JFRSEAjs.j.getInstance(),a=()=>{t.updateLastActivity()},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let L=t.getTokenInfo().crudifyTokens.expiresIn||0;return L<300*1e3?30*1e3:L<1800*1e3?60*1e3:120*1e3},y,E=()=>{let k=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let L=t.getTokenInfo(),x=L.crudifyTokens.expiresIn||0,v=((L.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=v)if(e(K=>({...K,isLoading:!0})),await t.refreshTokens()){let K=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else e(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let Y=t.getTimeSinceLastActivity(),_=1800*1e3;Y>_?await d():E()},k)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),_react.useEffect.call(void 0, ()=>{let c=_chunkX3JFRSEAjs.i.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else _chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){_chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>c()},[r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=I.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),_chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[]);let T=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:m,clearError:w,getTokenInfo:b,updateActivity:T,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 Se=_react.createContext.call(void 0, null),ii=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}),de= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[d,m]=_react.useState.call(void 0, []),w=_react.useCallback.call(void 0, (a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return _chunkX3JFRSEAjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(_chunkX3JFRSEAjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=_uuid.v4.call(void 0, ),E={id:y,message:a,severity:l,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]), () => (s))};return m(k=>[...k.length>=i?k.slice(-(i-1)):k,E]),y},[i,e,o,s]),b=_react.useCallback.call(void 0, a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=_react.useCallback.call(void 0, ()=>{m([])},[]),c={showNotification:w,hideNotification:b,clearAllNotifications:T};return _jsxruntime.jsxs.call(void 0, Se.Provider,{value:c,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:d.map(a=>_jsxruntime.jsx.call(void 0, ti,{notification:a,onClose:()=>b(a.id)},a.id))})})]})},ti=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[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:ii(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},we= exports.h =()=>{let r=_react.useContext.call(void 0, Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ne=_react.createContext.call(void 0, void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=we();s=n}catch (e5){}let d={};try{let n=be();n.isInitialized&&n.adminCredentials&&(d=n.adminCredentials)}catch (e6){}let m=_react.useMemo.call(void 0, ()=>{let n=_chunkX3JFRSEAjs.c.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])]),w=_react2.default.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,m]),b=ke(w),T=_react.useMemo.call(void 0, ()=>{let n=_chunkX3JFRSEAjs.c.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])]),c=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([b, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!b.isAuthenticated)return null;try{let n=_chunkX3JFRSEAjs.k.call(void 0, b.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let y={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=n[E])}),y}}catch(n){_chunkX3JFRSEAjs.a.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[_optionalChain([b, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken]),b.isAuthenticated]),a={...b,sessionData:c,config:T},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, Ne.Provider,{value:a,children:r})}function lt(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, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}):_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}function ai(){let r=_react.useContext.call(void 0, Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ct(){let r=ai();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 yt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[w,b]=_react.useState.call(void 0, null),[T,c]=_react.useState.call(void 0, {}),a=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),y=_react.useRef.call(void 0, 0),E=_react.useCallback.call(void 0, ()=>{s(null),b(null),m(!1),c({})},[]),k=_react.useCallback.call(void 0, async()=>{let L=_chunkX3JFRSEAjs.l.call(void 0, );if(!L){l.current&&(b("No user email available"),m(!1));return}a.current&&a.current.abort();let x=new AbortController;a.current=x;let P=++n.current;try{l.current&&(m(!0),b(null));let M=await _crudifybrowser2.default.readItems("users",{filter:{email:L},pagination:{limit:1}});if(P===n.current&&l.current&&!x.signal.aborted)if(M.success&&M.data&&M.data.length>0){let v=M.data[0];s(v);let Y={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(_=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(_)).reduce((_,X)=>({..._,[X]:v[X]}),{})}};c(Y),b(null),y.current=0}else b("User profile not found"),s(null),c({})}catch(M){if(P===n.current&&l.current){let v=M;if(v.name==="AbortError")return;e&&y.current<t&&(_optionalChain([v, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([v, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("Failed to fetch")]))?(y.current++,setTimeout(()=>{l.current&&k()},1e3*y.current)):(b("Failed to load user profile"),s(null),c({}))}}finally{P===n.current&&l.current&&m(!1),a.current===x&&(a.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&k()},[i,k]),_react.useEffect.call(void 0, ()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:o,loading:d,error:w,extendedData:T,refreshProfile:k,clearProfile:E}};var Tt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:d=0,separator:m=""}=r,[w,b]=_react.useState.call(void 0, ""),[T,c]=_react.useState.call(void 0, !1),[a,l]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),y=_react.useCallback.call(void 0, x=>{let P=String(x).padStart(d,"0");return`${s}${m}${P}`},[s,d,m]),E=_react.useCallback.call(void 0, async()=>{c(!0),l(null);try{let x=await _crudifybrowser2.default.getNextSequence(s);if(x.success&&_optionalChain([x, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let P=y(x.data.value);b(P),_optionalChain([t, 'optionalCall', _115 => _115(P)])}else{let P=_optionalChain([x, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";l(P),_optionalChain([o, 'optionalCall', _119 => _119(P)])}}catch(x){let P=x instanceof Error?x.message:"Unknown error";l(P),_optionalChain([o, 'optionalCall', _120 => _120(P)])}finally{c(!1)}},[s,y,t,o]),k=_react.useCallback.call(void 0, async()=>{await E()},[E]),L=_react.useCallback.call(void 0, ()=>{l(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:k,clearError:L}};var ye=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:o,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunkX3JFRSEAjs.a.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _121 => _121.state, 'access', _122 => _122.publicApiKey, 'optionalAccess', _123 => _123.slice, 'call', _124 => _124(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&_chunkX3JFRSEAjs.a.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkX3JFRSEAjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&_chunkX3JFRSEAjs.a.info(`[CrudifyInitialization] Successfully initialized by ${d} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,_chunkX3JFRSEAjs.a.error(`[CrudifyInitialization] Initialization failed for ${d}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=_crudifybrowser2.default.getTokenData();if(o&&o.endpoint){t&&_chunkX3JFRSEAjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let s=t?"debug":"none",d=await _crudifybrowser2.default.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},oe= exports.o =ye.getInstance();var De=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,gi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),o=Math.random().toString(36).substring(2,8);return`${t}_${o}${e}`},Nt= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:d,onUploadError:m,onFileRemoved:w,onFilesChange:b}=r,[T,c]=_react.useState.call(void 0, []),[a,l]=_react.useState.call(void 0, !1),n=_react.useRef.call(void 0, new Map),y=_react.useCallback.call(void 0, ()=>{l(!0)},[]),E=_react.useCallback.call(void 0, (u,h)=>{c(g=>g.map(A=>A.id===u?{...A,...h}:A))},[]),k=_react.useCallback.call(void 0, u=>{_optionalChain([b, 'optionalCall', _125 => _125(u)])},[b]),L=_react.useCallback.call(void 0, u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),x=_react.useCallback.call(void 0, async(u,h)=>{try{if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=gi(h.name),S=await _crudifybrowser2.default.generateSignedUrl({fileName:g,contentType:h.type,visibility:s});if(!S.success||!S.data)throw new Error("Failed to get upload URL");let{uploadUrl:A,s3Key:R,publicUrl:D}=S.data;if(!A||!R)throw new Error("Incomplete signed URL response");let U=R.indexOf("/"),W=U>0?R.substring(U+1):R;E(u.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",G=>{if(G.lengthComputable){let Me=Math.round(G.loaded/G.total*100);E(u.id,{progress:Me})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?le():$(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{$(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),F.open("PUT",A),F.setRequestHeader("Content-Type",h.type),F.send(h)});let He={status:"completed",progress:100,filePath:W,visibility:s,publicUrl:s==="public"?D:void 0,file:void 0};c(le=>{let $=le.map(G=>G.id===u.id?{...G,...He}:G);k($);let F=$.find(G=>G.id===u.id);return F&&_optionalChain([d, 'optionalCall', _126 => _126(F)]),$})}catch(g){let S=g instanceof Error?g.message:"Unknown error";E(u.id,{status:"error",progress:0,errorMessage:S}),c(A=>{let R=A.find(D=>D.id===u.id);return R&&_optionalChain([m, 'optionalCall', _127 => _127(R,S)]),A})}},[E,d,m,s]),P=_react.useCallback.call(void 0, async u=>{let h=Array.from(u),g=[];c(S=>{if(t!==void 0){let D=S.filter(W=>W.status!=="error").length,U=t-D;if(U<=0)return _chunkX3JFRSEAjs.a.warn(`File limit of ${t} already reached`),S;h.length>U&&(h=h.slice(0,U),_chunkX3JFRSEAjs.a.warn(`Only ${U} files will be added to not exceed limit`))}let A=[];for(let D of h){let U=L(D),W={id:De(),name:D.name,size:D.size,contentType:D.type,status:U.valid?"pending":"error",progress:0,createdAt:Date.now(),file:U.valid?D:void 0,errorMessage:U.error};A.push(W)}g=A;let R=[...S,...A];return k(R),R}),setTimeout(()=>{let S=g.filter(A=>A.status==="pending"&&A.file);for(let A of S)if(A.file){let R=x(A,A.file);n.current.set(A.id,R),R.finally(()=>{n.current.delete(A.id)})}},0)},[t,L,x,k]),M=_react.useCallback.call(void 0, async u=>{let h=T.find(g=>g.id===u);if(!h)return!1;E(u,{status:"removing"});try{if(h.filePath){if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await _crudifybrowser2.default.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let S=g.filter(A=>A.id!==u);return k(S),S}),_optionalChain([w, 'optionalCall', _128 => _128(h)]),!0}catch(g){return E(u,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,k,w]),v=_react.useCallback.call(void 0, ()=>{c([]),k([])},[k]),Y=_react.useCallback.call(void 0, async u=>{let h=T.find(S=>S.id===u);if(!h||h.status!=="error"||!h.file){_chunkX3JFRSEAjs.a.warn("Cannot retry: file not found or no original file");return}E(u,{status:"pending",progress:0,errorMessage:void 0});let g=x(h,h.file);n.current.set(u,g),g.finally(()=>{n.current.delete(u)})},[T,E,x]),_=_react.useCallback.call(void 0, async()=>{let u=Array.from(n.current.values());u.length>0&&await Promise.allSettled(u)},[]),X=u=>{let h=_optionalChain([u, 'access', _129 => _129.split, 'call', _130 => _130("."), 'access', _131 => _131.pop, 'call', _132 => _132(), 'optionalAccess', _133 => _133.toLowerCase, 'call', _134 => _134()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},K=_react.useCallback.call(void 0, u=>{let h=u.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,R=A.includes("/public/")||A.startsWith("public/")?"public":"private",D=g.contentType||X(g.name);return{id:De(),name:g.name,size:g.size||0,contentType:D,status:"completed",progress:100,filePath:g.filePath,visibility:R,createdAt:Date.now()}});c(h),k(h)},[k]),ae=_react.useCallback.call(void 0, async u=>{let h=T.find(g=>g.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!oe.isInitialized())return null;let g=await _crudifybrowser2.default.getFileUrl({filePath:h.filePath,expiresIn:3600});return g.success&&_optionalChain([g, 'access', _135 => _135.data, 'optionalAccess', _136 => _136.url])?g.data.url:null}catch (e7){return null}},[T]),Fe=_react.useMemo.call(void 0, ()=>T.some(u=>u.status==="uploading"||u.status==="pending"),[T]),ze=_react.useMemo.call(void 0, ()=>T.filter(u=>u.status==="uploading"||u.status==="pending").length,[T]),Ke=_react.useMemo.call(void 0, ()=>T.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[T]),{isValid:Ue,validationError:Oe}=_react.useMemo.call(void 0, ()=>{let u=T.filter(g=>g.status==="completed").length;return u<o?{isValid:!1,validationError:o===1?"At least one file is required":`At least ${o} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,o,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:P,removeFile:M,clearFiles:v,retryUpload:Y,isValid:Ue,validationError:Oe,waitForUploads:_,completedFilePaths:Ke,initializeFiles:K,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};exports.a = j; exports.b = Ie; exports.c = be; exports.d = I; exports.e = Q; exports.f = ke; exports.g = de; exports.h = we; exports.i = lt; exports.j = ai; exports.k = ct; exports.l = yt; exports.m = Tt; exports.n = ye; exports.o = oe; exports.p = Nt;
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 _chunkNXXCVAVEjs = require('./chunk-NXXCVAVE.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ue=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){_chunkNXXCVAVEjs.a.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(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}},j= exports.a =ue.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ae=_react.createContext.call(void 0, void 0),Ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[w,b]=_react.useState.call(void 0, ""),[T,c]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&d){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{_crudifybrowser2.default.config(r.env||"prod");let y=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(c(y),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")m(!0),b(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";_chunkNXXCVAVEjs.a.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),s(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,d]);let a={crudify:d?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:d,adminCredentials:T};return _jsxruntime.jsx.call(void 0, Ae.Provider,{value:a,children:i})},be= exports.c =()=>{let r=_react.useContext.call(void 0, Ae);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 f=class f{static setStorageType(i){f.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(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch (e2){return _chunkNXXCVAVEjs.a.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.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 f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(_chunkNXXCVAVEjs.a.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return _chunkNXXCVAVEjs.a.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return _chunkNXXCVAVEjs.a.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,o),_chunkNXXCVAVEjs.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunkNXXCVAVEjs.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(_chunkNXXCVAVEjs.a.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(_chunkNXXCVAVEjs.a.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return _chunkNXXCVAVEjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),_chunkNXXCVAVEjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkNXXCVAVEjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),_chunkNXXCVAVEjs.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunkNXXCVAVEjs.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.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=f.getTokens();if(!t){_chunkNXXCVAVEjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){_chunkNXXCVAVEjs.a.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){_chunkNXXCVAVEjs.a.debug("Crudify: Tokens updated in another tab");let o=f.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var I=f;var Q=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},I.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkNXXCVAVEjs.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=I.getTokens();e?I.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):I.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=I.getTokens(),s={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 I.saveTokens(s),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(s)]),{success:!0,tokens:s,data:t.data}}catch(t){return _chunkNXXCVAVEjs.a.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),I.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),I.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=I.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"),I.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=I.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return I.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),I.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||I.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=I.getExpirationInfo(),t=I.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:I.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),I.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 I.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),I.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"),_chunkNXXCVAVEjs.i.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(I.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkNXXCVAVEjs.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"),_chunkNXXCVAVEjs.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=_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",s=await _crudifybrowser2.default.init(t,o);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw _chunkNXXCVAVEjs.a.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(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(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.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(){I.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkNXXCVAVEjs.e.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 ke(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),o=_react.useCallback.call(void 0, async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let c={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(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=_react.useCallback.call(void 0, async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",y=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:n})),{success:!1,error:n}}},[t]),d=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),m=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),w=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),b=_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 c=_chunkNXXCVAVEjs.j.getInstance(),a=()=>{t.updateLastActivity()},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let L=t.getTokenInfo().crudifyTokens.expiresIn||0;return L<300*1e3?30*1e3:L<1800*1e3?60*1e3:120*1e3},y,E=()=>{let k=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let L=t.getTokenInfo(),x=L.crudifyTokens.expiresIn||0,v=((L.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=v)if(e(K=>({...K,isLoading:!0})),await t.refreshTokens()){let K=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else e(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let Y=t.getTimeSinceLastActivity(),_=1800*1e3;Y>_?await d():E()},k)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),_react.useEffect.call(void 0, ()=>{let c=_chunkNXXCVAVEjs.i.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else _chunkNXXCVAVEjs.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){_chunkNXXCVAVEjs.i.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>c()},[r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=I.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),_chunkNXXCVAVEjs.i.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[]);let T=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:m,clearError:w,getTokenInfo:b,updateActivity:T,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 Se=_react.createContext.call(void 0, null),ii=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}),de= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[d,m]=_react.useState.call(void 0, []),w=_react.useCallback.call(void 0, (a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return _chunkNXXCVAVEjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(_chunkNXXCVAVEjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=_uuid.v4.call(void 0, ),E={id:y,message:a,severity:l,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]), () => (s))};return m(k=>[...k.length>=i?k.slice(-(i-1)):k,E]),y},[i,e,o,s]),b=_react.useCallback.call(void 0, a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=_react.useCallback.call(void 0, ()=>{m([])},[]),c={showNotification:w,hideNotification:b,clearAllNotifications:T};return _jsxruntime.jsxs.call(void 0, Se.Provider,{value:c,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:d.map(a=>_jsxruntime.jsx.call(void 0, ti,{notification:a,onClose:()=>b(a.id)},a.id))})})]})},ti=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[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:ii(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},we= exports.h =()=>{let r=_react.useContext.call(void 0, Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ne=_react.createContext.call(void 0, void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=we();s=n}catch (e5){}let d={};try{let n=be();n.isInitialized&&n.adminCredentials&&(d=n.adminCredentials)}catch (e6){}let m=_react.useMemo.call(void 0, ()=>{let n=_chunkNXXCVAVEjs.c.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])]),w=_react2.default.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,m]),b=ke(w),T=_react.useMemo.call(void 0, ()=>{let n=_chunkNXXCVAVEjs.c.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])]),c=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([b, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!b.isAuthenticated)return null;try{let n=_chunkNXXCVAVEjs.k.call(void 0, b.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let y={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=n[E])}),y}}catch(n){_chunkNXXCVAVEjs.a.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[_optionalChain([b, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken]),b.isAuthenticated]),a={...b,sessionData:c,config:T},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, Ne.Provider,{value:a,children:r})}function lt(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, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}):_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}function ai(){let r=_react.useContext.call(void 0, Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ct(){let r=ai();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 yt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[w,b]=_react.useState.call(void 0, null),[T,c]=_react.useState.call(void 0, {}),a=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),y=_react.useRef.call(void 0, 0),E=_react.useCallback.call(void 0, ()=>{s(null),b(null),m(!1),c({})},[]),k=_react.useCallback.call(void 0, async()=>{let L=_chunkNXXCVAVEjs.l.call(void 0, );if(!L){l.current&&(b("No user email available"),m(!1));return}a.current&&a.current.abort();let x=new AbortController;a.current=x;let P=++n.current;try{l.current&&(m(!0),b(null));let M=await _crudifybrowser2.default.readItems("users",{filter:{email:L},pagination:{limit:1}});if(P===n.current&&l.current&&!x.signal.aborted)if(M.success&&M.data&&M.data.length>0){let v=M.data[0];s(v);let Y={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(_=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(_)).reduce((_,X)=>({..._,[X]:v[X]}),{})}};c(Y),b(null),y.current=0}else b("User profile not found"),s(null),c({})}catch(M){if(P===n.current&&l.current){let v=M;if(v.name==="AbortError")return;e&&y.current<t&&(_optionalChain([v, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([v, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("Failed to fetch")]))?(y.current++,setTimeout(()=>{l.current&&k()},1e3*y.current)):(b("Failed to load user profile"),s(null),c({}))}}finally{P===n.current&&l.current&&m(!1),a.current===x&&(a.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&k()},[i,k]),_react.useEffect.call(void 0, ()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:o,loading:d,error:w,extendedData:T,refreshProfile:k,clearProfile:E}};var Tt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:d=0,separator:m=""}=r,[w,b]=_react.useState.call(void 0, ""),[T,c]=_react.useState.call(void 0, !1),[a,l]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),y=_react.useCallback.call(void 0, x=>{let P=String(x).padStart(d,"0");return`${s}${m}${P}`},[s,d,m]),E=_react.useCallback.call(void 0, async()=>{c(!0),l(null);try{let x=await _crudifybrowser2.default.getNextSequence(s);if(x.success&&_optionalChain([x, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let P=y(x.data.value);b(P),_optionalChain([t, 'optionalCall', _115 => _115(P)])}else{let P=_optionalChain([x, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";l(P),_optionalChain([o, 'optionalCall', _119 => _119(P)])}}catch(x){let P=x instanceof Error?x.message:"Unknown error";l(P),_optionalChain([o, 'optionalCall', _120 => _120(P)])}finally{c(!1)}},[s,y,t,o]),k=_react.useCallback.call(void 0, async()=>{await E()},[E]),L=_react.useCallback.call(void 0, ()=>{l(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:k,clearError:L}};var ye=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:o,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunkNXXCVAVEjs.a.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _121 => _121.state, 'access', _122 => _122.publicApiKey, 'optionalAccess', _123 => _123.slice, 'call', _124 => _124(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkNXXCVAVEjs.a.debug(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkNXXCVAVEjs.a.debug(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&_chunkNXXCVAVEjs.a.debug(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&_chunkNXXCVAVEjs.a.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkNXXCVAVEjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkNXXCVAVEjs.a.debug(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&_chunkNXXCVAVEjs.a.info(`[CrudifyInitialization] Successfully initialized by ${d} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,_chunkNXXCVAVEjs.a.error(`[CrudifyInitialization] Initialization failed for ${d}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&_chunkNXXCVAVEjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=_crudifybrowser2.default.getTokenData();if(o&&o.endpoint){t&&_chunkNXXCVAVEjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let s=t?"debug":"none",d=await _crudifybrowser2.default.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},oe= exports.o =ye.getInstance();var De=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,gi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),o=Math.random().toString(36).substring(2,8);return`${t}_${o}${e}`},Nt= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:d,onUploadError:m,onFileRemoved:w,onFilesChange:b}=r,[T,c]=_react.useState.call(void 0, []),[a,l]=_react.useState.call(void 0, !1),n=_react.useRef.call(void 0, new Map),y=_react.useCallback.call(void 0, ()=>{l(!0)},[]),E=_react.useCallback.call(void 0, (u,h)=>{c(g=>g.map(A=>A.id===u?{...A,...h}:A))},[]),k=_react.useCallback.call(void 0, u=>{_optionalChain([b, 'optionalCall', _125 => _125(u)])},[b]),L=_react.useCallback.call(void 0, u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),x=_react.useCallback.call(void 0, async(u,h)=>{try{if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=gi(h.name),S=await _crudifybrowser2.default.generateSignedUrl({fileName:g,contentType:h.type,visibility:s});if(!S.success||!S.data)throw new Error("Failed to get upload URL");let{uploadUrl:A,s3Key:R,publicUrl:D}=S.data;if(!A||!R)throw new Error("Incomplete signed URL response");let U=R.indexOf("/"),W=U>0?R.substring(U+1):R;E(u.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",G=>{if(G.lengthComputable){let Me=Math.round(G.loaded/G.total*100);E(u.id,{progress:Me})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?le():$(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{$(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),F.open("PUT",A),F.setRequestHeader("Content-Type",h.type),F.send(h)});let He={status:"completed",progress:100,filePath:W,visibility:s,publicUrl:s==="public"?D:void 0,file:void 0};c(le=>{let $=le.map(G=>G.id===u.id?{...G,...He}:G);k($);let F=$.find(G=>G.id===u.id);return F&&_optionalChain([d, 'optionalCall', _126 => _126(F)]),$})}catch(g){let S=g instanceof Error?g.message:"Unknown error";E(u.id,{status:"error",progress:0,errorMessage:S}),c(A=>{let R=A.find(D=>D.id===u.id);return R&&_optionalChain([m, 'optionalCall', _127 => _127(R,S)]),A})}},[E,d,m,s]),P=_react.useCallback.call(void 0, async u=>{let h=Array.from(u),g=[];c(S=>{if(t!==void 0){let D=S.filter(W=>W.status!=="error").length,U=t-D;if(U<=0)return _chunkNXXCVAVEjs.a.warn(`File limit of ${t} already reached`),S;h.length>U&&(h=h.slice(0,U),_chunkNXXCVAVEjs.a.warn(`Only ${U} files will be added to not exceed limit`))}let A=[];for(let D of h){let U=L(D),W={id:De(),name:D.name,size:D.size,contentType:D.type,status:U.valid?"pending":"error",progress:0,createdAt:Date.now(),file:U.valid?D:void 0,errorMessage:U.error};A.push(W)}g=A;let R=[...S,...A];return k(R),R}),setTimeout(()=>{let S=g.filter(A=>A.status==="pending"&&A.file);for(let A of S)if(A.file){let R=x(A,A.file);n.current.set(A.id,R),R.finally(()=>{n.current.delete(A.id)})}},0)},[t,L,x,k]),M=_react.useCallback.call(void 0, async u=>{let h=T.find(g=>g.id===u);if(!h)return!1;E(u,{status:"removing"});try{if(h.filePath){if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await _crudifybrowser2.default.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let S=g.filter(A=>A.id!==u);return k(S),S}),_optionalChain([w, 'optionalCall', _128 => _128(h)]),!0}catch(g){return E(u,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,k,w]),v=_react.useCallback.call(void 0, ()=>{c([]),k([])},[k]),Y=_react.useCallback.call(void 0, async u=>{let h=T.find(S=>S.id===u);if(!h||h.status!=="error"||!h.file){_chunkNXXCVAVEjs.a.warn("Cannot retry: file not found or no original file");return}E(u,{status:"pending",progress:0,errorMessage:void 0});let g=x(h,h.file);n.current.set(u,g),g.finally(()=>{n.current.delete(u)})},[T,E,x]),_=_react.useCallback.call(void 0, async()=>{let u=Array.from(n.current.values());u.length>0&&await Promise.allSettled(u)},[]),X=u=>{let h=_optionalChain([u, 'access', _129 => _129.split, 'call', _130 => _130("."), 'access', _131 => _131.pop, 'call', _132 => _132(), 'optionalAccess', _133 => _133.toLowerCase, 'call', _134 => _134()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},K=_react.useCallback.call(void 0, u=>{let h=u.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,R=A.includes("/public/")||A.startsWith("public/")?"public":"private",D=g.contentType||X(g.name);return{id:De(),name:g.name,size:g.size||0,contentType:D,status:"completed",progress:100,filePath:g.filePath,visibility:R,createdAt:Date.now()}});c(h),k(h)},[k]),ae=_react.useCallback.call(void 0, async u=>{let h=T.find(g=>g.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!oe.isInitialized())return null;let g=await _crudifybrowser2.default.getFileUrl({filePath:h.filePath,expiresIn:3600});return g.success&&_optionalChain([g, 'access', _135 => _135.data, 'optionalAccess', _136 => _136.url])?g.data.url:null}catch (e7){return null}},[T]),Fe=_react.useMemo.call(void 0, ()=>T.some(u=>u.status==="uploading"||u.status==="pending"),[T]),ze=_react.useMemo.call(void 0, ()=>T.filter(u=>u.status==="uploading"||u.status==="pending").length,[T]),Ke=_react.useMemo.call(void 0, ()=>T.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[T]),{isValid:Ue,validationError:Oe}=_react.useMemo.call(void 0, ()=>{let u=T.filter(g=>g.status==="completed").length;return u<o?{isValid:!1,validationError:o===1?"At least one file is required":`At least ${o} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,o,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:P,removeFile:M,clearFiles:v,retryUpload:Y,isValid:Ue,validationError:Oe,waitForUploads:_,completedFilePaths:Ke,initializeFiles:K,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};exports.a = j; exports.b = Ie; exports.c = be; exports.d = I; exports.e = Q; exports.f = ke; exports.g = de; exports.h = we; exports.i = lt; exports.j = ai; exports.k = ct; exports.l = yt; exports.m = Tt; exports.n = ye; exports.o = oe; exports.p = Nt;