@nocios/crudify-ui 4.4.72 → 4.4.76

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.
Files changed (51) hide show
  1. package/dist/{CrudiaMarkdownField-Bs940oF4.d.ts → CrudiaMarkdownField-C30enyF9.d.ts} +2 -2
  2. package/dist/{CrudiaMarkdownField-CKPdr2JL.d.mts → CrudiaMarkdownField-D-VooBtq.d.mts} +2 -2
  3. package/dist/{api-Djqihi4n.d.mts → api-RK-xY1Ah.d.mts} +22 -2
  4. package/dist/{api-Djqihi4n.d.ts → api-RK-xY1Ah.d.ts} +22 -2
  5. package/dist/chunk-2G33BADS.mjs +1 -0
  6. package/dist/{chunk-ZANWILS7.mjs → chunk-7J5RTLCS.mjs} +1 -1
  7. package/dist/chunk-AEHAZP5F.js +1 -0
  8. package/dist/{chunk-4LSVF26Q.js → chunk-D3NBX3SM.js} +1 -1
  9. package/dist/chunk-GCH3QGKL.mjs +1 -0
  10. package/dist/chunk-GNGIFVA4.js +1 -0
  11. package/dist/{chunk-L454VIXN.js → chunk-HDNGW5H5.js} +1 -1
  12. package/dist/chunk-IYTXJHKO.js +1 -0
  13. package/dist/{chunk-Q5EJLSB4.mjs → chunk-NZIH26GS.mjs} +1 -1
  14. package/dist/chunk-ZKWTILQT.mjs +1 -0
  15. package/dist/components.d.mts +1 -1
  16. package/dist/components.d.ts +1 -1
  17. package/dist/components.js +1 -1
  18. package/dist/components.mjs +1 -1
  19. package/dist/{errorTranslation-BuEEtVg4.d.mts → errorTranslation-B4wcHzD3.d.mts} +1 -1
  20. package/dist/{errorTranslation-BIyBYuGF.d.ts → errorTranslation-CCC5IWoN.d.ts} +1 -1
  21. package/dist/hooks.d.mts +4 -3
  22. package/dist/hooks.d.ts +4 -3
  23. package/dist/hooks.js +1 -1
  24. package/dist/hooks.mjs +1 -1
  25. package/dist/{index-CQnAzvOE.d.mts → index-DEnlzdtV.d.mts} +90 -16
  26. package/dist/{index-BVT7flO5.d.ts → index-pQmuVg3q.d.ts} +90 -16
  27. package/dist/index.d.mts +101 -70
  28. package/dist/index.d.ts +101 -70
  29. package/dist/index.js +2 -2
  30. package/dist/index.mjs +2 -2
  31. package/dist/utils.d.mts +11 -4
  32. package/dist/utils.d.ts +11 -4
  33. package/dist/utils.js +1 -1
  34. package/dist/utils.mjs +1 -1
  35. package/package.json +3 -3
  36. package/coverage/base.css +0 -224
  37. package/coverage/block-navigation.js +0 -87
  38. package/coverage/configResolver.ts.html +0 -499
  39. package/coverage/coverage-final.json +0 -2
  40. package/coverage/favicon.png +0 -0
  41. package/coverage/index.html +0 -116
  42. package/coverage/prettify.css +0 -1
  43. package/coverage/prettify.js +0 -2
  44. package/coverage/sort-arrow-sprite.png +0 -0
  45. package/coverage/sorter.js +0 -210
  46. package/dist/chunk-JCMHUFYK.mjs +0 -1
  47. package/dist/chunk-LPC6P3Z7.mjs +0 -1
  48. package/dist/chunk-SEDLJT7G.js +0 -1
  49. package/dist/chunk-UJD6SL66.mjs +0 -1
  50. package/dist/chunk-X3JFRSEA.js +0 -1
  51. package/dist/chunk-YLKGZV2N.js +0 -1
@@ -18,8 +18,8 @@ interface UserLoginData {
18
18
  username?: string;
19
19
  email?: string;
20
20
  userId?: string;
21
- profile?: any;
22
- [key: string]: any;
21
+ profile?: Record<string, unknown>;
22
+ [key: string]: unknown;
23
23
  }
