@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.
- package/dist/{CrudiaMarkdownField-Bs940oF4.d.ts → CrudiaMarkdownField-C30enyF9.d.ts} +2 -2
- package/dist/{CrudiaMarkdownField-CKPdr2JL.d.mts → CrudiaMarkdownField-D-VooBtq.d.mts} +2 -2
- package/dist/{api-Djqihi4n.d.mts → api-RK-xY1Ah.d.mts} +22 -2
- package/dist/{api-Djqihi4n.d.ts → api-RK-xY1Ah.d.ts} +22 -2
- package/dist/chunk-2G33BADS.mjs +1 -0
- package/dist/{chunk-ZANWILS7.mjs → chunk-7J5RTLCS.mjs} +1 -1
- package/dist/chunk-AEHAZP5F.js +1 -0
- package/dist/{chunk-4LSVF26Q.js → chunk-D3NBX3SM.js} +1 -1
- package/dist/chunk-GCH3QGKL.mjs +1 -0
- package/dist/chunk-GNGIFVA4.js +1 -0
- package/dist/{chunk-L454VIXN.js → chunk-HDNGW5H5.js} +1 -1
- package/dist/chunk-IYTXJHKO.js +1 -0
- package/dist/{chunk-Q5EJLSB4.mjs → chunk-NZIH26GS.mjs} +1 -1
- package/dist/chunk-ZKWTILQT.mjs +1 -0
- package/dist/components.d.mts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/{errorTranslation-BuEEtVg4.d.mts → errorTranslation-B4wcHzD3.d.mts} +1 -1
- package/dist/{errorTranslation-BIyBYuGF.d.ts → errorTranslation-CCC5IWoN.d.ts} +1 -1
- package/dist/hooks.d.mts +4 -3
- package/dist/hooks.d.ts +4 -3
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-CQnAzvOE.d.mts → index-DEnlzdtV.d.mts} +90 -16
- package/dist/{index-BVT7flO5.d.ts → index-pQmuVg3q.d.ts} +90 -16
- package/dist/index.d.mts +101 -70
- package/dist/index.d.ts +101 -70
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +11 -4
- package/dist/utils.d.ts +11 -4
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +3 -3
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/configResolver.ts.html +0 -499
- package/coverage/coverage-final.json +0 -2
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -116
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/dist/chunk-JCMHUFYK.mjs +0 -1
- package/dist/chunk-LPC6P3Z7.mjs +0 -1
- package/dist/chunk-SEDLJT7G.js +0 -1
- package/dist/chunk-UJD6SL66.mjs +0 -1
- package/dist/chunk-X3JFRSEA.js +0 -1
- package/dist/chunk-YLKGZV2N.js +0 -1
package/dist/chunk-SEDLJT7G.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkX3JFRSEAjs = require('./chunk-X3JFRSEA.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ue=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){_chunkX3JFRSEAjs.a.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(t)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},j= exports.a =ue.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ae=_react.createContext.call(void 0, void 0),Ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[w,b]=_react.useState.call(void 0, ""),[T,c]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&d){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{_crudifybrowser2.default.config(r.env||"prod");let y=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(c(y),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")m(!0),b(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";_chunkX3JFRSEAjs.a.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),s(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,d]);let a={crudify:d?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:d,adminCredentials:T};return _jsxruntime.jsx.call(void 0, Ae.Provider,{value:a,children:i})},be= exports.c =()=>{let r=_react.useContext.call(void 0, Ae);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var f=class f{static setStorageType(i){f.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(i).toString()}static getEncryptionKey(){if(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch (e2){return _chunkX3JFRSEAjs.a.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e3){return!1}}static getStorage(){return f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(_chunkX3JFRSEAjs.a.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return _chunkX3JFRSEAjs.a.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return _chunkX3JFRSEAjs.a.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,o),_chunkX3JFRSEAjs.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunkX3JFRSEAjs.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(_chunkX3JFRSEAjs.a.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(_chunkX3JFRSEAjs.a.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return _chunkX3JFRSEAjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),_chunkX3JFRSEAjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkX3JFRSEAjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),_chunkX3JFRSEAjs.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunkX3JFRSEAjs.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=f.getTokens();if(!t){_chunkX3JFRSEAjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){_chunkX3JFRSEAjs.a.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){_chunkX3JFRSEAjs.a.debug("Crudify: Tokens updated in another tab");let o=f.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var I=f;var Q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},I.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=I.getTokens();e?I.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):I.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=I.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return I.saveTokens(s),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(s)]),{success:!0,tokens:s,data:t.data}}catch(t){return _chunkX3JFRSEAjs.a.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),I.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}catch(i){this.log("Logout error:",i),I.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=I.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),I.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=I.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return I.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),I.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||I.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=I.getExpirationInfo(),t=I.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:I.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),I.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return I.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),I.clearTokens(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunkX3JFRSEAjs.i.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(I.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkX3JFRSEAjs.i.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",s=await _crudifybrowser2.default.init(t,o);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw _chunkX3JFRSEAjs.a.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(i)}),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||_optionalChain([o, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([o, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([o, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([o, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([o, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([o, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([o, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([o, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([o, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.status])){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.data]))try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e4){}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){I.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkX3JFRSEAjs.e.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};function ke(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),o=_react.useCallback.call(void 0, async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=_react.useCallback.call(void 0, async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",y=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:n})),{success:!1,error:n}}},[t]),d=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),m=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),w=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),b=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{o()},[o]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let c=_chunkX3JFRSEAjs.j.getInstance(),a=()=>{t.updateLastActivity()},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let L=t.getTokenInfo().crudifyTokens.expiresIn||0;return L<300*1e3?30*1e3:L<1800*1e3?60*1e3:120*1e3},y,E=()=>{let k=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let L=t.getTokenInfo(),x=L.crudifyTokens.expiresIn||0,v=((L.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=v)if(e(K=>({...K,isLoading:!0})),await t.refreshTokens()){let K=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else e(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let Y=t.getTimeSinceLastActivity(),_=1800*1e3;Y>_?await d():E()},k)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),_react.useEffect.call(void 0, ()=>{let c=_chunkX3JFRSEAjs.i.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else _chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){_chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>c()},[r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=I.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),_chunkX3JFRSEAjs.i.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[]);let T=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:m,clearError:w,getTokenInfo:b,updateActivity:T,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var Se=_react.createContext.call(void 0, null),ii=r=>_dompurify2.default.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),de= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[d,m]=_react.useState.call(void 0, []),w=_react.useCallback.call(void 0, (a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return _chunkX3JFRSEAjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(_chunkX3JFRSEAjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=_uuid.v4.call(void 0, ),E={id:y,message:a,severity:l,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (s))};return m(k=>[...k.length>=i?k.slice(-(i-1)):k,E]),y},[i,e,o,s]),b=_react.useCallback.call(void 0, a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=_react.useCallback.call(void 0, ()=>{m([])},[]),c={showNotification:w,hideNotification:b,clearAllNotifications:T};return _jsxruntime.jsxs.call(void 0, Se.Provider,{value:c,children:[r,o&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:d.map(a=>_jsxruntime.jsx.call(void 0, ti,{notification:a,onClose:()=>b(a.id)},a.id))})})]})},ti=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,o]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ii(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},we= exports.h =()=>{let r=_react.useContext.call(void 0, Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ne=_react.createContext.call(void 0, void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=we();s=n}catch (e5){}let d={};try{let n=be();n.isInitialized&&n.adminCredentials&&(d=n.adminCredentials)}catch (e6){}let m=_react.useMemo.call(void 0, ()=>{let n=_chunkX3JFRSEAjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _81 => _81.env]),enableDebug:_optionalChain([i, 'optionalAccess', _82 => _82.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _83 => _83.enableLogging])]),w=_react2.default.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,m]),b=ke(w),T=_react.useMemo.call(void 0, ()=>{let n=_chunkX3JFRSEAjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),appName:_optionalChain([e, 'optionalAccess', _88 => _88.appName]),logo:_optionalChain([e, 'optionalAccess', _89 => _89.logo]),loginActions:_optionalChain([e, 'optionalAccess', _90 => _90.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),c=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([b, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!b.isAuthenticated)return null;try{let n=_chunkX3JFRSEAjs.k.call(void 0, b.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let y={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=n[E])}),y}}catch(n){_chunkX3JFRSEAjs.a.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[_optionalChain([b, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken]),b.isAuthenticated]),a={...b,sessionData:c,config:T},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, Ne.Provider,{value:a,children:r})}function lt(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.allowHtml])||!1};return _optionalChain([r, 'access', _105 => _105.config, 'optionalAccess', _106 => _106.publicApiKey])?_jsxruntime.jsx.call(void 0, Ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}):_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}function ai(){let r=_react.useContext.call(void 0, Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ct(){let r=ai();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var yt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[w,b]=_react.useState.call(void 0, null),[T,c]=_react.useState.call(void 0, {}),a=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),y=_react.useRef.call(void 0, 0),E=_react.useCallback.call(void 0, ()=>{s(null),b(null),m(!1),c({})},[]),k=_react.useCallback.call(void 0, async()=>{let L=_chunkX3JFRSEAjs.l.call(void 0, );if(!L){l.current&&(b("No user email available"),m(!1));return}a.current&&a.current.abort();let x=new AbortController;a.current=x;let P=++n.current;try{l.current&&(m(!0),b(null));let M=await _crudifybrowser2.default.readItems("users",{filter:{email:L},pagination:{limit:1}});if(P===n.current&&l.current&&!x.signal.aborted)if(M.success&&M.data&&M.data.length>0){let v=M.data[0];s(v);let Y={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(_=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(_)).reduce((_,X)=>({..._,[X]:v[X]}),{})}};c(Y),b(null),y.current=0}else b("User profile not found"),s(null),c({})}catch(M){if(P===n.current&&l.current){let v=M;if(v.name==="AbortError")return;e&&y.current<t&&(_optionalChain([v, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([v, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("Failed to fetch")]))?(y.current++,setTimeout(()=>{l.current&&k()},1e3*y.current)):(b("Failed to load user profile"),s(null),c({}))}}finally{P===n.current&&l.current&&m(!1),a.current===x&&(a.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&k()},[i,k]),_react.useEffect.call(void 0, ()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:o,loading:d,error:w,extendedData:T,refreshProfile:k,clearProfile:E}};var Tt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:d=0,separator:m=""}=r,[w,b]=_react.useState.call(void 0, ""),[T,c]=_react.useState.call(void 0, !1),[a,l]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),y=_react.useCallback.call(void 0, x=>{let P=String(x).padStart(d,"0");return`${s}${m}${P}`},[s,d,m]),E=_react.useCallback.call(void 0, async()=>{c(!0),l(null);try{let x=await _crudifybrowser2.default.getNextSequence(s);if(x.success&&_optionalChain([x, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let P=y(x.data.value);b(P),_optionalChain([t, 'optionalCall', _115 => _115(P)])}else{let P=_optionalChain([x, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";l(P),_optionalChain([o, 'optionalCall', _119 => _119(P)])}}catch(x){let P=x instanceof Error?x.message:"Unknown error";l(P),_optionalChain([o, 'optionalCall', _120 => _120(P)])}finally{c(!1)}},[s,y,t,o]),k=_react.useCallback.call(void 0, async()=>{await E()},[E]),L=_react.useCallback.call(void 0, ()=>{l(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:k,clearError:L}};var ye=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:o,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunkX3JFRSEAjs.a.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _121 => _121.state, 'access', _122 => _122.publicApiKey, 'optionalAccess', _123 => _123.slice, 'call', _124 => _124(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&_chunkX3JFRSEAjs.a.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkX3JFRSEAjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&_chunkX3JFRSEAjs.a.info(`[CrudifyInitialization] Successfully initialized by ${d} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,_chunkX3JFRSEAjs.a.error(`[CrudifyInitialization] Initialization failed for ${d}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&_chunkX3JFRSEAjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=_crudifybrowser2.default.getTokenData();if(o&&o.endpoint){t&&_chunkX3JFRSEAjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let s=t?"debug":"none",d=await _crudifybrowser2.default.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},oe= exports.o =ye.getInstance();var De=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,gi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),o=Math.random().toString(36).substring(2,8);return`${t}_${o}${e}`},Nt= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:d,onUploadError:m,onFileRemoved:w,onFilesChange:b}=r,[T,c]=_react.useState.call(void 0, []),[a,l]=_react.useState.call(void 0, !1),n=_react.useRef.call(void 0, new Map),y=_react.useCallback.call(void 0, ()=>{l(!0)},[]),E=_react.useCallback.call(void 0, (u,h)=>{c(g=>g.map(A=>A.id===u?{...A,...h}:A))},[]),k=_react.useCallback.call(void 0, u=>{_optionalChain([b, 'optionalCall', _125 => _125(u)])},[b]),L=_react.useCallback.call(void 0, u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),x=_react.useCallback.call(void 0, async(u,h)=>{try{if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=gi(h.name),S=await _crudifybrowser2.default.generateSignedUrl({fileName:g,contentType:h.type,visibility:s});if(!S.success||!S.data)throw new Error("Failed to get upload URL");let{uploadUrl:A,s3Key:R,publicUrl:D}=S.data;if(!A||!R)throw new Error("Incomplete signed URL response");let U=R.indexOf("/"),W=U>0?R.substring(U+1):R;E(u.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",G=>{if(G.lengthComputable){let Me=Math.round(G.loaded/G.total*100);E(u.id,{progress:Me})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?le():$(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{$(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),F.open("PUT",A),F.setRequestHeader("Content-Type",h.type),F.send(h)});let He={status:"completed",progress:100,filePath:W,visibility:s,publicUrl:s==="public"?D:void 0,file:void 0};c(le=>{let $=le.map(G=>G.id===u.id?{...G,...He}:G);k($);let F=$.find(G=>G.id===u.id);return F&&_optionalChain([d, 'optionalCall', _126 => _126(F)]),$})}catch(g){let S=g instanceof Error?g.message:"Unknown error";E(u.id,{status:"error",progress:0,errorMessage:S}),c(A=>{let R=A.find(D=>D.id===u.id);return R&&_optionalChain([m, 'optionalCall', _127 => _127(R,S)]),A})}},[E,d,m,s]),P=_react.useCallback.call(void 0, async u=>{let h=Array.from(u),g=[];c(S=>{if(t!==void 0){let D=S.filter(W=>W.status!=="error").length,U=t-D;if(U<=0)return _chunkX3JFRSEAjs.a.warn(`File limit of ${t} already reached`),S;h.length>U&&(h=h.slice(0,U),_chunkX3JFRSEAjs.a.warn(`Only ${U} files will be added to not exceed limit`))}let A=[];for(let D of h){let U=L(D),W={id:De(),name:D.name,size:D.size,contentType:D.type,status:U.valid?"pending":"error",progress:0,createdAt:Date.now(),file:U.valid?D:void 0,errorMessage:U.error};A.push(W)}g=A;let R=[...S,...A];return k(R),R}),setTimeout(()=>{let S=g.filter(A=>A.status==="pending"&&A.file);for(let A of S)if(A.file){let R=x(A,A.file);n.current.set(A.id,R),R.finally(()=>{n.current.delete(A.id)})}},0)},[t,L,x,k]),M=_react.useCallback.call(void 0, async u=>{let h=T.find(g=>g.id===u);if(!h)return!1;E(u,{status:"removing"});try{if(h.filePath){if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await _crudifybrowser2.default.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let S=g.filter(A=>A.id!==u);return k(S),S}),_optionalChain([w, 'optionalCall', _128 => _128(h)]),!0}catch(g){return E(u,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,k,w]),v=_react.useCallback.call(void 0, ()=>{c([]),k([])},[k]),Y=_react.useCallback.call(void 0, async u=>{let h=T.find(S=>S.id===u);if(!h||h.status!=="error"||!h.file){_chunkX3JFRSEAjs.a.warn("Cannot retry: file not found or no original file");return}E(u,{status:"pending",progress:0,errorMessage:void 0});let g=x(h,h.file);n.current.set(u,g),g.finally(()=>{n.current.delete(u)})},[T,E,x]),_=_react.useCallback.call(void 0, async()=>{let u=Array.from(n.current.values());u.length>0&&await Promise.allSettled(u)},[]),X=u=>{let h=_optionalChain([u, 'access', _129 => _129.split, 'call', _130 => _130("."), 'access', _131 => _131.pop, 'call', _132 => _132(), 'optionalAccess', _133 => _133.toLowerCase, 'call', _134 => _134()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},K=_react.useCallback.call(void 0, u=>{let h=u.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,R=A.includes("/public/")||A.startsWith("public/")?"public":"private",D=g.contentType||X(g.name);return{id:De(),name:g.name,size:g.size||0,contentType:D,status:"completed",progress:100,filePath:g.filePath,visibility:R,createdAt:Date.now()}});c(h),k(h)},[k]),ae=_react.useCallback.call(void 0, async u=>{let h=T.find(g=>g.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!oe.isInitialized())return null;let g=await _crudifybrowser2.default.getFileUrl({filePath:h.filePath,expiresIn:3600});return g.success&&_optionalChain([g, 'access', _135 => _135.data, 'optionalAccess', _136 => _136.url])?g.data.url:null}catch (e7){return null}},[T]),Fe=_react.useMemo.call(void 0, ()=>T.some(u=>u.status==="uploading"||u.status==="pending"),[T]),ze=_react.useMemo.call(void 0, ()=>T.filter(u=>u.status==="uploading"||u.status==="pending").length,[T]),Ke=_react.useMemo.call(void 0, ()=>T.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[T]),{isValid:Ue,validationError:Oe}=_react.useMemo.call(void 0, ()=>{let u=T.filter(g=>g.status==="completed").length;return u<o?{isValid:!1,validationError:o===1?"At least one file is required":`At least ${o} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,o,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:P,removeFile:M,clearFiles:v,retryUpload:Y,isValid:Ue,validationError:Oe,waitForUploads:_,completedFilePaths:Ke,initializeFiles:K,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};exports.a = j; exports.b = Ie; exports.c = be; exports.d = I; exports.e = Q; exports.f = ke; exports.g = de; exports.h = we; exports.i = lt; exports.j = ai; exports.k = ct; exports.l = yt; exports.m = Tt; exports.n = ye; exports.o = oe; exports.p = Nt;
|
package/dist/chunk-UJD6SL66.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var p=r=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+r+"=([^;]+)"));return e?e[2]:null};var C=[/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],A="prod",S="CrudifyUI",v=class{constructor(){this.env=A,this.prefix=S}sanitize(e){let t=e;for(let n of C)t=t.replace(n,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[n,o]of Object.entries(e))if(o!=null)if(n==="userId"&&typeof o=="string")t[n]=o.length>8?`${o.substring(0,8)}***`:o;else if(n==="email"&&typeof o=="string"){let[s,l]=o.split("@");t[n]=s&&l?`${s.substring(0,3)}***@${l}`:"[REDACTED]"}else typeof o=="string"?t[n]=this.sanitize(o):typeof o=="object"&&o!==null?t[n]=this.sanitizeContext(o):t[n]=o;return t}shouldLog(e){return!((this.env==="prod"||this.env==="production"||this.env==="api")&&e!=="error")}log(e,t,n){if(!this.shouldLog(e))return;let o=this.sanitize(t),s=n?this.sanitizeContext(n):void 0,l={timestamp:new Date().toISOString(),level:e,environment:this.env,service:this.prefix,message:o,...s&&Object.keys(s).length>0&&{context:s}},u=JSON.stringify(l);switch(e){case"error":console.error(u);break;case"warn":console.warn(u);break;case"info":console.info(u);break;case"debug":console.log(u);break}}error(e,t){let n;t instanceof Error?n={errorName:t.name,errorMessage:t.message,stack:t.stack}:n=t,this.log("error",e,n)}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.env}setEnvironment(e){this.env=e,A=e}},i=new v;function O(r={}){let{publicApiKey:e,env:t,appName:n,logo:o,loginActions:s,featureKeys:l,enableDebug:u=!1}=r,c={configSource:"none"},h=p("publicApiKey");if(h){let a=p("environment"),d=p("appName"),y=p("logo"),R=p("loginActions"),T=p("featureKeys"),I=p("theme");return c={publicApiKey:decodeURIComponent(h),env:a&&["dev","stg","api","prod"].includes(a)?a:"prod",appName:d?decodeURIComponent(d):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(f=>f.trim()).filter(Boolean):void 0,featureKeys:T?decodeURIComponent(T).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:I?(()=>{try{return JSON.parse(decodeURIComponent(I))}catch(f){u&&i.warn("[ConfigResolver] Failed to parse theme cookie",f instanceof Error?{errorMessage:f.message}:{message:String(f)});return}})():void 0,configSource:"cookies"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c),c}return e&&(c={publicApiKey:e,env:t||"prod",appName:n,logo:o,loginActions:s,featureKeys:l,configSource:"props"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c)),c}function K(r={}){return O(r)}var w=["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 E(r,e){let{translateFn:t,currentLanguage:n,enableDebug:o}=e;o&&i.debug(`[ErrorTranslation] Translating error code: ${r} (lang: ${n||"unknown"})`);let s=r.toUpperCase(),l=D[s],u=w.map(a=>a.replace("{category}",l||"general").replace("{code}",s));o&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:u});for(let a of u){let d=t(a);if(o&&i.debug(`[ErrorTranslation] Checking key: "${a}" -> result: "${d}" (same as key: ${d===a})`),d&&d!==a)return o&&i.debug(`[ErrorTranslation] Found translation at key: ${a} = "${d}"`),d}let c=L[s];if(c)return o&&i.debug(`[ErrorTranslation] Using default message: "${c}"`),c;let h=s.replace(/_/g," ").toLowerCase().replace(/\b\w/g,a=>a.toUpperCase());return o&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${h}"`),h}function _(r,e){return r.map(t=>E(t,e))}function k(r,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:r});let n=E(r.code,e);return n!==r.code.toUpperCase()&&n!==r.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${n}"`),r.field?`${r.field}: ${n}`:n):r.message&&!r.message.includes("Error:")&&r.message.length>0&&r.message!==r.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${r.message}"`),r.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${n}"`),r.field?`${r.field}: ${n}`:n)}function V(r,e={}){let t={translateFn:r,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:n=>E(n,t),translateErrorCodes:n=>_(n,t),translateError:n=>k(n,t),translateApiError:n=>n?.data?.response?.status?E(n.data.response.status,t):n?.status?E(n.status,t):n?.code?E(n.code,t):"Unknown error"}}var m=class r{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return r.instance||(r.instance=new r),r.instance}emit(e,t){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&n-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let o={type:e,details:t,timestamp:n};this.listeners.forEach(s=>{try{s(o)}catch(l){i.error("AuthEventBus: Error in listener",l instanceof Error?l:{message:String(l)})}}),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}},B=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 n=e.originalPushState.apply(this,t);return e.notifyListeners(),n},window.history.replaceState=function(...t){let n=e.originalReplaceState.apply(this,t);return e.notifyListeners(),n},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 N=g;var b=r=>{try{let e=r.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],n=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(n))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},X=()=>{try{let r=null;if(r=sessionStorage.getItem("authToken"),r||(r=sessionStorage.getItem("token")),r||(r=localStorage.getItem("authToken")||localStorage.getItem("token")),!r)return null;let e=b(r);return e&&(e.email||e["cognito:username"])||null}catch(r){return i.warn("Failed to get current user email",r instanceof Error?{errorMessage:r.message}:{message:String(r)}),null}},Q=r=>{try{let e=b(r);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch{return!0}};export{i as a,p as b,O as c,K as d,E as e,_ as f,k as g,V as h,B as i,N as j,b as k,X as l,Q as m};
|
package/dist/chunk-X3JFRSEA.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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 p=r=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+r+"=([^;]+)"));return e?e[2]:null};var C=[/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],A="prod",S="CrudifyUI",v=class{constructor(){this.env=A,this.prefix=S}sanitize(e){let t=e;for(let n of C)t=t.replace(n,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[n,o]of Object.entries(e))if(o!=null)if(n==="userId"&&typeof o=="string")t[n]=o.length>8?`${o.substring(0,8)}***`:o;else if(n==="email"&&typeof o=="string"){let[s,l]=o.split("@");t[n]=s&&l?`${s.substring(0,3)}***@${l}`:"[REDACTED]"}else typeof o=="string"?t[n]=this.sanitize(o):typeof o=="object"&&o!==null?t[n]=this.sanitizeContext(o):t[n]=o;return t}shouldLog(e){return!((this.env==="prod"||this.env==="production"||this.env==="api")&&e!=="error")}log(e,t,n){if(!this.shouldLog(e))return;let o=this.sanitize(t),s=n?this.sanitizeContext(n):void 0,l={timestamp:new Date().toISOString(),level:e,environment:this.env,service:this.prefix,message:o,...s&&Object.keys(s).length>0&&{context:s}},u=JSON.stringify(l);switch(e){case"error":console.error(u);break;case"warn":console.warn(u);break;case"info":console.info(u);break;case"debug":console.log(u);break}}error(e,t){let n;t instanceof Error?n={errorName:t.name,errorMessage:t.message,stack:t.stack}:n=t,this.log("error",e,n)}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.env}setEnvironment(e){this.env=e,A=e}},i= exports.a =new v;function O(r={}){let{publicApiKey:e,env:t,appName:n,logo:o,loginActions:s,featureKeys:l,enableDebug:u=!1}=r,c={configSource:"none"},h=p("publicApiKey");if(h){let a=p("environment"),d=p("appName"),y=p("logo"),R=p("loginActions"),T=p("featureKeys"),I=p("theme");return c={publicApiKey:decodeURIComponent(h),env:a&&["dev","stg","api","prod"].includes(a)?a:"prod",appName:d?decodeURIComponent(d):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(f=>f.trim()).filter(Boolean):void 0,featureKeys:T?decodeURIComponent(T).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:I?(()=>{try{return JSON.parse(decodeURIComponent(I))}catch(f){u&&i.warn("[ConfigResolver] Failed to parse theme cookie",f instanceof Error?{errorMessage:f.message}:{message:String(f)});return}})():void 0,configSource:"cookies"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c),c}return e&&(c={publicApiKey:e,env:t||"prod",appName:n,logo:o,loginActions:s,featureKeys:l,configSource:"props"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c)),c}function K(r={}){return O(r)}var w=["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 E(r,e){let{translateFn:t,currentLanguage:n,enableDebug:o}=e;o&&i.debug(`[ErrorTranslation] Translating error code: ${r} (lang: ${n||"unknown"})`);let s=r.toUpperCase(),l=D[s],u=w.map(a=>a.replace("{category}",l||"general").replace("{code}",s));o&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:u});for(let a of u){let d=t(a);if(o&&i.debug(`[ErrorTranslation] Checking key: "${a}" -> result: "${d}" (same as key: ${d===a})`),d&&d!==a)return o&&i.debug(`[ErrorTranslation] Found translation at key: ${a} = "${d}"`),d}let c=L[s];if(c)return o&&i.debug(`[ErrorTranslation] Using default message: "${c}"`),c;let h=s.replace(/_/g," ").toLowerCase().replace(/\b\w/g,a=>a.toUpperCase());return o&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${h}"`),h}function _(r,e){return r.map(t=>E(t,e))}function k(r,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:r});let n=E(r.code,e);return n!==r.code.toUpperCase()&&n!==r.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${n}"`),r.field?`${r.field}: ${n}`:n):r.message&&!r.message.includes("Error:")&&r.message.length>0&&r.message!==r.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${r.message}"`),r.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${n}"`),r.field?`${r.field}: ${n}`:n)}function V(r,e={}){let t={translateFn:r,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:n=>E(n,t),translateErrorCodes:n=>_(n,t),translateError:n=>k(n,t),translateApiError:n=>_optionalChain([n, 'optionalAccess', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.status])?E(n.data.response.status,t):_optionalChain([n, 'optionalAccess', _5 => _5.status])?E(n.status,t):_optionalChain([n, 'optionalAccess', _6 => _6.code])?E(n.code,t):"Unknown error"}}var m=class r{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return r.instance||(r.instance=new r),r.instance}emit(e,t){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&n-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let o={type:e,details:t,timestamp:n};this.listeners.forEach(s=>{try{s(o)}catch(l){i.error("AuthEventBus: Error in listener",l instanceof Error?l:{message:String(l)})}}),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}},B= 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 n=e.originalPushState.apply(this,t);return e.notifyListeners(),n},window.history.replaceState=function(...t){let n=e.originalReplaceState.apply(this,t);return e.notifyListeners(),n},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', _7 => _7.instance, 'optionalAccess', _8 => _8.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var N=g;var b=r=>{try{let e=r.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],n=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(n))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},X= exports.l =()=>{try{let r=null;if(r=sessionStorage.getItem("authToken"),r||(r=sessionStorage.getItem("token")),r||(r=localStorage.getItem("authToken")||localStorage.getItem("token")),!r)return null;let e=b(r);return e&&(e.email||e["cognito:username"])||null}catch(r){return i.warn("Failed to get current user email",r instanceof Error?{errorMessage:r.message}:{message:String(r)}),null}},Q= exports.m =r=>{try{let e=b(r);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 = p; exports.c = O; exports.d = K; exports.e = E; exports.f = _; exports.g = k; exports.h = V; exports.i = B; exports.j = N; exports.k = b; exports.l = X; exports.m = Q;
|
package/dist/chunk-YLKGZV2N.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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 _chunkSEDLJT7Gjs = require('./chunk-SEDLJT7G.js');var _chunkX3JFRSEAjs = require('./chunk-X3JFRSEA.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var J=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=_chunkSEDLJT7Gjs.j.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, a&&T),[_,p]=_react.useState.call(void 0, null),u=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),m=_react.useRef.call(void 0, 0),l=_react.useRef.call(void 0, 0),x=_react.useCallback.call(void 0, ()=>c&&(c.email||c["cognito:username"])||null,[c]),P=_react.useCallback.call(void 0, ()=>{d(null),p(null),A(!1),l.current=0},[]),w=_react.useCallback.call(void 0, async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await _crudifybrowser2.default.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(_optionalChain([r, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.data]))try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e2){}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(_optionalChain([r, 'access', _5 => _5.data, 'optionalAccess', _6 => _6.data, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.data]))try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch (e3){}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(_optionalChain([t, 'access', _9 => _9.message, 'optionalAccess', _10 => _10.includes, 'call', _11 => _11("Network Error")])||_optionalChain([t, 'access', _12 => _12.message, 'optionalAccess', _13 => _13.includes, 'call', _14 => _14("Failed to fetch")]))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return _react.useEffect.call(void 0, ()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};var te=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=_chunkSEDLJT7Gjs.j.call(void 0, ),u=_react.useCallback.call(void 0, m=>{m?_chunkX3JFRSEAjs.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=_optionalChain([g, 'optionalAccess', _15 => _15.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:_optionalChain([g, 'optionalAccess', _16 => _16.accessToken])||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};var ae=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=_chunkSEDLJT7Gjs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!a&&!N,[S,a,N]),c=_react.useCallback.call(void 0, async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItems(o,m||{},l)),[R]),d=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.readItem(o,m,l)),[R]),y=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.createItem(o,m,l)),[R]),A=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.updateItem(o,m,l)),[R]),_=_react.useCallback.call(void 0, async(o,m,l)=>(await R(),await _crudifybrowser2.default.deleteItem(o,m,l)),[R]),p=_react.useCallback.call(void 0, async(o,m)=>(await R(),await _crudifybrowser2.default.transaction(o,m)),[R]),u=_react.useCallback.call(void 0, async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};var Q={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:a}=_chunkSEDLJT7Gjs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=_react.useCallback.call(void 0, e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _17 => _17.errors, 'access', _18 => _18._transaction, 'optionalAccess', _19 => _19.includes, 'call', _20 => _20("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _21 => _21.errors, 'access', _22 => _22._error, 'optionalAccess', _23 => _23.includes, 'call', _24 => _24("TOO_MANY_REQUESTS")]))||!e.success&&_optionalChain([e, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.status])==="TOO_MANY_REQUESTS"),[]),y=_react.useCallback.call(void 0, (e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),_=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=_react.useCallback.call(void 0, (e,i,r)=>{let t=_optionalChain([r, 'optionalAccess', _28 => _28.key])&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=_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 r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(_optionalChain([r, 'optionalAccess', _29 => _29.includes, 'call', _30 => _30("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(_optionalChain([s, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.errorCode])){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(_optionalChain([s, 'optionalAccess', _33 => _33.response, 'optionalAccess', _34 => _34.data]))return s.response.data}if(_optionalChain([n, 'optionalAccess', _35 => _35.response, 'optionalAccess', _36 => _36.message])){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch (e4){return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Q[e.errorCode]?Q[e.errorCode]:"error",[]),m=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _37 => _37.actionConfig]),s=_optionalChain([n, 'optionalAccess', _38 => _38.key])||"create",f=_optionalChain([n, 'optionalAccess', _39 => _39.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.updateItem(e,i,r),n=_optionalChain([r, 'optionalAccess', _40 => _40.skipNotifications])===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=_optionalChain([r, 'optionalAccess', _41 => _41.actionConfig]),f=_optionalChain([s, 'optionalAccess', _42 => _42.key])||"update",O=_optionalChain([s, 'optionalAccess', _43 => _43.moduleKey])||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=_optionalChain([r, 'optionalAccess', _44 => _44.actionConfig]),s=_optionalChain([n, 'optionalAccess', _45 => _45.key])||"delete",f=_optionalChain([n, 'optionalAccess', _46 => _46.moduleKey])||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=_react.useCallback.call(void 0, async(e,i,r)=>{let t=await _crudifybrowser2.default.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=_react.useCallback.call(void 0, async(e,i)=>{let r=await _crudifybrowser2.default.transaction(e,i),t=_optionalChain([i, 'optionalAccess', _47 => _47.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(_optionalChain([i, 'optionalAccess', _48 => _48.actionConfig])?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
|