@nocios/crudify-ui 4.4.52 → 4.4.56

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.
@@ -234,4 +234,41 @@ interface CrudiaFileFieldProps {
234
234
  */
235
235
  declare const CrudiaFileField: React.FC<CrudiaFileFieldProps>;
236
236
 
237
- export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, type CrudifyLoginConfig as c, type CrudifyLoginProps as d, type CrudifyLoginTranslations as e, type UserLoginData as f, type PolicyAction as g, type CrudiaAutoGenerateProps as h, type CrudiaFileFieldProps as i, POLICY_ACTIONS as j, PREFERRED_POLICY_ORDER as k };
237
+ /**
238
+ * Markdown field component with rich text editing using MDXEditor
239
+ * - WYSIWYG markdown editing
240
+ * - Toolbar with formatting options
241
+ * - Saves content as markdown string
242
+ */
243
+
244
+ /**
245
+ * Props del componente CrudiaMarkdownField
246
+ */
247
+ interface CrudiaMarkdownFieldProps {
248
+ /** Label del campo */
249
+ label?: string;
250
+ /** Valor actual (markdown string) */
251
+ value?: string;
252
+ /** Callback cuando cambia el contenido */
253
+ onChange?: (value: string) => void;
254
+ /** Campo requerido */
255
+ required?: boolean;
256
+ /** Campo deshabilitado/solo lectura */
257
+ disabled?: boolean;
258
+ /** Error externo */
259
+ error?: boolean;
260
+ /** Texto de ayuda o error */
261
+ helperText?: string;
262
+ /** Texto placeholder */
263
+ placeholder?: string;
264
+ /** Altura mínima del editor en píxeles */
265
+ minHeight?: number;
266
+ /** Altura máxima del editor en píxeles (después se hace scroll) */
267
+ maxHeight?: number;
268
+ }
269
+ /**
270
+ * CrudiaMarkdownField - Editor de Markdown con soporte completo de MDXEditor
271
+ */
272
+ declare const CrudiaMarkdownField: React.FC<CrudiaMarkdownFieldProps>;
273
+
274
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m };
@@ -234,4 +234,41 @@ interface CrudiaFileFieldProps {
234
234
  */
235
235
  declare const CrudiaFileField: React.FC<CrudiaFileFieldProps>;
236
236
 
237
- export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, type CrudifyLoginConfig as c, type CrudifyLoginProps as d, type CrudifyLoginTranslations as e, type UserLoginData as f, type PolicyAction as g, type CrudiaAutoGenerateProps as h, type CrudiaFileFieldProps as i, POLICY_ACTIONS as j, PREFERRED_POLICY_ORDER as k };
237
+ /**
238
+ * Markdown field component with rich text editing using MDXEditor
239
+ * - WYSIWYG markdown editing
240
+ * - Toolbar with formatting options
241
+ * - Saves content as markdown string
242
+ */
243
+
244
+ /**
245
+ * Props del componente CrudiaMarkdownField
246
+ */
247
+ interface CrudiaMarkdownFieldProps {
248
+ /** Label del campo */
249
+ label?: string;
250
+ /** Valor actual (markdown string) */
251
+ value?: string;
252
+ /** Callback cuando cambia el contenido */
253
+ onChange?: (value: string) => void;
254
+ /** Campo requerido */
255
+ required?: boolean;
256
+ /** Campo deshabilitado/solo lectura */
257
+ disabled?: boolean;
258
+ /** Error externo */
259
+ error?: boolean;
260
+ /** Texto de ayuda o error */
261
+ helperText?: string;
262
+ /** Texto placeholder */
263
+ placeholder?: string;
264
+ /** Altura mínima del editor en píxeles */
265
+ minHeight?: number;
266
+ /** Altura máxima del editor en píxeles (después se hace scroll) */
267
+ maxHeight?: number;
268
+ }
269
+ /**
270
+ * CrudiaMarkdownField - Editor de Markdown con soporte completo de MDXEditor
271
+ */
272
+ declare const CrudiaMarkdownField: React.FC<CrudiaMarkdownFieldProps>;
273
+
274
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m };
@@ -0,0 +1 @@
1
+ import{b as le,d as me,h as O,i as Te,j as ve,k as Ee}from"./chunk-6GPSBDW6.mjs";import{createContext as Me,useContext as Ge,useEffect as $e,useState as W}from"react";import Z from"@nocios/crudify-browser";var ce=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},q=ce.getInstance();import{jsx as _e}from"react/jsx-runtime";var Ae=Me(void 0),be=({config:r,children:i})=>{let[e,t]=W(!0),[n,s]=W(null),[d,h]=W(!1),[S,b]=W(""),[T,c]=W();$e(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&d){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{Z.config(r.env||"prod");let y=await Z.init(r.publicApiKey,"none");if(c(y),typeof Z.transaction=="function"&&typeof Z.login=="function")h(!0),b(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&q.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let m=y instanceof Error?y.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",y),s(m),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,d]);let a={crudify:d?Z:null,isLoading:e,error:n,isInitialized:d,adminCredentials:T};return _e(Ae.Provider,{value:a,children:i})},Ie=()=>{let r=Ge(Ae);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import j from"crypto-js";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 j.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{return console.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{return!1}}static getStorage(){return f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(console.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return j.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=f.getEncryptionKey();return j.AES.decrypt(i,e).toString(j.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",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()},n=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,n),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",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),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",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){console.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){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let n=f.getTokens();i(n)}}};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 A=f;import R from"@nocios/crudify-browser";var J=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},A.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),R.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),O.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=A.getTokens();e?A.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):A.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 R.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let n=A.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return A.saveTokens(s),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await R.logout(),A.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),A.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=A.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"),A.clearTokens(),!1;if(R.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),R.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 n=A.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return A.clearTokens(),await R.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),A.clearTokens(),await R.logout(),!1}}isAuthenticated(){return R.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=R.getTokenData(),e=A.getExpirationInfo(),t=A.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:A.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await R.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return A.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){R.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"),O.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(A.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),O.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"),O.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=R.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";R.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await R.init(t,n);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 console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(n=>n.errorType==="Unauthorized"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let n=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")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,n.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."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){A.clearTokens(),R.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?me("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as Ve,useEffect as Q,useCallback as _}from"react";function ke(r={}){let[i,e]=Ve({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=J.getInstance(),n=_(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(o=>({...o,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:o=>{e(y=>({...y,isAuthenticated:!0,tokens:o,error:null})),r.onSessionRestored?.(o)},onLoginSuccess:o=>{e(y=>({...y,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",a),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",l),e(o=>({...o,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=_(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(o=>({...o,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let o=l instanceof Error?l.message:"Login failed",y=o.includes("INVALID_CREDENTIALS")||o.includes("Invalid email")||o.includes("Invalid password")||o.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:o})),{success:!1,error:o}}},[t]),d=_(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]),h=_(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]),S=_(()=>{e(c=>({...c,error:null}))},[]),b=_(()=>t.getTokenInfo(),[t]);Q(()=>{n()},[n]),Q(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=Te.getInstance(),a=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},l=c.subscribe(a);window.addEventListener("popstate",a);let o=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},y,m=()=>{let k=o();y=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),m();return}let C=t.getTokenInfo(),I=C.crudifyTokens.expiresIn||0,F=(C.crudifyTokens.expiresAt||0)-(Date.now()-I),v=F*.5;if(I>0&&I<=v){let X=Math.round(I/F*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${X}% of TTL (${Math.round(I/6e4)}min remaining), refreshing...`),e(K=>({...K,isLoading:!0})),await t.refreshTokens()){let K=t.getTokenInfo();e(se=>({...se,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 B=t.getTimeSinceLastActivity(),G=1800*1e3;B>G?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await d()):m()},k)};return m(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),Q(()=>{let c=O.subscribe(async a=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${a.type}`),a.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let o=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),O.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){r.enableLogging&&console.error("\u274C Error during token refresh:",l),O.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")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${a.type}), logging out...`),e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),Q(()=>{let c=A.subscribeToChanges(a=>{a?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(l=>({...l,tokens:a,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(l=>({...l,isAuthenticated:!1,tokens:null})),O.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let T=_(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:h,clearError:S,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}}import{useState as xe,createContext as Be,useContext as Xe,useCallback as ee,useEffect as Ye}from"react";import{Snackbar as We,Alert as Ze,Box as qe,Portal as je}from"@mui/material";import{v4 as Je}from"uuid";import Qe from"dompurify";import{jsx as V,jsxs as ti}from"react/jsx-runtime";var Se=Be(null),ei=r=>Qe.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}),ue=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[d,h]=xe([]),S=ee((a,l="info",o)=>{if(!n)return"";if(!a||typeof a!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=Je(),m={id:y,message:a,severity:l,autoHideDuration:o?.autoHideDuration??e,persistent:o?.persistent??!1,allowHtml:o?.allowHtml??s};return h(k=>[...k.length>=i?k.slice(-(i-1)):k,m]),y},[i,e,n,s]),b=ee(a=>{h(l=>l.filter(o=>o.id!==a))},[]),T=ee(()=>{h([])},[]),c={showNotification:S,hideNotification:b,clearAllNotifications:T};return ti(Se.Provider,{value:c,children:[r,n&&V(je,{children:V(qe,{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=>V(ii,{notification:a,onClose:()=>b(a.id)},a.id))})})]})},ii=({notification:r,onClose:i})=>{let[e,t]=xe(!0),n=ee((s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ye(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),V(We,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:V(Ze,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?V("span",{dangerouslySetInnerHTML:{__html:ei(r.message)}}):V("span",{children:r.message})})})},we=()=>{let r=Xe(Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import ri,{createContext as ni,useContext as oi,useMemo as de}from"react";import{Fragment as ai,jsx as P,jsxs as H}from"react/jsx-runtime";var Ne=ni(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:n={}}){let s;try{let{showNotification:o}=we();s=o}catch{}let d={};try{let o=Ie();o.isInitialized&&o.adminCredentials&&(d=o.adminCredentials)}catch{}let h=de(()=>{let o=le({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,i?.enableLogging]),S=ri.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,h]),b=ke(S),T=de(()=>{let o=le({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,i?.enableLogging]),c=de(()=>{if(!b.tokens?.accessToken||!b.isAuthenticated)return null;try{let o=ve(b.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let y={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(m=>{["sub","email","subscriber"].includes(m)||(y[m]=o[m])}),y}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[b.tokens?.accessToken,b.isAuthenticated]),a={...b,sessionData:c,config:T},l={enabled:t,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return P(Ne.Provider,{value:a,children:r})}function it(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?P(be,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:P(ue,{...i,children:P(Pe,{...r})})}):P(ue,{...i,children:P(Pe,{...r})})}function si(){let r=oi(Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function tt(){let r=si();return r.isInitialized?H("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[P("h4",{children:"Session Debug Info"}),H("div",{children:[P("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),H("div",{children:[P("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),H("div",{children:[P("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&H(ai,{children:[H("div",{children:[P("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),H("div",{children:[P("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),H("div",{children:[P("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),H("div",{children:[P("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),H("div",{children:[P("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):P("div",{children:"Session not initialized"})}import{useState as ie,useEffect as Re,useCallback as Ce,useRef as te}from"react";import li from"@nocios/crudify-browser";var lt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=ie(null),[d,h]=ie(!1),[S,b]=ie(null),[T,c]=ie({}),a=te(null),l=te(!0),o=te(0),y=te(0),m=Ce(()=>{s(null),b(null),h(!1),c({})},[]),k=Ce(async()=>{let C=Ee();if(!C){l.current&&(b("No user email available"),h(!1));return}a.current&&a.current.abort();let I=new AbortController;a.current=I;let w=++o.current;try{l.current&&(h(!0),b(null));let F=await li.readItems("users",{filter:{email:C},pagination:{limit:1}});if(w===o.current&&l.current&&!I.signal.aborted)if(F.success&&F.data&&F.data.length>0){let v=F.data[0];s(v);let B={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(G=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(G)).reduce((G,X)=>({...G,[X]:v[X]}),{})}};c(B),b(null),y.current=0}else b("User profile not found"),s(null),c({})}catch(F){if(w===o.current&&l.current){let v=F;if(v.name==="AbortError")return;e&&y.current<t&&(v.message?.includes("Network Error")||v.message?.includes("Failed to fetch"))?(y.current++,setTimeout(()=>{l.current&&k()},1e3*y.current)):(b("Failed to load user profile"),s(null),c({}))}}finally{w===o.current&&l.current&&h(!1),a.current===I&&(a.current=null)}},[e,t]);return Re(()=>{i&&k()},[i,k]),Re(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:n,loading:d,error:S,extendedData:T,refreshProfile:k,clearProfile:m}};import{useState as fe,useEffect as ci,useCallback as re,useRef as ui}from"react";import di from"@nocios/crudify-browser";var ft=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:n}=i,{prefix:s,padding:d=0,separator:h=""}=r,[S,b]=fe(""),[T,c]=fe(!1),[a,l]=fe(null),o=ui(!1),y=re(I=>{let w=String(I).padStart(d,"0");return`${s}${h}${w}`},[s,d,h]),m=re(async()=>{c(!0),l(null);try{let I=await di.getNextSequence(s);if(I.success&&I.data?.value){let w=y(I.data.value);b(w),t?.(w)}else{let w=I.errors?._error?.[0]||"Failed to generate code";l(w),n?.(w)}}catch(I){let w=I instanceof Error?I.message:"Unknown error";l(w),n?.(w)}finally{c(!1)}},[s,y,t,n]),k=re(async()=>{await m()},[m]),C=re(()=>{l(null)},[]);return ci(()=>{e&&!S&&!o.current&&(o.current=!0,m())},[e,S,m]),{value:S,loading:T,error:a,regenerate:k,clearError:C}};import ge from"@nocios/crudify-browser";var pe=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:n,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&console.log(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[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&&console.log(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=n,this.state.error=null,s&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${d} (${e} priority)`)}catch(h){throw this.state.status="ERROR",this.state.error=h instanceof Error?h:new Error(String(h)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${d}:`,h),h}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let n=ge.getTokenData();if(n&&n.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}ge.config(e);let s=t?"debug":"none",d=await ge.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&q.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}}},ne=pe.getInstance();import{useState as Le,useCallback as z,useRef as fi,useMemo as oe}from"react";import ye from"@nocios/crudify-browser";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(),n=Math.random().toString(36).substring(2,8);return`${t}_${n}${e}`},Et=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:s="private",onUploadComplete:d,onUploadError:h,onFileRemoved:S,onFilesChange:b}=r,[T,c]=Le([]),[a,l]=Le(!1),o=fi(new Map),y=z(()=>{l(!0)},[]),m=z((u,p)=>{c(g=>g.map(E=>E.id===u?{...E,...p}:E))},[]),k=z(u=>{b?.(u)},[b]),C=z(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]),I=z(async(u,p)=>{try{if(!ne.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=gi(p.name),x=await ye.generateSignedUrl({fileName:g,contentType:p.type,visibility:s});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let{uploadUrl:E,s3Key:N,publicUrl:L}=x.data;if(!E||!N)throw new Error("Incomplete signed URL response");let U=N.indexOf("/"),Y=U>0?N.substring(U+1):N;m(u.id,{status:"uploading",progress:0}),await new Promise((ae,$)=>{let D=new XMLHttpRequest;D.upload.addEventListener("progress",M=>{if(M.lengthComputable){let He=Math.round(M.loaded/M.total*100);m(u.id,{progress:He})}}),D.addEventListener("load",()=>{D.status>=200&&D.status<300?ae():$(new Error(`Upload failed with status ${D.status}`))}),D.addEventListener("error",()=>{$(new Error("Network error during upload"))}),D.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),D.open("PUT",E),D.setRequestHeader("Content-Type",p.type),D.send(p)});let Oe={status:"completed",progress:100,filePath:Y,visibility:s,publicUrl:s==="public"?L:void 0,file:void 0};c(ae=>{let $=ae.map(M=>M.id===u.id?{...M,...Oe}:M);k($);let D=$.find(M=>M.id===u.id);return D&&d?.(D),$})}catch(g){let x=g instanceof Error?g.message:"Unknown error";m(u.id,{status:"error",progress:0,errorMessage:x}),c(E=>{let N=E.find(L=>L.id===u.id);return N&&h?.(N,x),E})}},[m,d,h,s]),w=z(async u=>{let p=Array.from(u),g=[];c(x=>{if(t!==void 0){let L=x.filter(Y=>Y.status!=="error").length,U=t-L;if(U<=0)return console.warn(`File limit of ${t} already reached`),x;p.length>U&&(p=p.slice(0,U),console.warn(`Only ${U} files will be added to not exceed limit`))}let E=[];for(let L of p){let U=C(L),Y={id:De(),name:L.name,size:L.size,contentType:L.type,status:U.valid?"pending":"error",progress:0,createdAt:Date.now(),file:U.valid?L:void 0,errorMessage:U.error};E.push(Y)}g=E;let N=[...x,...E];return k(N),N}),setTimeout(()=>{let x=g.filter(E=>E.status==="pending"&&E.file);for(let E of x)if(E.file){let N=I(E,E.file);o.current.set(E.id,N),N.finally(()=>{o.current.delete(E.id)})}},0)},[t,C,I,k]),F=z(async u=>{let p=T.find(g=>g.id===u);if(!p)return!1;m(u,{status:"removing"});try{if(p.filePath){if(!ne.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await ye.disableFile({filePath:p.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let x=g.filter(E=>E.id!==u);return k(x),x}),S?.(p),!0}catch(g){return m(u,{status:p.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,m,k,S]),v=z(()=>{c([]),k([])},[k]),B=z(async u=>{let p=T.find(x=>x.id===u);if(!p||p.status!=="error"||!p.file){console.warn("Cannot retry: file not found or no original file");return}m(u,{status:"pending",progress:0,errorMessage:void 0});let g=I(p,p.file);o.current.set(u,g),g.finally(()=>{o.current.delete(u)})},[T,m,I]),G=z(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),X=u=>{let p=u.split(".").pop()?.toLowerCase()||"";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"}[p]||"application/octet-stream"},he=z(u=>{let p=u.map(g=>{let E=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,N=E.includes("/public/")||E.startsWith("public/")?"public":"private",L=g.contentType||X(g.name);return{id:De(),name:g.name,size:g.size||0,contentType:L,status:"completed",progress:100,filePath:g.filePath,visibility:N,createdAt:Date.now()}});c(p),k(p)},[k]),K=z(async u=>{let p=T.find(g=>g.id===u);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!ne.isInitialized())return null;let g=await ye.getFileUrl({filePath:p.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[T]),se=oe(()=>T.some(u=>u.status==="uploading"||u.status==="pending"),[T]),ze=oe(()=>T.filter(u=>u.status==="uploading"||u.status==="pending").length,[T]),Fe=oe(()=>T.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[T]),{isValid:Ke,validationError:Ue}=oe(()=>{let u=T.filter(g=>g.status==="completed").length;return u<n?{isValid:!1,validationError:n===1?"At least one file is required":`At least ${n} 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,n,t]);return{files:T,isUploading:se,pendingCount:ze,addFiles:w,removeFile:F,clearFiles:v,retryUpload:B,isValid:Ke,validationError:Ue,waitForUploads:G,completedFilePaths:Fe,initializeFiles:he,isTouched:a,markAsTouched:y,getPreviewUrl:K}};export{q as a,be as b,Ie as c,A as d,J as e,ke as f,ue as g,we as h,it as i,si as j,tt as k,lt as l,ft as m,pe as n,ne as o,Et as p};
@@ -1 +1 @@
1
- import{h as $,j as D}from"./chunk-MU7DIUCZ.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
1
+ import{h as $,j as D}from"./chunk-5PKTOZAY.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};