24
24
  interface CrudifyLoginProps {
25
25
  onScreenChange?: (screen: BoxScreenType, params?: Record<string, string>) => void;
@@ -18,8 +18,8 @@ interface UserLoginData {
18
18
  username?: string;
19
19
  email?: string;
20
20
  userId?: string;
21
- profile?: any;
22
- [key: string]: any;
21
+ profile?: Record<string, unknown>;
22
+ [key: string]: unknown;
23
23
  }
24
24
  interface CrudifyLoginProps {
25
25
  onScreenChange?: (screen: BoxScreenType, params?: Record<string, string>) => void;
@@ -3,7 +3,7 @@ interface CrudifyApiResponse<T = unknown> {
3
3
  data?: T;
4
4
  errors?: string | Record<string, string[]> | string[];
5
5
  errorCode?: string;
6
- fieldsWarning?: Record<string, string[]>;
6
+ fieldsWarning?: Record<string, string[]> | null;
7
7
  }
8
8
  interface CrudifyTransactionResponse {
9
9
  success: boolean;
@@ -78,5 +78,25 @@ interface ValidationError {
78
78
  message: string;
79
79
  code: string;
80
80
  }
81
+ /**
82
+ * Options for Crudify request operations
83
+ */
84
+ interface CrudifyRequestOptions {
85
+ signal?: AbortSignal;
86
+ }
87
+ /**
88
+ * Represents a single operation within a transaction.
89
+ */
90
+ interface TransactionOperation {
91
+ operation: "create" | "update" | "delete" | string;
92
+ moduleKey: string;
93
+ data?: Record<string, unknown>;
94
+ _id?: string;
95
+ [key: string]: unknown;
96
+ }
97
+ /**
98
+ * Input for transaction operations. Can be a single operation or an array of operations.
99
+ */
100
+ type TransactionInput = TransactionOperation | TransactionOperation[] | Record<string, unknown>;
81
101
 
82
- export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c };
102
+ export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c, CrudifyRequestOptions as d, TransactionInput as e };
@@ -3,7 +3,7 @@ interface CrudifyApiResponse<T = unknown> {
3
3
  data?: T;
4
4
  errors?: string | Record<string, string[]> | string[];
5
5
  errorCode?: string;
6
- fieldsWarning?: Record<string, string[]>;
6
+ fieldsWarning?: Record<string, string[]> | null;
7
7
  }
8
8
  interface CrudifyTransactionResponse {
9
9
  success: boolean;
@@ -78,5 +78,25 @@ interface ValidationError {
78
78
  message: string;
79
79
  code: string;
80
80
  }
81
+ /**
82
+ * Options for Crudify request operations
83
+ */
84
+ interface CrudifyRequestOptions {
85
+ signal?: AbortSignal;
86
+ }
87
+ /**
88
+ * Represents a single operation within a transaction.
89
+ */
90
+ interface TransactionOperation {
91
+ operation: "create" | "update" | "delete" | string;
92
+ moduleKey: string;
93
+ data?: Record<string, unknown>;
94
+ _id?: string;
95
+ [key: string]: unknown;
96
+ }
97
+ /**
98
+ * Input for transaction operations. Can be a single operation or an array of operations.
99
+ */
100
+ type TransactionInput = TransactionOperation | TransactionOperation[] | Record<string, unknown>;
81
101
 
82
- export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c };
102
+ export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c, CrudifyRequestOptions as d, TransactionInput as e };
@@ -0,0 +1 @@
1
+ import{a as p,c as ce,e as me,i as M,j as Ee,k as Te,l as ve}from"./chunk-GCH3QGKL.mjs";import{createContext as _e,useContext as $e,useEffect as Ve,useState as Z}from"react";import q from"@nocios/crudify-browser";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){p.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=ue.getInstance();import{jsx as Be}from"react/jsx-runtime";var Ae=_e(void 0),Ie=({config:r,children:i})=>{let[e,t]=Z(!0),[s,o]=Z(null),[c,m]=Z(!1),[w,I]=Z(""),[T,u]=Z();Ve(()=>{if(!r.publicApiKey){o("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&c){t(!1);return}(async()=>{t(!0),o(null),m(!1);try{q.config(r.env||"prod");let y=await q.init(r.publicApiKey,"none");if(u(y),typeof q.transaction=="function"&&typeof q.login=="function")m(!0),I(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";p.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),o(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,c]);let a={crudify:c?q:null,isLoading:e,error:s,isInitialized:c,adminCredentials:T};return Be(Ae.Provider,{value:a,children:i})},ke=()=>{let r=$e(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 p.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]:(p.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 p.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return J.AES.decrypt(i,e).toString(J.enc.Utf8)||i}catch(e){return p.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()},s=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,s),p.debug("Crudify: Tokens saved successfully")}catch(t){p.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),s=JSON.parse(t);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(p.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(p.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(e){return p.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),p.debug("Crudify: Tokens cleared from storage")}catch(e){p.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),p.info("Crudify: Encryption key rotated successfully")}catch(i){p.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){p.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){p.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){p.debug("Crudify: Tokens updated in another tab");let s=f.getTokens();i(s)}}};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 v=f;import N from"@nocios/crudify-browser";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},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),N.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),M.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=v.getTokens();e?v.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):v.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 N.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let s=v.getTokens(),o=t.data,c={accessToken:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,apiEndpointAdmin:s?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:s?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return v.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:o}}catch(t){return p.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 N.logout(),v.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),v.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=v.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"),v.clearTokens(),!1;if(N.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),N.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 s=v.getTokens();return s&&this.config.onSessionRestored?.(s),!0}return v.clearTokens(),await N.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),v.clearTokens(),await N.logout(),!1}}isAuthenticated(){return N.isLogin()||v.hasValidTokens()}getTokenInfo(){let i=N.getTokenData(),e=v.getExpirationInfo(),t=v.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:v.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 N.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return v.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){N.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"),M.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(v.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),M.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"),M.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=N.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";N.config(e);let t=this.config.publicApiKey,s=this.config.enableLogging?"debug":"none",o=await N.init(t,s);if(o&&o.success===!1&&o.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(o.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw p.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(s=>s.errorType==="Unauthorized"||s.message?.includes("Unauthorized")||s.message?.includes("Not Authorized")||s.message?.includes("NOT_AUTHORIZED")||s.message?.includes("Token")||s.message?.includes("TOKEN")||s.message?.includes("Authentication")||s.message?.includes("UNAUTHENTICATED")||s.extensions?.code==="UNAUTHENTICATED"||s.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 s=Object.values(i.errors).flat().find(o=>typeof o=="string"&&(o.includes("NOT_AUTHORIZED")||o.includes("TOKEN_REFRESH_FAILED")||o.includes("TOKEN_HAS_EXPIRED")||o.includes("PLEASE_LOGIN")||o.includes("Unauthorized")||o.includes("UNAUTHENTICATED")||o.includes("SESSION_EXPIRED")||o.includes("INVALID_TOKEN")));s&&typeof s=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,s.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."):s.includes("TOKEN_HAS_EXPIRED")||s.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):s.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=String(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(){v.clearTokens(),N.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().map(String).join(", "):"Authentication failed":"Unknown error"}};import{useState as Ye,useEffect as ee,useCallback as V}from"react";function be(r={}){let[i,e]=Ye({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),s=V(async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(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(u),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(u){let a=u instanceof Error?u.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),o=V(async(u,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(u,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]),c=V(async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),m=V(async()=>{try{let u=await t.refreshTokens();if(u){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 u}catch(u){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),w=V(()=>{e(u=>({...u,error:null}))},[]),I=V(()=>t.getTokenInfo(),[t]);ee(()=>{s()},[s]),ee(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=Ee.getInstance(),a=()=>{t.updateLastActivity()},l=u.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},y,E=()=>{let b=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let C=t.getTokenInfo(),S=C.crudifyTokens.expiresIn||0,O=((C.crudifyTokens.expiresAt||0)-(Date.now()-S))*.5;if(S>0&&S<=O)if(e(L=>({...L,isLoading:!0})),await t.refreshTokens()){let L=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:L.crudifyTokens.accessToken?{accessToken:L.crudifyTokens.accessToken,refreshToken:L.crudifyTokens.refreshToken,expiresAt:L.crudifyTokens.expiresAt,refreshExpiresAt:L.crudifyTokens.refreshExpiresAt}:null}))}else e(L=>({...L,isLoading:!1,isAuthenticated:!1,tokens:null}));let k=t.getTimeSinceLastActivity(),W=1800*1e3;k>W?await c():E()},b)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,c]),ee(()=>{let u=M.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 M.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){M.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:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>u()},[r.onSessionExpired,t]),ee(()=>{let u=v.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),M.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[]);let T=V(()=>{t.updateLastActivity()},[t]);return{...i,login:o,logout:c,refreshTokens:m,clearError:w,getTokenInfo:I,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 Xe,useContext as We,useCallback as ie,useEffect as Ze}from"react";import{Snackbar as qe,Alert as je,Box as Je,Portal as Qe}from"@mui/material";import{v4 as ei}from"uuid";import ii from"dompurify";import{jsx as B,jsxs as ni}from"react/jsx-runtime";var Se=Xe(null),ti=r=>ii.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=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:o=!1})=>{let[c,m]=xe([]),w=ie((a,l="info",n)=>{if(!s)return"";if(!a||typeof a!="string")return p.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(p.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=ei(),E={id:y,message:a,severity:l,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??o};return m(b=>[...b.length>=i?b.slice(-(i-1)):b,E]),y},[i,e,s,o]),I=ie(a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=ie(()=>{m([])},[]),u={showNotification:w,hideNotification:I,clearAllNotifications:T};return ni(Se.Provider,{value:u,children:[r,s&&B(Qe,{children:B(Je,{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:c.map(a=>B(ri,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ri=({notification:r,onClose:i})=>{let[e,t]=xe(!0),s=ie((o,c)=>{c!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ze(()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{s()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,s]),B(qe,{open:e,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:B(je,{variant:"filled",severity:r.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?B("span",{dangerouslySetInnerHTML:{__html:ti(r.message)}}):B("span",{children:r.message})})})},we=()=>{let r=We(Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import si,{createContext as oi,useContext as ai,useMemo as fe}from"react";import{Fragment as ci,jsx as R,jsxs as G}from"react/jsx-runtime";var Re=oi(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:s={}}){let o;try{let{showNotification:n}=we();o=n}catch{}let c={};try{let n=ke();n.isInitialized&&n.adminCredentials&&(c=n.adminCredentials)}catch{}let m=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),w=si.useMemo(()=>({...i,showNotification:o,apiEndpointAdmin:c.apiEndpointAdmin,apiKeyEndpointAdmin:c.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,o,c.apiEndpointAdmin,c.apiKeyEndpointAdmin,m]),I=be(w),T=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),u=fe(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let n=Te(I.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){p.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[I.tokens?.accessToken,I.isAuthenticated]),a={...I,sessionData:u,config:T},l={enabled:t,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return R(Re.Provider,{value:a,children:r})}function ct(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?R(Ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:R(de,{...i,children:R(Pe,{...r})})}):R(de,{...i,children:R(Pe,{...r})})}function li(){let r=ai(Re);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ut(){let r=li();return r.isInitialized?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[R("h4",{children:"Session Debug Info"}),G("div",{children:[R("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),G("div",{children:[R("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),G("div",{children:[R("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&G(ci,{children:[G("div",{children:[R("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[R("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[R("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),G("div",{children:[R("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[R("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):R("div",{children:"Session not initialized"})}import{useState as te,useEffect as Ne,useCallback as Ce,useRef as re}from"react";import ui from"@nocios/crudify-browser";var ht=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[s,o]=te(null),[c,m]=te(!1),[w,I]=te(null),[T,u]=te({}),a=re(null),l=re(!0),n=re(0),y=re(0),E=Ce(()=>{o(null),I(null),m(!1),u({})},[]),b=Ce(async()=>{let C=ve();if(!C){l.current&&(I("No user email available"),m(!1));return}a.current&&a.current.abort();let S=new AbortController;a.current=S;let D=++n.current;try{l.current&&(m(!0),I(null));let F=await ui.readItems("users",{filter:{email:C},pagination:{limit:1}});if(D===n.current&&l.current&&!S.signal.aborted){let O=F.data;if(F.success&&O&&O.length>0){let k=O[0];o(k);let W={fullProfile:k,totalFields:Object.keys(k).length,displayData:{id:k.id,email:k.email,username:k.username,firstName:k.firstName,lastName:k.lastName,fullName:k.fullName||`${k.firstName||""} ${k.lastName||""}`.trim(),role:k.role,permissions:k.permissions||[],isActive:k.isActive,lastLogin:k.lastLogin,createdAt:k.createdAt,updatedAt:k.updatedAt,...Object.keys(k).filter(Y=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(Y)).reduce((Y,L)=>({...Y,[L]:k[L]}),{})}};u(W),I(null),y.current=0}else I("User profile not found"),o(null),u({})}}catch(F){if(D===n.current&&l.current){let O=F;if(O.name==="AbortError")return;e&&y.current<t&&(O.message?.includes("Network Error")||O.message?.includes("Failed to fetch"))?(y.current++,setTimeout(()=>{l.current&&b()},1e3*y.current)):(I("Failed to load user profile"),o(null),u({}))}}finally{D===n.current&&l.current&&m(!1),a.current===S&&(a.current=null)}},[e,t]);return Ne(()=>{i&&b()},[i,b]),Ne(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:s,loading:c,error:w,extendedData:T,refreshProfile:b,clearProfile:E}};import{useState as pe,useEffect as di,useCallback as ne,useRef as fi}from"react";import pi from"@nocios/crudify-browser";var vt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:s}=i,{prefix:o,padding:c=0,separator:m=""}=r,[w,I]=pe(""),[T,u]=pe(!1),[a,l]=pe(null),n=fi(!1),y=ne(S=>{let D=String(S).padStart(c,"0");return`${o}${m}${D}`},[o,c,m]),E=ne(async()=>{u(!0),l(null);try{let S=await pi.getNextSequence(o),D=S.data;if(S.success&&D?.value){let F=y(D.value);I(F),t?.(F)}else{let F=S.errors?._error?.[0]||"Failed to generate code";l(F),s?.(F)}}catch(S){let D=S instanceof Error?S.message:"Unknown error";l(D),s?.(D)}finally{u(!1)}},[o,y,t,s]),b=ne(async()=>{await E()},[E]),C=ne(()=>{l(null)},[]);return di(()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:b,clearError:C}};import ge from"@nocios/crudify-browser";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:s,enableLogging:o,requestedBy:c}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&p.warn(`[CrudifyInitialization] ${c} 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 o&&p.debug(`[CrudifyInitialization] ${c} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&p.debug(`[CrudifyInitialization] ${c} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(c),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(c),this.getState().status==="INITIALIZED"){o&&p.debug(`[CrudifyInitialization] ${c} found initialization completed by HIGH priority`);return}o&&p.warn(`[CrudifyInitialization] ${c} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(p.warn(`[CrudifyInitialization] HIGH priority request from ${c} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&p.debug(`[CrudifyInitialization] ${c} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=c,this.initializationPromise=this.performInitialization(t,s,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=s,this.state.error=null,o&&p.info(`[CrudifyInitialization] Successfully initialized by ${c} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,p.error(`[CrudifyInitialization] Initialization failed for ${c}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let s=0,o=setInterval(()=>{if(s+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){s=0;return}s>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),i&&p.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let s=ge.getTokenData();if(s&&s.endpoint){t&&p.debug("[CrudifyInitialization] SDK already initialized externally");return}ge.config(e);let o=t?"debug":"none",c=await ge.init(i,o);if(c.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(c.errors||"Unknown error")}`);c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.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}}},se=ye.getInstance();import{useState as De,useCallback as U,useRef as gi,useMemo as oe}from"react";import he from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),s=Math.random().toString(36).substring(2,8);return`${t}_${s}${e}`},Nt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:s=0,visibility:o="private",onUploadComplete:c,onUploadError:m,onFileRemoved:w,onFilesChange:I}=r,[T,u]=De([]),[a,l]=De(!1),n=gi(new Map),y=U(()=>{l(!0)},[]),E=U((d,h)=>{u(g=>g.map(A=>A.id===d?{...A,...h}:A))},[]),b=U(d=>{I?.(d)},[I]),C=U(d=>i&&i.length>0&&!i.includes(d.type)?{valid:!1,error:`File type not allowed: ${d.type}`}:d.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),S=U(async(d,h)=>{try{if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=yi(h.name),x=await he.generateSignedUrl({fileName:g,contentType:h.type,visibility:o});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let A=x.data,{uploadUrl:z,s3Key:P,publicUrl:H}=A;if(!z||!P)throw new Error("Incomplete signed URL response");let X=P.indexOf("/"),He=X>0?P.substring(X+1):P;E(d.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let K=new XMLHttpRequest;K.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ge=Math.round(_.loaded/_.total*100);E(d.id,{progress:Ge})}}),K.addEventListener("load",()=>{K.status>=200&&K.status<300?le():$(new Error(`Upload failed with status ${K.status}`))}),K.addEventListener("error",()=>{$(new Error("Network error during upload"))}),K.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),K.open("PUT",z),K.setRequestHeader("Content-Type",h.type),K.send(h)});let Me={status:"completed",progress:100,filePath:He,visibility:o,publicUrl:o==="public"?H:void 0,file:void 0};u(le=>{let $=le.map(_=>_.id===d.id?{..._,...Me}:_);b($);let K=$.find(_=>_.id===d.id);return K&&c?.(K),$})}catch(g){let x=g instanceof Error?g.message:"Unknown error";E(d.id,{status:"error",progress:0,errorMessage:x}),u(A=>{let z=A.find(P=>P.id===d.id);return z&&m?.(z,x),A})}},[E,c,m,o]),D=U(async d=>{let h=Array.from(d),g=[];u(x=>{if(t!==void 0){let P=x.filter(X=>X.status!=="error").length,H=t-P;if(H<=0)return p.warn(`File limit of ${t} already reached`),x;h.length>H&&(h=h.slice(0,H),p.warn(`Only ${H} files will be added to not exceed limit`))}let A=[];for(let P of h){let H=C(P),X={id:Le(),name:P.name,size:P.size,contentType:P.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?P:void 0,errorMessage:H.error};A.push(X)}g=A;let z=[...x,...A];return b(z),z}),setTimeout(()=>{let x=g.filter(A=>A.status==="pending"&&A.file);for(let A of x)if(A.file){let z=S(A,A.file);n.current.set(A.id,z),z.finally(()=>{n.current.delete(A.id)})}},0)},[t,C,S,b]),F=U(async d=>{let h=T.find(g=>g.id===d);if(!h)return!1;E(d,{status:"removing"});try{if(h.filePath){if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await he.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return u(g=>{let x=g.filter(A=>A.id!==d);return b(x),x}),w?.(h),!0}catch(g){return E(d,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,b,w]),O=U(()=>{u([]),b([])},[b]),k=U(async d=>{let h=T.find(x=>x.id===d);if(!h||h.status!=="error"||!h.file){p.warn("Cannot retry: file not found or no original file");return}E(d,{status:"pending",progress:0,errorMessage:void 0});let g=S(h,h.file);n.current.set(d,g),g.finally(()=>{n.current.delete(d)})},[T,E,S]),W=U(async()=>{let d=Array.from(n.current.values());d.length>0&&await Promise.allSettled(d)},[]),Y=d=>{let h=d.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"}[h]||"application/octet-stream"},L=U(d=>{let h=d.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,z=A.includes("/public/")||A.startsWith("public/")?"public":"private",P=g.contentType||Y(g.name);return{id:Le(),name:g.name,size:g.size||0,contentType:P,status:"completed",progress:100,filePath:g.filePath,visibility:z,createdAt:Date.now()}});u(h),b(h)},[b]),ae=U(async d=>{let h=T.find(g=>g.id===d);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!se.isInitialized())return null;let g=await he.getFileUrl({filePath:h.filePath,expiresIn:3600}),x=g.data;return g.success&&x?.url?x.url:null}catch{return null}},[T]),Fe=oe(()=>T.some(d=>d.status==="uploading"||d.status==="pending"),[T]),ze=oe(()=>T.filter(d=>d.status==="uploading"||d.status==="pending").length,[T]),Ke=oe(()=>T.filter(d=>d.status==="completed"&&d.filePath).map(d=>d.filePath),[T]),{isValid:Ue,validationError:Oe}=oe(()=>{let d=T.filter(g=>g.status==="completed").length;return d<s?{isValid:!1,validationError:s===1?"At least one file is required":`At least ${s} files are required`}:t!==void 0&&d>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,s,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:D,removeFile:F,clearFiles:O,retryUpload:k,isValid:Ue,validationError:Oe,waitForUploads:W,completedFilePaths:Ke,initializeFiles:L,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};export{j as a,Ie as b,ke as c,v as d,Q as e,be as f,de as g,we as h,ct as i,li as j,ut as k,ht as l,vt as m,ye as n,se as o,Nt as p};
@@ -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-GCH3QGKL.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};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkIYTXJHKOjs = require('./chunk-IYTXJHKO.js');var _chunkGNGIFVA4js = require('./chunk-GNGIFVA4.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var J=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:m=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:p}=_chunkIYTXJHKOjs.j.call(void 0, ),[R,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, c&&T),[C,E]=_react.useState.call(void 0, null),l=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),f=_react.useRef.call(void 0, 0),F=_react.useCallback.call(void 0, ()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),P=_react.useCallback.call(void 0, ()=>{d(null),E(null),A(!1),f.current=0},[]),D=_react.useCallback.call(void 0, async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}l.current&&l.current.abort();let e=new AbortController;l.current=e;let i=++g.current;try{o.current&&(A(!0),E(null));let s=await _crudifybrowser2.default.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===g.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.data]))try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e2){}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.data]))try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e3){}}r?(d(r),E(null),f.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===g.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&f.current<m&&(_optionalChain([r, 'access', _7 => _7.message, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("Network Error")])||_optionalChain([r, 'access', _10 => _10.message, 'optionalAccess', _11 => _11.includes, 'call', _12 => _12("Failed to fetch")]))?(f.current++,setTimeout(()=>{o.current&&D()},1e3*f.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===g.current&&o.current&&A(!1),l.current===e&&(l.current=null)}},[I,F,N,m]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?D():T||P()},[c,T,I,D,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{user:{session:u,data:R},loading:y,error:C,refreshProfile:D,clearProfile:P}};var te=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:m,error:T,sessionData:I,login:u,logout:p,refreshTokens:R,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=_chunkIYTXJHKOjs.j.call(void 0, ),l=_react.useCallback.call(void 0, g=>{g?_chunkGNGIFVA4js.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):p()},[p]),o=_optionalChain([m, 'optionalAccess', _13 => _13.expiresAt])?new Date(m.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([m, 'optionalAccess', _14 => _14.accessToken])||null,user:I,tokenExpiration:o,setToken:l,logout:p,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:y,clearError:d}};var ae=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:m,login:T}=_chunkIYTXJHKOjs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),u=_react.useCallback.call(void 0, async()=>new Promise((o,g)=>{let f=()=>{I()?o():N?g(new Error(N)):setTimeout(f,100)};f()}),[I,N]),p=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.readItems(o,g||{},f)),[p]),d=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.readItem(o,g,f)),[p]),y=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.createItem(o,g,f)),[p]),A=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.updateItem(o,g,f)),[p]),C=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.deleteItem(o,g,f)),[p]),E=_react.useCallback.call(void 0, async(o,g)=>(await p(),await _crudifybrowser2.default.transaction(o,g)),[p]),l=_react.useCallback.call(void 0, async(o,g)=>{try{let f=await T(o,g);return f.success?{success:!0,data:f.tokens}:{success:!1,errors:f.error||"Login failed"}}catch(f){return{success:!1,errors:f instanceof Error?f.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:y,updateItem:A,deleteItem:C,transaction:E,login:l,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};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"},de= exports.d =(S={})=>{let{showNotification:c}=_chunkIYTXJHKOjs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:m=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:p=[],translateFn:R=e=>e}=S,d=_react.useCallback.call(void 0, e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _15 => _15.errors, 'access', _16 => _16._transaction, 'optionalAccess', _17 => _17.includes, 'call', _18 => _18("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _19 => _19.errors, 'access', _20 => _20._error, 'optionalAccess', _21 => _21.includes, 'call', _22 => _22("TOO_MANY_REQUESTS")])))return!1;let i=e.data;return!(!e.success&&_optionalChain([i, 'optionalAccess', _23 => _23.response, 'optionalAccess', _24 => _24.status])==="TOO_MANY_REQUESTS")},[]),y=_react.useCallback.call(void 0, (e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),C=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:p.some(s=>s.key===e):!1,[N,p,A]),E=_react.useCallback.call(void 0, (e,i,s)=>{let r=_optionalChain([s, 'optionalAccess', _25 => _25.key])&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=y(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=y(a);if(O!==R("error.unknown"))return R(t,{item:O});{let L=`action.onSuccess.${r}WithoutItem`,x=y(L);return x!==R("error.unknown")?x:n}}return n}return R("success.transaction")},[y,R,A]),l=_react.useCallback.call(void 0, 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 s of i){let r=y(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==R("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 s=e.errors._transaction;if(_optionalChain([s, 'optionalAccess', _26 => _26.includes, 'call', _27 => _27("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(_optionalChain([n, 'optionalAccess', _28 => _28.response, 'optionalAccess', _29 => _29.errorCode])){let a=n.response.errorCode;if(M[a])return y(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let L of O){let x=y(L);if(x!==y("error.unknown"))return x}}if(_optionalChain([n, 'optionalAccess', _30 => _30.response, 'optionalAccess', _31 => _31.data]))return n.response.data}if(_optionalChain([t, 'optionalAccess', _32 => _32.response, 'optionalAccess', _33 => _33.message])){let n=t.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch (e4){return r.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),g=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.createItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _34 => _34.actionConfig]),n=_optionalChain([t, 'optionalAccess', _35 => _35.key])||"create",a=_optionalChain([t, 'optionalAccess', _36 => _36.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),f=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.updateItem(e,i,s),t=_optionalChain([s, 'optionalAccess', _37 => _37.skipNotifications])===!0;if(!t&&!r.success&&m&&d(r)){let n=l(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=_optionalChain([s, 'optionalAccess', _38 => _38.actionConfig]),a=_optionalChain([n, 'optionalAccess', _39 => _39.key])||"update",O=_optionalChain([n, 'optionalAccess', _40 => _40.moduleKey])||e;if(C(a,O)){let L=E(a,O,n);c(L,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),F=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.deleteItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _41 => _41.actionConfig]),n=_optionalChain([t, 'optionalAccess', _42 => _42.key])||"delete",a=_optionalChain([t, 'optionalAccess', _43 => _43.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),P=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.readItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),D=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.readItems(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),q=_react.useCallback.call(void 0, async(e,i)=>{let s=await _crudifybrowser2.default.transaction(e,i),r=_optionalChain([i, 'optionalAccess', _44 => _44.skipNotifications])===!0;if(!r&&!s.success&&m&&d(s)){let t=l(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(_optionalChain([i, 'optionalAccess', _45 => _45.actionConfig])?(a=i.actionConfig,t=a.key,n=a.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(t=e[0].operation,a=p.find(O=>O.key===t),a&&(n=a.moduleKey)),C(t,n)){let O=E(t,n,a);c(O,"success",{autoHideDuration:u})}}return s},[m,C,c,l,o,E,u,d,p]),h=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&m&&d(e)){let s=l(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[m,N,c,l,o,u,d,R]);return{createItem:g,updateItem:f,deleteItem:F,readItem:P,readItems:D,transaction:q,handleResponse:h,getErrorMessage:l,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkX3JFRSEAjs = require('./chunk-X3JFRSEA.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);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 _cryptojs2.default.SHA256(t).toString()}setItem(t,e,n){try{let r=_cryptojs2.default.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){_chunkX3JFRSEAjs.a.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=_cryptojs2.default.AES.decrypt(r,this.encryptionKey).toString(_cryptojs2.default.enc.Utf8);return i||(_chunkX3JFRSEAjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunkX3JFRSEAjs.a.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 (e2){_chunkX3JFRSEAjs.a.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 (e3){return _chunkX3JFRSEAjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y= exports.a =new c("sessionStorage"),h= exports.b =new c("localStorage");exports.a = y; exports.b = h;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkGNGIFVA4js = require('./chunk-GNGIFVA4.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);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 _cryptojs2.default.SHA256(t).toString()}setItem(t,e,n){try{let r=_cryptojs2.default.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){_chunkGNGIFVA4js.a.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=_cryptojs2.default.AES.decrypt(r,this.encryptionKey).toString(_cryptojs2.default.enc.Utf8);return i||(_chunkGNGIFVA4js.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunkGNGIFVA4js.a.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 (e2){_chunkGNGIFVA4js.a.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 (e3){return _chunkGNGIFVA4js.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y= exports.a =new c("sessionStorage"),h= exports.b =new c("localStorage");exports.a = y; exports.b = h;
@@ -0,0 +1 @@
1
+ var b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function S(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function w(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=S("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,O="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=O}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:w()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i=new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function _(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:s.loginActions?.length,featureKeysCount:s.featureKeys?.length}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:s.loginActions?.length,featureKeysCount:s.featureKeys?.length}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return _(n)}var k=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function H(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>o?.data?.response?.status?h(o.data.response.status,t):o?.status?h(o.status,t):o?.code?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},J=m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){g.instance?.isPatched&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j=()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q=n=>{try{let e=T(n);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch{return!0}};export{i as a,f as b,_ as c,M as d,h as e,U as f,x as g,H as h,J as i,I as j,T as k,j as l,q as m};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function S(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function w(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=S("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,O="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=O}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:w()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i= exports.a =new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function _(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _2 => _2.loginActions, 'optionalAccess', _3 => _3.length]),featureKeysCount:_optionalChain([s, 'access', _4 => _4.featureKeys, 'optionalAccess', _5 => _5.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _6 => _6.loginActions, 'optionalAccess', _7 => _7.length]),featureKeysCount:_optionalChain([s, 'access', _8 => _8.featureKeys, 'optionalAccess', _9 => _9.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return _(n)}var k=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function H(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>_optionalChain([o, 'optionalAccess', _10 => _10.data, 'optionalAccess', _11 => _11.response, 'optionalAccess', _12 => _12.status])?h(o.data.response.status,t):_optionalChain([o, 'optionalAccess', _13 => _13.status])?h(o.status,t):_optionalChain([o, 'optionalAccess', _14 => _14.code])?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},J= exports.i =m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){_optionalChain([g, 'access', _15 => _15.instance, 'optionalAccess', _16 => _16.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j= exports.l =()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q= exports.m =n=>{try{let e=T(n);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch (e2){return!0}};exports.a = i; exports.b = f; exports.c = _; exports.d = M; exports.e = h; exports.f = U; exports.g = x; exports.h = H; exports.i = J; exports.j = I; exports.k = T; exports.l = j; exports.m = q;