@nocios/crudify-ui 4.4.88 → 4.4.92
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/coverage/base.css +224 -0
- package/coverage/block-navigation.js +87 -0
- package/coverage/coverage-final.json +68 -0
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +431 -0
- package/coverage/prettify.css +1 -0
- package/coverage/prettify.js +2 -0
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +210 -0
- package/dist/{CrudiaMarkdownField-D-VooBtq.d.mts → CrudiaMarkdownField-CKuypna1.d.mts} +31 -1
- package/dist/{CrudiaMarkdownField-C30enyF9.d.ts → CrudiaMarkdownField-Cy8VBvkO.d.ts} +31 -1
- package/dist/chunk-DXIXGRHJ.mjs +1 -0
- package/dist/chunk-E4ILHUTV.js +1 -0
- package/dist/chunk-HO44TY3Z.mjs +1 -0
- package/dist/chunk-KCWS6BRD.js +1 -0
- package/dist/{chunk-FXGNV35X.js → chunk-OTCV6Y6D.js} +1 -1
- package/dist/{chunk-MWJHOPSA.mjs → chunk-QJI47CHZ.mjs} +1 -1
- 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/hooks.d.mts +1 -1
- package/dist/hooks.d.ts +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-C1A99cUn.d.ts → index-By0tDIvO.d.ts} +42 -5
- package/dist/{index-COUyZtYr.d.mts → index-e0fEu7Sq.d.mts} +42 -5
- package/dist/index.d.mts +45 -3
- package/dist/index.d.ts +45 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-GDED4O5Q.mjs +0 -1
- package/dist/chunk-HXT7TEWJ.js +0 -1
- package/dist/chunk-TZK23M4A.mjs +0 -1
- package/dist/chunk-XBRMX26N.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ge=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){_chunk34FAL7YWjs.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}},ee= exports.a =ge.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ie=_react.createContext.call(void 0, void 0),Se= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[s,l]=_react.useState.call(void 0, null),[f,T]=_react.useState.call(void 0, !1),[P,A]=_react.useState.call(void 0, ""),[L,c]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){l("No publicApiKey provided"),t(!1),T(!1);return}let d=`${r.publicApiKey}-${r.env}`;if(d===P&&f){t(!1);return}(async()=>{t(!0),l(null),T(!1);try{_crudifybrowser2.default.config(r.env||"prod");let E=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(c(E),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")T(!0),A(d),E.apiEndpointAdmin&&E.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:E.apiEndpointAdmin,apiKey:E.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(E){let I=E instanceof Error?E.message:"Failed to initialize Crudify";_chunk34FAL7YWjs.a.error("[CrudifyProvider] Initialization error",E instanceof Error?E:{message:String(E)}),l(I),T(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,P,f]);let o={crudify:f?_crudifybrowser2.default:null,isLoading:e,error:s,isInitialized:f,adminCredentials:L};return _jsxruntime.jsx.call(void 0, Ie.Provider,{value:o,children:i})},xe= exports.c =()=>{let r=_react.useContext.call(void 0, Ie);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 m=class m{static setStorageType(i){m.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(m.encryptionKey)return m.encryptionKey;let i=window.localStorage;if(!i)return m.encryptionKey=m.generateEncryptionKey(),m.encryptionKey;try{let e=i.getItem(m.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=m.generateEncryptionKey(),i.setItem(m.ENCRYPTION_KEY_STORAGE,e)),m.encryptionKey=e,e}catch (e2){return _chunk34FAL7YWjs.a.warn("Crudify: Cannot persist encryption key, using temporary key"),m.encryptionKey=m.generateEncryptionKey(),m.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 m.storageType==="none"?null:m.isStorageAvailable(m.storageType)?window[m.storageType]:(_chunk34FAL7YWjs.a.warn(`Crudify: ${m.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=m.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return _chunk34FAL7YWjs.a.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=m.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return _chunk34FAL7YWjs.a.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=m.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},s=m.encrypt(JSON.stringify(t));e.setItem(m.TOKEN_KEY,s),_chunk34FAL7YWjs.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunk34FAL7YWjs.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=m.getStorage();if(!i)return null;try{let e=i.getItem(m.TOKEN_KEY);if(!e)return null;let t=m.decrypt(e),s=JSON.parse(t);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(_chunk34FAL7YWjs.a.warn("Crudify: Incomplete token data found, clearing storage"),m.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(_chunk34FAL7YWjs.a.info("Crudify: Refresh token expired, clearing storage"),m.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(e){return _chunk34FAL7YWjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),m.clearTokens(),null}}static clearTokens(){let i=m.getStorage();if(i)try{i.removeItem(m.TOKEN_KEY),_chunk34FAL7YWjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunk34FAL7YWjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{m.clearTokens(),m.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(m.ENCRYPTION_KEY_STORAGE),_chunk34FAL7YWjs.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunk34FAL7YWjs.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return m.getTokens()!==null}static getExpirationInfo(){let i=m.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=m.getTokens();if(!t){_chunk34FAL7YWjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}m.saveTokens({...t,accessToken:i,expiresAt:e})}static createSyncEvent(i,e,t){return{type:i,tokens:e,hadPreviousTokens:t}}static subscribeToChanges(i){let e=t=>{if(t.key!==m.TOKEN_KEY)return;let s=t.oldValue!==null&&t.oldValue!=="";if(t.newValue===null){_chunk34FAL7YWjs.a.debug("Crudify: Tokens removed in another tab"),i(null,m.SYNC_EVENTS.TOKENS_CLEARED,s);return}if(t.newValue){_chunk34FAL7YWjs.a.debug("Crudify: Tokens updated in another tab");let l=m.getTokens();i(l,m.SYNC_EVENTS.TOKENS_UPDATED,s)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};m.TOKEN_KEY="crudify_tokens",m.ENCRYPTION_KEY_STORAGE="crudify_enc_key",m.encryptionKey=null,m.storageType="localStorage",m.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"};var b=m;var te=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},b.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunk34FAL7YWjs.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=b.getTokens();e?b.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):b.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 s=b.getTokens(),l=t.data,f={accessToken:l.token,refreshToken:l.refreshToken,expiresAt:l.expiresAt,refreshExpiresAt:l.refreshExpiresAt,apiEndpointAdmin:_optionalChain([s, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([s, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return b.saveTokens(f),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(f)]),{success:!0,tokens:f,data:l}}catch(t){return _chunk34FAL7YWjs.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(),b.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),b.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=b.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"),b.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 s=b.getTokens();return s&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(s)]),!0}return b.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),b.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||b.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=b.getExpirationInfo(),t=b.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:b.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),b.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=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return b.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),b.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"),_chunk34FAL7YWjs.i.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(b.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunk34FAL7YWjs.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"),_chunk34FAL7YWjs.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,s=this.config.enableLogging?"debug":"none",l=await _crudifybrowser2.default.init(t,s);if(l&&l.success===!1&&l.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(l.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw _chunk34FAL7YWjs.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(s=>s.errorType==="Unauthorized"||_optionalChain([s, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([s, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([s, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([s, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([s, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([s, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([s, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([s, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([s, '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 s=Object.values(i.errors).flat().find(l=>typeof l=="string"&&(l.includes("NOT_AUTHORIZED")||l.includes("TOKEN_REFRESH_FAILED")||l.includes("TOKEN_HAS_EXPIRED")||l.includes("PLEASE_LOGIN")||l.includes("Unauthorized")||l.includes("UNAUTHENTICATED")||l.includes("SESSION_EXPIRED")||l.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&&_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=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(){b.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk34FAL7YWjs.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().map(String).join(", "):"Authentication failed":"Unknown error"}};function Pe(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=te.getInstance(),s=_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(E=>({...E,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(E=>({...E,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let o=t.isAuthenticated(),d=t.getTokenInfo();e(n=>({...n,isAuthenticated:o,isInitialized:!0,isLoading:!1,tokens:d.crudifyTokens.accessToken?{accessToken:d.crudifyTokens.accessToken,refreshToken:d.crudifyTokens.refreshToken,expiresAt:d.crudifyTokens.expiresAt,refreshExpiresAt:d.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let o=c instanceof Error?c.message:"Initialization failed";_chunk34FAL7YWjs.a.error("[useSession] Initialize failed",c instanceof Error?c:{message:o}),e(d=>({...d,isLoading:!1,isInitialized:!0,error:o}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),l=_react.useCallback.call(void 0, async(c,o)=>{e(d=>({...d,isLoading:!0,error:null}));try{let d=await t.login(c,o);return d.success&&d.tokens?e(n=>({...n,isAuthenticated:!0,tokens:d.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),d}catch(d){let n=d instanceof Error?d.message:"Login failed";_chunk34FAL7YWjs.a.error("[useSession] Login error",d instanceof Error?d:{message:n});let E=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(I=>({...I,isAuthenticated:!1,tokens:null,isLoading:!1,error:E?null:n})),{success:!1,error:n}}},[t]),f=_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(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),T=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let o=t.getTokenInfo();e(d=>({...d,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(o=>({...o,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),P=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),A=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{s()},[s]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let c=_chunk34FAL7YWjs.j.getInstance(),o=()=>{t.updateLastActivity()},d=c.subscribe(o);window.addEventListener("popstate",o);let n=()=>{let R=t.getTokenInfo().crudifyTokens.expiresIn||0;return R<300*1e3?30*1e3:R<1800*1e3?60*1e3:120*1e3},E,I=()=>{let S=n();E=setTimeout(async()=>{if(t.isRefreshing()){I();return}let R=t.getTokenInfo(),x=R.crudifyTokens.expiresIn||0,C=((R.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=C)if(e(z=>({...z,isLoading:!0})),await t.refreshTokens()){let z=t.getTokenInfo();e(ue=>({...ue,isLoading:!1,tokens:z.crudifyTokens.accessToken?{accessToken:z.crudifyTokens.accessToken,refreshToken:z.crudifyTokens.refreshToken,expiresAt:z.crudifyTokens.expiresAt,refreshExpiresAt:z.crudifyTokens.refreshExpiresAt}:null}))}else e(z=>({...z,isLoading:!1,isAuthenticated:!1,tokens:null}));let v=t.getTimeSinceLastActivity(),X=1800*1e3;v>X?await f():I()},S)};return I(),()=>{clearTimeout(E),window.removeEventListener("popstate",o),d()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),_react.useEffect.call(void 0, ()=>{let c=_chunk34FAL7YWjs.i.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(d=>({...d,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(E=>({...E,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else _chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(d){_chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:d instanceof Error?d.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(e(d=>({...d,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([o, '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=b.subscribeToChanges((o,d,n)=>{d===b.SYNC_EVENTS.TOKENS_CLEARED?n&&i.isAuthenticated?(_chunk34FAL7YWjs.a.debug("[useSession] Cross-tab logout detected"),e(E=>({...E,isAuthenticated:!1,tokens:null})),_optionalChain([r, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()])):n&&e(E=>({...E,isAuthenticated:!1,tokens:null})):d===b.SYNC_EVENTS.TOKENS_UPDATED&&o&&(_chunk34FAL7YWjs.a.debug("[useSession] Cross-tab login/refresh detected"),e(E=>({...E,tokens:o,isAuthenticated:!0,error:null})))});return()=>c()},[i.isAuthenticated,r.onSessionExpired]);let L=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:l,logout:f,refreshTokens:T,clearError:P,getTokenInfo:A,updateActivity:L,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 Ne=_react.createContext.call(void 0, null),Ei=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}),pe= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:l=!1})=>{let[f,T]=_react.useState.call(void 0, []),P=_react.useCallback.call(void 0, (o,d="info",n)=>{if(!s)return"";if(!o||typeof o!="string")return _chunk34FAL7YWjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(_chunk34FAL7YWjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let E=_uuid.v4.call(void 0, ),I={id:E,message:o,severity:d,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _80 => _80.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _81 => _81.allowHtml]), () => (l))};return T(S=>[...S.length>=i?S.slice(-(i-1)):S,I]),E},[i,e,s,l]),A=_react.useCallback.call(void 0, o=>{T(d=>d.filter(n=>n.id!==o))},[]),L=_react.useCallback.call(void 0, ()=>{T([])},[]),c={showNotification:P,hideNotification:A,clearAllNotifications:L};return _jsxruntime.jsxs.call(void 0, Ne.Provider,{value:c,children:[r,s&&_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:f.map(o=>_jsxruntime.jsx.call(void 0, vi,{notification:o,onClose:()=>A(o.id)},o.id))})})]})},vi=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),s=_react.useCallback.call(void 0, (l,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let l=setTimeout(()=>{s()},r.autoHideDuration);return()=>clearTimeout(l)}},[r.autoHideDuration,r.persistent,s]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:s,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:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:Ei(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},Re= exports.h =()=>{let r=_react.useContext.call(void 0, Ne);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var De=_react.createContext.call(void 0, void 0);function Ce({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:s={}}){let l;try{let{showNotification:n}=Re();l=n}catch (e5){}let f={};try{let n=xe();n.isInitialized&&n.adminCredentials&&(f=n.adminCredentials)}catch (e6){}let T=_react.useMemo.call(void 0, ()=>{let n=_chunk34FAL7YWjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _82 => _82.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _83 => _83.env]),enableDebug:_optionalChain([i, 'optionalAccess', _84 => _84.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _85 => _85.enableLogging])]),P=_react2.default.useMemo(()=>({...i,showNotification:l,apiEndpointAdmin:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:T.publicApiKey,env:T.env,onSessionExpired:()=>{_optionalChain([i, 'access', _86 => _86.onSessionExpired, 'optionalCall', _87 => _87()])}}),[i,l,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,T]),A=Pe(P),L=_react.useMemo.call(void 0, ()=>{let n=_chunk34FAL7YWjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _88 => _88.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _89 => _89.env]),appName:_optionalChain([e, 'optionalAccess', _90 => _90.appName]),logo:_optionalChain([e, 'optionalAccess', _91 => _91.logo]),loginActions:_optionalChain([e, 'optionalAccess', _92 => _92.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _93 => _93.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _94 => _94.enableLogging])]),c=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([A, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken])||!A.isAuthenticated)return null;try{let n=_chunk34FAL7YWjs.k.call(void 0, A.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let E={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(I=>{["sub","email","subscriber"].includes(I)||(E[I]=n[I])}),E}}catch(n){_chunk34FAL7YWjs.a.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[_optionalChain([A, 'access', _97 => _97.tokens, 'optionalAccess', _98 => _98.accessToken]),A.isAuthenticated]),o={...A,sessionData:c,config:L},d={enabled:t,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, De.Provider,{value:o,children:r})}function xt(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.allowHtml])||!1};return _optionalChain([r, 'access', _107 => _107.config, 'optionalAccess', _108 => _108.publicApiKey])?_jsxruntime.jsx.call(void 0, Se,{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, pe,{...i,children:_jsxruntime.jsx.call(void 0, Ce,{...r})})}):_jsxruntime.jsx.call(void 0, pe,{...i,children:_jsxruntime.jsx.call(void 0, Ce,{...r})})}function Ii(){let r=_react.useContext.call(void 0, De);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Pt(){let r=Ii();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 Ft=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[s,l]=_react.useState.call(void 0, null),[f,T]=_react.useState.call(void 0, !1),[P,A]=_react.useState.call(void 0, null),[L,c]=_react.useState.call(void 0, {}),o=_react.useRef.call(void 0, null),d=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),E=_react.useRef.call(void 0, 0),I=_react.useCallback.call(void 0, ()=>{l(null),A(null),T(!1),c({})},[]),S=_react.useCallback.call(void 0, async()=>{let R=_chunk34FAL7YWjs.l.call(void 0, );if(!R){d.current&&(A("No user email available"),T(!1));return}o.current&&o.current.abort();let x=new AbortController;o.current=x;let K=++n.current;try{d.current&&(T(!0),A(null));let U=await _crudifybrowser2.default.readItems("users",{filter:{email:R},pagination:{limit:1}});if(K===n.current&&d.current&&!x.signal.aborted){let C=U.data;if(U.success&&C&&C.length>0){let v=C[0];l(v);let X={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((_,z)=>({..._,[z]:v[z]}),{})}};c(X),A(null),E.current=0}else A("User profile not found"),l(null),c({})}}catch(U){if(K===n.current&&d.current){let C=U;if(C.name==="AbortError")return;e&&E.current<t&&(_optionalChain([C, 'access', _109 => _109.message, 'optionalAccess', _110 => _110.includes, 'call', _111 => _111("Network Error")])||_optionalChain([C, 'access', _112 => _112.message, 'optionalAccess', _113 => _113.includes, 'call', _114 => _114("Failed to fetch")]))?(E.current++,setTimeout(()=>{d.current&&S()},1e3*E.current)):(A("Failed to load user profile"),l(null),c({}))}}finally{K===n.current&&d.current&&T(!1),o.current===x&&(o.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&S()},[i,S]),_react.useEffect.call(void 0, ()=>(d.current=!0,()=>{d.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:f,error:P,extendedData:L,refreshProfile:S,clearProfile:I}};var Ut=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:s}=i,{prefix:l,padding:f=0,separator:T=""}=r,[P,A]=_react.useState.call(void 0, ""),[L,c]=_react.useState.call(void 0, !1),[o,d]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),E=_react.useCallback.call(void 0, x=>{let K=String(x).padStart(f,"0");return`${l}${T}${K}`},[l,f,T]),I=_react.useCallback.call(void 0, async()=>{c(!0),d(null);try{let x=await _crudifybrowser2.default.getNextSequence(l),K=x.data;if(x.success&&_optionalChain([K, 'optionalAccess', _115 => _115.value])){let U=E(K.value);A(U),_optionalChain([t, 'optionalCall', _116 => _116(U)])}else{let U=_optionalChain([x, 'access', _117 => _117.errors, 'optionalAccess', _118 => _118._error, 'optionalAccess', _119 => _119[0]])||"Failed to generate code";d(U),_optionalChain([s, 'optionalCall', _120 => _120(U)])}}catch(x){let K=x instanceof Error?x.message:"Unknown error";d(K),_optionalChain([s, 'optionalCall', _121 => _121(K)])}finally{c(!1)}},[l,E,t,s]),S=_react.useCallback.call(void 0, async()=>{await I()},[I]),R=_react.useCallback.call(void 0, ()=>{d(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!P&&!n.current&&(n.current=!0,I())},[e,P,I]),{value:P,loading:L,error:o,regenerate:S,clearError:R}};var Ee=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:l,requestedBy:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunk34FAL7YWjs.a.warn(`[CrudifyInitialization] ${f} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _122 => _122.state, 'access', _123 => _123.publicApiKey, 'optionalAccess', _124 => _124.slice, 'call', _125 => _125(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return l&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(l&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(l),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){l&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}l&&_chunk34FAL7YWjs.a.warn(`[CrudifyInitialization] ${f} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunk34FAL7YWjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),l&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,this.initializationPromise=this.performInitialization(t,s,l);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=s,this.state.error=null,l&&_chunk34FAL7YWjs.a.info(`[CrudifyInitialization] Successfully initialized by ${f} (${e} priority)`)}catch(T){throw this.state.status="ERROR",this.state.error=T instanceof Error?T:new Error(String(T)),this.initializationPromise=null,_chunk34FAL7YWjs.a.error(`[CrudifyInitialization] Initialization failed for ${f}`,T instanceof Error?T:{message:String(T)}),T}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let s=0,l=setInterval(()=>{if(s+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(l),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){s=0;return}s>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(l),i&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let s=_crudifybrowser2.default.getTokenData();if(s&&s.endpoint){t&&_chunk34FAL7YWjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let l=t?"debug":"none",f=await _crudifybrowser2.default.init(i,l);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`);f.apiEndpointAdmin&&f.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:f.apiEndpointAdmin,apiKey:f.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}}},Q= exports.o =Ee.getInstance();var Ke=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,Ci=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}`},ve=(r,i)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let e=new URL(r);return e.pathname.startsWith("/")?e.pathname.substring(1):e.pathname}catch (e7){if(i&&r.startsWith(i))return r.substring(i.length)}return i&&r.startsWith(i)?r.substring(i.length):r},Bt= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:s=0,visibility:l="private",onUploadComplete:f,onUploadError:T,onFileRemoved:P,onFilesChange:A,mode:L="edit"}=r,[c,o]=_react.useState.call(void 0, []),[d,n]=_react.useState.call(void 0, !1),[E,I]=_react.useState.call(void 0, !1),[S,R]=_react.useState.call(void 0, []),x=_react.useRef.call(void 0, new Map),K=_react.useCallback.call(void 0, ()=>{n(!0)},[]),U=_react.useCallback.call(void 0, ()=>{I(!0),n(!0)},[]),C=_react.useCallback.call(void 0, (a,g)=>{o(u=>u.map(h=>h.id===a?{...h,...g}:h))},[]),v=_react.useCallback.call(void 0, a=>{_optionalChain([A, 'optionalCall', _126 => _126(a)])},[A]),X=_react.useCallback.call(void 0, a=>i&&i.length>0&&!i.includes(a.type)?{valid:!1,error:`File type not allowed: ${a.type}`}:a.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),_=_react.useCallback.call(void 0, async(a,g)=>{try{if(!Q.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let u=Ci(g.name),y=await _crudifybrowser2.default.generateSignedUrl({fileName:u,contentType:g.type,visibility:l});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:w,s3Key:k,publicUrl:H}=h;if(!w||!k)throw new Error("Incomplete signed URL response");let $=k.indexOf("/"),ii=$>0?k.substring($+1):k;C(a.id,{status:"uploading",progress:0}),await new Promise((de,Y)=>{let O=new XMLHttpRequest;O.upload.addEventListener("progress",G=>{if(G.lengthComputable){let ri=Math.round(G.loaded/G.total*100);C(a.id,{progress:ri})}}),O.addEventListener("load",()=>{O.status>=200&&O.status<300?de():Y(new Error(`Upload failed with status ${O.status}`))}),O.addEventListener("error",()=>{Y(new Error("Network error during upload"))}),O.addEventListener("abort",()=>{Y(new Error("Upload cancelled"))}),O.open("PUT",w),O.setRequestHeader("Content-Type",g.type),O.send(g)});let ti={status:"completed",progress:100,filePath:ii,visibility:l,publicUrl:l==="public"?H:void 0,file:void 0};o(de=>{let Y=de.map(G=>G.id===a.id?{...G,...ti}:G);v(Y);let O=Y.find(G=>G.id===a.id);return O&&_optionalChain([f, 'optionalCall', _127 => _127(O)]),Y})}catch(u){let y=u instanceof Error?u.message:"Unknown error";C(a.id,{status:"error",progress:0,errorMessage:y}),o(h=>{let w=h.find(k=>k.id===a.id);return w&&_optionalChain([T, 'optionalCall', _128 => _128(w,y)]),h})}},[C,f,T,l]),z=_react.useCallback.call(void 0, async a=>{let g=Array.from(a),u=[];o(y=>{if(t!==void 0){let k=y.filter($=>$.status!=="pendingDeletion"&&$.status!=="error").length,H=t-k;if(H<=0)return _chunk34FAL7YWjs.a.warn(`File limit of ${t} already reached`),y;g.length>H&&(g=g.slice(0,H),_chunk34FAL7YWjs.a.warn(`Only ${H} files will be added to not exceed limit`))}let h=[];for(let k of g){let H=X(k),$={id:Ke(),name:k.name,size:k.size,contentType:k.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?k:void 0,errorMessage:H.error,isExisting:!1};h.push($)}u=h;let w=[...y,...h];return v(w),w}),setTimeout(()=>{let y=u.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let w=_(h,h.file);x.current.set(h.id,w),w.finally(()=>{x.current.delete(h.id)})}},0)},[t,X,_,v]),ue=_react.useCallback.call(void 0, async a=>{let g=c.find(y=>y.id===a);if(!g)return{needsConfirmation:!1,isExisting:!1};let u=g.isExisting===!0;return L==="create"||!u?{needsConfirmation:!0,isExisting:u}:(R(y=>[...y,a]),o(y=>{let h=y.map(k=>k.id===a?{...k,status:"pendingDeletion"}:k),w=h.filter(k=>k.status!=="pendingDeletion");return v(w),h}),{needsConfirmation:!1,isExisting:u})},[c,L,v]),ze=_react.useCallback.call(void 0, async a=>{let g=c.find(u=>u.id===a);if(!g)return{success:!1,error:"File not found"};if(!g.filePath)return o(u=>{let y=u.filter(h=>h.id!==a);return v(y),y}),{success:!0};try{if(!Q.isInitialized())return{success:!1,error:"Crudify not initialized"};let u=ve(g.filePath);return(await _crudifybrowser2.default.disableFile({filePath:u})).success?(o(h=>{let w=h.filter(k=>k.id!==a);return v(w),w}),_optionalChain([P, 'optionalCall', _129 => _129(g)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(u){return{success:!1,error:u instanceof Error?u.message:"Unknown error"}}},[c,v,P]),Ue=_react.useCallback.call(void 0, a=>{let g=c.find(u=>u.id===a);return!g||!g.isExisting?!1:(R(u=>u.filter(y=>y!==a)),o(u=>{let y=u.map(h=>h.id===a?{...h,status:"completed"}:h);return v(y),y}),!0)},[c,v]),Oe=_react.useCallback.call(void 0, ()=>{S.length!==0&&(o(a=>{let g=a.map(u=>S.includes(u.id)?{...u,status:"completed"}:u);return v(g),g}),R([]))},[S,v]),He=_react.useCallback.call(void 0, async()=>{if(S.length===0)return{success:!0,errors:[]};let a=[],g=[];if(!Q.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let u of S){let y=c.find(h=>h.id===u);if(!_optionalChain([y, 'optionalAccess', _130 => _130.filePath])){g.push(u);continue}try{let h=ve(y.filePath);(await _crudifybrowser2.default.disableFile({filePath:h})).success?(g.push(u),_optionalChain([P, 'optionalCall', _131 => _131(y)])):a.push(`Failed to delete ${y.name}`)}catch(h){a.push(`Error deleting ${y.name}: ${h instanceof Error?h.message:"Unknown error"}`)}}return g.length>0&&(o(u=>u.filter(h=>!g.includes(h.id))),R(u=>u.filter(y=>!g.includes(y)))),{success:a.length===0,errors:a}},[c,S,P]),Me=_react.useCallback.call(void 0, ()=>{o([]),v([])},[v]),_e=_react.useCallback.call(void 0, async a=>{let g=c.find(y=>y.id===a);if(!g||g.status!=="error"||!g.file){_chunk34FAL7YWjs.a.warn("Cannot retry: file not found or no original file");return}C(a,{status:"pending",progress:0,errorMessage:void 0});let u=_(g,g.file);x.current.set(a,u),u.finally(()=>{x.current.delete(a)})},[c,C,_]),Ge=_react.useCallback.call(void 0, async()=>{let a=Array.from(x.current.values());a.length>0&&await Promise.allSettled(a)},[]),Ve=a=>{let g=_optionalChain([a, 'access', _132 => _132.split, 'call', _133 => _133("."), 'access', _134 => _134.pop, 'call', _135 => _135(), 'optionalAccess', _136 => _136.toLowerCase, 'call', _137 => _137()])||"";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"}[g]||"application/octet-stream"},$e=_react.useCallback.call(void 0, (a,g)=>{let u=a.map(y=>{let h=ve(y.filePath,g),w=h.includes("/public/")||h.startsWith("public/")?"public":"private",k=y.contentType||Ve(y.name);return{id:Ke(),name:y.name,size:y.size||0,contentType:k,status:"completed",progress:100,filePath:h,visibility:w,createdAt:Date.now(),isExisting:!0}});o(u),v(u)},[v]),Ye=_react.useCallback.call(void 0, async a=>{let g=c.find(u=>u.id===a);if(!g||!g.filePath)return null;if(g.visibility==="public"&&g.publicUrl)return g.publicUrl;try{if(!Q.isInitialized())return null;let u=await _crudifybrowser2.default.getFileUrl({filePath:g.filePath,expiresIn:3600}),y=u.data;return u.success&&_optionalChain([y, 'optionalAccess', _138 => _138.url])?y.url:null}catch (e8){return null}},[c]),We=_react.useMemo.call(void 0, ()=>c.some(a=>a.status==="uploading"||a.status==="pending"),[c]),Be=_react.useMemo.call(void 0, ()=>c.filter(a=>a.status==="uploading"||a.status==="pending").length,[c]),Xe=_react.useMemo.call(void 0, ()=>c.filter(a=>a.status==="completed"&&a.filePath).map(a=>a.filePath),[c]),Z=_react.useMemo.call(void 0, ()=>c.filter(a=>a.status!=="pendingDeletion"),[c]),Ze=_react.useMemo.call(void 0, ()=>Z.filter(a=>a.status==="completed"||a.status==="pending"||a.status==="uploading").length,[Z]),{isValid:qe,validationError:je,validationErrorKey:Je,validationErrorParams:Qe}=_react.useMemo.call(void 0, ()=>{let a=Z.filter(u=>u.status==="completed").length;if(a<s){let u=s===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:u,validationErrorKey:u,validationErrorParams:{count:s}}}return t!==void 0&&a>t?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:t}}:Z.some(u=>u.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[Z,s,t]),ei=S.length>0;return{files:c,activeFiles:Z,activeFileCount:Ze,isUploading:We,pendingCount:Be,addFiles:z,removeFile:ue,deleteFileImmediately:ze,restoreFile:Ue,clearFiles:Me,retryUpload:_e,isValid:qe,validationError:je,validationErrorKey:Je,validationErrorParams:Qe,waitForUploads:Ge,completedFilePaths:Xe,initializeFiles:$e,isTouched:d,markAsTouched:K,isSubmitted:E,markAsSubmitted:U,getPreviewUrl:Ye,pendingDeletions:S,hasPendingDeletions:ei,commitDeletions:He,restorePendingDeletions:Oe}};exports.a = ee; exports.b = Se; exports.c = xe; exports.d = b; exports.e = te; exports.f = Pe; exports.g = pe; exports.h = Re; exports.i = xt; exports.j = Ii; exports.k = Pt; exports.l = Ft; exports.m = Ut; exports.n = Ee; exports.o = Q; exports.p = Bt;
|
|
@@ -1 +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 _chunkXBRMX26Njs = require('./chunk-XBRMX26N.js');var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.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}=_chunkXBRMX26Njs.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}=_chunkXBRMX26Njs.j.call(void 0, ),l=_react.useCallback.call(void 0, g=>{g?_chunk34FAL7YWjs.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}=_chunkXBRMX26Njs.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}=_chunkXBRMX26Njs.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
|
+
"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 _chunkKCWS6BRDjs = require('./chunk-KCWS6BRD.js');var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.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}=_chunkKCWS6BRDjs.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}=_chunkKCWS6BRDjs.j.call(void 0, ),l=_react.useCallback.call(void 0, g=>{g?_chunk34FAL7YWjs.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}=_chunkKCWS6BRDjs.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}=_chunkKCWS6BRDjs.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
|
-
import{h as $,j as U}from"./chunk-GDED4O5Q.mjs";import{a as V}from"./chunk-SUWV767V.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var J=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:m=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:p}=U(),[R,d]=K(null),[y,A]=K(c&&T),[C,E]=K(null),l=v(null),o=v(!0),g=v(0),f=v(0),F=j(()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),P=j(()=>{d(null),E(null),A(!1),f.current=0},[]),D=j(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 Q.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)&&t.response?.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{}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)&&t.data?.response?.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{}}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&&(r.message?.includes("Network Error")||r.message?.includes("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 z(()=>{c&&T&&I?D():T||P()},[c,T,I,D,P]),z(()=>(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}};import{useCallback as W}from"react";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}=U(),l=W(g=>{g?V.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):p()},[p]),o=m?.expiresAt?new Date(m.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:m?.accessToken||null,user:I,tokenExpiration:o,setToken:l,logout:p,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:y,clearError:d}};import{useCallback as w}from"react";import k from"@nocios/crudify-browser";var ae=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:m,login:T}=U(),I=w(()=>S&&!c&&!N,[S,c,N]),u=w(async()=>new Promise((o,g)=>{let f=()=>{I()?o():N?g(new Error(N)):setTimeout(f,100)};f()}),[I,N]),p=w(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=w(async(o,g,f)=>(await p(),await k.readItems(o,g||{},f)),[p]),d=w(async(o,g,f)=>(await p(),await k.readItem(o,g,f)),[p]),y=w(async(o,g,f)=>(await p(),await k.createItem(o,g,f)),[p]),A=w(async(o,g,f)=>(await p(),await k.updateItem(o,g,f)),[p]),C=w(async(o,g,f)=>(await p(),await k.deleteItem(o,g,f)),[p]),E=w(async(o,g)=>(await p(),await k.transaction(o,g)),[p]),l=w(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}};import{useCallback as _}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de=(S={})=>{let{showNotification:c}=$(),{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=_(e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS")))return!1;let i=e.data;return!(!e.success&&i?.response?.status==="TOO_MANY_REQUESTS")},[]),y=_((e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_(e=>["create","update","delete"].includes(e),[]),C=_((e,i)=>N?A(e)&&i?!0:p.some(s=>s.key===e):!1,[N,p,A]),E=_((e,i,s)=>{let r=s?.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=_(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(s?.includes("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(n?.response?.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(n?.response?.data)return n.response.data}if(t?.response?.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{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=_(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),g=_(async(e,i,s)=>{let r=await b.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=s?.actionConfig,n=t?.key||"create",a=t?.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=_(async(e,i,s)=>{let r=await b.updateItem(e,i,s),t=s?.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=s?.actionConfig,a=n?.key||"update",O=n?.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=_(async(e,i,s)=>{let r=await b.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=s?.actionConfig,n=t?.key||"delete",a=t?.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=_(async(e,i,s)=>{let r=await b.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=_(async(e,i,s)=>{let r=await b.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=_(async(e,i)=>{let s=await b.transaction(e,i),r=i?.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(i?.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=_((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}};export{J as a,te as b,ae as c,de as d};
|
|
1
|
+
import{h as $,j as U}from"./chunk-DXIXGRHJ.mjs";import{a as V}from"./chunk-SUWV767V.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var J=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:m=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:p}=U(),[R,d]=K(null),[y,A]=K(c&&T),[C,E]=K(null),l=v(null),o=v(!0),g=v(0),f=v(0),F=j(()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),P=j(()=>{d(null),E(null),A(!1),f.current=0},[]),D=j(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 Q.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)&&t.response?.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{}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)&&t.data?.response?.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{}}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&&(r.message?.includes("Network Error")||r.message?.includes("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 z(()=>{c&&T&&I?D():T||P()},[c,T,I,D,P]),z(()=>(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}};import{useCallback as W}from"react";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}=U(),l=W(g=>{g?V.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):p()},[p]),o=m?.expiresAt?new Date(m.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:m?.accessToken||null,user:I,tokenExpiration:o,setToken:l,logout:p,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:y,clearError:d}};import{useCallback as w}from"react";import k from"@nocios/crudify-browser";var ae=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:m,login:T}=U(),I=w(()=>S&&!c&&!N,[S,c,N]),u=w(async()=>new Promise((o,g)=>{let f=()=>{I()?o():N?g(new Error(N)):setTimeout(f,100)};f()}),[I,N]),p=w(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=w(async(o,g,f)=>(await p(),await k.readItems(o,g||{},f)),[p]),d=w(async(o,g,f)=>(await p(),await k.readItem(o,g,f)),[p]),y=w(async(o,g,f)=>(await p(),await k.createItem(o,g,f)),[p]),A=w(async(o,g,f)=>(await p(),await k.updateItem(o,g,f)),[p]),C=w(async(o,g,f)=>(await p(),await k.deleteItem(o,g,f)),[p]),E=w(async(o,g)=>(await p(),await k.transaction(o,g)),[p]),l=w(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}};import{useCallback as _}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de=(S={})=>{let{showNotification:c}=$(),{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=_(e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS")))return!1;let i=e.data;return!(!e.success&&i?.response?.status==="TOO_MANY_REQUESTS")},[]),y=_((e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_(e=>["create","update","delete"].includes(e),[]),C=_((e,i)=>N?A(e)&&i?!0:p.some(s=>s.key===e):!1,[N,p,A]),E=_((e,i,s)=>{let r=s?.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=_(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(s?.includes("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(n?.response?.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(n?.response?.data)return n.response.data}if(t?.response?.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{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=_(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),g=_(async(e,i,s)=>{let r=await b.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=s?.actionConfig,n=t?.key||"create",a=t?.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=_(async(e,i,s)=>{let r=await b.updateItem(e,i,s),t=s?.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=s?.actionConfig,a=n?.key||"update",O=n?.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=_(async(e,i,s)=>{let r=await b.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=s?.actionConfig,n=t?.key||"delete",a=t?.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=_(async(e,i,s)=>{let r=await b.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=_(async(e,i,s)=>{let r=await b.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=_(async(e,i)=>{let s=await b.transaction(e,i),r=i?.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(i?.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=_((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}};export{J as a,te as b,ae as c,de as d};
|
package/dist/components.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, d as CrudifyLoginConfig, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-
|
|
1
|
+
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, d as CrudifyLoginConfig, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-CKuypna1.mjs';
|
|
2
2
|
export { G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.mjs';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import 'react';
|
package/dist/components.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, d as CrudifyLoginConfig, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-
|
|
1
|
+
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, d as CrudifyLoginConfig, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-Cy8VBvkO.js';
|
|
2
2
|
export { G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.js';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import 'react';
|
package/dist/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkE4ILHUTVjs = require('./chunk-E4ILHUTV.js');var _chunkKCWS6BRDjs = require('./chunk-KCWS6BRD.js');require('./chunk-YIIUEOXC.js');require('./chunk-34FAL7YW.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=_chunkKCWS6BRDjs.f.call(void 0, ),[i,y]=_react.useState.call(void 0, 0),[h,C]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return _jsxruntime.jsxs.call(void 0, "div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudiaAutoGenerate = _chunkE4ILHUTVjs.o; exports.CrudiaFileField = _chunkE4ILHUTVjs.p; exports.CrudiaMarkdownField = _chunkE4ILHUTVjs.q; exports.CrudifyLogin = _chunkE4ILHUTVjs.h; exports.GlobalNotificationProvider = _chunkKCWS6BRDjs.g; exports.LoginComponent = _chunkE4ILHUTVjs.m; exports.Policies = _chunkE4ILHUTVjs.l; exports.SessionStatus = _chunkE4ILHUTVjs.n; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunkE4ILHUTVjs.i; exports.useGlobalNotification = _chunkKCWS6BRDjs.h;
|
package/dist/components.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as N,i as T,l as M,m as k,n as G,o as L,p as A,q as R}from"./chunk-
|
|
1
|
+
import{h as N,i as T,l as M,m as k,n as G,o as L,p as A,q as R}from"./chunk-HO44TY3Z.mjs";import{f as d,g as F,h as I}from"./chunk-DXIXGRHJ.mjs";import"./chunk-BJ6PIVZR.mjs";import"./chunk-SUWV767V.mjs";import{useEffect as B,useState as l}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=d(),[i,y]=l(0),[h,C]=l(100);if(B(()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return n("div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{L as CrudiaAutoGenerate,A as CrudiaFileField,R as CrudiaMarkdownField,N as CrudifyLogin,F as GlobalNotificationProvider,k as LoginComponent,M as Policies,G as SessionStatus,z as SessionTimeIndicator,T as UserProfileDisplay,I as useGlobalNotification};
|
package/dist/hooks.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { F as FileItem, v as FileStatus, d as SessionState, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, i as useUserData, q as useUserProfile } from './index-
|
|
1
|
+
export { F as FileItem, v as FileStatus, d as SessionState, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, i as useUserData, q as useUserProfile } from './index-e0fEu7Sq.mjs';
|
|
2
2
|
export { A as AutoGenerateConfig, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate } from './GlobalNotificationProvider-Zq18OkpI.mjs';
|
|
3
3
|
import './api-RK-xY1Ah.mjs';
|
|
4
4
|
import 'react/jsx-runtime';
|
package/dist/hooks.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { F as FileItem, v as FileStatus, d as SessionState, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, i as useUserData, q as useUserProfile } from './index-
|
|
1
|
+
export { F as FileItem, v as FileStatus, d as SessionState, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, i as useUserData, q as useUserProfile } from './index-By0tDIvO.js';
|
|
2
2
|
export { A as AutoGenerateConfig, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate } from './GlobalNotificationProvider-Zq18OkpI.js';
|
|
3
3
|
import './api-RK-xY1Ah.js';
|
|
4
4
|
import 'react/jsx-runtime';
|
package/dist/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkOTCV6Y6Djs = require('./chunk-OTCV6Y6D.js');var _chunkKCWS6BRDjs = require('./chunk-KCWS6BRD.js');require('./chunk-34FAL7YW.js');exports.useAuth = _chunkOTCV6Y6Djs.b; exports.useAutoGenerate = _chunkKCWS6BRDjs.m; exports.useCrudifyWithNotifications = _chunkOTCV6Y6Djs.d; exports.useData = _chunkOTCV6Y6Djs.c; exports.useFileUpload = _chunkKCWS6BRDjs.p; exports.useSession = _chunkKCWS6BRDjs.f; exports.useUserData = _chunkOTCV6Y6Djs.a; exports.useUserProfile = _chunkKCWS6BRDjs.l;
|
package/dist/hooks.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as u,c as a,d as p}from"./chunk-
|
|
1
|
+
import{a as s,b as u,c as a,d as p}from"./chunk-QJI47CHZ.mjs";import{f as e,l as t,m as o,p as r}from"./chunk-DXIXGRHJ.mjs";import"./chunk-SUWV767V.mjs";export{u as useAuth,o as useAutoGenerate,p as useCrudifyWithNotifications,a as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
|
|
@@ -567,7 +567,7 @@ declare const useUserProfile: (options?: UseUserProfileOptions) => UseUserProfil
|
|
|
567
567
|
/**
|
|
568
568
|
* Individual file status
|
|
569
569
|
*/
|
|
570
|
-
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing";
|
|
570
|
+
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing" | "pendingDeletion";
|
|
571
571
|
/**
|
|
572
572
|
* Represents a file in the system
|
|
573
573
|
*/
|
|
@@ -604,6 +604,8 @@ interface FileItem {
|
|
|
604
604
|
createdAt: number;
|
|
605
605
|
/** Original file (only during upload) */
|
|
606
606
|
file?: File;
|
|
607
|
+
/** Whether this file existed before (was loaded from server) */
|
|
608
|
+
isExisting?: boolean;
|
|
607
609
|
}
|
|
608
610
|
/**
|
|
609
611
|
* Hook configuration
|
|
@@ -630,6 +632,8 @@ interface UseFileUploadOptions {
|
|
|
630
632
|
onFileRemoved?: (file: FileItem) => void;
|
|
631
633
|
/** Callback when the file list changes */
|
|
632
634
|
onFilesChange?: (files: FileItem[]) => void;
|
|
635
|
+
/** Form mode: 'create' or 'edit' - affects delete behavior */
|
|
636
|
+
mode?: "create" | "edit";
|
|
633
637
|
}
|
|
634
638
|
/**
|
|
635
639
|
* Hook return type
|
|
@@ -637,22 +641,40 @@ interface UseFileUploadOptions {
|
|
|
637
641
|
interface UseFileUploadReturn {
|
|
638
642
|
/** Current file list */
|
|
639
643
|
files: FileItem[];
|
|
644
|
+
/** Active files (excluding pendingDeletion) */
|
|
645
|
+
activeFiles: FileItem[];
|
|
646
|
+
/** Count of active files */
|
|
647
|
+
activeFileCount: number;
|
|
640
648
|
/** Whether uploads are in progress */
|
|
641
649
|
isUploading: boolean;
|
|
642
650
|
/** Number of pending uploads */
|
|
643
651
|
pendingCount: number;
|
|
644
652
|
/** Add files (triggers automatic upload) */
|
|
645
653
|
addFiles: (files: FileList | File[]) => Promise<void>;
|
|
646
|
-
/** Remove a file
|
|
647
|
-
removeFile: (fileId: string) => Promise<
|
|
654
|
+
/** Remove a file - returns whether confirmation is needed */
|
|
655
|
+
removeFile: (fileId: string) => Promise<{
|
|
656
|
+
needsConfirmation: boolean;
|
|
657
|
+
isExisting: boolean;
|
|
658
|
+
}>;
|
|
659
|
+
/** Delete a file immediately from server (for new files or create mode) */
|
|
660
|
+
deleteFileImmediately: (fileId: string) => Promise<{
|
|
661
|
+
success: boolean;
|
|
662
|
+
error?: string;
|
|
663
|
+
}>;
|
|
664
|
+
/** Restore a file that was marked for deletion */
|
|
665
|
+
restoreFile: (fileId: string) => boolean;
|
|
648
666
|
/** Clear all files */
|
|
649
667
|
clearFiles: () => void;
|
|
650
668
|
/** Retry upload for a failed file */
|
|
651
669
|
retryUpload: (fileId: string) => Promise<void>;
|
|
652
670
|
/** Validate if minimum requirements are met */
|
|
653
671
|
isValid: boolean;
|
|
654
|
-
/** Validation error message */
|
|
672
|
+
/** Validation error message (i18n key) */
|
|
655
673
|
validationError: string | null;
|
|
674
|
+
/** Validation error i18n key */
|
|
675
|
+
validationErrorKey: string | null;
|
|
676
|
+
/** Validation error params for i18n interpolation */
|
|
677
|
+
validationErrorParams: Record<string, string | number>;
|
|
656
678
|
/** Wait for all uploads to complete */
|
|
657
679
|
waitForUploads: () => Promise<void>;
|
|
658
680
|
/**
|
|
@@ -666,17 +688,32 @@ interface UseFileUploadReturn {
|
|
|
666
688
|
name: string;
|
|
667
689
|
size?: number;
|
|
668
690
|
contentType?: string;
|
|
669
|
-
}
|
|
691
|
+
}>, baseUrl?: string) => void;
|
|
670
692
|
/** Whether the user has interacted with the field */
|
|
671
693
|
isTouched: boolean;
|
|
672
694
|
/** Mark the field as touched (to show validation errors) */
|
|
673
695
|
markAsTouched: () => void;
|
|
696
|
+
/** Whether the form has been submitted */
|
|
697
|
+
isSubmitted: boolean;
|
|
698
|
+
/** Mark the form as submitted (to show all validation errors) */
|
|
699
|
+
markAsSubmitted: () => void;
|
|
674
700
|
/**
|
|
675
701
|
* Get URL for file preview
|
|
676
702
|
* - Public: returns publicUrl directly
|
|
677
703
|
* - Private: requests signed URL from backend
|
|
678
704
|
*/
|
|
679
705
|
getPreviewUrl: (fileId: string) => Promise<string | null>;
|
|
706
|
+
/** List of file IDs pending deletion */
|
|
707
|
+
pendingDeletions: string[];
|
|
708
|
+
/** Whether there are files pending deletion */
|
|
709
|
+
hasPendingDeletions: boolean;
|
|
710
|
+
/** Execute all pending deletions (call this on form submit) */
|
|
711
|
+
commitDeletions: () => Promise<{
|
|
712
|
+
success: boolean;
|
|
713
|
+
errors: string[];
|
|
714
|
+
}>;
|
|
715
|
+
/** Cancel all pending deletions and restore files */
|
|
716
|
+
restorePendingDeletions: () => void;
|
|
680
717
|
}
|
|
681
718
|
/**
|
|
682
719
|
* Hook for complete file handling with S3 upload
|
|
@@ -567,7 +567,7 @@ declare const useUserProfile: (options?: UseUserProfileOptions) => UseUserProfil
|
|
|
567
567
|
/**
|
|
568
568
|
* Individual file status
|
|
569
569
|
*/
|
|
570
|
-
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing";
|
|
570
|
+
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing" | "pendingDeletion";
|
|
571
571
|
/**
|
|
572
572
|
* Represents a file in the system
|
|
573
573
|
*/
|
|
@@ -604,6 +604,8 @@ interface FileItem {
|
|
|
604
604
|
createdAt: number;
|
|
605
605
|
/** Original file (only during upload) */
|
|
606
606
|
file?: File;
|
|
607
|
+
/** Whether this file existed before (was loaded from server) */
|
|
608
|
+
isExisting?: boolean;
|
|
607
609
|
}
|
|
608
610
|
/**
|
|
609
611
|
* Hook configuration
|
|
@@ -630,6 +632,8 @@ interface UseFileUploadOptions {
|
|
|
630
632
|
onFileRemoved?: (file: FileItem) => void;
|
|
631
633
|
/** Callback when the file list changes */
|
|
632
634
|
onFilesChange?: (files: FileItem[]) => void;
|
|
635
|
+
/** Form mode: 'create' or 'edit' - affects delete behavior */
|
|
636
|
+
mode?: "create" | "edit";
|
|
633
637
|
}
|
|
634
638
|
/**
|
|
635
639
|
* Hook return type
|
|
@@ -637,22 +641,40 @@ interface UseFileUploadOptions {
|
|
|
637
641
|
interface UseFileUploadReturn {
|
|
638
642
|
/** Current file list */
|
|
639
643
|
files: FileItem[];
|
|
644
|
+
/** Active files (excluding pendingDeletion) */
|
|
645
|
+
activeFiles: FileItem[];
|
|
646
|
+
/** Count of active files */
|
|
647
|
+
activeFileCount: number;
|
|
640
648
|
/** Whether uploads are in progress */
|
|
641
649
|
isUploading: boolean;
|
|
642
650
|
/** Number of pending uploads */
|
|
643
651
|
pendingCount: number;
|
|
644
652
|
/** Add files (triggers automatic upload) */
|
|
645
653
|
addFiles: (files: FileList | File[]) => Promise<void>;
|
|
646
|
-
/** Remove a file
|
|
647
|
-
removeFile: (fileId: string) => Promise<
|
|
654
|
+
/** Remove a file - returns whether confirmation is needed */
|
|
655
|
+
removeFile: (fileId: string) => Promise<{
|
|
656
|
+
needsConfirmation: boolean;
|
|
657
|
+
isExisting: boolean;
|
|
658
|
+
}>;
|
|
659
|
+
/** Delete a file immediately from server (for new files or create mode) */
|
|
660
|
+
deleteFileImmediately: (fileId: string) => Promise<{
|
|
661
|
+
success: boolean;
|
|
662
|
+
error?: string;
|
|
663
|
+
}>;
|
|
664
|
+
/** Restore a file that was marked for deletion */
|
|
665
|
+
restoreFile: (fileId: string) => boolean;
|
|
648
666
|
/** Clear all files */
|
|
649
667
|
clearFiles: () => void;
|
|
650
668
|
/** Retry upload for a failed file */
|
|
651
669
|
retryUpload: (fileId: string) => Promise<void>;
|
|
652
670
|
/** Validate if minimum requirements are met */
|
|
653
671
|
isValid: boolean;
|
|
654
|
-
/** Validation error message */
|
|
672
|
+
/** Validation error message (i18n key) */
|
|
655
673
|
validationError: string | null;
|
|
674
|
+
/** Validation error i18n key */
|
|
675
|
+
validationErrorKey: string | null;
|
|
676
|
+
/** Validation error params for i18n interpolation */
|
|
677
|
+
validationErrorParams: Record<string, string | number>;
|
|
656
678
|
/** Wait for all uploads to complete */
|
|
657
679
|
waitForUploads: () => Promise<void>;
|
|
658
680
|
/**
|
|
@@ -666,17 +688,32 @@ interface UseFileUploadReturn {
|
|
|
666
688
|
name: string;
|
|
667
689
|
size?: number;
|
|
668
690
|
contentType?: string;
|
|
669
|
-
}
|
|
691
|
+
}>, baseUrl?: string) => void;
|
|
670
692
|
/** Whether the user has interacted with the field */
|
|
671
693
|
isTouched: boolean;
|
|
672
694
|
/** Mark the field as touched (to show validation errors) */
|
|
673
695
|
markAsTouched: () => void;
|
|
696
|
+
/** Whether the form has been submitted */
|
|
697
|
+
isSubmitted: boolean;
|
|
698
|
+
/** Mark the form as submitted (to show all validation errors) */
|
|
699
|
+
markAsSubmitted: () => void;
|
|
674
700
|
/**
|
|
675
701
|
* Get URL for file preview
|
|
676
702
|
* - Public: returns publicUrl directly
|
|
677
703
|
* - Private: requests signed URL from backend
|
|
678
704
|
*/
|
|
679
705
|
getPreviewUrl: (fileId: string) => Promise<string | null>;
|
|
706
|
+
/** List of file IDs pending deletion */
|
|
707
|
+
pendingDeletions: string[];
|
|
708
|
+
/** Whether there are files pending deletion */
|
|
709
|
+
hasPendingDeletions: boolean;
|
|
710
|
+
/** Execute all pending deletions (call this on form submit) */
|
|
711
|
+
commitDeletions: () => Promise<{
|
|
712
|
+
success: boolean;
|
|
713
|
+
errors: string[];
|
|
714
|
+
}>;
|
|
715
|
+
/** Cancel all pending deletions and restore files */
|
|
716
|
+
restorePendingDeletions: () => void;
|
|
680
717
|
}
|
|
681
718
|
/**
|
|
682
719
|
* Hook for complete file handling with S3 upload
|