@nocios/crudify-components 2.0.38 → 2.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/coverage/coverage-final.json +88 -55
  2. package/coverage/index.html +360 -240
  3. package/dist/{CrudiaMarkdownField-CggOpcBM.d.ts → CrudiaMarkdownField-CXAuu-v2.d.ts} +6 -1
  4. package/dist/{CrudiaMarkdownField-BvJn2GL8.d.mts → CrudiaMarkdownField-TNyMLb-h.d.mts} +6 -1
  5. package/dist/chunk-2IOB6HHT.js +1 -0
  6. package/dist/chunk-2WHCDP7V.mjs +1 -0
  7. package/dist/chunk-37WOWEJG.js +1 -0
  8. package/dist/chunk-MFQKGZI4.js +1 -0
  9. package/dist/chunk-NJERBWND.mjs +1 -0
  10. package/dist/chunk-XMEZUDF6.mjs +1 -0
  11. package/dist/components.d.mts +1 -1
  12. package/dist/components.d.ts +1 -1
  13. package/dist/components.js +1 -1
  14. package/dist/components.mjs +1 -1
  15. package/dist/hooks.js +1 -1
  16. package/dist/hooks.mjs +1 -1
  17. package/dist/index.d.mts +4 -4
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +2 -2
  20. package/dist/index.mjs +1 -1
  21. package/package.json +2 -2
  22. package/coverage/components/CrudiaAutoGenerate.tsx.html +0 -583
  23. package/coverage/components/CrudiaFileField/CrudiaFileField.tsx.html +0 -1276
  24. package/coverage/components/CrudiaFileField/components/DeleteConfirmationDialog.tsx.html +0 -355
  25. package/coverage/components/CrudiaFileField/components/DropZone.tsx.html +0 -433
  26. package/coverage/components/CrudiaFileField/components/FileItemRow.tsx.html +0 -751
  27. package/coverage/components/CrudiaFileField/components/FileThumbnail.tsx.html +0 -1195
  28. package/coverage/components/CrudiaFileField/components/index.html +0 -176
  29. package/coverage/components/CrudiaFileField/components/index.ts.html +0 -115
  30. package/coverage/components/CrudiaFileField/hooks/index.html +0 -146
  31. package/coverage/components/CrudiaFileField/hooks/index.ts.html +0 -112
  32. package/coverage/components/CrudiaFileField/hooks/useDeleteConfirmation.ts.html +0 -421
  33. package/coverage/components/CrudiaFileField/hooks/useDragDrop.ts.html +0 -403
  34. package/coverage/components/CrudiaFileField/index.html +0 -131
  35. package/coverage/components/CrudiaFileField/index.ts.html +0 -112
  36. package/coverage/components/CrudiaFileField/utils/formatters.ts.html +0 -163
  37. package/coverage/components/CrudiaFileField/utils/icons.tsx.html +0 -253
  38. package/coverage/components/CrudiaFileField/utils/index.html +0 -131
  39. package/coverage/components/CrudiaMarkdownField.tsx.html +0 -619
  40. package/coverage/components/CrudifyLogin/Forms/CheckCodeForm.tsx.html +0 -586
  41. package/coverage/components/CrudifyLogin/Forms/ForgotPasswordForm.tsx.html +0 -694
  42. package/coverage/components/CrudifyLogin/Forms/LoginForm.tsx.html +0 -835
  43. package/coverage/components/CrudifyLogin/Forms/ResetPasswordForm.tsx.html +0 -1180
  44. package/coverage/components/CrudifyLogin/Forms/components/CodeInput.tsx.html +0 -283
  45. package/coverage/components/CrudifyLogin/Forms/components/FormAlert.tsx.html +0 -202
  46. package/coverage/components/CrudifyLogin/Forms/components/PasswordInput.tsx.html +0 -340
  47. package/coverage/components/CrudifyLogin/Forms/components/index.html +0 -161
  48. package/coverage/components/CrudifyLogin/Forms/components/index.ts.html +0 -106
  49. package/coverage/components/CrudifyLogin/Forms/index.html +0 -161
  50. package/coverage/components/CrudifyLogin/Forms/utils/errorTranslation.ts.html +0 -268
  51. package/coverage/components/CrudifyLogin/Forms/utils/index.html +0 -161
  52. package/coverage/components/CrudifyLogin/Forms/utils/index.ts.html +0 -106
  53. package/coverage/components/CrudifyLogin/Forms/utils/paramUtils.ts.html +0 -478
  54. package/coverage/components/CrudifyLogin/Forms/utils/validation.ts.html +0 -289
  55. package/coverage/components/CrudifyLogin/components/CrudifyInitializer.tsx.html +0 -262
  56. package/coverage/components/CrudifyLogin/components/index.html +0 -116
  57. package/coverage/components/CrudifyLogin/context/CrudifyProvider.tsx.html +0 -382
  58. package/coverage/components/CrudifyLogin/context/I18nProvider.tsx.html +0 -397
  59. package/coverage/components/CrudifyLogin/context/LoginStateProvider.tsx.html +0 -1249
  60. package/coverage/components/CrudifyLogin/context/index.html +0 -146
  61. package/coverage/components/CrudifyLogin/hooks/index.html +0 -116
  62. package/coverage/components/CrudifyLogin/hooks/useTranslationsFromUrl.ts.html +0 -292
  63. package/coverage/components/CrudifyLogin/index.html +0 -116
  64. package/coverage/components/CrudifyLogin/index.tsx.html +0 -475
  65. package/coverage/components/GlobalNotificationProvider.tsx.html +0 -781
  66. package/coverage/components/LoginComponent.tsx.html +0 -727
  67. package/coverage/components/PasswordRequirements/index.html +0 -116
  68. package/coverage/components/PasswordRequirements/index.tsx.html +0 -226
  69. package/coverage/components/PublicPolicies/FieldSelector/FieldSelector.tsx.html +0 -982
  70. package/coverage/components/PublicPolicies/FieldSelector/index.html +0 -131
  71. package/coverage/components/PublicPolicies/FieldSelector/index.ts.html +0 -85
  72. package/coverage/components/PublicPolicies/Policies.tsx.html +0 -610
  73. package/coverage/components/PublicPolicies/PolicyItem/PolicyItem.tsx.html +0 -856
  74. package/coverage/components/PublicPolicies/PolicyItem/index.html +0 -131
  75. package/coverage/components/PublicPolicies/PolicyItem/index.ts.html +0 -85
  76. package/coverage/components/PublicPolicies/constants.ts.html +0 -127
  77. package/coverage/components/PublicPolicies/index.html +0 -131
  78. package/coverage/components/SessionTimeIndicator/index.html +0 -116
  79. package/coverage/components/SessionTimeIndicator/index.tsx.html +0 -505
  80. package/coverage/components/UserProfile/UserProfileDisplay.tsx.html +0 -826
  81. package/coverage/components/UserProfile/index.html +0 -131
  82. package/coverage/components/UserProfile/index.ts.html +0 -85
  83. package/coverage/components/index.html +0 -176
  84. package/coverage/components/index.ts.html +0 -160
  85. package/coverage/core/CrossTabSyncManager.ts.html +0 -814
  86. package/coverage/core/CrudifyInitializationManager.ts.html +0 -1132
  87. package/coverage/core/SessionManager.ts.html +0 -2764
  88. package/coverage/core/index.html +0 -146
  89. package/coverage/hooks/index.html +0 -131
  90. package/coverage/hooks/useAutoGenerate.ts.html +0 -562
  91. package/coverage/hooks/useFileUpload/index.html +0 -131
  92. package/coverage/hooks/useFileUpload/index.ts.html +0 -112
  93. package/coverage/hooks/useFileUpload/services/index.html +0 -116
  94. package/coverage/hooks/useFileUpload/services/uploadService.ts.html +0 -610
  95. package/coverage/hooks/useFileUpload/useFileUpload.ts.html +0 -1870
  96. package/coverage/hooks/useFileUpload/utils/fileUtils.ts.html +0 -271
  97. package/coverage/hooks/useFileUpload/utils/index.html +0 -146
  98. package/coverage/hooks/useFileUpload/utils/mimeTypes.ts.html +0 -235
  99. package/coverage/hooks/useFileUpload/utils/validation.ts.html +0 -379
  100. package/coverage/hooks/useSession/constants.ts.html +0 -217
  101. package/coverage/hooks/useSession/hooks/index.html +0 -176
  102. package/coverage/hooks/useSession/hooks/useAuthEventSubscriber.ts.html +0 -331
  103. package/coverage/hooks/useSession/hooks/useCrossTabSync.ts.html +0 -433
  104. package/coverage/hooks/useSession/hooks/useSessionActions.ts.html +0 -664
  105. package/coverage/hooks/useSession/hooks/useSessionState.ts.html +0 -295
  106. package/coverage/hooks/useSession/hooks/useTokenRefreshScheduler.ts.html +0 -490
  107. package/coverage/hooks/useSession/index.html +0 -161
  108. package/coverage/hooks/useSession/index.ts.html +0 -127
  109. package/coverage/hooks/useSession/types.ts.html +0 -427
  110. package/coverage/hooks/useSession/useSession.ts.html +0 -526
  111. package/coverage/hooks/useSession/utils/index.html +0 -131
  112. package/coverage/hooks/useSession/utils/initializeSession.ts.html +0 -424
  113. package/coverage/hooks/useSession/utils/tokenUtils.ts.html +0 -280
  114. package/coverage/hooks/useUserProfile.ts.html +0 -658
  115. package/coverage/providers/SessionProvider.tsx.html +0 -1150
  116. package/coverage/providers/TranslationsProvider.tsx.html +0 -1450
  117. package/coverage/providers/index.html +0 -131
  118. package/coverage/services/credentialsEventBus.ts.html +0 -310
  119. package/coverage/services/index.html +0 -131
  120. package/coverage/services/translationService.ts.html +0 -1318
  121. package/coverage/translations/critical.ts.html +0 -1195
  122. package/coverage/translations/index.html +0 -116
  123. package/coverage/types/index.html +0 -116
  124. package/coverage/types/password.ts.html +0 -178
  125. package/coverage/utils/authEventBus.ts.html +0 -454
  126. package/coverage/utils/configResolver.ts.html +0 -460
  127. package/coverage/utils/cookieSync.ts.html +0 -580
  128. package/coverage/utils/errorHandler.ts.html +0 -1264
  129. package/coverage/utils/errorTranslation.ts.html +0 -862
  130. package/coverage/utils/index.html +0 -296
  131. package/coverage/utils/jwtUtils.ts.html +0 -301
  132. package/coverage/utils/logger.ts.html +0 -901
  133. package/coverage/utils/navigationTracker.ts.html +0 -565
  134. package/coverage/utils/passwordValidation.ts.html +0 -259
  135. package/coverage/utils/redirectSecurity.ts.html +0 -715
  136. package/coverage/utils/tenantConfig.ts.html +0 -700
  137. package/coverage/utils/tokenStorage.ts.html +0 -1768
  138. package/coverage/utils/webCrypto.ts.html +0 -472
  139. package/dist/chunk-77UKXG5L.mjs +0 -1
  140. package/dist/chunk-H6XXWDUT.js +0 -1
  141. package/dist/chunk-NIRLP2TC.js +0 -1
  142. package/dist/chunk-O4FUHIQG.mjs +0 -1
  143. package/dist/chunk-SYHNHKFA.mjs +0 -1
  144. package/dist/chunk-W4ZYKPOK.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 _chunk4LMFQECSjs = require('./chunk-4LMFQECS.js');var Ke="crudify_storage_version",Me=2,a=class a{static setStorageType(e){a.storageType=e}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let t=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunk4LMFQECSjs.h.call(void 0, a.fingerprint,a.salt);return}catch(n){t=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(s=>setTimeout(s,100*i))}throw _chunk4LMFQECSjs.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(t, () => ({message:"Unknown error"}))),t})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Ke)||"1",10)<Me){let t=a.getStorage();t&&t.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Ke,Me.toString()),_chunk4LMFQECSjs.a.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch (e2){}}static getOrCreateSalt(){try{let t=localStorage.getItem(a.SALT_KEY);if(t){let i=atob(t),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}}catch (e3){}let e=_chunk4LMFQECSjs.k.call(void 0, );try{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);localStorage.setItem(a.SALT_KEY,btoa(t))}catch (e4){_chunk4LMFQECSjs.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return e}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch (e5){}let t=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await _chunk4LMFQECSjs.g.call(void 0, t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunk4LMFQECSjs.a.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(e){try{let t=window[e],i="__storage_test__";return t.setItem(i,"test"),t.removeItem(i),!0}catch (e7){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(_chunk4LMFQECSjs.a.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(e){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunk4LMFQECSjs.i.call(void 0, e,a.encryptionKey,a.salt)}static async decryptData(e){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunk4LMFQECSjs.l.call(void 0, e)?_chunk4LMFQECSjs.j.call(void 0, e,a.fingerprint):(_chunk4LMFQECSjs.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(e){let t=a.getStorage();if(t)try{let i={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));t.setItem(a.TOKEN_KEY,n),_chunk4LMFQECSjs.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunk4LMFQECSjs.a.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let i=await a.decryptData(t);if(!i)return _chunk4LMFQECSjs.a.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(i);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(_chunk4LMFQECSjs.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunk4LMFQECSjs.a.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(t){return _chunk4LMFQECSjs.a.error("Crudify: Failed to retrieve tokens",t instanceof Error?t:{message:String(t)}),await a.clearTokens(),null}}static async clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),_chunk4LMFQECSjs.a.debug("Crudify: Tokens cleared from storage")}catch(t){_chunk4LMFQECSjs.a.error("Crudify: Failed to clear tokens",t instanceof Error?t:{message:String(t)})}}static async rotateEncryptionKey(){try{await a.clearTokens(),a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.initPromise=null;try{localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY)}catch (e8){}_chunk4LMFQECSjs.a.info("Crudify: Encryption key rotated successfully")}catch(e){_chunk4LMFQECSjs.a.error("Crudify: Failed to rotate encryption key",e instanceof Error?e:{message:String(e)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let e=await a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static async updateAccessToken(e,t){let i=await a.getTokens();if(!i){_chunk4LMFQECSjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:e,expiresAt:t})}static createSyncEvent(e,t,i){return{type:e,tokens:t,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(e){let t=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=_optionalChain([a, 'access', _2 => _2.getStorage, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getItem, 'call', _5 => _5(a.TOKEN_KEY)]);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){_chunk4LMFQECSjs.a.debug("Crudify: Tokens removed in another tab"),e(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunk4LMFQECSjs.a.debug("Crudify: Tokens updated in another tab");let s=await a.getTokens();e(s,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",t),()=>{window.removeEventListener("storage",t)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,9);return`tab_${e}_${t}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=e=>{this.handleMessage(e.data)},this.broadcastChannel.onmessageerror=()=>{_chunk4LMFQECSjs.a.warn("Crudify: CrossTabSync message error")},_chunk4LMFQECSjs.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunk4LMFQECSjs.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(e){_chunk4LMFQECSjs.a.warn("Crudify: Failed to initialize CrossTabSync",{message:e instanceof Error?e.message:String(e)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(e){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(e),_chunk4LMFQECSjs.a.debug(`Crudify: CrossTab broadcast ${e.type}`))}catch(t){_chunk4LMFQECSjs.a.warn("Crudify: Failed to broadcast cross-tab message",{message:t instanceof Error?t.message:String(t)})}}handleMessage(e){e.tabId!==this.tabId&&(_chunk4LMFQECSjs.a.debug(`Crudify: CrossTab received ${e.type} from ${e.tabId}`),e.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:e.tabId}}),this.listeners.forEach(t=>{try{t(e)}catch(i){_chunk4LMFQECSjs.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var me=K,_= exports.c =me.getInstance();var _crudifysdk = require('@nocios/crudify-sdk');var ie="crudify_auth",he=r=>{if(r==="dev"||typeof window>"u"||!window.location)return"";if(!r){let e=window.location.hostname;return e?e.endsWith(".nocios.link")||e==="nocios.link"?".nocios.link":e.endsWith(".crudia.com")||e==="crudia.com"?".crudia.com":"":""}return r==="prod"||r==="api"?".crudia.com":".nocios.link"},Ut=(r,e,t)=>{if(typeof document>"u"){_chunk4LMFQECSjs.a.debug("[CookieSync] No document available (SSR), skipping cookie set");return}if(!r){_chunk4LMFQECSjs.a.warn("[CookieSync] Attempted to set cookie with empty token");return}try{let i=he(t),n=Date.now(),s=Math.max(0,Math.floor((e-n)/1e3)),l=[`${ie}=${encodeURIComponent(r)}`,"path=/","SameSite=Lax",`max-age=${s}`];typeof window<"u"&&window.location.protocol==="https:"&&l.push("Secure"),i&&l.push(`domain=${i}`),document.cookie=l.join("; "),_chunk4LMFQECSjs.a.debug("[CookieSync] Cookie set successfully",{domain:i||"(current host)",maxAgeSeconds:s,tokenLength:r.length})}catch(i){_chunk4LMFQECSjs.a.error("[CookieSync] Failed to set cookie",i instanceof Error?i:{message:String(i)})}},Ft=r=>{if(typeof document>"u"){_chunk4LMFQECSjs.a.debug("[CookieSync] No document available (SSR), skipping cookie clear");return}try{let e=he(r),t=[`${ie}=`,"path=/","max-age=0","expires=Thu, 01 Jan 1970 00:00:00 GMT"];e&&t.push(`domain=${e}`),document.cookie=t.join("; "),document.cookie=`${ie}=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT`,_chunk4LMFQECSjs.a.debug("[CookieSync] Cookie cleared successfully",{domain:e||"(current host)"})}catch(e){_chunk4LMFQECSjs.a.error("[CookieSync] Failed to clear cookie",e instanceof Error?e:{message:String(e)})}},zt=()=>{if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${ie}=`));if(!e)return null;let t=e.split("=")[1];return t?decodeURIComponent(t):null}catch(r){return _chunk4LMFQECSjs.a.error("[CookieSync] Failed to read cookie",r instanceof Error?r:{message:String(r)}),null}},B={setCrossSubdomainCookie:Ut,clearCrossSubdomainCookie:Ft,getCrossSubdomainCookie:zt,getCookieDomain:he};var re=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null;this.isSessionActive=!1;this.isColdStartRestore=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(e={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...e},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifysdk.CrudifyInstance.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunk4LMFQECSjs.f.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let t=await v.getTokens();t?await v.saveTokens({...t,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(e,t){try{let i=await _crudifysdk.CrudifyInstance.login(e,t);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),s=i.data,l={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _6 => _6.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),this.isSessionActive=!0,this.isColdStartRestore=!1,B.setCrossSubdomainCookie(l.accessToken,l.expiresAt,this.config.env),_.notifyLogin(),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(l)]),{success:!0,tokens:l,data:s}}catch(i){return _chunk4LMFQECSjs.a.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){this.isSessionActive=!1;try{this.log("Logging out..."),_chunk4LMFQECSjs.f.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),B.clearCrossSubdomainCookie(this.config.env),await _crudifysdk.CrudifyInstance.logout(),await v.clearTokens(),_.notifyLogout(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(e){this.log("Logout error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),_.notifyLogout()}}async restoreSession(){try{this.isColdStartRestore=!0,this.log("Attempting to restore session (cold start)...");let e=await v.getTokens();if(!e)return this.log("No valid tokens found in storage"),this.isColdStartRestore=!1,!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage (cold start - no notification)"),await v.clearTokens(),this.isColdStartRestore=!1,!1;if(_crudifysdk.CrudifyInstance.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifysdk.CrudifyInstance.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting silent refresh..."),await this.refreshTokensSilent())){this.log("Session restored successfully via silent token refresh"),this.isSessionActive=!0,this.isColdStartRestore=!1;let n=await v.getTokens();return n&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(n)]),!0}return this.log("Could not restore session, clearing tokens (cold start - no notification)"),await v.clearTokens(),await _crudifysdk.CrudifyInstance.logout(),this.isColdStartRestore=!1,!1}return this.log("Session restored successfully"),this.isSessionActive=!0,this.isColdStartRestore=!1,this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(e)]),!0}catch(e){return this.log("Session restore error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),await _crudifysdk.CrudifyInstance.logout(),this.isColdStartRestore=!1,!1}}async isAuthenticated(){return _crudifysdk.CrudifyInstance.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=_crudifysdk.CrudifyInstance.getTokenData(),t=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:_optionalChain([i, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([i, 'optionalAccess', _21 => _21.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 e=await _crudifysdk.CrudifyInstance.refreshAccessToken();if(!e.success)return this.log("Token refresh failed",{errors:e.errors}),await v.clearTokens(),this.isSessionActive&&!this.isColdStartRestore&&_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),this.isSessionActive=!1,!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),B.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),_.notifyTokenRefreshed(),!0}catch(e){return this.log("Token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),this.isSessionActive&&!this.isColdStartRestore&&_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),this.isSessionActive=!1,!1}}isRefreshing(){return this.isRefreshingLocally}async refreshTokensSilent(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Silent refresh: waiting for existing refresh promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefreshSilent();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefreshSilent(){try{this.log("Starting silent token refresh (cold start)...");let e=await _crudifysdk.CrudifyInstance.refreshAccessToken();if(!e.success)return this.log("Silent token refresh failed",{errors:e.errors}),await v.clearTokens(),!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed silently and saved successfully"),B.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),_.notifyTokenRefreshed(),!0}catch(e){return this.log("Silent token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),!1}}getIsSessionActive(){return this.isSessionActive}setupResponseInterceptor(){_crudifysdk.CrudifyInstance.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:t.errorType,shouldLogout:t.shouldTriggerLogout}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunk4LMFQECSjs.f.emit("TOKEN_REFRESH_FAILED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"}),e;t.shouldTriggerLogout&&(await v.hasValidTokens()&&!t.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunk4LMFQECSjs.f.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunk4LMFQECSjs.f.emit("SESSION_EXPIRED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return e}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let e=_crudifysdk.CrudifyInstance.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";_crudifysdk.CrudifyInstance.config(t);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk.CrudifyInstance.init(i,n);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(e){throw _chunk4LMFQECSjs.a.error("[SessionManager] Failed to initialize crudify",e instanceof Error?e:{message:String(e)}),e}}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(e.errors&&Array.isArray(e.errors)){let i=e.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([n, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([n, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([n, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([n, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([n, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="FORBIDDEN");i&&(t.isAuthError=!0,t.errorType="GraphQL Array",t.errorDetails=i,t.shouldTriggerLogout=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([i, 'access', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([i, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(t.isTokenExpired=!0),_optionalChain([i, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(t.isUnauthorized=!0))}if(!t.isAuthError&&e.errors&&typeof e.errors=="object"&&!Array.isArray(e.errors)){let n=Object.values(e.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(t.isAuthError=!0,t.errorType="GraphQL Object",t.errorDetails=e.errors,t.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(t.isTokenRefreshFailed=!0,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(t.isTokenExpired=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&_optionalChain([e, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let i=e.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(t.isAuthError=!0,t.errorType="Status",t.errorDetails=e.data.response,t.isUnauthorized=!0,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&_optionalChain([e, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let i=typeof e.data.response.data=="string"?JSON.parse(e.data.response.data):e.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Parsed Data",t.errorDetails=i,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(t.isRefreshTokenInvalid=!0,t.isTokenRefreshFailed=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e9){}if(!t.isAuthError&&e.errorCode){let i=String(e.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Error Code",t.errorDetails={errorCode:i},t.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?t.isTokenExpired=!0:t.isUnauthorized=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let t=1800*1e3;return e>t?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){B.clearCrossSubdomainCookie(this.config.env),await v.clearTokens(),await _crudifysdk.CrudifyInstance.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk4LMFQECSjs.m.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(e,t){this.config.enableLogging&&_chunk4LMFQECSjs.a.debug(`[SessionManager] ${e}`,t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);var He={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Ge(){let[r,e]=_react.useState.call(void 0, He),t=_react.useCallback.call(void 0, o=>{e(d=>({...d,isLoading:o}))},[]),i=_react.useCallback.call(void 0, (o,d)=>{e(p=>({...p,isAuthenticated:o,tokens:d,error:o?null:p.error}))},[]),n=_react.useCallback.call(void 0, o=>{e(d=>({...d,isLoggingOut:o}))},[]),s=_react.useCallback.call(void 0, o=>{e(d=>({...d,error:o}))},[]),l=_react.useCallback.call(void 0, o=>{e(d=>({...d,isInitialized:o}))},[]);return{state:r,setState:e,setLoading:t,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}var ne={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},ye={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},_e=.5;function Ve(r){return r?r.expiresAt-Date.now()<3e5:!1}function $e(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function Ye(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function V(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function We(r){let{sessionManager:e,stateManager:t}=r,i=_react.useCallback.call(void 0, async(o,d)=>{t.setState(p=>({...p,isLoading:!0,isLoggingOut:!1,error:null}));try{let p=await e.login(o,d);return p.success&&p.tokens?t.setState(b=>({...b,isAuthenticated:!0,tokens:p.tokens,isLoading:!1,isLoggingOut:!1,error:null})):t.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),p}catch(p){let b=p instanceof Error?p.message:"Login failed";_chunk4LMFQECSjs.a.error("[useSession] Login error",p instanceof Error?p:{message:b});let S=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return t.setState(g=>({...g,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:S?null:b})),{success:!1,error:b}}},[e,t]),n=_react.useCallback.call(void 0, async()=>{t.setState(o=>({...o,isLoading:!0,isLoggingOut:!0}));try{await e.logout(),t.setState(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(o){t.setState(d=>({...d,isAuthenticated:!1,tokens:null,isLoading:!1,error:o instanceof Error?o.message:"Logout error"}))}},[e,t]),s=_react.useCallback.call(void 0, async()=>{try{let o=await e.refreshTokens();if(o){let d=await e.getTokenInfo();t.setState(p=>({...p,tokens:V(d),error:null}))}else t.setState(d=>({...d,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return t.setState(d=>({...d,isAuthenticated:!1,tokens:null,error:o instanceof Error?o.message:"Token refresh failed"})),!1}},[e,t]),l=_react.useCallback.call(void 0, ()=>{t.setError(null)},[t]);return{login:i,logout:n,refreshTokens:s,clearError:l}}function Vt(r){return r<ye.AGGRESSIVE?ne.AGGRESSIVE:r<ye.MODERATE?ne.MODERATE:ne.RELAXED}function Be(r){let{isAuthenticated:e,tokens:t,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,d=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!e||!t)return;let b=_chunk4LMFQECSjs.q.getInstance().subscribe(d);window.addEventListener("popstate",d);let S,g=!0,I=async()=>{if(!g)return;let k=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,R=Vt(k);S=setTimeout(async()=>{if(!g)return;if(i.isRefreshing()){I();return}let A=await i.getTokenInfo(),O=A.crudifyTokens.expiresIn||0,F=((A.crudifyTokens.expiresAt||0)-(Date.now()-O))*_e;if(O>0&&O<=F)if(l(!0),await i.refreshTokens()){let W=await i.getTokenInfo();n(V(W)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():g&&I()},R)};return I(),()=>{g=!1,clearTimeout(S),window.removeEventListener("popstate",d),b()}},[e,t,i,d,n,s,l,o])}function Xe(r){let{sessionManager:e,onTokensUpdated:t,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;_react.useEffect.call(void 0, ()=>{let l=_chunk4LMFQECSjs.f.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(e.isRefreshing())return;n(!0);try{if(await e.refreshTokens()){let p=await e.getTokenInfo();t(V(p)),n(!1)}else _chunk4LMFQECSjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(d){_chunk4LMFQECSjs.f.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")&&(t(null),n(!1),_optionalChain([o, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.isColdStart])!==!0&&_optionalChain([o, 'access', _75 => _75.details, 'optionalAccess', _76 => _76.shouldShowNotification])!==!1&&s(_optionalChain([o, 'access', _77 => _77.details, 'optionalAccess', _78 => _78.message, 'optionalAccess', _79 => _79.toString, 'call', _80 => _80()])||"Session expired"),i())});return()=>l()},[e,t,i,n,s])}function qe(r){let{isAuthenticated:e,onTokensUpdated:t,onSessionExpired:i}=r;_react.useEffect.call(void 0, ()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(_chunk4LMFQECSjs.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),t(o))}catch(o){_chunk4LMFQECSjs.a.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(_chunk4LMFQECSjs.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),t(null),e&&i())}catch(o){_chunk4LMFQECSjs.a.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_PING":case"SESSION_PONG":break}},s=_.subscribe(n);return()=>s()},[e,t,i]),_react.useEffect.call(void 0, ()=>{let n=v.subscribeToChanges(async(s,l,o)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;o&&e?(t(null),i()):o&&t(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&s&&t(s)});return()=>n()},[e,t,i])}async function je(r){let{sessionManager:e,options:t,stateActions:i}=r;try{i.setState(o=>({...o,isLoading:!0,error:null}));let n={autoRestore:_nullishCoalesce(t.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(t.enableLogging, () => (!1)),showNotification:t.showNotification,translateFn:t.translateFn,apiEndpointAdmin:t.apiEndpointAdmin,apiKeyEndpointAdmin:t.apiKeyEndpointAdmin,publicApiKey:t.publicApiKey,env:t.env||"stg",onSessionExpired:()=>{let o=e.getIsSessionActive();i.setState(d=>({...d,isAuthenticated:!1,tokens:null,error:o?"Session expired":null})),_optionalChain([t, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},onSessionRestored:o=>{i.setState(d=>({...d,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([t, 'access', _83 => _83.onSessionRestored, 'optionalCall', _84 => _84(o)])},onLoginSuccess:o=>{i.setState(d=>({...d,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};await e.initialize(n),e.setupResponseInterceptor();let s=await e.isAuthenticated(),l=await e.getTokenInfo();i.setState(o=>({...o,isAuthenticated:s,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:V(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";_chunk4LMFQECSjs.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function Ee(r={}){let e=re.getInstance(),t=Ge(),{state:i}=t,{login:n,logout:s,refreshTokens:l,clearError:o}=We({sessionManager:e,stateManager:t}),d=_react.useCallback.call(void 0, f=>{t.setAuthenticated(!!f,f)},[t]),p=_react.useCallback.call(void 0, ()=>{t.setAuthenticated(!1,null),_optionalChain([r, 'access', _85 => _85.onSessionExpired, 'optionalCall', _86 => _86()])},[t,r.onSessionExpired]),b=_react.useCallback.call(void 0, f=>{t.setLoading(f)},[t]),S=_react.useCallback.call(void 0, f=>{t.setError(f)},[t]);_react.useEffect.call(void 0, ()=>{je({sessionManager:e,options:r,stateActions:t})},[]),Be({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:e,onTokensRefreshed:d,onSessionExpired:p,onSetLoading:b,logout:s}),Xe({sessionManager:e,onTokensUpdated:d,onSessionExpired:p,onSetLoading:b,onSetError:S}),qe({isAuthenticated:i.isAuthenticated,onTokensUpdated:d,onSessionExpired:p});let g=_react.useCallback.call(void 0, ()=>{e.updateLastActivity()},[e]),I=_react.useCallback.call(void 0, async()=>e.getTokenInfo(),[e]);return{...i,login:n,logout:s,refreshTokens:l,clearError:o,getTokenInfo:I,updateActivity:g,isExpiringSoon:Ve(i.tokens),expiresIn:$e(i.tokens),refreshExpiresIn:Ye(i.tokens)}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var Qe=_react.createContext.call(void 0, null),ti=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}),Se= exports.f =({children:r,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=_react.useState.call(void 0, []),d=_react.useCallback.call(void 0, (g,I="info",f)=>{if(!n)return"";if(!g||typeof g!="string")return _chunk4LMFQECSjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";g.length>1e3&&(_chunk4LMFQECSjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),g=g.substring(0,1e3)+"...");let k=_uuid.v4.call(void 0, ),R={id:k,message:g,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _87 => _87.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _88 => _88.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _89 => _89.allowHtml]), () => (s))};return o(A=>[...A.length>=e?A.slice(-(e-1)):A,R]),k},[e,t,n,s]),p=_react.useCallback.call(void 0, g=>{o(I=>I.filter(f=>f.id!==g))},[]),b=_react.useCallback.call(void 0, ()=>{o([])},[]),S={showNotification:d,hideNotification:p,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, Qe.Provider,{value:S,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(g=>_jsxruntime.jsx.call(void 0, ii,{notification:g,onClose:()=>p(g.id)},g.id))})})]})},ii=({notification:r,onClose:e})=>{let[t,i]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:n,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:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ti(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},et= exports.g =()=>{let r=_react.useContext.call(void 0, Qe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Te=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(e){this.credentials=e,this.isReady=!0,this.listeners.forEach(t=>{try{t(e)}catch(i){_chunk4LMFQECSjs.a.error("[CredentialsEventBus] Error in listener",i instanceof Error?i:{message:String(i)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(e=>{this.listeners.push(e)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ae= exports.h =Te.getInstance();var tt=_react.createContext.call(void 0, void 0),it= exports.i =({config:r,children:e})=>{let[t,i]=_react.useState.call(void 0, !0),[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[d,p]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),i(!1),o(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===d&&l){i(!1);return}(async()=>{i(!0),s(null),o(!1);try{_crudifysdk.CrudifyInstance.config(r.env||"prod");let k=await _crudifysdk.CrudifyInstance.init(r.publicApiKey,"none");if(S(k),typeof _crudifysdk.CrudifyInstance.transaction=="function"&&typeof _crudifysdk.CrudifyInstance.login=="function")o(!0),p(I),k.apiEndpointAdmin&&k.apiKeyEndpointAdmin&&ae.notifyCredentialsReady({apiUrl:k.apiEndpointAdmin,apiKey:k.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(k){let R=k instanceof Error?k.message:"Failed to initialize Crudify";_chunk4LMFQECSjs.a.error("[CrudifyProvider] Initialization error",k instanceof Error?k:{message:String(k)}),s(R),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,d,l]);let g={crudify:l?_crudifysdk.CrudifyInstance:null,isLoading:t,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, tt.Provider,{value:g,children:e})},rt= exports.j =()=>{let r=_react.useContext.call(void 0, tt);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var st=_react.createContext.call(void 0, void 0);function nt({children:r,options:e={},config:t,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:f}=et();s=f}catch (e10){}let l={};try{let f=rt();f.isInitialized&&f.adminCredentials&&(l=f.adminCredentials)}catch (e11){}let o=_react.useMemo.call(void 0, ()=>{let f=_chunk4LMFQECSjs.d.call(void 0, {publicApiKey:_optionalChain([t, 'optionalAccess', _90 => _90.publicApiKey]),env:_optionalChain([t, 'optionalAccess', _91 => _91.env]),enableDebug:_optionalChain([e, 'optionalAccess', _92 => _92.enableLogging])});return{publicApiKey:f.publicApiKey,env:f.env||"prod"}},[t,_optionalChain([e, 'optionalAccess', _93 => _93.enableLogging])]),d=_react2.default.useMemo(()=>({...e,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{_optionalChain([e, 'access', _94 => _94.onSessionExpired, 'optionalCall', _95 => _95()])}}),[e,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),p=Ee(d),b=_react.useMemo.call(void 0, ()=>{let f=_chunk4LMFQECSjs.d.call(void 0, {publicApiKey:_optionalChain([t, 'optionalAccess', _96 => _96.publicApiKey]),env:_optionalChain([t, 'optionalAccess', _97 => _97.env]),appName:_optionalChain([t, 'optionalAccess', _98 => _98.appName]),logo:_optionalChain([t, 'optionalAccess', _99 => _99.logo]),loginActions:_optionalChain([t, 'optionalAccess', _100 => _100.loginActions]),enableDebug:_optionalChain([e, 'optionalAccess', _101 => _101.enableLogging])});return{publicApiKey:f.publicApiKey,env:f.env,appName:f.appName,loginActions:f.loginActions,logo:f.logo}},[t,_optionalChain([e, 'optionalAccess', _102 => _102.enableLogging])]),S=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([p, 'access', _103 => _103.tokens, 'optionalAccess', _104 => _104.accessToken])||!p.isAuthenticated)return null;try{let f=_chunk4LMFQECSjs.r.call(void 0, p.tokens.accessToken);if(f&&f.sub&&f.email&&f.subscriber){let k={_id:f.sub,email:f.email,subscriberKey:f.subscriber};return Object.keys(f).forEach(R=>{["sub","email","subscriber"].includes(R)||(k[R]=f[R])}),k}}catch(f){_chunk4LMFQECSjs.a.error("Error decoding JWT token for sessionData",f instanceof Error?f:{message:String(f)})}return null},[_optionalChain([p, 'access', _105 => _105.tokens, 'optionalAccess', _106 => _106.accessToken]),p.isAuthenticated]),g={...p,sessionData:S,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, st.Provider,{value:g,children:r})}function en(r){let e={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _107 => _107.notificationOptions, 'optionalAccess', _108 => _108.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _109 => _109.notificationOptions, 'optionalAccess', _110 => _110.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _111 => _111.notificationOptions, 'optionalAccess', _112 => _112.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _113 => _113.notificationOptions, 'optionalAccess', _114 => _114.allowHtml])||!1};return _optionalChain([r, 'access', _115 => _115.config, 'optionalAccess', _116 => _116.publicApiKey])?_jsxruntime.jsx.call(void 0, it,{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, Se,{...e,children:_jsxruntime.jsx.call(void 0, nt,{...r})})}):_jsxruntime.jsx.call(void 0, Se,{...e,children:_jsxruntime.jsx.call(void 0, nt,{...r})})}function di(){let r=_react.useContext.call(void 0, st);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function tn(){let r=di();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 ln=(r={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:i=3}=r,[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[d,p]=_react.useState.call(void 0, null),[b,S]=_react.useState.call(void 0, {}),g=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),f=_react.useRef.call(void 0, 0),k=_react.useRef.call(void 0, 0),R=_react.useCallback.call(void 0, ()=>{s(null),p(null),o(!1),S({})},[]),A=_react.useCallback.call(void 0, async()=>{let O=_chunk4LMFQECSjs.s.call(void 0, );if(!O){I.current&&(p("No user email available"),o(!1));return}g.current&&g.current.abort();let w=new AbortController;g.current=w;let U=++f.current;try{I.current&&(o(!0),p(null));let F=await _crudifysdk.CrudifyInstance.readItems("users",{filter:{email:O},pagination:{limit:1}});if(U===f.current&&I.current&&!w.signal.aborted){let L=F.data;if(F.success&&L&&L.length>0){let T=L[0];s(T);let W={fullProfile:T,totalFields:Object.keys(T).length,displayData:{id:T.id,email:T.email,username:T.username,firstName:T.firstName,lastName:T.lastName,fullName:T.fullName||`${T.firstName||""} ${T.lastName||""}`.trim(),role:T.role,permissions:T.permissions||[],isActive:T.isActive,lastLogin:T.lastLogin,createdAt:T.createdAt,updatedAt:T.updatedAt,...Object.keys(T).filter(G=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(G)).reduce((G,te)=>({...G,[te]:T[te]}),{})}};S(W),p(null),k.current=0}else p("User profile not found"),s(null),S({})}}catch(F){if(U===f.current&&I.current){let L=F;if(L.name==="AbortError")return;t&&k.current<i&&(_optionalChain([L, 'access', _117 => _117.message, 'optionalAccess', _118 => _118.includes, 'call', _119 => _119("Network Error")])||_optionalChain([L, 'access', _120 => _120.message, 'optionalAccess', _121 => _121.includes, 'call', _122 => _122("Failed to fetch")]))?(k.current++,setTimeout(()=>{I.current&&A()},1e3*k.current)):(p("Failed to load user profile"),s(null),S({}))}}finally{U===f.current&&I.current&&o(!1),g.current===w&&(g.current=null)}},[t,i]);return _react.useEffect.call(void 0, ()=>{e&&A()},[e,A]),_react.useEffect.call(void 0, ()=>(I.current=!0,()=>{I.current=!1,g.current&&(g.current.abort(),g.current=null)}),[]),{userProfile:n,loading:l,error:d,extendedData:b,refreshProfile:A,clearProfile:R}};var fn=(r,e={})=>{let{autoFetch:t=!0,onSuccess:i,onError:n}=e,{prefix:s,padding:l=0,separator:o=""}=r,[d,p]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, !1),[g,I]=_react.useState.call(void 0, null),f=_react.useRef.call(void 0, !1),k=_react.useCallback.call(void 0, w=>{let U=String(w).padStart(l,"0");return`${s}${o}${U}`},[s,l,o]),R=_react.useCallback.call(void 0, async()=>{S(!0),I(null);try{let w=await _crudifysdk.CrudifyInstance.getNextSequence(s),U=w.data;if(w.success&&_optionalChain([U, 'optionalAccess', _123 => _123.value])){let F=k(U.value);p(F),_optionalChain([i, 'optionalCall', _124 => _124(F)])}else{let F=_optionalChain([w, 'access', _125 => _125.errors, 'optionalAccess', _126 => _126._error, 'optionalAccess', _127 => _127[0]])||"Failed to generate code";I(F),_optionalChain([n, 'optionalCall', _128 => _128(F)])}}catch(w){let U=w instanceof Error?w.message:"Unknown error";I(U),_optionalChain([n, 'optionalCall', _129 => _129(U)])}finally{S(!1)}},[s,k,i,n]),A=_react.useCallback.call(void 0, async()=>{await R()},[R]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{t&&!d&&!f.current&&(f.current=!0,R())},[t,d,R]),{value:d,loading:b,error:g,regenerate:A,clearError:O}};var ke=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(e){let{priority:t,publicApiKey:i,env:n,enableLogging:s,requestedBy:l}=e;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&_chunk4LMFQECSjs.a.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _130 => _130.state, 'access', _131 => _131.publicApiKey, 'optionalAccess', _132 => _132.slice, 'call', _133 => _133(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunk4LMFQECSjs.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunk4LMFQECSjs.a.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){s&&_chunk4LMFQECSjs.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&_chunk4LMFQECSjs.a.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunk4LMFQECSjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunk4LMFQECSjs.a.debug(`[CrudifyInitialization] ${l} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=l,this.initializationPromise=this.performInitialization(i,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=i,this.state.env=n,this.state.error=null,s&&_chunk4LMFQECSjs.a.info(`[CrudifyInitialization] Successfully initialized by ${l} (${t} priority)`)}catch(o){throw this.state.status="ERROR",this.state.error=o instanceof Error?o:new Error(String(o)),this.initializationPromise=null,_chunk4LMFQECSjs.a.error(`[CrudifyInitialization] Initialization failed for ${l}`,o instanceof Error?o:{message:String(o)}),o}}async waitForHighPriorityOrTimeout(e){return new Promise(t=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),e&&_chunk4LMFQECSjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(e,t,i){let n=_crudifysdk.CrudifyInstance.getTokenData();if(n&&n.endpoint){i&&_chunk4LMFQECSjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk.CrudifyInstance.config(t);let s=i?"debug":"none",l=await _crudifysdk.CrudifyInstance.init(e,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&ae.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.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}}},de= exports.q =ke.getInstance();var lt=r=>{let e=new Uint8Array(r);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").substring(0,r)},Ae=()=>`file_${Date.now()}_${lt(7)}`,ct=r=>{let e=r.lastIndexOf("."),t=e>0?r.substring(e):"",i=Date.now(),n=lt(6);return`${i}_${n}${t}`},fe=(r,e)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let t=new URL(r);return t.pathname.startsWith("/")?t.pathname.substring(1):t.pathname}catch (e12){if(e&&r.startsWith(e))return r.substring(e.length)}return e&&r.startsWith(e)?r.substring(e.length):r};var yi={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"},ut=r=>{let e=_optionalChain([r, 'access', _134 => _134.split, 'call', _135 => _135("."), 'access', _136 => _136.pop, 'call', _137 => _137(), 'optionalAccess', _138 => _138.toLowerCase, 'call', _139 => _139()])||"";return yi[e]||"application/octet-stream"};var dt=(r,e,t=10485760)=>e&&e.length>0&&!e.includes(r.type)?{valid:!1,error:`File type not allowed: ${r.type}`}:r.size>t?{valid:!1,error:`File exceeds maximum size of ${(t/1048576).toFixed(1)}MB`}:{valid:!0},ft=(r,e=0,t)=>{let i=r.filter(s=>s.status==="completed").length;if(i<e){let s=e===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:s,validationErrorKey:s,validationErrorParams:{count:e}}}return t!==void 0&&i>t?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:t}}:r.some(s=>s.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}};var pt=async(r,e,t)=>{if(!de.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let i=ct(r),n=await _crudifysdk.CrudifyInstance.generateSignedUrl({fileName:i,contentType:e,visibility:t});if(!n.success||!n.data)throw new Error("Failed to get upload URL");let s=n.data,{uploadUrl:l,s3Key:o,publicUrl:d}=s;if(!l||!o)throw new Error("Incomplete signed URL response");let p=o.indexOf("/"),b=p>0?o.substring(p+1):o;return{uploadUrl:l,filePath:b,publicUrl:t==="public"?d:void 0}},gt=async(r,e,t)=>new Promise((i,n)=>{let s=new XMLHttpRequest;s.upload.addEventListener("progress",l=>{if(l.lengthComputable&&_optionalChain([t, 'optionalAccess', _140 => _140.onProgress])){let o=Math.round(l.loaded/l.total*100);t.onProgress(o)}}),s.addEventListener("load",()=>{s.status>=200&&s.status<300?i():n(new Error(`Upload failed with status ${s.status}`))}),s.addEventListener("error",()=>{n(new Error("Network error during upload"))}),s.addEventListener("abort",()=>{n(new Error("Upload cancelled"))}),s.open("PUT",e),s.setRequestHeader("Content-Type",r.type),s.send(r)}),Ce=async(r,e)=>{if(!de.isInitialized())return{success:!1,error:"Crudify not initialized"};try{let t=fe(r,e);return(await _crudifysdk.CrudifyInstance.disableFile({filePath:t})).success?{success:!0}:{success:!1,error:"Failed to delete file"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}},mt=async(r,e=3600)=>{if(!de.isInitialized())return null;try{let t=await _crudifysdk.CrudifyInstance.getFileUrl({filePath:r,expiresIn:e}),i=t.data;return t.success&&_optionalChain([i, 'optionalAccess', _141 => _141.url])?i.url:null}catch (e13){return null}};var Si=(r={})=>{let{acceptedTypes:e,maxFileSize:t=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:d,onFilesChange:p,mode:b="edit"}=r,[S,g]=_react.useState.call(void 0, []),[I,f]=_react.useState.call(void 0, !1),[k,R]=_react.useState.call(void 0, !1),[A,O]=_react.useState.call(void 0, []),w=_react.useRef.call(void 0, new Map),U=_react.useCallback.call(void 0, ()=>{f(!0)},[]),F=_react.useCallback.call(void 0, ()=>{R(!0),f(!0)},[]),L=_react.useCallback.call(void 0, (u,h)=>{g(E=>E.map(m=>m.id===u?{...m,...h}:m))},[]),T=_react.useCallback.call(void 0, u=>{_optionalChain([p, 'optionalCall', _142 => _142(u)])},[p]),W=_react.useCallback.call(void 0, u=>dt(u,e,t),[e,t]),G=_react.useCallback.call(void 0, async(u,h)=>{try{let{uploadUrl:E,filePath:y,publicUrl:m}=await pt(h.name,h.type,s);L(u.id,{status:"uploading",progress:0}),await gt(h,E,{onProgress:x=>L(u.id,{progress:x})});let C={status:"completed",progress:100,filePath:y,visibility:s,publicUrl:m,file:void 0};g(x=>{let z=x.map(j=>j.id===u.id?{...j,...C}:j);T(z);let $=z.find(j=>j.id===u.id);return $&&_optionalChain([l, 'optionalCall', _143 => _143($)]),z})}catch(E){let y=E instanceof Error?E.message:"Unknown error";L(u.id,{status:"error",progress:0,errorMessage:y}),g(m=>{let C=m.find(x=>x.id===u.id);return C&&_optionalChain([o, 'optionalCall', _144 => _144(C,y)]),m})}},[L,l,o,s,T]),te=_react.useCallback.call(void 0, async u=>{let h=Array.from(u),E=[];g(y=>{if(i!==void 0){let x=y.filter($=>$.status!=="pendingDeletion"&&$.status!=="error").length,z=i-x;if(z<=0)return _chunk4LMFQECSjs.a.warn(`File limit of ${i} already reached`),y;h.length>z&&(h=h.slice(0,z),_chunk4LMFQECSjs.a.warn(`Only ${z} files will be added to not exceed limit`))}let m=[];for(let x of h){let z=W(x),$={id:Ae(),name:x.name,size:x.size,contentType:x.type,status:z.valid?"pending":"error",progress:0,createdAt:Date.now(),file:z.valid?x:void 0,errorMessage:z.error,isExisting:!1};m.push($)}E=m;let C=[...y,...m];return T(C),C}),setTimeout(()=>{let y=E.filter(m=>m.status==="pending"&&m.file);for(let m of y)if(m.file){let C=G(m,m.file);w.current.set(m.id,C),C.finally(()=>{w.current.delete(m.id)})}},0)},[i,W,G,T]),ht=_react.useCallback.call(void 0, async u=>{let h=S.find(y=>y.id===u);if(!h)return{needsConfirmation:!1,isExisting:!1};let E=h.isExisting===!0;return b==="create"||!E?{needsConfirmation:!0,isExisting:E}:(O(y=>[...y,u]),g(y=>{let m=y.map(x=>x.id===u?{...x,status:"pendingDeletion"}:x),C=m.filter(x=>x.status!=="pendingDeletion");return T(C),m}),{needsConfirmation:!1,isExisting:E})},[S,b,T]),yt=_react.useCallback.call(void 0, async u=>{let h=S.find(y=>y.id===u);if(!h)return{success:!1,error:"File not found"};if(!h.filePath)return g(y=>{let m=y.filter(C=>C.id!==u);return T(m),m}),{success:!0};let E=await Ce(h.filePath);return E.success?(g(y=>{let m=y.filter(C=>C.id!==u);return T(m),m}),_optionalChain([d, 'optionalCall', _145 => _145(h)]),{success:!0}):{success:!1,error:E.error||"Failed to delete file"}},[S,T,d]),Et=_react.useCallback.call(void 0, u=>{let h=S.find(E=>E.id===u);return!h||!h.isExisting?!1:(O(E=>E.filter(y=>y!==u)),g(E=>{let y=E.map(m=>m.id===u?{...m,status:"completed"}:m);return T(y),y}),!0)},[S,T]),St=_react.useCallback.call(void 0, ()=>{A.length!==0&&(g(u=>{let h=u.map(E=>A.includes(E.id)?{...E,status:"completed"}:E);return T(h),h}),O([]))},[A,T]),Tt=_react.useCallback.call(void 0, async()=>{if(A.length===0)return{success:!0,errors:[]};let u=[],h=[];for(let E of A){let y=S.find(C=>C.id===E);if(!_optionalChain([y, 'optionalAccess', _146 => _146.filePath])){h.push(E);continue}let m=await Ce(y.filePath);m.success?(h.push(E),_optionalChain([d, 'optionalCall', _147 => _147(y)])):u.push(m.error||`Failed to delete ${y.name}`)}return h.length>0&&(g(E=>E.filter(m=>!h.includes(m.id))),O(E=>E.filter(y=>!h.includes(y)))),{success:u.length===0,errors:u}},[S,A,d]),vt=_react.useCallback.call(void 0, ()=>{g([]),T([])},[T]),bt=_react.useCallback.call(void 0, async u=>{let h=S.find(y=>y.id===u);if(!h||h.status!=="error"||!h.file){_chunk4LMFQECSjs.a.warn("Cannot retry: file not found or no original file");return}L(u,{status:"pending",progress:0,errorMessage:void 0});let E=G(h,h.file);w.current.set(u,E),E.finally(()=>{w.current.delete(u)})},[S,L,G]),It=_react.useCallback.call(void 0, async()=>{let u=Array.from(w.current.values());return u.length>0&&await Promise.allSettled(u),new Promise(h=>{setTimeout(()=>{g(E=>{let y=E.filter(m=>m.status==="completed"&&m.filePath).map(m=>m.filePath);return h(y),E})},0)})},[]),kt=_react.useCallback.call(void 0, (u,h)=>{let E=u.map(y=>{let m=fe(y.filePath,h),C=m.includes("/public/")||m.startsWith("public/")?"public":"private",x=y.contentType||ut(y.name);return{id:Ae(),name:y.name,size:y.size||0,contentType:x,status:"completed",progress:100,filePath:m,visibility:C,createdAt:Date.now(),isExisting:!0}});g(E),T(E)},[T]),At=_react.useCallback.call(void 0, async u=>{let h=S.find(E=>E.id===u);return!h||!h.filePath?null:h.visibility==="public"&&h.publicUrl?h.publicUrl:mt(h.filePath,3600)},[S]),xt=_react.useMemo.call(void 0, ()=>S.some(u=>u.status==="uploading"||u.status==="pending"),[S]),Ct=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="uploading"||u.status==="pending").length,[S]),wt=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[S]),q=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status!=="pendingDeletion"),[S]),Rt=_react.useMemo.call(void 0, ()=>q.filter(u=>u.status==="completed"||u.status==="pending"||u.status==="uploading").length,[q]),{isValid:Nt,validationError:Pt,validationErrorKey:Dt,validationErrorParams:Lt}=_react.useMemo.call(void 0, ()=>ft(q,n,i),[q,n,i]),Ot=A.length>0;return{files:S,activeFiles:q,activeFileCount:Rt,isUploading:xt,pendingCount:Ct,addFiles:te,removeFile:ht,deleteFileImmediately:yt,restoreFile:Et,clearFiles:vt,retryUpload:bt,isValid:Nt,validationError:Pt,validationErrorKey:Dt,validationErrorParams:Lt,waitForUploads:It,completedFilePaths:wt,initializeFiles:kt,isTouched:I,markAsTouched:U,isSubmitted:k,markAsSubmitted:F,getPreviewUrl:At,pendingDeletions:A,hasPendingDeletions:Ot,commitDeletions:Tt,restorePendingDeletions:St}};exports.a = v; exports.b = me; exports.c = _; exports.d = re; exports.e = Ee; exports.f = Se; exports.g = et; exports.h = ae; exports.i = it; exports.j = rt; exports.k = en; exports.l = di; exports.m = tn; exports.n = ln; exports.o = fn; exports.p = ke; exports.q = de; exports.r = Si;
@@ -0,0 +1 @@
1
+ import{g as z,l as b}from"./chunk-2WHCDP7V.mjs";import{a as Y,v as j}from"./chunk-44VU4TSP.mjs";import{useState as K,useEffect as H,useCallback as q,useRef as F}from"react";import{CrudifyInstance as re}from"@nocios/crudify-sdk";var ue=(r={})=>{let{autoFetch:o=!0,retryOnError:a=!1,maxRetries:t=3}=r,{isAuthenticated:s,isInitialized:n,sessionData:u,tokens:l}=b(),[E,d]=K(null),[A,I]=K(o&&s),[S,C]=K(null),N=F(null),f=F(!0),y=F(0),e=F(0),m=q(()=>{if(!u)return null;let i=u["cognito:username"];return u.email||(typeof i=="string"?i:null)},[u]),c=q(()=>{d(null),C(null),I(!1),e.current=0},[]),p=q(async()=>{let i=m();if(!i){f.current&&(C("No user email available from session data"),I(!1));return}if(!n){f.current&&(C("Session not initialized"),I(!1));return}N.current&&N.current.abort();let g=new AbortController;N.current=g;let O=++y.current;try{f.current&&(I(!0),C(null));let w=await re.readItems("users",{filter:{email:i},pagination:{limit:1}});if(O===y.current&&f.current&&!g.signal.aborted){let h=null;if(w.success){let R=w.data;if(Array.isArray(R)&&R.length>0)h=R[0];else if(R&&typeof R=="object"&&!Array.isArray(R)&&R.response?.data)try{let D=R.response.data,k=typeof D=="string"?JSON.parse(D):D;k&&k.items&&Array.isArray(k.items)&&k.items.length>0&&(h=k.items[0])}catch{}else R&&typeof R=="object"&&!Array.isArray(R)&&R.items&&Array.isArray(R.items)&&R.items.length>0&&(h=R.items[0]);if(!h&&R&&typeof R=="object"&&!Array.isArray(R)&&R.data?.response?.data)try{let D=R.data.response.data,k=typeof D=="string"?JSON.parse(D):D;k&&k.items&&Array.isArray(k.items)&&k.items.length>0&&(h=k.items[0])}catch{}}h?(d(h),C(null),e.current=0):(C("User profile not found in database"),d(null))}}catch(w){if(O===y.current&&f.current){let h=w;if(h.name==="AbortError")return;a&&e.current<t&&(h.message?.includes("Network Error")||h.message?.includes("Failed to fetch"))?(e.current++,setTimeout(()=>{f.current&&p()},1e3*e.current)):(C("Failed to load user profile from database"),d(null))}}finally{O===y.current&&f.current&&I(!1),N.current===g&&(N.current=null)}},[n,m,a,t]);return H(()=>{o&&s&&n?p():s||c()},[o,s,n,p,c]),H(()=>(f.current=!0,()=>{f.current=!1,N.current&&(N.current.abort(),N.current=null)}),[]),{user:{session:u,data:E},loading:A,error:S,refreshProfile:p,clearProfile:c}};import{useCallback as te}from"react";var ye=()=>{let{isAuthenticated:r,isLoading:o,isInitialized:a,tokens:t,error:s,sessionData:n,login:u,logout:l,refreshTokens:E,clearError:d,getTokenInfo:A,isExpiringSoon:I,expiresIn:S,refreshExpiresIn:C}=b(),N=te(y=>{y?Y.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):l()},[l]),f=t?.expiresAt?new Date(t.expiresAt):null;return{isAuthenticated:r,loading:o,error:s,token:t?.accessToken||null,user:n,tokenExpiration:f,setToken:N,logout:l,refreshToken:E,login:u,isExpiringSoon:I,expiresIn:S,refreshExpiresIn:C,getTokenInfo:A,clearError:d}};import{useCallback as T}from"react";import{CrudifyInstance as P}from"@nocios/crudify-sdk";var Oe=()=>{let{isInitialized:r,isLoading:o,error:a,isAuthenticated:t,login:s}=b(),n=T(()=>r&&!o&&!a,[r,o,a]),u=T(async()=>new Promise((f,y)=>{let e=()=>{n()?f():a?y(new Error(a)):setTimeout(e,100)};e()}),[n,a]),l=T(async()=>{if(!n())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[n]),E=T(async(f,y,e)=>(await l(),await P.readItems(f,y||{},e)),[l]),d=T(async(f,y,e)=>(await l(),await P.readItem(f,y,e)),[l]),A=T(async(f,y,e)=>(await l(),await P.createItem(f,y,e)),[l]),I=T(async(f,y,e)=>(await l(),await P.updateItem(f,y,e)),[l]),S=T(async(f,y,e)=>(await l(),await P.deleteItem(f,y,e)),[l]),C=T(async(f,y)=>(await l(),await P.transaction(f,y)),[l]),N=T(async(f,y)=>{try{let e=await s(f,y);return e.success?{success:!0,data:e.tokens}:{success:!1,errors:e.error||"Login failed"}}catch(e){return{success:!1,errors:e instanceof Error?e.message:"Login failed"}}},[s]);return{readItems:E,readItem:d,createItem:A,updateItem:I,deleteItem:S,transaction:C,login:N,isInitialized:r,isInitializing:o,initializationError:a,isReady:n,waitForReady:u}};import{useCallback as L}from"react";var x={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"},W=["errors.auth.","errors.data.","errors.system.","errors."],$=["create","update","delete"],G="Ha ocurrido un error inesperado",Q=6e3;function M(r){if(!r.success&&r.errors&&(Object.keys(r.errors).some(t=>t!=="_error"&&t!=="_graphql"&&t!=="_transaction")||r.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||r.errors._error?.includes("TOO_MANY_REQUESTS")))return!1;let o=r.data;return!(!r.success&&o?.response?.status==="TOO_MANY_REQUESTS")}function V(r){return $.includes(r)}function B(r,o,a,t){return a?V(r)&&o?!0:t.some(s=>s.key===r):!1}function J(r,o,a){for(let t of W){let s=`${t}${r}`,n=o(s);if(n!==a("error.unknown"))return n}return null}function se(r,o,a){if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(!Array.isArray(r)||r.length===0)return o("error.transaction","Error en la operaci\xF3n");let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>0){let n=s[0];if(n?.response?.errorCode){let u=n.response.errorCode;if(x[u])return o(x[u]);let l=J(u,o,a);if(l)return l}if(n?.response?.data)return n.response.data}if(s?.response?.message){let n=s.response.message.toLowerCase();return n.includes("expired")?o("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?o("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):s.response.message}}catch{return t.toLowerCase().includes("expired")?o("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?o("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}return o("error.transaction","Error en la operaci\xF3n")}function oe(r,o,a){let t=Object.keys(r);if(t.length===1&&t[0]==="_transaction")return se(r._transaction,o,a);if(t.length===1&&t[0]==="_error"){let s=r._error;return Array.isArray(s)?s[0]:String(s)}return t.length===1&&t[0]==="_graphql"?o("errors.system.DATABASE_CONNECTION_ERROR"):`${o("errors.data.FIELD_ERROR")}: ${t.join(", ")}`}function X(r,o){let{customErrorMessages:a,defaultErrorMessage:t,translateFn:s,getSafeTranslation:n}=o;if(r.errorCode&&a[r.errorCode])return a[r.errorCode];if(r.errorCode&&x[r.errorCode])return n(x[r.errorCode]);if(r.errorCode){let u=J(r.errorCode,n,s);if(u)return u}if(typeof r.data=="string"&&r.data.startsWith("errors.")){let u=n(r.data);if(u!==s("error.unknown"))return u}return r.errors&&Object.keys(r.errors).length>0?oe(r.errors,n,s):t||s("error.unknown")}function Z(r,o,a,t){let{translateFn:s,getSafeTranslation:n}=t,u=a?.key&&typeof a.key=="string"?a.key:r,l=`action.onSuccess.${u}`,E=n(l);if(E!==s("error.unknown")){if(V(u)&&o){let d=`action.${o}Singular`,A=n(d);if(A!==s("error.unknown"))return s(l,{item:A});{let I=`action.onSuccess.${u}WithoutItem`,S=n(I);return S!==s("error.unknown")?S:E}}return E}return s("base.success.transaction")}import{useCallback as U}from"react";import{CrudifyInstance as v}from"@nocios/crudify-sdk";function ee(r){let{showErrorNotifications:o,showSuccessNotifications:a,autoHideDuration:t,appStructure:s,showNotification:n,getErrorMessage:u,getErrorSeverity:l,getSuccessMessage:E}=r,d=U(e=>{if(!e.success&&o&&M(e)){let m=u(e),c=l(e);n(m,c,{autoHideDuration:t})}},[o,n,u,l,t]),A=U((e,m,c,p)=>{if(e.success&&B(m,c,a,s)){let _=E(m,c,p);n(_,"success",{autoHideDuration:t})}},[a,s,n,E,t]),I=U(async(e,m,c)=>{let p=await v.createItem(e,m,c);if(!(c?.skipNotifications===!0)&&(d(p),p.success)){let i=c?.actionConfig,g=i?.key||"create",O=i?.moduleKey||e;A(p,g,O,i)}return p},[d,A]),S=U(async(e,m,c)=>{let p=await v.updateItem(e,m,c);if(!(c?.skipNotifications===!0)&&(d(p),p.success)){let i=c?.actionConfig,g=i?.key||"update",O=i?.moduleKey||e;A(p,g,O,i)}return p},[d,A]),C=U(async(e,m,c)=>{let p=await v.deleteItem(e,m,c);if(!(c?.skipNotifications===!0)&&(d(p),p.success)){let i=c?.actionConfig,g=i?.key||"delete",O=i?.moduleKey||e;A(p,g,O,i)}return p},[d,A]),N=U(async(e,m,c)=>{let p=await v.readItem(e,m,c);return c?.skipNotifications===!0||d(p),p},[d]),f=U(async(e,m,c)=>{let p=await v.readItems(e,m,c);return c?.skipNotifications===!0||d(p),p},[d]),y=U(async(e,m)=>{let c=await v.transaction(e,m);if(!(m?.skipNotifications===!0)&&(d(c),c.success)){let _="transaction",i,g=null;if(m?.actionConfig)g=m.actionConfig,_=g.key,i=g.moduleKey;else if(Array.isArray(e)&&e.length>0&&"operation"in e[0]&&e[0].operation){_=e[0].operation;let O=s.find(w=>w.key===_);O&&(g=O,i=O.moduleKey)}A(c,_,i,g??void 0)}return c},[d,A,s]);return{createItem:I,updateItem:S,deleteItem:C,readItem:N,readItems:f,transaction:y}}var ie=(r={})=>{let{showNotification:o}=z(),{showSuccessNotifications:a=!1,showErrorNotifications:t=!0,customErrorMessages:s={},defaultErrorMessage:n=G,autoHideDuration:u=Q,appStructure:l=[],translateFn:E=i=>i}=r,d=L((i,g)=>{let O=E(i);return O===i?g||E("error.unknown"):O},[E]),A={customErrorMessages:s,defaultErrorMessage:n,translateFn:E,getSafeTranslation:d},I={translateFn:E,getSafeTranslation:d},S=L(i=>X(i,A),[s,n,E,d]),C=L(i=>i.errorCode&&j[i.errorCode]?j[i.errorCode]:"error",[]),N=L((i,g,O)=>Z(i,g,O,I),[E,d]),{createItem:f,updateItem:y,deleteItem:e,readItem:m,readItems:c,transaction:p}=ee({showErrorNotifications:t,showSuccessNotifications:a,autoHideDuration:u,appStructure:l,showNotification:o,getErrorMessage:S,getErrorSeverity:C,getSuccessMessage:N}),_=L((i,g)=>{if(!i.success&&t&&M(i)){let O=S(i),w=C(i);o(O,w,{autoHideDuration:u})}else i.success&&a&&g&&o(g,"success",{autoHideDuration:u});return i},[t,a,o,S,C,u]);return{createItem:f,updateItem:y,deleteItem:e,readItem:m,readItems:c,transaction:p,handleResponse:_,getErrorMessage:S,getErrorSeverity:C,shouldShowNotification:M}};export{ue as a,ye as b,Oe as c,ie as d};
@@ -0,0 +1 @@
1
+ import{g as ho,i as yo,j as ge,l as he,n as bo,o as wo,r as xo}from"./chunk-2WHCDP7V.mjs";import{A as $,a as x,b as po,d as mo,f as fo,p as go}from"./chunk-44VU4TSP.mjs";var ue={es:{"base.actions.create":"Nuevo","base.actions.delete":"Eliminar","base.actions.read":"Ver","base.actions.refresh":"Refrescar","base.actions.update":"Editar","base.btn.back":"Volver","base.btn.cancel":"Cancelar","base.btn.hidePassword":"Ocultar contrase\xF1a","base.btn.showPassword":"Mostrar contrase\xF1a","base.errors.errorUnknown":"Ocurri\xF3 un error desconocido.","base.fields.actions":"Acciones","base.fields.confirmPassword":"Confirmar contrase\xF1a","base.fields.createdAt":"Creado el","base.fields.email":"Correo electr\xF3nico","base.fields.lastName":"Apellido","base.fields.name":"Nombre","base.fields.password":"Contrase\xF1a","base.fields.profile":"Perfil","base.fields.updatedAt":"Actualizado el","base.file.allowedTypes":"Tipos permitidos: {{types}}","base.file.clickToDownload":"Clic para descargar","base.file.clickToPreview":"Clic para ver imagen","base.file.confirmDelete.cancel":"Cancelar","base.file.confirmDelete.confirm":"Eliminar","base.file.confirmDelete.message":"\xBFEst\xE1s seguro de que deseas eliminar este archivo? Esta acci\xF3n no se puede deshacer.","base.file.confirmDelete.title":"Eliminar archivo","base.file.delete":"Eliminar","base.file.deleting":"Eliminando...","base.file.dragOrClick":"Arrastra archivos aqu\xED o haz clic para seleccionar","base.file.dropHere":"Suelta el archivo aqu\xED","base.file.maxFiles":"M\xE1ximo {{count}} archivos","base.file.maxSize":"M\xE1ximo {{size}} por archivo","base.file.noPreview":"Sin vista previa","base.file.pendingDeletion":"Pendiente de eliminaci\xF3n","base.file.privateFile":"Archivo privado","base.file.restore":"Restaurar","base.file.uploading":"Subiendo archivos...","base.file.validation.filesWithErrors":"Algunos archivos tienen errores","base.file.validation.maxFilesExceeded":"M\xE1ximo {{count}} archivos permitidos","base.file.validation.minFilesRequired":"Se requiere al menos un archivo","base.file.validation.minFilesRequiredPlural":"Se requieren al menos {{count}} archivos","base.lastUpdated":"\xDAltima actualizaci\xF3n a las {{formattedLastUpdated}}","base.loading.configInitial":"Cargando configuraci\xF3n inicial...","base.loading.pleaseWait":"Cargando, por favor espera...","base.loading.starting":"Iniciando aplicaci\xF3n...","base.loading.themeSetup":"Generando tema...","base.loading.validatingSession":"Validando sesi\xF3n...","base.titles.create":"Nuevo {{moduleName}}","base.titles.read":"Ver {{moduleName}}","base.titles.update":"Editar {{moduleName}}","base.success.transaction":"La operaci\xF3n se ha completado con \xE9xito.","base.loading.executing":"Ejecutando operaci\xF3n...","checkCode.codeLabel":"C\xF3digo de Verificaci\xF3n","checkCode.codePlaceholder":"Ingresa el c\xF3digo de 6 d\xEDgitos","checkCode.codeRequired":"El c\xF3digo es obligatorio","checkCode.emailLabel":"Correo Electr\xF3nico","checkCode.emailPlaceholder":"Ingresa tu correo electr\xF3nico","checkCode.emailRequired":"El correo electr\xF3nico es obligatorio","checkCode.instructions":"Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a tu correo electr\xF3nico.","checkCode.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","checkCode.resendCodeLink":"Reenviar c\xF3digo","checkCode.title":"Verificar C\xF3digo","checkCode.verifyButton":"Verificar C\xF3digo","error.app.config":"Error de Configuraci\xF3n: {{message}}","error.app.initialization":"Error durante la inicializaci\xF3n final de la aplicaci\xF3n.","error.transaction":"Error en la operaci\xF3n","errors.DUPLICATE":"El campo <b>{{field}}</b> debe ser \xFAnico.","errors.FOREIGN_KEY_NOT_FOUND":"El campo <b>{{field}}</b> debe referenciar un \xEDtem existente.","errors.INVALID_EMAIL":"El campo <b>{{field}}</b> debe ser un correo electr\xF3nico v\xE1lido.","errors.INVALID_OBJECT_ID":"El campo <b>{{field}}</b> debe ser un valor v\xE1lido.","errors.IN_USE":"El \xEDtem est\xE1 en uso y no puede ser eliminado.","errors.MAX_LENGTH":"El campo <b>{{field}}</b> no debe exceder los <b>{{length}}</b> caracteres.","errors.MIN_LENGTH":"El campo <b>{{field}}</b> debe tener al menos <b>{{length}}</b> caracteres.","errors.MUST_NOT_BE_EMAIL":"El campo <b>{{field}}</b> no debe ser un correo electr\xF3nico.","errors.NO_PERMISSION":"No tienes permiso para realizar esta acci\xF3n.","errors.NO_SPACES":"El campo <b>{{field}}</b> no debe contener espacios.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Error en la operaci\xF3n","errors.REQUIRED":"El campo <b>{{field}}</b> es obligatorio.","errors.TOKEN_HAS_EXPIRED":"La sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.TOO_MANY_REQUESTS":"L\xEDmite de solicitudes alcanzado. Por favor intenta m\xE1s tarde.","errors.UNAUTHORIZED":"No est\xE1s autorizado para realizar esta acci\xF3n.","errors.all_password_fields_required":"Todos los campos de contrase\xF1a son obligatorios","errors.auth.INVALID_API_KEY":"Clave de API inv\xE1lida","errors.auth.INVALID_CREDENTIALS":"Usuario y/o contrase\xF1a incorrectos","errors.auth.NO_PERMISSION":"No tienes permisos suficientes","errors.auth.SESSION_EXPIRED":"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.auth.TOO_MANY_REQUESTS":"Demasiados intentos. Por favor espera 15 minutos e intenta nuevamente","errors.auth.UNAUTHORIZED":"No tienes permisos para realizar esta acci\xF3n","errors.auth.USER_NOT_ACTIVE":"Usuario no activo","errors.auth.USER_NOT_FOUND":"Usuario no encontrado","errors.data.BAD_REQUEST":"Solicitud inv\xE1lida","errors.data.FIELD_ERROR":"Error en los datos ingresados","errors.data.IN_USE":"El elemento est\xE1 en uso y no puede ser eliminado","errors.data.ITEM_NOT_FOUND":"El elemento solicitado no fue encontrado","errors.data.NOT_FOUND":"No se encontr\xF3 lo solicitado","errors.internal_error_changing_password":"Error interno al cambiar la contrase\xF1a. Intenta nuevamente","errors.password_min_length":"La contrase\xF1a debe tener al menos 8 caracteres","errors.password_mismatch":"Las contrase\xF1as no coinciden","errors.password_must_be_different":"La nueva contrase\xF1a debe ser diferente a la actual","errors.system.DATABASE_CONNECTION_ERROR":"Error de conexi\xF3n. Verifica tu conexi\xF3n a internet.","errors.system.INTERNAL_SERVER_ERROR":"Error interno del servidor. Intenta nuevamente.","errors.system.INVALID_CONFIGURATION":"Error de configuraci\xF3n del sistema","errors.system.TOO_MANY_REQUESTS":"Demasiadas solicitudes. Por favor espera un momento e intenta nuevamente","errors.system.UNKNOWN_OPERATION":"Operaci\xF3n no reconocida","errors.users_module_not_configured":"M\xF3dulo de usuarios no configurado","footer.copyright":"Nocios S.R.L. Todos los derechos reservados.","footer.version":"Versi\xF3n","forgotPassword.checkEmailInstructions":"Revisa tu bandeja de entrada para el c\xF3digo de verificaci\xF3n","forgotPassword.codeAlreadyExistsMessage":"Ya se envi\xF3 un c\xF3digo y a\xFAn es v\xE1lido","forgotPassword.emailLabel":"Correo Electr\xF3nico","forgotPassword.emailPlaceholder":"Ingresa tu correo electr\xF3nico","forgotPassword.emailRequired":"El correo electr\xF3nico es obligatorio","forgotPassword.emailSentMessage":"C\xF3digo enviado exitosamente","forgotPassword.enterCodeLink":"Ingresar C\xF3digo","forgotPassword.instructions":"Ingresa tu correo electr\xF3nico y te enviaremos un c\xF3digo para restablecer tu contrase\xF1a.","forgotPassword.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","forgotPassword.sendCodeButton":"Enviar C\xF3digo","forgotPassword.title":"Recuperar Contrase\xF1a","login.alreadyHaveCodeLink":"\xBFYa tienes un c\xF3digo?","login.forgotPasswordLink":"\xBFOlvidaste tu contrase\xF1a?","login.initializationError":"Error de inicializaci\xF3n","login.initializing":"Inicializando...","login.loginButton":"Iniciar sesi\xF3n","login.logoAlt":"Logotipo","login.noAccountPrompt":"\xBFNo tienes una cuenta?","login.notInitialized":"Sistema no inicializado","login.passwordLabel":"Contrase\xF1a","login.passwordPlaceholder":"Ingresa tu contrase\xF1a","login.passwordRequired":"Contrase\xF1a es obligatoria","login.signUpLink":"Reg\xEDstrate","login.usernameOrEmailLabel":"Usuario o correo electr\xF3nico","login.usernameOrEmailPlaceholder":"Ingresa tu correo electr\xF3nico","login.usernameRequired":"El usuario es requerido","passwordRequirements.lowercase":"Una letra min\xFAscula","passwordRequirements.minLength":"M\xEDnimo 8 caracteres","passwordRequirements.number":"Un n\xFAmero","passwordRequirements.special":"Un car\xE1cter especial (!@#$%...)","passwordRequirements.uppercase":"Una letra may\xFAscula","profiles.actions.assignProfiles":"Asignar perfiles","profiles.moduleName":"Perfiles","profiles.moduleSingular":"Perfil","publicPolicies.fields.conditions.customEdit":"Edici\xF3n personalizada","resetPassword.codeExpiredOrInvalid":"El c\xF3digo ha expirado o es inv\xE1lido","resetPassword.confirmPasswordLabel":"Confirmar Contrase\xF1a","resetPassword.confirmPasswordPlaceholder":"Confirma tu nueva contrase\xF1a","resetPassword.confirmPasswordRequired":"Confirma tu contrase\xF1a","resetPassword.goToLoginButton":"Ir al Login","resetPassword.instructions":"Ingresa tu nueva contrase\xF1a.","resetPassword.invalidCode":"El c\xF3digo de verificaci\xF3n es inv\xE1lido. Por favor, verifica el enlace o solicita uno nuevo.","resetPassword.missingParameters":"Faltan par\xE1metros obligatorios","resetPassword.newPasswordLabel":"Nueva Contrase\xF1a","resetPassword.newPasswordPlaceholder":"Ingresa tu nueva contrase\xF1a","resetPassword.newPasswordRequired":"La nueva contrase\xF1a es obligatoria","resetPassword.passwordRequirementsNotMet":"La contrase\xF1a no cumple con todos los requisitos","resetPassword.passwordTooShort":"La contrase\xF1a debe tener al menos 8 caracteres","resetPassword.passwordsDoNotMatch":"Las contrase\xF1as no coinciden","resetPassword.requestNewCodeButton":"Solicitar Nuevo C\xF3digo","resetPassword.resetPasswordButton":"Restablecer Contrase\xF1a","resetPassword.successInstructions":"Ahora puedes iniciar sesi\xF3n con tu nueva contrase\xF1a","resetPassword.successMessage":"Contrase\xF1a restablecida exitosamente","resetPassword.title":"Nueva Contrase\xF1a","resetPassword.validatingCode":"Validando c\xF3digo...","translations.fields.lang":"Idioma","translations.moduleName":"Traducciones","translations.moduleSingular":"Traducci\xF3n","users.fields.currentPassword":"Contrase\xF1a actual","users.fields.newPassword":"Nueva Contrase\xF1a","users.fields.repeatNewPassword":"Repetir Nueva Contrase\xF1a","users.moduleName":"Usuarios","users.moduleSingular":"Usuario"},en:{"base.actions.create":"New","base.actions.delete":"Delete","base.actions.read":"View","base.actions.refresh":"Refresh","base.actions.update":"Edit","base.btn.back":"Back","base.btn.cancel":"Cancel","base.btn.hidePassword":"Hide password","base.btn.showPassword":"Show password","base.errors.errorUnknown":"An unknown error occurred.","base.fields.actions":"Actions","base.fields.confirmPassword":"Confirm password","base.fields.createdAt":"Created at","base.fields.email":"Email","base.fields.lastName":"Last name","base.fields.name":"Name","base.fields.password":"Password","base.fields.profile":"Profile","base.fields.updatedAt":"Updated at","base.file.allowedTypes":"Allowed types: {{types}}","base.file.clickToDownload":"Click to download","base.file.clickToPreview":"Click to preview image","base.file.confirmDelete.cancel":"Cancel","base.file.confirmDelete.confirm":"Delete","base.file.confirmDelete.message":"Are you sure you want to delete this file? This action cannot be undone.","base.file.confirmDelete.title":"Delete file","base.file.delete":"Delete","base.file.deleting":"Deleting...","base.file.dragOrClick":"Drag files here or click to select","base.file.dropHere":"Drop file here","base.file.maxFiles":"Maximum {{count}} files","base.file.maxSize":"Maximum {{size}} per file","base.file.noPreview":"No preview","base.file.pendingDeletion":"Pending deletion","base.file.privateFile":"Private file","base.file.restore":"Restore","base.file.uploading":"Uploading files...","base.file.validation.filesWithErrors":"Some files have errors","base.file.validation.maxFilesExceeded":"Maximum {{count}} files allowed","base.file.validation.minFilesRequired":"At least one file is required","base.file.validation.minFilesRequiredPlural":"At least {{count}} files are required","base.lastUpdated":"Last updated at {{formattedLastUpdated}}","base.loading.configInitial":"Loading initial configuration...","base.loading.pleaseWait":"Loading, please wait...","base.loading.starting":"Starting application...","base.loading.themeSetup":"Generating theme...","base.loading.validatingSession":"Validating session...","base.titles.create":"New {{moduleName}}","base.titles.read":"View {{moduleName}}","base.titles.update":"Edit {{moduleName}}","base.success.transaction":"The operation has been completed successfully.","base.loading.executing":"Processing\u2026","checkCode.codeLabel":"Verification Code","checkCode.codePlaceholder":"Enter the 6-digit code","checkCode.codeRequired":"Code is required","checkCode.emailLabel":"Email","checkCode.emailPlaceholder":"Enter your email","checkCode.emailRequired":"Email is required","checkCode.instructions":"Enter the 6-digit code we sent to your email.","checkCode.invalidEmail":"Enter a valid email address","checkCode.resendCodeLink":"Resend code","checkCode.title":"Verify Code","checkCode.verifyButton":"Verify Code","error.app.config":"Configuration Error: {{message}}","error.app.initialization":"Error during final application initialization.","error.transaction":"Operation error","errors.DUPLICATE":"The <b>{{field}}</b> field must be unique.","errors.FOREIGN_KEY_NOT_FOUND":"The <b>{{field}}</b> field must reference an existing item.","errors.INVALID_EMAIL":"The <b>{{field}}</b> field must be a valid email address.","errors.INVALID_OBJECT_ID":"The <b>{{field}}</b> field must be a valid value.","errors.IN_USE":"The item is in use and cannot be deleted.","errors.MAX_LENGTH":"The <b>{{field}}</b> field must not exceed <b>{{length}}</b> characters.","errors.MIN_LENGTH":"The <b>{{field}}</b> field must be at least <b>{{length}}</b> characters.","errors.MUST_NOT_BE_EMAIL":"The <b>{{field}}</b> field must not be an email.","errors.NO_PERMISSION":"You don't have permission to perform this action.","errors.NO_SPACES":"The <b>{{field}}</b> field must not contain spaces.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Operation error","errors.REQUIRED":"The <b>{{field}}</b> field is required.","errors.TOKEN_HAS_EXPIRED":"Session has expired. Please log in again.","errors.TOO_MANY_REQUESTS":"Request limit reached. Please try again later.","errors.UNAUTHORIZED":"You are not authorized to perform this action.","errors.all_password_fields_required":"All password fields are required","errors.auth.INVALID_API_KEY":"Invalid API key","errors.auth.INVALID_CREDENTIALS":"Invalid username and/or password","errors.auth.NO_PERMISSION":"You don't have sufficient permissions","errors.auth.SESSION_EXPIRED":"Your session has expired. Please log in again.","errors.auth.TOO_MANY_REQUESTS":"Too many attempts. Please wait 15 minutes and try again","errors.auth.UNAUTHORIZED":"You don't have permission to perform this action","errors.auth.USER_NOT_ACTIVE":"User not active","errors.auth.USER_NOT_FOUND":"User not found","errors.data.BAD_REQUEST":"Invalid request","errors.data.FIELD_ERROR":"Error in submitted data","errors.data.IN_USE":"The item is in use and cannot be deleted","errors.data.ITEM_NOT_FOUND":"The requested item was not found","errors.data.NOT_FOUND":"Not found","errors.internal_error_changing_password":"Internal error changing password. Please try again","errors.password_min_length":"Password must be at least 8 characters","errors.password_mismatch":"Passwords do not match","errors.password_must_be_different":"New password must be different from current password","errors.system.DATABASE_CONNECTION_ERROR":"Connection error. Please check your internet connection.","errors.system.INTERNAL_SERVER_ERROR":"Internal server error. Please try again.","errors.system.INVALID_CONFIGURATION":"System configuration error","errors.system.TOO_MANY_REQUESTS":"Too many requests. Please wait a moment and try again","errors.system.UNKNOWN_OPERATION":"Unrecognized operation","errors.users_module_not_configured":"Users module not configured","footer.copyright":"Nocios S.R.L. All rights reserved.","footer.version":"Version","forgotPassword.checkEmailInstructions":"Check your inbox for the verification code","forgotPassword.codeAlreadyExistsMessage":"A code has already been sent and is still valid","forgotPassword.emailLabel":"Email","forgotPassword.emailPlaceholder":"Enter your email","forgotPassword.emailRequired":"Email is required","forgotPassword.emailSentMessage":"Code sent successfully","forgotPassword.enterCodeLink":"Enter Code","forgotPassword.instructions":"Enter your email and we'll send you a code to reset your password.","forgotPassword.invalidEmail":"Enter a valid email address","forgotPassword.sendCodeButton":"Send Code","forgotPassword.title":"Recover Password","login.alreadyHaveCodeLink":"Already have a code?","login.forgotPasswordLink":"Forgot your password?","login.initializationError":"Initialization error","login.initializing":"Initializing...","login.loginButton":"Log In","login.logoAlt":"Logo","login.noAccountPrompt":"Don't have an account?","login.notInitialized":"System not initialized","login.passwordLabel":"Password","login.passwordPlaceholder":"Enter your password","login.passwordRequired":"Password is required","login.signUpLink":"Sign up","login.usernameOrEmailLabel":"Username or email","login.usernameOrEmailPlaceholder":"Enter your email","login.usernameRequired":"Username is required","passwordRequirements.lowercase":"One lowercase letter","passwordRequirements.minLength":"Minimum 8 characters","passwordRequirements.number":"One number","passwordRequirements.special":"One special character (!@#$%...)","passwordRequirements.uppercase":"One uppercase letter","profiles.actions.assignProfiles":"Assign profiles","profiles.moduleName":"Profiles","profiles.moduleSingular":"Profile","publicPolicies.fields.conditions.customEdit":"Custom edit","resetPassword.codeExpiredOrInvalid":"The code has expired or is invalid","resetPassword.confirmPasswordLabel":"Confirm Password","resetPassword.confirmPasswordPlaceholder":"Confirm your new password","resetPassword.confirmPasswordRequired":"Confirm your password","resetPassword.goToLoginButton":"Go to Login","resetPassword.instructions":"Enter your new password.","resetPassword.invalidCode":"The verification code is invalid. Please check the link or request a new one.","resetPassword.missingParameters":"Missing required parameters","resetPassword.newPasswordLabel":"New Password","resetPassword.newPasswordPlaceholder":"Enter your new password","resetPassword.newPasswordRequired":"New password is required","resetPassword.passwordRequirementsNotMet":"Password does not meet all requirements","resetPassword.passwordTooShort":"Password must be at least 8 characters","resetPassword.passwordsDoNotMatch":"Passwords do not match","resetPassword.requestNewCodeButton":"Request New Code","resetPassword.resetPasswordButton":"Reset Password","resetPassword.successInstructions":"You can now log in with your new password","resetPassword.successMessage":"Password reset successfully","resetPassword.title":"New Password","resetPassword.validatingCode":"Validating code...","translations.fields.lang":"Language","translations.moduleName":"Translations","translations.moduleSingular":"Translation","users.fields.currentPassword":"Current password","users.fields.newPassword":"New Password","users.fields.repeatNewPassword":"Repeat New Password","users.moduleName":"Users","users.moduleSingular":"User"}},as=()=>Object.keys(ue),is=e=>ue[e]||ue.es;import{CrudifyInstance as Xe}from"@nocios/crudify-sdk";var Co="crudify_translations_",Ot=3600*1e3;function Po(e){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return Math.abs(r).toString(36)}var vr=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(r){this.enableDebug=r}async ensureCrudifyInitialized(r,o){if(!this.isInitialized)return this.initializationPromise?(this.enableDebug&&x.debug("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&x.debug("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Xe.getTokenData();if(t&&t.endpoint){this.enableDebug&&x.debug("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Xe.config(o);let a=await Xe.init(r,this.enableDebug?"debug":"none");if(a.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(a.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&x.debug("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw x.error("[TranslationService] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(r){let{apiKey:o,featureKeys:t,crudifyEnv:a="stg",urlTranslations:n}=r;this.enableDebug&&x.debug("[TranslationService] fetchTranslations called with:",{apiKeyHash:Po(o),crudifyEnv:a,featureKeys:t,hasUrlTranslations:!!n});let i=this.getFromCache(o),l=i?this.isCacheExpired(i):!0;if(i&&!l)return this.enableDebug&&x.debug("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(i.data.translations,n);try{await this.ensureCrudifyInitialized(o,a)}catch(s){return x.error("[TranslationService] Failed to initialize crudify",s instanceof Error?s:{message:String(s)}),i?(x.warn("[TranslationService] Using expired cache (init failed)"),this.mergeWithUrlTranslations(i.data.translations,n)):(x.warn("[TranslationService] Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&x.debug("[TranslationService] Fetching from API via crudify SDK");let s=await this.fetchFromAPI(t);this.hasDataChanged(i,s)||!i?this.saveToCache(o,s):this.refreshCacheTimestamp(o);let p=this.mergeWithUrlTranslations(s.translations,n);return this.enableDebug&&x.debug("[TranslationService] Translations loaded:",{languages:Object.keys(p),keysCount:p[Object.keys(p)[0]]?Object.keys(p[Object.keys(p)[0]]).length:0}),p}catch(s){return x.error("[TranslationService] API fetch failed",s instanceof Error?s:{message:String(s)}),i?(x.warn("[TranslationService] Using expired cache as fallback"),this.mergeWithUrlTranslations(i.data.translations,n)):(x.warn("[TranslationService] Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Xe.getTranslation(r);if(!o.success)throw new Error(`Crudify API error: ${o.errors?JSON.stringify(o.errors):"Unknown error"}`);if(!o.data)throw new Error("No translation data in response");return o.data}mergeWithUrlTranslations(r,o){if(!o||Object.keys(o).length===0)return r;let t={};return Object.keys(r).forEach(a=>{t[a]={...r[a],...o}}),t}hasDataChanged(r,o){if(!r||r.data.timestamp!==o.timestamp)return!0;let t=this.hashData(o.translations);return r.dataHash!==t}hashData(r){let o=JSON.stringify(r),t=0;for(let a=0;a<o.length;a++){let n=o.charCodeAt(a);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),a={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(a)),this.enableDebug&&x.debug("[TranslationService] Saved to cache:",{cacheKey:t})}catch(t){x.error("[TranslationService] Failed to save cache",t instanceof Error?t:{message:String(t)})}}getFromCache(r){try{let o=this.getCacheKey(r),t=localStorage.getItem(o);return t?JSON.parse(t):null}catch(o){return x.error("[TranslationService] Failed to read cache",o instanceof Error?o:{message:String(o)}),null}}refreshCacheTimestamp(r){try{let o=this.getFromCache(r);if(o){o.cachedAt=Date.now();let t=this.getCacheKey(r);localStorage.setItem(t,JSON.stringify(o))}}catch(o){x.error("[TranslationService] Failed to refresh cache timestamp",o instanceof Error?o:{message:String(o)})}}isCacheExpired(r){return Date.now()-r.cachedAt>Ot}hasValidCache(r){let o=this.getFromCache(r);return o?!this.isCacheExpired(o):!1}getCacheKey(r){return`${Co}${Po(r)}`}getCriticalTranslationsOnly(){return ue}invalidateCache(r){let o=this.getCacheKey(r);localStorage.removeItem(o),this.enableDebug&&x.debug("[TranslationService] Cache invalidated:",{cacheKey:o})}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&x.debug("[TranslationService] Prefetch completed")}catch(o){x.error("[TranslationService] Prefetch failed",o instanceof Error?o:{message:String(o)})}}clearAllCaches(){try{let o=Object.keys(localStorage).filter(t=>t.startsWith(Co));o.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&x.debug(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){x.error("[TranslationService] Failed to clear caches",r instanceof Error?r:{message:String(r)})}}},Ze=vr.getInstance();import{createContext as Nt,useContext as Bt,useEffect as To,useState as De,useMemo as vo,useCallback as Ut}from"react";import{Fragment as Mt,jsx as Qe}from"react/jsx-runtime";var Je=null,Er=!1,Ro=Nt(null);function Eo(e,r,o){return{...e,...r,...o||{}}}function zt(e,r,o,t,a){To(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){a&&x.debug("[TranslationsProvider] i18next not found, skipping auto-sync");return}a&&x.debug("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:r}),Object.keys(e).forEach(i=>{e[i]&&Object.keys(e[i]).length>0&&(n.addResourceBundle(i,"translation",e[i],!0,!0),a&&x.debug(`[TranslationsProvider] Synced ${Object.keys(e[i]).length} keys for language: ${i}`))}),n.language!==r&&n.changeLanguage&&(n.changeLanguage(r),a&&x.debug(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,a])}var bs=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:a="es",devTranslations:n,translationUrl:i,enableDebug:l=!1,skipAutoInit:s=!0,autoSyncI18n:m=!0,i18nInstance:p,loadingFallback:b,waitForInitialLoad:w=!0})=>{let d=vo(()=>mo({publicApiKey:r,env:o,featureKeys:t,enableDebug:l}),[r,o,t,l]),u=d.publicApiKey||"",y=d.env||o||"prod",c=d.featureKeys||t,[f,h]=De({}),[C,I]=De(!0),[R,g]=De(!0),[E,A]=De(null),[W,ke]=De(void 0),[le,te]=De(!1),Z=Ut(async()=>{if(!u){l&&x.debug("[TranslationsProvider] No apiKey - skipping translation fetch"),I(!1),g(!1);return}if(le){l&&x.debug("[TranslationsProvider] Skipping reload - using fallback translations");return}if(Ze.hasValidCache(u)&&R&&(l&&x.debug("[TranslationsProvider] Valid cache found - not blocking initial render"),g(!1)),Er&&Je){l&&x.debug("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let v=await Je;h(v),I(!1);return}catch{l&&x.warn("[TranslationsProvider] Global fetch failed, retrying")}}Er=!0,I(!0),A(null);let S;if(i)try{l&&x.debug(`[TranslationsProvider] Fetching translations from URL: ${i}`);let v=await fetch(i);if(!v.ok)throw new Error(`Failed to fetch translations: ${v.statusText}`);S=await v.json(),ke(S),l&&x.debug("[TranslationsProvider] URL translations loaded:",{keysCount:S?Object.keys(S).length:0})}catch(v){x.error("[TranslationsProvider] Failed to load URL translations",v instanceof Error?v:{message:String(v)}),S=void 0,ke(void 0)}let J=(async()=>{try{Ze.setDebug(l);let v=await Ze.fetchTranslations({apiKey:u,crudifyEnv:y,featureKeys:c,urlTranslations:S}),O={};return Object.keys(v).forEach(N=>{let ce=ue[N]||{},j=v[N]||{};O[N]=Eo(ce,j,n)}),l&&x.debug("[TranslationsProvider] Loaded translations:",{languages:Object.keys(O),keysCount:Object.keys(O[a]||{}).length}),O}catch(v){x.error("[TranslationsProvider] Failed to load",v instanceof Error?v:{message:String(v)}),A(v instanceof Error?v.message:String(v)),te(!0);let O={};return Object.keys(ue).forEach(N=>{let ce=ue[N],j=S||W||{};O[N]=Eo(ce,j,n)}),l&&x.debug("[TranslationsProvider] Using fallback translations (critical + URL)"),O}})();Je=J;try{let v=await J;h(v)}finally{I(!1),g(!1),Er=!1,setTimeout(()=>{Je=null},1e3)}},[u,y,c,i,n,l,a,le]);To(()=>{Z();let T=setInterval(Z,3600*1e3);return()=>clearInterval(T)},[Z]);let Pe=vo(()=>(T,S)=>{let v=(f[a]||{})[T];if(!v){let O=Object.keys(f);for(let N of O)if(f[N][T]){v=f[N][T];break}}return v||(l&&x.warn(`[TranslationsProvider] Missing translation: "${T}"`),v=T),S&&typeof v=="string"&&Object.entries(S).forEach(([O,N])=>{let ce=new RegExp(`{{${O}}}`,"g");v=v.replace(ce,String(N))}),v},[f,a,l]);zt(f,a,p,m,l);let Le={t:Pe,language:a,availableLanguages:Object.keys(f),translations:f,isLoading:C,error:E,refreshTranslations:Z};return u?w&&R&&C?b||Qe("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:Qe("div",{children:"Loading translations..."})}):Qe(Ro.Provider,{value:Le,children:e}):(l&&x.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),Qe(Mt,{children:e}))},Ee=()=>{let e=Bt(Ro);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};var Vt=/^[a-zA-Z0-9\-_./\?=&%#]+$/,qt=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],So=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return x.warn("Open redirect blocked (relative path)",{path:e}),r;if(!Vt.test(o))return x.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let n of qt)if(n.test(t))return x.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let a=o.split("?")[0].split("/").filter(Boolean);if(a.length===0)return o;for(let n of a)if(n===".."||n.includes(":")||n.length>100)return x.warn("Open redirect blocked (suspicious path part)",{part:n}),r;return o},Wt=[/^files\.nocios\.link$/,/^files\.crudia\.com$/,/^[a-z0-9][a-z0-9-]*\.nocios\.link$/,/^[a-z0-9][a-z0-9-]*\.crudia\.com$/],Io=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(o.startsWith("/"))return So(o,r);try{if(o.includes("..")||o.includes("//",8))return x.warn("Redirect blocked (dangerous path pattern)",{url:o}),r;let t=new URL(o);if(t.protocol!=="https:")return x.warn("Redirect blocked (non-HTTPS protocol)",{url:o}),r;let a=t.hostname.toLowerCase();return Wt.some(i=>i.test(a))?o:(x.warn("Redirect blocked (untrusted domain)",{url:o,hostname:a}),r)}catch{return x.warn("Redirect blocked (invalid URL)",{url:o}),r}},Ps=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let a=decodeURIComponent(t);return So(a,r)}catch(o){return x.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Box as ko,Typography as Ht}from"@mui/material";import Kt from"@mui/icons-material/CheckCircle";import $t from"@mui/icons-material/RadioButtonUnchecked";import{jsx as ze,jsxs as Yt}from"react/jsx-runtime";var jt=({message:e,valid:r})=>Yt(ko,{sx:{display:"flex",alignItems:"center",gap:.5,py:.25},children:[r?ze(Kt,{sx:{fontSize:16,color:"success.main"}}):ze($t,{sx:{fontSize:16,color:"text.disabled"}}),ze(Ht,{variant:"caption",sx:{color:r?"success.main":"text.secondary",transition:"color 0.2s ease"},children:e})]}),Gt=({requirements:e,show:r=!0})=>!r||e.length===0?null:ze(ko,{sx:{mt:.5,mb:1,px:.5},children:e.map((o,t)=>ze(jt,{message:o.message,valid:o.valid},t))}),Lo=Gt;var Xt=/[A-Z]/,Zt=/[a-z]/,Jt=/[0-9]/,Qt=/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,en=/^[A-Za-z0-9]+$/;function Ao(e,r){return r.map(o=>{let t=!0;switch(o.type){case"minLength":t=e.length>=Number(o.value??0);break;case"alphanumeric":t=e.length>0&&en.test(e);break;case"uppercase":t=Xt.test(e);break;case"lowercase":t=Zt.test(e);break;case"number":t=Jt.test(e);break;case"special":t=Qt.test(e);break;default:t=!0}return{message:o.message,valid:t,enforce:!!o.enforce}})}function Do(e){return e.filter(r=>r.enforce).every(r=>r.valid)}var Fo=[{type:"minLength",value:8,message:"passwordRequirements.minLength",enforce:!0},{type:"uppercase",message:"passwordRequirements.uppercase",enforce:!0},{type:"lowercase",message:"passwordRequirements.lowercase",enforce:!0},{type:"number",message:"passwordRequirements.number",enforce:!0},{type:"special",message:"passwordRequirements.special",enforce:!0}];import{Box as ea,Typography as ra}from"@mui/material";import{createContext as on,useContext as tn,useMemo as Rr}from"react";import{useState as Tr,useEffect as rn}from"react";var _o=(e,r)=>{let[o,t]=Tr({}),[a,n]=Tr(!1),[i,l]=Tr(null);return rn(()=>{if(r&&Object.keys(r).length>0){t(r),n(!1),l(null);return}if(!e){t({}),n(!1),l(null);return}let s=!1;return n(!0),l(null),fetch(e).then(m=>{if(!m.ok)throw new Error(`Failed to load translations: ${m.status}`);return m.json()}).then(m=>{s||(t(m),n(!1))}).catch(m=>{s||(x.error("[I18nProvider] Failed to load translations from URL",m instanceof Error?m:{message:String(m),url:e}),l(m instanceof Error?m.message:String(m)),t({}),n(!1))}),()=>{s=!0}},[e,r]),{translations:o,loading:a,error:i}};import{jsx as Oo}from"react/jsx-runtime";var No=on(null),nn=()=>{try{return Ee()}catch{return null}},an=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,a)=>t&&typeof t=="object"?t[a]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},Bo=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=nn()?.translations?.[t]||{},{translations:i,loading:l}=_o(o,r),s=Rr(()=>({...n,...i,...r||{}}),[n,i,r]),m=Rr(()=>(b,w)=>{let d=an(s,b);return d==null&&(d=b),w&&typeof d=="string"&&Object.entries(w).forEach(([u,y])=>{d=d.replace(new RegExp(`{{${u}}}`,"g"),y)}),typeof d=="string"?d:b},[s]),p=Rr(()=>({t:m,language:t}),[m,t]);return l?Oo("div",{children:"Loading translations..."}):Oo(No.Provider,{value:p,children:e})},Q=()=>{let e=tn(No);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as sn,useContext as ln,useReducer as cn,useEffect as Sr,useCallback as dn}from"react";import{jsx as pn}from"react/jsx-runtime";var Uo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function un(e,r){switch(r.type){case"SET_SCREEN":let o={...e,currentScreen:r.payload.screen,searchParams:r.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(o.searchParams),a=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",a)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"CLEAR_SEARCH_PARAMS":return{...e,searchParams:{}};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...r.payload},errors:{...e.errors,...Object.keys(r.payload).reduce((n,i)=>({...n,[i]:void 0}),{})}};case"SET_LOADING":return{...e,loading:r.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...r.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:r.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:r.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:r.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:r.payload};case"RESET_FORM":return{...e,formData:Uo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:r.payload};default:return e}}var zo=sn(void 0),Mo=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[a,n]=cn(un,{...Uo,currentScreen:r});Sr(()=>{n({type:"INIT_CONFIG",payload:(()=>{let u={};if(t)try{let y=po();y.configSource!=="none"&&y.logo&&(u.logo=y.logo)}catch(y){x.error("Error reading configuration",y instanceof Error?y:{message:String(y)})}return{publicApiKey:o?.publicApiKey,env:o?.env,appName:o?.appName,logo:o?.logo||u.logo,loginActions:o?.loginActions}})()})},[o,t]),Sr(()=>{let d=new URLSearchParams(window.location.search),u={};d.forEach((y,c)=>{u[c]=y}),Object.keys(u).length>0&&n({type:"SET_SEARCH_PARAMS",payload:u}),r==="checkCode"&&u.email&&n({type:"UPDATE_FORM_DATA",payload:{email:u.email,code:u.code||""}}),r==="resetPassword"&&u.link&&n({type:"SET_SEARCH_PARAMS",payload:u})},[r]),Sr(()=>{let d=fo.subscribe(u=>{(u.type==="LOGOUT"||u.type==="SESSION_EXPIRED")&&(x.debug("LoginStateProvider: Clearing state due to auth event",{type:u.type}),n({type:"CLEAR_SEARCH_PARAMS"}),n({type:"RESET_FORM"}))});return()=>d()},[]);let i=(d,u)=>{n({type:"SET_SCREEN",payload:{screen:d,params:u}})},l=d=>{n({type:"UPDATE_FORM_DATA",payload:d})},s=(d,u)=>{n({type:"SET_ERRORS",payload:{[d]:u}})},m=()=>{n({type:"CLEAR_ERRORS"})},p=d=>{n({type:"SET_LOADING",payload:d})},b=dn(()=>{n({type:"CLEAR_SEARCH_PARAMS"})},[]),w={state:a,dispatch:n,setScreen:i,updateFormData:l,setFieldError:s,clearErrors:m,setLoading:p,clearSearchParams:b};return pn(zo.Provider,{value:w,children:e})},er=()=>{let e=ln(zo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as mn,useRef as fn}from"react";import{Typography as Ir,TextField as Vo,Button as gn,Box as Me,CircularProgress as hn,Alert as yn,Link as qo}from"@mui/material";import{Fragment as wn,jsx as ee,jsxs as Ve}from"react/jsx-runtime";var bn=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:a="/"})=>{let{state:n,updateFormData:i,setFieldError:l,clearErrors:s,setLoading:m}=er(),{login:p}=he(),b=Q(),{t:w}=b,d="i18n"in b?b.i18n:void 0,u=fn(null),y=go(w,{currentLanguage:d?.language,enableDebug:!1}),c=()=>{if(n.searchParams.redirect)try{let g=decodeURIComponent(n.searchParams.redirect);return Io(g,a||"/")}catch{}return a||"/"};mn(()=>{let g=setTimeout(()=>{u.current&&u.current.focus()},100);return()=>clearTimeout(g)},[]);let f=g=>y.translateError({code:g.code,message:g.message,field:g.field}),h=async()=>{if(!n.loading){if(!n.formData.username.trim()){l("username",w("login.usernameRequired"));return}if(!n.formData.password.trim()){l("password",w("login.passwordRequired"));return}s(),m(!0);try{let g=await p(n.formData.username,n.formData.password);if(m(!1),g.success){let E=c();o&&o(g.data,E)}else{let E=g.rawResponse||g;C(E)}}catch(g){m(!1);let A=$(g).map(f);l("global",A),t&&t(A.join(", "))}}},C=g=>{let E=$(g),A=[];E.forEach(W=>{W.field?l(W.field,f(W)):A.push(f(W))}),A.length>0&&l("global",A)};return Ve(wn,{children:[Ve(Me,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),h()},onKeyDown:g=>{g.key==="Enter"&&!n.loading&&(g.preventDefault(),h())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ve(Me,{sx:{mb:1},children:[ee(Ir,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.usernameOrEmailLabel")}),ee(Vo,{fullWidth:!0,id:"email",name:"email",type:"email",value:n.formData.username,disabled:n.loading,onChange:g=>i({username:g.target.value}),error:!!n.errors.username,helperText:n.errors.username,autoComplete:"email",placeholder:w("login.usernameOrEmailPlaceholder"),inputRef:u,required:!0})]}),Ve(Me,{sx:{mb:1},children:[ee(Ir,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.passwordLabel")}),ee(Vo,{fullWidth:!0,id:"password",name:"password",type:"password",value:n.formData.password,disabled:n.loading,onChange:g=>i({password:g.target.value}),error:!!n.errors.password,helperText:n.errors.password,autoComplete:"current-password",placeholder:w("login.passwordPlaceholder"),required:!0})]}),n.config.loginActions?.includes("forgotPassword")&&ee(Me,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:ee(qo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",n.searchParams)},variant:"body2",color:"secondary",children:w("login.forgotPasswordLink")})}),ee(gn,{disabled:n.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:n.loading?ee(hn,{size:20}):w("login.loginButton")})]}),ee(Me,{children:n.errors.global&&n.errors.global.length>0&&n.errors.global.map((g,E)=>ee(yn,{variant:"filled",sx:{mt:2},severity:"error",children:ee("div",{children:g})},E))}),n.config.loginActions?.includes("createUser")&&Ve(Ir,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[w("login.noAccountPrompt")," ",ee(qo,{sx:{cursor:"pointer"},onClick:()=>{let E=`/public/users/create${Object.keys(n.searchParams).length>0?`?${new URLSearchParams(n.searchParams).toString()}`:""}`;r?.(E)},fontWeight:"medium",color:"secondary",children:w("login.signUpLink")})]})]})},Wo=bn;import{useState as Fe,useEffect as Cn,useRef as Pn}from"react";import{Typography as _e,TextField as vn,Button as Ho,Box as be,CircularProgress as En,Alert as Tn,Link as kr}from"@mui/material";var Te=(e,r)=>o=>{let t=[`errors.auth.${o.code}`,`errors.data.${o.code}`,`errors.system.${o.code}`,`errors.${o.code}`,`${r}.${o.code.toLowerCase()}`];for(let a of t){let n=e(a);if(n!==a)return n}return o.message||e("base.errors.errorUnknown")};var ye=(e,r)=>e?e instanceof URLSearchParams?e.get(r):e[r]||null:null;var xn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,rr=e=>!e||typeof e!="string"?!1:xn.test(e.trim());var or=e=>!e||typeof e!="string"?"":e.replace(/\D/g,"").slice(0,6);import{Fragment as Ko,jsx as B,jsxs as Re}from"react/jsx-runtime";var Rn=({onScreenChange:e,onError:r})=>{let{crudify:o}=ge(),[t,a]=Fe(""),[n,i]=Fe(!1),[l,s]=Fe([]),[m,p]=Fe(null),[b,w]=Fe(!1),[d,u]=Fe(!1),y=Pn(null),{t:c}=Q(),f=Te(c,"forgotPassword");Cn(()=>{y.current&&!b&&!d&&y.current.focus()},[b,d]);let h=async()=>{if(!(n||!o)){if(s([]),p(null),!t){p(c("forgotPassword.emailRequired"));return}if(!rr(t)){p(c("forgotPassword.invalidEmail"));return}i(!0);try{let g=[{operation:"requestPasswordReset",data:{email:t}}],E=await o.transaction(g);if(E.success)E.data&&E.data.existingCodeValid?u(!0):w(!0);else{let W=$(E).map(f);s(W)}}catch(g){let A=$(g).map(f);s(A),r&&r(A.join(", "))}finally{i(!1)}}},C=()=>{e?.("login")},I=()=>{if(b||d){e?.("checkCode",{email:t});return}if(!t){p(c("forgotPassword.emailRequired"));return}if(!rr(t)){p(c("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return b||d?B(Ko,{children:Re(be,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[Re(be,{sx:{mb:2},children:[B(_e,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:c(d?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(_e,{variant:"body2",sx:{color:d?"success.main":"grey.600"},children:c("forgotPassword.checkEmailInstructions")})]}),B(Ho,{type:"button",onClick:I,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:c("forgotPassword.enterCodeLink")}),B(be,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(kr,{sx:{cursor:"pointer"},onClick:C,variant:"body2",color:"secondary",children:c("base.btn.back")})})]})}):Re(Ko,{children:[Re(be,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),h()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Re(be,{sx:{mb:2},children:[B(_e,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:c("forgotPassword.title")}),B(_e,{variant:"body2",sx:{color:"grey.600"},children:c("forgotPassword.instructions")})]}),Re(be,{sx:{mb:1},children:[B(_e,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:c("forgotPassword.emailLabel")}),B(vn,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:g=>a(g.target.value),error:!!m,helperText:m,autoComplete:"email",placeholder:c("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:y})]}),B(Ho,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(En,{size:20}):c("forgotPassword.sendCodeButton")}),Re(be,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(kr,{sx:{cursor:"pointer"},onClick:C,variant:"body2",color:"secondary",children:c("base.btn.back")}),B(_e,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(kr,{sx:{cursor:"pointer"},onClick:I,variant:"body2",color:"secondary",children:c("login.alreadyHaveCodeLink")})]})]}),B(be,{children:l.length>0&&l.map((g,E)=>B(Tn,{variant:"filled",sx:{mt:2},severity:"error",children:g},E))})]})},$o=Rn;import{useState as Y,useEffect as Lr,useMemo as Ar,useRef as Bn,useCallback as Un}from"react";import{Typography as ar,Button as zn,Box as Se,CircularProgress as Go,Link as Mn}from"@mui/material";import{useState as Sn}from"react";import{TextField as In,IconButton as kn,InputAdornment as Ln}from"@mui/material";import An from"@mui/icons-material/Visibility";import Dn from"@mui/icons-material/VisibilityOff";import{jsx as qe}from"react/jsx-runtime";var Fn=({id:e,name:r,value:o,onChange:t,disabled:a=!1,error:n=!1,helperText:i,label:l,placeholder:s,autoComplete:m="current-password",showPasswordLabel:p="Show password",hidePasswordLabel:b="Hide password"})=>{let[w,d]=Sn(!1);return qe(In,{fullWidth:!0,id:e,name:r,type:w?"text":"password",value:o,disabled:a,onChange:t,error:n,helperText:i,autoComplete:m,placeholder:s,label:l,required:!0,InputProps:{endAdornment:qe(Ln,{position:"end",children:qe(kn,{"aria-label":w?b:p,onClick:()=>{d(y=>!y)},edge:"end",size:"small",disabled:a,children:w?qe(Dn,{}):qe(An,{})})})}})},tr=Fn;import{TextField as Al}from"@mui/material";import{jsx as _l}from"react/jsx-runtime";import{Box as _n,Alert as On}from"@mui/material";import{jsx as jo}from"react/jsx-runtime";var Nn=({errors:e,severity:r="error",variant:o="filled"})=>!e||e.length===0?null:jo(_n,{children:e.map((t,a)=>jo(On,{variant:o,severity:r,sx:{mt:2},children:t},a))}),nr=Nn;import{Fragment as qn,jsx as M,jsxs as We}from"react/jsx-runtime";var Vn=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t,passwordRules:a})=>{let{crudify:n}=ge(),[i,l]=Y(""),[s,m]=Y(""),[p,b]=Y(!1),[w,d]=Y([]),[u,y]=Y(null),[c,f]=Y(null),[h,C]=Y(""),[I,R]=Y(""),[g,E]=Y(!1),[A,W]=Y(!0),[ke,le]=Y(!1),[te,Z]=Y(null),[Pe,Le]=Y(!1),{t:T}=Q(),S=Bn(null);Lr(()=>()=>{S.current&&clearTimeout(S.current)},[]);let J=Un((z,D=3e3)=>{S.current&&clearTimeout(S.current),S.current=setTimeout(()=>e?.(z),D)},[e]),v=Ar(()=>(a||Fo).map(D=>({...D,message:T(D.message)})),[a,T]),O=Ar(()=>Ao(i,v),[i,v]),N=Ar(()=>Do(O),[O]),ce=i===s,j=Te(T,"resetPassword");Lr(()=>{if(!o)return;let z=ye(o,"fromCodeVerification"),D=ye(o,"email"),H=ye(o,"code");if(z==="true"&&D&&H){C(D),R(H),E(!0),le(!0),W(!1);return}let G=ye(o,"link");if(G)try{let K=decodeURIComponent(G),[de,ve]=K.split("/");if(de&&ve&&de.length===6){R(de),C(ve),E(!1),Z({email:ve,code:de});return}}catch(K){console.warn("Failed to parse reset password link:",K)}if(D&&H){C(D),R(H),E(!1),Z({email:D,code:H});return}d([T("resetPassword.invalidCode")]),W(!1),J("forgotPassword")},[o,T,J]),Lr(()=>{n&&te&&!Pe&&(Le(!0),(async(D,H)=>{try{let G=[{operation:"validatePasswordResetCode",data:{email:D,codePassword:H}}],K=await n.transaction(G);if(K.data&&Array.isArray(K.data)&&K.data[0]?.response?.status==="OK"){le(!0);return}if(K.success)le(!0);else{let ve=$(K).map(j);d(ve),J("forgotPassword")}}catch(G){let de=$(G).map(j);d(de),J("forgotPassword")}finally{W(!1),Z(null),Le(!1)}})(te.email,te.code))},[n,te,Pe,T,j,J]);let wr=async()=>{if(p||!n)return;d([]),y(null),f(null);let z=!1;if(i?N||(y(T("resetPassword.passwordRequirementsNotMet")),z=!0):(y(T("resetPassword.newPasswordRequired")),z=!0),s?ce||(f(T("resetPassword.passwordsDoNotMatch")),z=!0):(f(T("resetPassword.confirmPasswordRequired")),z=!0),!z){b(!0);try{let D=[{operation:"validateAndResetPassword",data:{email:h,codePassword:I,newPassword:i}}],H=await n.transaction(D);if(H.success)d([]),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{t?.()},1e3);else{let K=$(H).map(j);d(K)}}catch(D){let G=$(D).map(j);d(G),r&&r(G.join(", "))}b(!1)}},Ge=()=>{g?e?.("checkCode",{email:h}):e?.("forgotPassword")};return A?M(Se,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:M(Go,{})}):ke?We(qn,{children:[We(Se,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[We(Se,{sx:{mb:2},children:[M(ar,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:T("resetPassword.title")}),M(ar,{variant:"body2",sx:{color:"grey.600"},children:T("resetPassword.instructions")})]}),We(Se,{sx:{mb:1},children:[M(ar,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:T("resetPassword.newPasswordLabel")}),M(tr,{id:"newPassword",name:"newPassword",value:i,disabled:p,onChange:z=>l(z.target.value),error:!!u,helperText:u??void 0,autoComplete:"new-password",placeholder:T("resetPassword.newPasswordPlaceholder"),showPasswordLabel:T("base.btn.showPassword"),hidePasswordLabel:T("base.btn.hidePassword")}),M(Lo,{requirements:O,show:i.length>0})]}),We(Se,{sx:{mb:1},children:[M(ar,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:T("resetPassword.confirmPasswordLabel")}),M(tr,{id:"confirmPassword",name:"confirmPassword",value:s,disabled:p,onChange:z=>m(z.target.value),error:!!c,helperText:c??void 0,autoComplete:"new-password",placeholder:T("resetPassword.confirmPasswordPlaceholder"),showPasswordLabel:T("base.btn.showPassword"),hidePasswordLabel:T("base.btn.hidePassword")})]}),M(zn,{disabled:p||!N||!ce||!i||!s,type:"button",onClick:wr,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:p?M(Go,{size:20}):T("resetPassword.resetPasswordButton")}),M(Se,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:M(Mn,{sx:{cursor:"pointer"},onClick:Ge,variant:"body2",color:"secondary",children:T("base.btn.back")})})]}),M(nr,{errors:w})]}):M(Se,{children:M(nr,{errors:w})})},Yo=Vn;import{useState as He,useEffect as Xo,useRef as Wn}from"react";import{Typography as Dr,TextField as Hn,Button as Kn,Box as Ke,CircularProgress as $n,Alert as jn,Link as Gn}from"@mui/material";import{Fragment as Xn,jsx as ae,jsxs as ir}from"react/jsx-runtime";var Yn=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=ge(),[a,n]=He(""),[i,l]=He(!1),[s,m]=He([]),[p,b]=He(null),[w,d]=He(""),u=Wn(null),{t:y}=Q(),c=Te(y,"checkCode");Xo(()=>{let R=ye(o,"email");R?d(R):e?.("forgotPassword")},[o,e]),Xo(()=>{u.current&&u.current.focus()},[]);let f=async()=>{if(!(i||!t)){if(m([]),b(null),!a){b(y("checkCode.codeRequired"));return}if(a.length!==6){b(y("checkCode.codeRequired"));return}l(!0);try{let R=[{operation:"validatePasswordResetCode",data:{email:w,codePassword:a}}],g=await t.transaction(R);if(g.success)e?.("resetPassword",{email:w,code:a,fromCodeVerification:"true"});else{let A=$(g).map(c);m(A),l(!1)}}catch(R){let E=$(R).map(c);m(E),l(!1),r&&r(E.join(", "))}}},h=()=>{e?.("forgotPassword")},C=R=>{n(or(R.target.value))};return ir(Xn,{children:[ir(Ke,{component:"form",noValidate:!0,onSubmit:R=>{R.preventDefault(),f()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ir(Ke,{sx:{mb:2},children:[ae(Dr,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y("checkCode.title")}),ae(Dr,{variant:"body2",sx:{color:"grey.600"},children:y("checkCode.instructions")})]}),ir(Ke,{sx:{mb:1},children:[ae(Dr,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:y("checkCode.codeLabel")}),ae(Hn,{fullWidth:!0,id:"code",name:"code",type:"text",value:a,disabled:i,onChange:C,error:!!p,helperText:p,placeholder:y("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:u})]}),ae(Kn,{disabled:i||a.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?ae($n,{size:20}):y("checkCode.verifyButton")}),ae(Ke,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:ae(Gn,{sx:{cursor:"pointer"},onClick:h,variant:"body2",color:"secondary",children:y("base.btn.back")})})]}),ae(Ke,{children:s.length>0&&s.map((R,g)=>ae(jn,{sx:{mt:2},severity:"error",children:R},g))})]})},Zo=Yn;import{Box as Zn,CircularProgress as Jn,Alert as Jo,Typography as Fr}from"@mui/material";import{Fragment as Qn,jsx as Oe,jsxs as Qo}from"react/jsx-runtime";var et=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:a}=ge(),{t:n}=Q();return o?r||Qo(Zn,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Oe(Jn,{}),Oe(Fr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Oe(Jo,{severity:"error",sx:{mt:2},children:Qo(Fr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):a?Oe(Qn,{children:e}):Oe(Jo,{severity:"warning",sx:{mt:2},children:Oe(Fr,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as re,jsxs as na}from"react/jsx-runtime";var oa=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:a="/",passwordRules:n})=>{let{t:i}=Q(),{state:l,setScreen:s}=er(),{config:m}=he(),{showNotification:p}=ho(),b=(d,u)=>{let y=u;d==="login"?y={}:d==="forgotPassword"&&!u&&(y={}),s(d,y),e?.(d,y)},w=()=>{let d={onScreenChange:b,onExternalNavigate:r,onError:t,redirectUrl:a};switch(l.currentScreen){case"forgotPassword":return re($o,{...d});case"checkCode":return re(Zo,{...d,searchParams:l.searchParams});case"resetPassword":return re(Yo,{...d,searchParams:l.searchParams,passwordRules:n,onResetSuccess:()=>{let u=i("resetPassword.successMessage");p(u,"success"),b("login")}});default:return re(Wo,{...d,onLoginSuccess:o})}};return na(et,{children:[re(ea,{sx:{display:"flex",justifyContent:"center",mb:3},children:re("img",{src:m.logo||"https://logos.crudia.com/nocios-default.png",alt:i("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let u=d.target;u.src="https://logos.crudia.com/nocios-default.png"}})}),!m.logo&&m.appName&&re(ra,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:m.appName}),w()]})},ta=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:a=!0,...n})=>{let{config:i}=he();return re(Bo,{translations:e,translationsUrl:r,language:o,children:re(yo,{config:i,children:re(Mo,{config:i,initialScreen:t,autoReadFromCookies:a,children:re(oa,{...n})})})})},Rc=ta;import{Box as X,Card as rt,CardContent as ot,Typography as oe,Chip as sr,Avatar as aa,Divider as ia,CircularProgress as sa,Alert as tt,List as la,ListItem as _r,ListItemText as Or,ListItemIcon as ca,Collapse as da,IconButton as Nr}from"@mui/material";import{Person as ua,Email as pa,Badge as ma,Security as fa,Schedule as ga,AccountCircle as ha,ExpandMore as ya,ExpandLess as ba,Info as wa}from"@mui/icons-material";import{useState as xa}from"react";import{Fragment as va,jsx as P,jsxs as k}from"react/jsx-runtime";var Ca=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:a,error:n,extendedData:i,refreshProfile:l}=bo({autoFetch:o,retryOnError:!0,maxRetries:3}),[s,m]=xa(!1);if(a)return k(X,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[P(sa,{}),P(oe,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return k(tt,{severity:"error",action:P(Nr,{color:"inherit",size:"small",onClick:l,children:P(oe,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return P(tt,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let p=i?.displayData||{},b=i?.totalFields||0,w=h=>{if(!h)return"No disponible";try{return new Date(h).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return h}},d=(h,C)=>C==null?"No disponible":typeof C=="boolean"?C?"S\xED":"No":Array.isArray(C)?C.length>0?C.join(", "):"Ninguno":typeof C=="object"?JSON.stringify(C,null,2):String(C),u=[{key:"id",label:"ID",icon:P(ma,{})},{key:"email",label:"Email",icon:P(pa,{})},{key:"username",label:"Usuario",icon:P(ua,{})},{key:"fullName",label:"Nombre completo",icon:P(ha,{})},{key:"role",label:"Rol",icon:P(fa,{})}],y=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],c=[...u.map(h=>h.key),...y.map(h=>h.key),"permissions"],f=Object.keys(p).filter(h=>!c.includes(h)).map(h=>({key:h,label:h}));return k(X,{children:[r&&P(rt,{sx:{mb:2},children:k(ot,{children:[k(X,{display:"flex",alignItems:"center",mb:2,children:[P(aa,{src:p.avatar,sx:{width:56,height:56,mr:2},children:p.fullName?.[0]||p.username?.[0]||p.email?.[0]}),k(X,{children:[P(oe,{variant:"h6",children:p.fullName||p.username||p.email}),P(oe,{variant:"body2",color:"text.secondary",children:p.role||"Usuario"}),p.isActive!==void 0&&P(sr,{label:p.isActive?"Activo":"Inactivo",color:p.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),P(X,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:u.map(({key:h,label:C,icon:I})=>p[h]?k(X,{display:"flex",alignItems:"center",children:[P(X,{sx:{mr:1,color:"text.secondary"},children:I}),k(X,{children:[P(oe,{variant:"caption",color:"text.secondary",children:C}),P(oe,{variant:"body2",children:d(h,p[h])})]})]},h):null)}),p.permissions&&Array.isArray(p.permissions)&&p.permissions.length>0&&k(X,{mt:2,children:[P(oe,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),k(X,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[p.permissions.slice(0,5).map((h,C)=>P(sr,{label:h,size:"small",variant:"outlined"},C)),p.permissions.length>5&&P(sr,{label:`+${p.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&P(rt,{children:k(ot,{children:[k(X,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[k(oe,{variant:"h6",display:"flex",alignItems:"center",children:[P(wa,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),P(sr,{label:`${b} campos totales`,size:"small"})]}),k(la,{dense:!0,children:[y.map(({key:h,label:C})=>p[h]!==void 0&&k(_r,{divider:!0,children:[P(ca,{children:P(ga,{fontSize:"small"})}),P(Or,{primary:C,secondary:h.includes("At")||h.includes("Login")?w(p[h]):d(h,p[h])})]},h)),f.length>0&&k(va,{children:[P(ia,{sx:{my:1}}),P(_r,{children:P(Or,{primary:k(X,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[k(oe,{variant:"subtitle2",children:["Campos Personalizados (",f.length,")"]}),P(Nr,{size:"small",onClick:()=>m(!s),children:s?P(ba,{}):P(ya,{})})]})})}),P(da,{in:s,children:f.map(({key:h,label:C})=>P(_r,{sx:{pl:4},children:P(Or,{primary:C,secondary:d(h,p[h])})},h))})]})]}),k(X,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[k(oe,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",w(p.updatedAt)]}),P(Nr,{size:"small",onClick:l,disabled:a,children:P(oe,{variant:"caption",children:"Actualizar"})})]})]})})]})},Pa=Ca;var nt=["create","read","update","delete"],at=["create","read","update","delete"];import{useRef as $a}from"react";import{useTranslation as ja}from"react-i18next";import{Box as dr,Typography as pt,Button as Ga,Stack as Ya,Alert as mt,Divider as Xa}from"@mui/material";import{Add as Za}from"@mui/icons-material";import{forwardRef as Fa}from"react";import{useTranslation as _a}from"react-i18next";import{Box as Ie,FormControl as Oa,InputLabel as Na,Select as Ba,MenuItem as Ua,IconButton as za,Typography as Ne,FormHelperText as Ma,Stack as cr,Paper as ut,Divider as Va,Button as Mr}from"@mui/material";import{Delete as qa,SelectAll as Wa,ClearAll as Ha}from"@mui/icons-material";import{useState as it,useEffect as st,useRef as lt}from"react";import{useTranslation as Ea}from"react-i18next";import{Box as lr,Typography as $e,Button as ct,Stack as Br,FormControlLabel as Ta,FormHelperText as dt,Switch as Ra,ToggleButton as Ur,ToggleButtonGroup as Sa}from"@mui/material";import{CheckCircle as Ia,Cancel as ka,SelectAll as La,ClearAll as Aa}from"@mui/icons-material";import{jsx as F,jsxs as we}from"react/jsx-runtime";var Da=({value:e,onChange:r,availableFields:o,error:t,disabled:a=!1})=>{let{t:n}=Ea(),[i,l]=it("custom"),[s,m]=it(!1),p=lt(null);st(()=>{s&&p.current?.scrollIntoView({behavior:"smooth",block:"start"})},[s]);let b=lt(!1);st(()=>{let c=e||{allow:[],owner_allow:[],deny:[]},f=new Set(o),h=(c.allow||[]).filter(g=>f.has(g)),C=(c.owner_allow||[]).filter(g=>f.has(g)),I=(c.deny||[]).filter(g=>f.has(g));o.forEach(g=>{!h.includes(g)&&!C.includes(g)&&!I.includes(g)&&I.push(g)});let R={allow:h,owner_allow:C,deny:I};JSON.stringify(R)!==JSON.stringify(c)&&r(R),h.length===o.length?l("all"):I.length===o.length?l("none"):l("custom")},[o,e]);let w=()=>{b.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),l("all"),setTimeout(()=>{b.current=!1},0)},d=()=>{b.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),l("none"),setTimeout(()=>{b.current=!1},0)},u=c=>e?.allow?.includes(c)?"allow":e?.owner_allow?.includes(c)?"owner_allow":"deny",y=(c,f)=>{b.current=!0;let h=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),I=new Set(e?.deny||[]);h.delete(c),C.delete(c),I.delete(c),f==="allow"&&h.add(c),f==="owner_allow"&&C.add(c),f==="deny"&&I.add(c),r({allow:Array.from(h),owner_allow:Array.from(C),deny:Array.from(I)}),l("custom"),setTimeout(()=>{b.current=!1},0)};return o.length===0?we(lr,{children:[F($e,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("publicPolicies.fields.conditions.label")}),F($e,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("publicPolicies.fields.conditions.noFieldsAvailable")}),t&&F(dt,{error:!0,sx:{mt:1},children:t})]}):we(lr,{children:[F($e,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.label")}),we(Br,{direction:"row",spacing:1,alignItems:"center",sx:{mb:s?3:1},children:[F(ct,{variant:i==="all"?"contained":"outlined",startIcon:F(La,{}),onClick:w,disabled:a,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("publicPolicies.fields.conditions.allFields")}),F(ct,{variant:i==="none"?"contained":"outlined",startIcon:F(Aa,{}),onClick:d,disabled:a,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("publicPolicies.fields.conditions.noFields")}),F(lr,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:F(Ta,{control:F(Ra,{size:"small",checked:s,onChange:()=>m(c=>!c),disabled:a,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),s&&we(lr,{ref:p,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[F($e,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.help")}),F(Br,{spacing:1,children:o.map(c=>{let f=u(c);return we(Br,{direction:"row",spacing:1,alignItems:"center",children:[F($e,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:c}),we(Sa,{value:f,exclusive:!0,size:"small",children:[we(Ur,{value:"allow",onClick:()=>y(c,"allow"),disabled:a,sx:{px:2,color:f==="allow"?"#ffffff":"#6b7280",backgroundColor:f==="allow"?"#16a34a":"#f3f4f6",borderColor:f==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:f==="allow"?"#15803d":"#e5e7eb",borderColor:f==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[F(Ia,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.allow")]}),F(Ur,{value:"owner_allow",onClick:()=>y(c,"owner_allow"),disabled:a,sx:{px:2,color:f==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:f==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:f==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:f==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:f==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("publicPolicies.fields.conditions.states.ownerAllow")}),we(Ur,{value:"deny",onClick:()=>y(c,"deny"),disabled:a,sx:{px:2,color:f==="deny"?"#ffffff":"#6b7280",backgroundColor:f==="deny"?"#dc2626":"#f3f4f6",borderColor:f==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:f==="deny"?"#b91c1c":"#e5e7eb",borderColor:f==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[F(ka,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.deny")]})]})]},c)})})]}),t&&F(dt,{error:!0,sx:{mt:1},children:t})]})},zr=Da;import{jsx as _,jsxs as V}from"react/jsx-runtime";var Ka=Fa(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:a=!1,usedActions:n,error:i},l)=>{let{t:s}=_a(),m=new Set(Array.from(n||[]));m.delete(e.action);let p=nt.map(b=>({value:b,label:s(`publicPolicies.fields.action.options.${b}`)}));return V(ut,{ref:l,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[V(Ie,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[_(Ne,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:s("publicPolicies.policyTitle")}),_(za,{onClick:o,size:"small",disabled:a,"aria-label":s("publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:_(qa,{})})]}),V(cr,{spacing:1,children:[_(cr,{direction:{xs:"column",md:"row"},spacing:2,children:_(Ie,{sx:{flex:1,minWidth:200},children:V(Oa,{fullWidth:!0,children:[_(Na,{children:s("publicPolicies.fields.action.label")}),_(Ba,{value:e.action,label:s("publicPolicies.fields.action.label"),disabled:a,onChange:b=>{let w=b.target.value,d={...e,action:w};w==="delete"?(d.permission="deny",delete d.fields):(d.fields={allow:[],owner_allow:[],deny:t},delete d.permission),r(d)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:p.map(b=>{let w=m.has(b.value);return _(Ua,{value:b.value,disabled:w,children:b.label},b.value)})}),i&&_(Ma,{error:!0,children:i})]})})}),e.action==="delete"?V(Ie,{children:[_(Ne,{variant:"body2",color:"text.secondary",sx:{mb:2},children:s("publicPolicies.fields.conditions.label")}),V(cr,{direction:"row",spacing:1,sx:{mb:1},children:[_(Mr,{variant:e.permission==="*"?"contained":"outlined",startIcon:_(Wa,{}),onClick:()=>r({...e,permission:"*"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:s("publicPolicies.fields.conditions.allFields")}),_(Mr,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:s("publicPolicies.fields.conditions.states.ownerAllow")}),_(Mr,{variant:e.permission==="deny"?"contained":"outlined",startIcon:_(Ha,{}),onClick:()=>r({...e,permission:"deny"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:s("publicPolicies.fields.conditions.noFields")})]})]}):_(zr,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:b=>r({...e,fields:b}),availableFields:t,disabled:a}),_(ut,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?V(Ne,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[V(Ie,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[s("publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):V(cr,{spacing:.5,divider:_(Va,{sx:{borderColor:"#e5e7eb"}}),children:[V(Ne,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[V(Ie,{component:"span",sx:{color:"#16a34a"},children:[s("publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),V(Ne,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[V(Ie,{component:"span",sx:{color:"#0ea5e9"},children:[s("publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),V(Ne,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[V(Ie,{component:"span",sx:{color:"#dc2626"},children:[s("publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),Vr=Ka;import{Fragment as ei,jsx as ie,jsxs as ur}from"react/jsx-runtime";var Ja=()=>typeof globalThis<"u"&&globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,Qa=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:a=!1})=>{let{t:n}=ja(),i=$a({}),l=new Set((e||[]).map(u=>u.action).filter(Boolean)),s=at.filter(u=>!l.has(u)),m=s.length>0,p=()=>{let u=s[0]||"create",y={id:Ja(),action:u};u==="delete"?y.permission="deny":y.fields={allow:[],owner_allow:[],deny:o};let c=[...e||[],y];r(c),setTimeout(()=>{let f=c.length-1,h=i.current[f];h&&h.scrollIntoView({behavior:"smooth",block:"center"})},100)},b=u=>{let y=[...e];y.splice(u,1),r(y)},w=(()=>{if(!t)return null;if(typeof t=="string")return t;let u=t._error;return typeof u=="string"?u:null})(),d=new Set((e||[]).map(u=>u.action));return ur(ei,{children:[ie(Xa,{sx:{borderColor:"#e0e4e7"}}),ur(dr,{children:[ie(dr,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:ur(dr,{children:[ie(pt,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("publicPolicies.title")}),ie(pt,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("publicPolicies.description")})]})}),w&&ie(mt,{severity:"error",sx:{mb:3},children:w}),ur(Ya,{spacing:3,children:[(e||[]).length===0?ie(mt,{severity:"info",children:n("publicPolicies.noPolicies")}):e.map((u,y)=>ie(Vr,{ref:c=>{i.current[y]=c},policy:u,onChange:c=>{let f=[...e];f[y]=c,r(f)},onRemove:()=>b(y),availableFields:o,isSubmitting:a,usedActions:d,error:typeof t=="object"&&t!==null&&!("_error"in t)&&u.id in t?t[u.id]:void 0},u.id)),m&&ie(dr,{children:ie(Ga,{type:"button",variant:"outlined",startIcon:ie(Za,{}),onClick:p,disabled:a,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("publicPolicies.addPolicy")})})]})]})]})},dd=Qa;import{useState as qr}from"react";import{Button as pr,TextField as ft,Box as Be,Alert as je,Typography as xe,CircularProgress as Wr}from"@mui/material";import{jsx as L,jsxs as pe}from"react/jsx-runtime";function yd(){let[e,r]=qr(""),[o,t]=qr(""),[a,n]=qr(!1),{isAuthenticated:i,isLoading:l,error:s,login:m,logout:p,refreshTokens:b,clearError:w,isExpiringSoon:d,expiresIn:u}=he(),y=async h=>{if(h.preventDefault(),!e||!o)return;(await m(e,o)).success&&(r(""),t(""),n(!1))},c=async()=>{await p()},f=async()=>{await b()};return i?pe(Be,{sx:{maxWidth:600,mx:"auto",p:3},children:[L(xe,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),L(je,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),pe(Be,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[L(xe,{variant:"h6",gutterBottom:!0,children:"Token Status"}),pe(xe,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(u/1e3/60)," minutes"]}),d&&L(je,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),pe(Be,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[L(pr,{variant:"contained",onClick:f,disabled:l,startIcon:l?L(Wr,{size:16}):null,children:"Refresh Tokens"}),L(pr,{variant:"outlined",color:"error",onClick:c,disabled:l,children:"Logout"})]}),s&&L(je,{severity:"error",sx:{mt:2},onClose:w,children:s})]}):pe(Be,{sx:{maxWidth:400,mx:"auto",p:3},children:[L(xe,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),L(je,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),a?pe("form",{onSubmit:y,children:[L(ft,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:h=>r(h.target.value),margin:"normal",required:!0,autoComplete:"email"}),L(ft,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:h=>t(h.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),L(pr,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:l,startIcon:l?L(Wr,{size:16}):null,sx:{mt:3,mb:2},children:l?"Logging in...":"Login"})]}):L(pr,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),s&&L(je,{severity:"error",sx:{mt:2},onClose:w,children:s})]})}function bd(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=he();return r?pe(Be,{sx:{display:"flex",alignItems:"center",gap:1},children:[L(Wr,{size:16}),L(xe,{variant:"caption",children:"Loading session..."})]}):e?pe(Be,{children:[L(xe,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&pe(xe,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):L(xe,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import ri from"@mui/material/TextField";import oi from"@mui/material/CircularProgress";import gt from"@mui/material/InputAdornment";import ti from"@mui/material/IconButton";import ni from"@mui/icons-material/Refresh";import{jsx as me}from"react/jsx-runtime";var ai=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),ii=({html:e})=>me("span",{dangerouslySetInnerHTML:{__html:ai(e)}}),Sd=({config:e,value:r,onChange:o,label:t,error:a=!1,helperText:n,readOnly:i=!1,disabled:l=!1,name:s,containerRef:m})=>{let{value:p,loading:b,error:w,regenerate:d}=wo(e,{autoFetch:!r,onSuccess:C=>{o?.(C)}}),u=r||p,y=a||!!w,c=w||n,f=y&&c&&(c.toLowerCase().includes("duplicate")||c.toLowerCase().includes("duplicado")||c.toLowerCase().includes("duplicada")||c.toLowerCase().includes("unique")||c.toLowerCase().includes("\xFAnico")||c.toLowerCase().includes("unico")||c.toLowerCase().includes("\xFAnica")||c.toLowerCase().includes("unica")||c.toLowerCase().includes("already exists")||c.toLowerCase().includes("ya existe")||c.toLowerCase().includes("e11000"));return me("div",{ref:m,children:me(ri,{name:s,label:t,fullWidth:!0,value:u,error:y,helperText:c?me(ii,{html:c}):" ",disabled:l,InputProps:{readOnly:!0,startAdornment:b?me(gt,{position:"start",children:me(oi,{size:20})}):void 0,endAdornment:f&&!b?me(gt,{position:"end",children:me(ti,{edge:"end",onClick:async()=>{!l&&!b&&await d()},disabled:l,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:me(ni,{})})}):void 0}})})};import eo,{useCallback as yr,useRef as ro}from"react";import Pt from"@mui/material/Box";import vt from"@mui/material/Typography";import _i from"@mui/material/CircularProgress";import Oi from"@mui/material/List";import Ni from"@mui/material/FormHelperText";var ht=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),yt=e=>{if(e===0)return"0 B";let r=1024,o=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(r));return`${parseFloat((e/Math.pow(r,t)).toFixed(1))} ${o[t]}`};import{useCallback as Hr,useState as si}from"react";var Kr=({disabled:e,onFilesDropped:r,onInteraction:o})=>{let[t,a]=si(!1),n=Hr(s=>{s.preventDefault(),s.stopPropagation(),e||a(!0)},[e]),i=Hr(s=>{s.preventDefault(),s.stopPropagation(),a(!1)},[]),l=Hr(s=>{if(s.preventDefault(),s.stopPropagation(),a(!1),e)return;o?.();let m=s.dataTransfer.files;m&&m.length>0&&r(m)},[e,r,o]);return{isDragging:t,handleDragOver:n,handleDragLeave:i,handleDrop:l}};import{useCallback as $r,useState as jr}from"react";var Gr=({deleteFileImmediately:e})=>{let[r,o]=jr(!1),[t,a]=jr(null),[n,i]=jr(!1),l=$r(p=>{a(p),o(!0)},[]),s=$r(async()=>{if(t){i(!0);try{let p=await e(t);p.success||x.error("Error deleting file",{error:p.error})}finally{i(!1),o(!1),a(null)}}},[t,e]),m=$r(()=>{o(!1),a(null)},[]);return{isOpen:r,isDeleting:n,fileToDelete:t,openConfirmation:l,handleConfirm:s,handleCancel:m}};import{useState as fi}from"react";import mr from"@mui/material/Box";import fr from"@mui/material/Typography";import Xr from"@mui/material/IconButton";import gi from"@mui/material/LinearProgress";import hi from"@mui/material/ListItem";import yi from"@mui/material/ListItemText";import bi from"@mui/material/ListItemSecondaryAction";import wi from"@mui/icons-material/Delete";import xi from"@mui/icons-material/Refresh";import Ci from"@mui/icons-material/Restore";import bt from"@mui/material/CircularProgress";import li from"@mui/material/Chip";import ci from"@mui/icons-material/InsertDriveFile";import di from"@mui/icons-material/Image";import ui from"@mui/icons-material/PictureAsPdf";import pi from"@mui/icons-material/CheckCircle";import mi from"@mui/icons-material/Error";import{jsx as Ce}from"react/jsx-runtime";var Yr=e=>e.startsWith("image/")?Ce(di,{color:"primary"}):e==="application/pdf"?Ce(ui,{color:"error"}):Ce(ci,{color:"action"}),wt=(e,r)=>{switch(e){case"completed":return Ce(pi,{color:"success",fontSize:"small"});case"error":return Ce(mi,{color:"error",fontSize:"small"});case"uploading":case"pending":return Ce(bt,{size:16});case"removing":return Ce(bt,{size:16,color:"error"});case"pendingDeletion":return Ce(li,{label:r("base.file.pendingDeletion"),size:"small",color:"warning",variant:"outlined",sx:{fontSize:"0.65rem",height:20}});default:return null}};import{jsx as q,jsxs as gr}from"react/jsx-runtime";var Zr=({file:e,baseUrl:r,disabled:o,onRemove:t,onRestore:a,onRetry:n})=>{let{t:i}=Ee(),[l,s]=fi(!1),m=e.status==="pendingDeletion",p=!o&&e.status!=="uploading"&&e.status!=="removing"&&!m,b=!o&&m,w=!o&&e.status==="error"&&e.file,d=e.contentType.startsWith("image/"),u=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),c=!e.filePath||!u?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,f=e.status==="completed"&&c,h=()=>d&&f&&!l?q(mr,{component:f?"a":"div",href:c||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.100",border:"1px solid",borderColor:"divider",cursor:f?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":f?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:q("img",{src:c,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>s(!0)})}):q(mr,{component:f?"a":"div",href:c||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.50",border:"1px solid",borderColor:"divider",cursor:f?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":f?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:Yr(e.contentType)});return gr(hi,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider",gap:1.5},children:[h(),q(yi,{primary:gr(mr,{sx:{display:"flex",alignItems:"center",gap:1},children:[q(fr,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",textDecoration:m?"line-through":"none",opacity:m?.6:1},children:e.name}),wt(e.status,i)]}),secondary:gr(mr,{sx:{opacity:m?.6:1},children:[e.size>0&&q(fr,{variant:"caption",color:"text.secondary",children:yt(e.size)}),e.status==="uploading"&&q(gi,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&q(fr,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),f&&q(fr,{variant:"caption",color:"primary",display:"block",component:"a",href:c||void 0,target:"_blank",rel:"noopener noreferrer",sx:{cursor:"pointer",textDecoration:"underline","&:hover":{textDecoration:"none"}},children:i(d?"base.file.clickToPreview":"base.file.clickToDownload")})]})}),gr(bi,{children:[w&&q(Xr,{edge:"end",size:"small",onClick:()=>n(e.id),color:"primary",title:i("base.file.restore"),children:q(xi,{fontSize:"small"})}),b&&q(Xr,{edge:"end",size:"small",onClick:()=>a(e.id),color:"primary",title:i("base.file.restore"),children:q(Ci,{fontSize:"small"})}),p&&q(Xr,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:i("base.file.delete"),children:q(wi,{fontSize:"small"})})]})]})};import{useState as mu}from"react";import gu from"@mui/material/Box";import yu from"@mui/material/Typography";import wu from"@mui/material/IconButton";import Cu from"@mui/material/CircularProgress";import vu from"@mui/icons-material/Delete";import Tu from"@mui/icons-material/Refresh";import Su from"@mui/icons-material/Restore";import ku from"@mui/icons-material/BrokenImage";import Au from"@mui/icons-material/Image";import{jsx as Ou,jsxs as Nu}from"react/jsx-runtime";import Pi from"@mui/material/Box";import vi from"@mui/material/Typography";import Ei from"@mui/material/Chip";import Ti from"@mui/material/Paper";import Ri from"@mui/icons-material/CloudUpload";import{jsx as hr,jsxs as Si}from"react/jsx-runtime";var Jr=({isDragging:e,disabled:r,hasError:o,placeholder:t,accept:a,onClick:n,onDragOver:i,onDragLeave:l,onDrop:s})=>Si(Ti,{variant:"outlined",onClick:n,onDragOver:i,onDragLeave:l,onDrop:s,sx:{p:3,textAlign:"center",cursor:r?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:e?"primary.main":o?"error.main":"divider",bgcolor:e?"primary.lighter":r?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":r?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[hr(Ri,{sx:{fontSize:48,color:e?"primary.main":r?"action.disabled":"action.active",mb:1}}),hr(vi,{variant:"body2",color:r?"text.disabled":"text.secondary",children:t}),a&&a.length>0&&!e&&hr(Pi,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:a.map(m=>hr(Ei,{label:m.split("/")[1]?.toUpperCase()||m,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},m))})]});import Ii from"@mui/material/Dialog";import ki from"@mui/material/DialogTitle";import Li from"@mui/material/DialogContent";import Ai from"@mui/material/DialogActions";import xt from"@mui/material/Button";import Di from"@mui/material/Typography";import Fi from"@mui/material/CircularProgress";import{jsx as Ue,jsxs as Ct}from"react/jsx-runtime";var Qr=({open:e,isDeleting:r,onConfirm:o,onCancel:t,title:a,message:n,cancelText:i,confirmText:l,deletingText:s})=>Ct(Ii,{open:e,onClose:r?void 0:t,children:[Ue(ki,{children:a}),Ue(Li,{children:Ue(Di,{children:n})}),Ct(Ai,{children:[Ue(xt,{onClick:t,disabled:r,children:i}),Ue(xt,{onClick:o,color:"error",variant:"contained",disabled:r,startIcon:r?Ue(Fi,{size:16,color:"inherit"}):void 0,children:r?s:l})]})]});import{jsx as se,jsxs as oo}from"react/jsx-runtime";var Bi=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:a,minFiles:n=0,required:i=!1,disabled:l=!1,error:s=!1,helperText:m,onChange:p,onValidation:b,initialFiles:w,placeholder:d,showFileList:u=!0,visibility:y="private",showPreview:c=!0,baseUrl:f,onDeletionHandlersReady:h,mode:C="create",name:I,containerRef:R})=>{let{t:g}=Ee(),E=ro(null),A=t?a:1,W=i?Math.max(n,1):n,ke={acceptedTypes:r,maxFileSize:o,maxFiles:A,minFiles:W,visibility:y,mode:C,onFilesChange:ne=>{let fe=ne.filter(Ye=>Ye.status==="completed"&&Ye.filePath).map(Ye=>{let Pr=Ye.filePath;return Pr.startsWith("/")?Pr:`/${Pr}`});p?.(fe)}},{files:le,isUploading:te,addFiles:Z,removeFile:Pe,restoreFile:Le,retryUpload:T,isValid:S,validationError:J,validationErrorKey:v,validationErrorParams:O,initializeFiles:N,isTouched:ce,markAsTouched:j,isSubmitted:wr,markAsSubmitted:Ge,getPreviewUrl:z,commitDeletions:D,restorePendingDeletions:H,hasPendingDeletions:G,deleteFileImmediately:K,activeFiles:de,activeFileCount:ve,waitForUploads:no,completedFilePaths:ao}=xo(ke),io=yr(()=>ao,[ao]),so=ro(!1),xr=ro(!1);eo.useEffect(()=>{w&&w.length>0&&!so.current&&!xr.current&&(xr.current=!0,(async()=>{try{await N(w,f),so.current=!0}catch(fe){x.error("Failed to initialize files",{error:fe})}finally{xr.current=!1}})())},[w,N,f]),eo.useEffect(()=>{b?.(S,J)},[S,J,b]),eo.useEffect(()=>{h&&h({commitDeletions:D,restorePendingDeletions:H,hasPendingDeletions:G,markAsSubmitted:Ge,isValid:S,isUploading:te,waitForUploads:no,getCompletedFilePaths:io})},[h,D,H,G,Ge,S,te,no,io]);let{isDragging:lo,handleDragOver:St,handleDragLeave:It,handleDrop:kt}=Kr({disabled:l,onFilesDropped:Z,onInteraction:j}),Ae=Gr({deleteFileImmediately:K}),Lt=yr(ne=>{j();let fe=ne.target.files;fe&&fe.length>0&&Z(fe),E.current&&(E.current.value="")},[Z,j]),At=yr(()=>{l||E.current?.click()},[l]),Dt=yr(async ne=>{(await Pe(ne)).needsConfirmation&&Ae.openConfirmation(ne)},[Pe,Ae]),Ft=r?.join(",")||"",_t=!l&&(t||ve===0),co=wr&&!S,Cr=s||co,uo=m||(co&&v?g(v,O):null);return se("div",{ref:R,children:oo(Pt,{sx:{width:"100%"},children:[e&&oo(vt,{variant:"body2",sx:{mb:1,fontWeight:500,color:Cr?"error.main":"text.primary"},children:[e,i&&se("span",{style:{color:"red"},children:" *"})]}),se("input",{ref:E,type:"file",name:I,accept:Ft,multiple:t,onChange:Lt,disabled:l,style:{display:"none"}}),_t&&se(Jr,{isDragging:lo,disabled:l,hasError:Cr,placeholder:d||g(lo?"base.file.dropHere":"base.file.dragOrClick"),accept:r,onClick:At,onDragOver:St,onDragLeave:It,onDrop:kt}),u&&le.length>0&&se(Oi,{dense:!0,sx:{mt:1,p:0},children:le.map(ne=>se(Zr,{file:ne,baseUrl:f,disabled:l,onRemove:Dt,onRestore:Le,onRetry:T},ne.id))}),te&&oo(Pt,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[se(_i,{size:16}),se(vt,{variant:"caption",color:"text.secondary",children:g("base.file.uploading")})]}),uo&&se(Ni,{error:Cr,sx:{mt:.5},dangerouslySetInnerHTML:{__html:ht(uo)}}),se(Qr,{open:Ae.isOpen,isDeleting:Ae.isDeleting,onConfirm:Ae.handleConfirm,onCancel:Ae.handleCancel,title:g("base.file.confirmDelete.title"),message:g("base.file.confirmDelete.message"),cancelText:g("base.file.confirmDelete.cancel"),confirmText:g("base.file.confirmDelete.confirm"),deletingText:g("base.file.deleting")})]})})};import{useCallback as Ui,useRef as zi,useEffect as Mi}from"react";import Et from"@mui/material/Box";import Tt from"@mui/material/Typography";import Rt from"@mui/material/FormHelperText";import{MDXEditor as Vi,headingsPlugin as qi,listsPlugin as Wi,quotePlugin as Hi,thematicBreakPlugin as Ki,markdownShortcutPlugin as $i,linkPlugin as ji,linkDialogPlugin as Gi,tablePlugin as Yi,toolbarPlugin as Xi,UndoRedo as Zi,BoldItalicUnderlineToggles as Ji,BlockTypeSelect as Qi,CreateLink as es,InsertTable as rs,ListsToggle as os,Separator as br}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as ts,jsx as U,jsxs as to}from"react/jsx-runtime";var Lp=({label:e,value:r="",onChange:o,required:t=!1,disabled:a=!1,error:n=!1,helperText:i,placeholder:l="Write here...",minHeight:s=200,maxHeight:m=500,name:p,containerRef:b})=>{let w=zi(null);Mi(()=>{w.current&&w.current.getMarkdown()!==r&&w.current.setMarkdown(r||"")},[r]);let d=Ui(u=>{o?.(u)},[o]);return U("div",{ref:b,children:to(Et,{sx:{width:"100%"},children:[e&&to(Tt,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&U(Tt,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),p&&U("input",{type:"hidden",name:p,value:r,readOnly:!0}),U(Et,{sx:{border:1,borderColor:n?"error.main":"divider",borderRadius:1,overflow:"hidden",opacity:a?.6:1,pointerEvents:a?"none":"auto","& .mdxeditor":{minHeight:s,maxHeight:m,overflow:"auto"},"& .mdxeditor-toolbar":{borderBottom:1,borderColor:"divider",backgroundColor:"background.default"},"& .mdxeditor-root-contenteditable":{padding:2,minHeight:s-50}},children:U(Vi,{ref:w,markdown:r||"",onChange:d,placeholder:l,readOnly:a,plugins:[qi(),Wi(),Hi(),Ki(),$i(),ji(),Gi(),Yi(),Xi({toolbarContents:()=>to(ts,{children:[U(Zi,{}),U(br,{}),U(Ji,{}),U(br,{}),U(Qi,{}),U(br,{}),U(os,{}),U(br,{}),U(es,{}),U(rs,{})]})})]})}),i&&U(Rt,{error:n,sx:{mx:0,mt:.5},children:i}),!i&&U(Rt,{sx:{mx:0,mt:.5},children:"\xA0"})]})})};export{ue as a,as as b,is as c,vr as d,Ze as e,bs as f,Ee as g,So as h,Io as i,Ps as j,Lo as k,Ao as l,Do as m,Fo as n,Rc as o,Pa as p,nt as q,at as r,dd as s,yd as t,bd as u,Sd as v,Bi as w,Lp as x};
@@ -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-BvJn2GL8.mjs';
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-TNyMLb-h.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';
@@ -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-CggOpcBM.js';
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-CXAuu-v2.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';
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkW4ZYKPOKjs = require('./chunk-W4ZYKPOK.js');var _chunkH6XXWDUTjs = require('./chunk-H6XXWDUT.js');require('./chunk-4LMFQECS.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}=_chunkH6XXWDUTjs.e.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 = _chunkW4ZYKPOKjs.v; exports.CrudiaFileField = _chunkW4ZYKPOKjs.w; exports.CrudiaMarkdownField = _chunkW4ZYKPOKjs.x; exports.CrudifyLogin = _chunkW4ZYKPOKjs.o; exports.GlobalNotificationProvider = _chunkH6XXWDUTjs.f; exports.LoginComponent = _chunkW4ZYKPOKjs.t; exports.Policies = _chunkW4ZYKPOKjs.s; exports.SessionStatus = _chunkW4ZYKPOKjs.u; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunkW4ZYKPOKjs.p; exports.useGlobalNotification = _chunkH6XXWDUTjs.g;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk2IOB6HHTjs = require('./chunk-2IOB6HHT.js');var _chunkMFQKGZI4js = require('./chunk-MFQKGZI4.js');require('./chunk-4LMFQECS.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}=_chunkMFQKGZI4js.e.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 = _chunk2IOB6HHTjs.v; exports.CrudiaFileField = _chunk2IOB6HHTjs.w; exports.CrudiaMarkdownField = _chunk2IOB6HHTjs.x; exports.CrudifyLogin = _chunk2IOB6HHTjs.o; exports.GlobalNotificationProvider = _chunkMFQKGZI4js.f; exports.LoginComponent = _chunk2IOB6HHTjs.t; exports.Policies = _chunk2IOB6HHTjs.s; exports.SessionStatus = _chunk2IOB6HHTjs.u; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunk2IOB6HHTjs.p; exports.useGlobalNotification = _chunkMFQKGZI4js.g;
@@ -1 +1 @@
1
- import{o as N,p as T,s as M,t as k,u as G,v as L,w as A,x as R}from"./chunk-SYHNHKFA.mjs";import{e as d,f as F,g as I}from"./chunk-O4FUHIQG.mjs";import"./chunk-44VU4TSP.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};
1
+ import{o as N,p as T,s as M,t as k,u as G,v as L,w as A,x as R}from"./chunk-XMEZUDF6.mjs";import{e as d,f as F,g as I}from"./chunk-2WHCDP7V.mjs";import"./chunk-44VU4TSP.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.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNIRLP2TCjs = require('./chunk-NIRLP2TC.js');var _chunkH6XXWDUTjs = require('./chunk-H6XXWDUT.js');require('./chunk-4LMFQECS.js');exports.useAuth = _chunkNIRLP2TCjs.b; exports.useAutoGenerate = _chunkH6XXWDUTjs.o; exports.useCrudifyWithNotifications = _chunkNIRLP2TCjs.d; exports.useData = _chunkNIRLP2TCjs.c; exports.useFileUpload = _chunkH6XXWDUTjs.r; exports.useSession = _chunkH6XXWDUTjs.e; exports.useUserData = _chunkNIRLP2TCjs.a; exports.useUserProfile = _chunkH6XXWDUTjs.n;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk37WOWEJGjs = require('./chunk-37WOWEJG.js');var _chunkMFQKGZI4js = require('./chunk-MFQKGZI4.js');require('./chunk-4LMFQECS.js');exports.useAuth = _chunk37WOWEJGjs.b; exports.useAutoGenerate = _chunkMFQKGZI4js.o; exports.useCrudifyWithNotifications = _chunk37WOWEJGjs.d; exports.useData = _chunk37WOWEJGjs.c; exports.useFileUpload = _chunkMFQKGZI4js.r; exports.useSession = _chunkMFQKGZI4js.e; exports.useUserData = _chunk37WOWEJGjs.a; exports.useUserProfile = _chunkMFQKGZI4js.n;
package/dist/hooks.mjs CHANGED
@@ -1 +1 @@
1
- import{a as s,b as p,c as u,d as a}from"./chunk-77UKXG5L.mjs";import{e,n as t,o,r}from"./chunk-O4FUHIQG.mjs";import"./chunk-44VU4TSP.mjs";export{p as useAuth,o as useAutoGenerate,a as useCrudifyWithNotifications,u as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
1
+ import{a as s,b as p,c as u,d as a}from"./chunk-NJERBWND.mjs";import{e,n as t,o,r}from"./chunk-2WHCDP7V.mjs";import"./chunk-44VU4TSP.mjs";export{p as useAuth,o as useAutoGenerate,a as useCrudifyWithNotifications,u as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import crudify__default from '@nocios/crudify-sdk';
1
+ import { CrudifyInstance } from '@nocios/crudify-sdk';
2
2
  export * from '@nocios/crudify-sdk';
3
3
  export { default as crudify } from '@nocios/crudify-sdk';
4
- import { d as CrudifyLoginConfig, l as PasswordRule, E as EvaluatedPasswordRule } from './CrudiaMarkdownField-BvJn2GL8.mjs';
5
- export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, o as CrudiaFileFieldDeletionHandlers, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, D as DEFAULT_PASSWORD_RULES, L as LoginComponent, m as POLICY_ACTIONS, n as PREFERRED_POLICY_ORDER, p as PasswordRuleType, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-BvJn2GL8.mjs';
4
+ import { d as CrudifyLoginConfig, l as PasswordRule, E as EvaluatedPasswordRule } from './CrudiaMarkdownField-TNyMLb-h.mjs';
5
+ export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, o as CrudiaFileFieldDeletionHandlers, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, D as DEFAULT_PASSWORD_RULES, L as LoginComponent, m as POLICY_ACTIONS, n as PREFERRED_POLICY_ORDER, p as PasswordRuleType, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-TNyMLb-h.mjs';
6
6
  import React, { ReactNode } from 'react';
7
7
  export { A as ApiError, f as CrudifyApiResponse, e as CrudifyEnvironment, l as CrudifyOperationOptions, m as CrudifyRequestOptions, g as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, i as LoginRequest, L as LoginResponse, j as ResetPasswordRequest, R as ResolvedTenantConfig, T as TenantConfig, a as TenantConfigOptions, o as TransactionInput, n as TransactionOperation, h as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, k as ValidationError, r as resolveTenantConfig, u as useTenantConfig } from './tenantConfig-DqJqQkoR.mjs';
8
8
  export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOptions, a as SessionConfig, g as SessionDebugInfo, S as SessionManager, e as SessionProvider, h as SessionProviderProps, d as SessionState, c as StorageType, b as TokenData, T as TokenStorage, 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, f as useSessionContext, i as useUserData, q as useUserProfile } from './index-U--xRr8A.mjs';
@@ -14,7 +14,7 @@ import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFil
14
14
  export { ActionCreateInput, ActionEditInput, ActionListFilters, ApiResponse, IAction, IModule, ModuleCreateInput, ModuleEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin-sdk';
15
15
 
16
16
  interface CrudifyContextValue {
17
- crudify: typeof crudify__default | null;
17
+ crudify: typeof CrudifyInstance | null;
18
18
  isLoading: boolean;
19
19
  error: string | null;
20
20
  isInitialized: boolean;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import crudify__default from '@nocios/crudify-sdk';
1
+ import { CrudifyInstance } from '@nocios/crudify-sdk';
2
2
  export * from '@nocios/crudify-sdk';
3
3
  export { default as crudify } from '@nocios/crudify-sdk';
4
- import { d as CrudifyLoginConfig, l as PasswordRule, E as EvaluatedPasswordRule } from './CrudiaMarkdownField-CggOpcBM.js';
5
- export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, o as CrudiaFileFieldDeletionHandlers, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, D as DEFAULT_PASSWORD_RULES, L as LoginComponent, m as POLICY_ACTIONS, n as PREFERRED_POLICY_ORDER, p as PasswordRuleType, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-CggOpcBM.js';
4
+ import { d as CrudifyLoginConfig, l as PasswordRule, E as EvaluatedPasswordRule } from './CrudiaMarkdownField-CXAuu-v2.js';
5
+ export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, o as CrudiaFileFieldDeletionHandlers, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, D as DEFAULT_PASSWORD_RULES, L as LoginComponent, m as POLICY_ACTIONS, n as PREFERRED_POLICY_ORDER, p as PasswordRuleType, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-CXAuu-v2.js';
6
6
  import React, { ReactNode } from 'react';
7
7
  export { A as ApiError, f as CrudifyApiResponse, e as CrudifyEnvironment, l as CrudifyOperationOptions, m as CrudifyRequestOptions, g as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, i as LoginRequest, L as LoginResponse, j as ResetPasswordRequest, R as ResolvedTenantConfig, T as TenantConfig, a as TenantConfigOptions, o as TransactionInput, n as TransactionOperation, h as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, k as ValidationError, r as resolveTenantConfig, u as useTenantConfig } from './tenantConfig-DqJqQkoR.js';
8
8
  export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOptions, a as SessionConfig, g as SessionDebugInfo, S as SessionManager, e as SessionProvider, h as SessionProviderProps, d as SessionState, c as StorageType, b as TokenData, T as TokenStorage, 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, f as useSessionContext, i as useUserData, q as useUserProfile } from './index-dXVRVcEB.js';
@@ -14,7 +14,7 @@ import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFil
14
14
  export { ActionCreateInput, ActionEditInput, ActionListFilters, ApiResponse, IAction, IModule, ModuleCreateInput, ModuleEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin-sdk';
15
15
 
16
16
  interface CrudifyContextValue {
17
- crudify: typeof crudify__default | null;
17
+ crudify: typeof CrudifyInstance | null;
18
18
  isLoading: boolean;
19
19
  error: string | null;
20
20
  isInitialized: boolean;