@nocios/crudify-components 2.0.32 → 2.0.38

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 (178) hide show
  1. package/coverage/base.css +224 -0
  2. package/coverage/block-navigation.js +87 -0
  3. package/coverage/components/CrudiaAutoGenerate.tsx.html +583 -0
  4. package/coverage/components/CrudiaFileField/CrudiaFileField.tsx.html +1276 -0
  5. package/coverage/components/CrudiaFileField/components/DeleteConfirmationDialog.tsx.html +355 -0
  6. package/coverage/components/CrudiaFileField/components/DropZone.tsx.html +433 -0
  7. package/coverage/components/CrudiaFileField/components/FileItemRow.tsx.html +751 -0
  8. package/coverage/components/CrudiaFileField/components/FileThumbnail.tsx.html +1195 -0
  9. package/coverage/components/CrudiaFileField/components/index.html +176 -0
  10. package/coverage/components/CrudiaFileField/components/index.ts.html +115 -0
  11. package/coverage/components/CrudiaFileField/hooks/index.html +146 -0
  12. package/coverage/components/CrudiaFileField/hooks/index.ts.html +112 -0
  13. package/coverage/components/CrudiaFileField/hooks/useDeleteConfirmation.ts.html +421 -0
  14. package/coverage/components/CrudiaFileField/hooks/useDragDrop.ts.html +403 -0
  15. package/coverage/components/CrudiaFileField/index.html +131 -0
  16. package/coverage/components/CrudiaFileField/index.ts.html +112 -0
  17. package/coverage/components/CrudiaFileField/utils/formatters.ts.html +163 -0
  18. package/coverage/components/CrudiaFileField/utils/icons.tsx.html +253 -0
  19. package/coverage/components/CrudiaFileField/utils/index.html +131 -0
  20. package/coverage/components/CrudiaMarkdownField.tsx.html +619 -0
  21. package/coverage/components/CrudifyLogin/Forms/CheckCodeForm.tsx.html +586 -0
  22. package/coverage/components/CrudifyLogin/Forms/ForgotPasswordForm.tsx.html +694 -0
  23. package/coverage/components/CrudifyLogin/Forms/LoginForm.tsx.html +835 -0
  24. package/coverage/components/CrudifyLogin/Forms/ResetPasswordForm.tsx.html +1180 -0
  25. package/coverage/components/CrudifyLogin/Forms/components/CodeInput.tsx.html +283 -0
  26. package/coverage/components/CrudifyLogin/Forms/components/FormAlert.tsx.html +202 -0
  27. package/coverage/components/CrudifyLogin/Forms/components/PasswordInput.tsx.html +340 -0
  28. package/coverage/components/CrudifyLogin/Forms/components/index.html +161 -0
  29. package/coverage/components/CrudifyLogin/Forms/components/index.ts.html +106 -0
  30. package/coverage/components/CrudifyLogin/Forms/index.html +161 -0
  31. package/coverage/components/CrudifyLogin/Forms/utils/errorTranslation.ts.html +268 -0
  32. package/coverage/components/CrudifyLogin/Forms/utils/index.html +161 -0
  33. package/coverage/components/CrudifyLogin/Forms/utils/index.ts.html +106 -0
  34. package/coverage/components/CrudifyLogin/Forms/utils/paramUtils.ts.html +478 -0
  35. package/coverage/components/CrudifyLogin/Forms/utils/validation.ts.html +289 -0
  36. package/coverage/components/CrudifyLogin/components/CrudifyInitializer.tsx.html +262 -0
  37. package/coverage/components/CrudifyLogin/components/index.html +116 -0
  38. package/coverage/components/CrudifyLogin/context/CrudifyProvider.tsx.html +382 -0
  39. package/coverage/components/CrudifyLogin/context/I18nProvider.tsx.html +397 -0
  40. package/coverage/components/CrudifyLogin/context/LoginStateProvider.tsx.html +1249 -0
  41. package/coverage/components/CrudifyLogin/context/index.html +146 -0
  42. package/coverage/components/CrudifyLogin/hooks/index.html +116 -0
  43. package/coverage/components/CrudifyLogin/hooks/useTranslationsFromUrl.ts.html +292 -0
  44. package/coverage/components/CrudifyLogin/index.html +116 -0
  45. package/coverage/components/CrudifyLogin/index.tsx.html +475 -0
  46. package/coverage/components/GlobalNotificationProvider.tsx.html +781 -0
  47. package/coverage/components/LoginComponent.tsx.html +727 -0
  48. package/coverage/components/PasswordRequirements/index.html +116 -0
  49. package/coverage/components/PasswordRequirements/index.tsx.html +226 -0
  50. package/coverage/components/PublicPolicies/FieldSelector/FieldSelector.tsx.html +982 -0
  51. package/coverage/components/PublicPolicies/FieldSelector/index.html +131 -0
  52. package/coverage/components/PublicPolicies/FieldSelector/index.ts.html +85 -0
  53. package/coverage/components/PublicPolicies/Policies.tsx.html +610 -0
  54. package/coverage/components/PublicPolicies/PolicyItem/PolicyItem.tsx.html +856 -0
  55. package/coverage/components/PublicPolicies/PolicyItem/index.html +131 -0
  56. package/coverage/components/PublicPolicies/PolicyItem/index.ts.html +85 -0
  57. package/coverage/components/PublicPolicies/constants.ts.html +127 -0
  58. package/coverage/components/PublicPolicies/index.html +131 -0
  59. package/coverage/components/SessionTimeIndicator/index.html +116 -0
  60. package/coverage/components/SessionTimeIndicator/index.tsx.html +505 -0
  61. package/coverage/components/UserProfile/UserProfileDisplay.tsx.html +826 -0
  62. package/coverage/components/UserProfile/index.html +131 -0
  63. package/coverage/components/UserProfile/index.ts.html +85 -0
  64. package/coverage/components/index.html +176 -0
  65. package/coverage/components/index.ts.html +160 -0
  66. package/coverage/core/CrossTabSyncManager.ts.html +814 -0
  67. package/coverage/core/CrudifyInitializationManager.ts.html +1132 -0
  68. package/coverage/core/SessionManager.ts.html +2764 -0
  69. package/coverage/core/index.html +146 -0
  70. package/coverage/coverage-final.json +87 -0
  71. package/coverage/favicon.png +0 -0
  72. package/coverage/hooks/index.html +131 -0
  73. package/coverage/hooks/useAutoGenerate.ts.html +562 -0
  74. package/coverage/hooks/useFileUpload/index.html +131 -0
  75. package/coverage/hooks/useFileUpload/index.ts.html +112 -0
  76. package/coverage/hooks/useFileUpload/services/index.html +116 -0
  77. package/coverage/hooks/useFileUpload/services/uploadService.ts.html +610 -0
  78. package/coverage/hooks/useFileUpload/useFileUpload.ts.html +1870 -0
  79. package/coverage/hooks/useFileUpload/utils/fileUtils.ts.html +271 -0
  80. package/coverage/hooks/useFileUpload/utils/index.html +146 -0
  81. package/coverage/hooks/useFileUpload/utils/mimeTypes.ts.html +235 -0
  82. package/coverage/hooks/useFileUpload/utils/validation.ts.html +379 -0
  83. package/coverage/hooks/useSession/constants.ts.html +217 -0
  84. package/coverage/hooks/useSession/hooks/index.html +176 -0
  85. package/coverage/hooks/useSession/hooks/useAuthEventSubscriber.ts.html +331 -0
  86. package/coverage/hooks/useSession/hooks/useCrossTabSync.ts.html +433 -0
  87. package/coverage/hooks/useSession/hooks/useSessionActions.ts.html +664 -0
  88. package/coverage/hooks/useSession/hooks/useSessionState.ts.html +295 -0
  89. package/coverage/hooks/useSession/hooks/useTokenRefreshScheduler.ts.html +490 -0
  90. package/coverage/hooks/useSession/index.html +161 -0
  91. package/coverage/hooks/useSession/index.ts.html +127 -0
  92. package/coverage/hooks/useSession/types.ts.html +427 -0
  93. package/coverage/hooks/useSession/useSession.ts.html +526 -0
  94. package/coverage/hooks/useSession/utils/index.html +131 -0
  95. package/coverage/hooks/useSession/utils/initializeSession.ts.html +424 -0
  96. package/coverage/hooks/useSession/utils/tokenUtils.ts.html +280 -0
  97. package/coverage/hooks/useUserProfile.ts.html +658 -0
  98. package/coverage/index.html +566 -0
  99. package/coverage/prettify.css +1 -0
  100. package/coverage/prettify.js +2 -0
  101. package/coverage/providers/SessionProvider.tsx.html +1150 -0
  102. package/coverage/providers/TranslationsProvider.tsx.html +1450 -0
  103. package/coverage/providers/index.html +131 -0
  104. package/coverage/services/credentialsEventBus.ts.html +310 -0
  105. package/coverage/services/index.html +131 -0
  106. package/coverage/services/translationService.ts.html +1318 -0
  107. package/coverage/sort-arrow-sprite.png +0 -0
  108. package/coverage/sorter.js +210 -0
  109. package/coverage/translations/critical.ts.html +1195 -0
  110. package/coverage/translations/index.html +116 -0
  111. package/coverage/types/index.html +116 -0
  112. package/coverage/types/password.ts.html +178 -0
  113. package/coverage/utils/authEventBus.ts.html +454 -0
  114. package/coverage/utils/configResolver.ts.html +460 -0
  115. package/coverage/utils/cookieSync.ts.html +580 -0
  116. package/coverage/utils/errorHandler.ts.html +1264 -0
  117. package/coverage/utils/errorTranslation.ts.html +862 -0
  118. package/coverage/utils/index.html +296 -0
  119. package/coverage/utils/jwtUtils.ts.html +301 -0
  120. package/coverage/utils/logger.ts.html +901 -0
  121. package/coverage/utils/navigationTracker.ts.html +565 -0
  122. package/coverage/utils/passwordValidation.ts.html +259 -0
  123. package/coverage/utils/redirectSecurity.ts.html +715 -0
  124. package/coverage/utils/tenantConfig.ts.html +700 -0
  125. package/coverage/utils/tokenStorage.ts.html +1768 -0
  126. package/coverage/utils/webCrypto.ts.html +472 -0
  127. package/dist/{CrudiaMarkdownField-C54-A_J3.d.mts → CrudiaMarkdownField-BvJn2GL8.d.mts} +17 -7
  128. package/dist/{CrudiaMarkdownField-C8HQh7s5.d.ts → CrudiaMarkdownField-CggOpcBM.d.ts} +17 -7
  129. package/dist/chunk-44VU4TSP.mjs +1 -0
  130. package/dist/chunk-4LMFQECS.js +1 -0
  131. package/dist/chunk-77UKXG5L.mjs +1 -0
  132. package/dist/{chunk-4VN5YRYZ.js → chunk-BXFEQ6KP.js} +1 -1
  133. package/dist/{chunk-6ONAT4QU.js → chunk-H6XXWDUT.js} +1 -1
  134. package/dist/chunk-NIRLP2TC.js +1 -0
  135. package/dist/chunk-O4FUHIQG.mjs +1 -0
  136. package/dist/chunk-SYHNHKFA.mjs +1 -0
  137. package/dist/chunk-W4ZYKPOK.js +1 -0
  138. package/dist/{chunk-RJBX4MWF.mjs → chunk-WMLIOPUC.mjs} +1 -1
  139. package/dist/components.d.mts +1 -1
  140. package/dist/components.d.ts +1 -1
  141. package/dist/components.js +1 -1
  142. package/dist/components.mjs +1 -1
  143. package/dist/errorTranslation-D-Y7uNN_.d.mts +141 -0
  144. package/dist/errorTranslation-DDlAXpMl.d.ts +141 -0
  145. package/dist/hooks.d.mts +2 -2
  146. package/dist/hooks.d.ts +2 -2
  147. package/dist/hooks.js +1 -1
  148. package/dist/hooks.mjs +1 -1
  149. package/dist/{index-DY90WVQQ.d.mts → index-U--xRr8A.d.mts} +225 -191
  150. package/dist/{index-d1vE803G.d.ts → index-dXVRVcEB.d.ts} +225 -191
  151. package/dist/index.d.mts +179 -6
  152. package/dist/index.d.ts +179 -6
  153. package/dist/index.js +2 -2
  154. package/dist/index.mjs +1 -1
  155. package/dist/{errorTranslation-By5Av0tL.d.ts → tenantConfig-DqJqQkoR.d.mts} +116 -139
  156. package/dist/{errorTranslation-DeeDj7Vt.d.mts → tenantConfig-DqJqQkoR.d.ts} +116 -139
  157. package/dist/utils.d.mts +2 -2
  158. package/dist/utils.d.ts +2 -2
  159. package/dist/utils.js +1 -1
  160. package/dist/utils.mjs +1 -1
  161. package/package.json +1 -1
  162. package/coverage/.tmp/coverage-102.json +0 -1
  163. package/coverage/.tmp/coverage-103.json +0 -1
  164. package/coverage/.tmp/coverage-104.json +0 -1
  165. package/coverage/.tmp/coverage-105.json +0 -1
  166. package/coverage/.tmp/coverage-106.json +0 -1
  167. package/coverage/.tmp/coverage-107.json +0 -1
  168. package/dist/api-B4uXiHF0.d.mts +0 -118
  169. package/dist/api-B4uXiHF0.d.ts +0 -118
  170. package/dist/chunk-4ILUXVPW.mjs +0 -1
  171. package/dist/chunk-5XBTRBE5.js +0 -1
  172. package/dist/chunk-CR5KJUST.js +0 -1
  173. package/dist/chunk-H5M2Q6PB.mjs +0 -1
  174. package/dist/chunk-JAPL7EZJ.mjs +0 -1
  175. package/dist/chunk-L7GKP6XY.mjs +0 -1
  176. package/dist/chunk-NSV6ECYO.js +0 -1
  177. package/dist/chunk-PTUSZGL4.mjs +0 -1
  178. package/dist/chunk-T6R65ROU.js +0 -1
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function w(){if(typeof window>"u")return"prod";let e=window.__TENANT_CONFIG__;return _optionalChain([e, 'optionalAccess', _2 => _2.environment])&&["dev","stg","api","prod"].includes(e.environment)?e.environment:window.__CRUDIFY_ENV__?window.__CRUDIFY_ENV__:"prod"}var h=null,D="CrudifyUI",y=class{constructor(){this.explicitEnv=null;this.explicitEnv=h,this.prefix=D}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:w()}sanitize(n){let r=n;for(let t of b)r=r.replace(t,"[REDACTED]");return r}sanitizeContext(n){let r={};for(let[t,i]of Object.entries(n))if(i!=null)if(t==="userId"&&typeof i=="string")r[t]=i.length>8?`${i.substring(0,8)}***`:i;else if(t==="email"&&typeof i=="string"){let[a,s]=i.split("@");r[t]=a&&s?`${a.substring(0,3)}***@${s}`:"[REDACTED]"}else typeof i=="string"?r[t]=this.sanitize(i):typeof i=="object"&&i!==null?r[t]=this.sanitizeContext(i):r[t]=i;return r}shouldLog(n){if(typeof window<"u"&&window.__CRUDIFY_DEBUG_MODE__)return!0;let r=this.getEffectiveEnv();return!((r==="prod"||r==="production"||r==="api")&&n!=="error")}log(n,r,t){if(!this.shouldLog(n))return;let i=this.sanitize(r),a=t?this.sanitizeContext(t):void 0,s={timestamp:new Date().toISOString(),level:n,environment:this.getEffectiveEnv(),service:this.prefix,message:i,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(s);switch(n){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(n,r){let t;r instanceof Error?t={errorName:r.name,errorMessage:r.message,stack:r.stack}:t=r,this.log("error",n,t)}warn(n,r){this.log("warn",n,r)}info(n,r){this.log("info",n,r)}debug(n,r){this.log("debug",n,r)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(n){if(this.explicitEnv=n,h=n,typeof window<"u"){let r=["dev","stg","api","prod"];window.__CRUDIFY_ENV__=r.includes(n)?n:void 0}}isExplicitlyConfigured(){return this.explicitEnv!==null}},u= exports.a =new y;var U=["dev","stg","api","prod"];function L(e){return!!e&&U.includes(e)}function x(){if(typeof window>"u")return null;let e=window.__TENANT_CONFIG__;return!e||!e.publicApiKey?null:e}function T(e={}){let{publicApiKey:n,env:r,appName:t,logo:i,loginActions:a,featureKeys:s,theme:l,enabledServices:g,enableDebug:d=!1}=e,c=x();if(c){d&&u.info("[TenantConfig] Using INJECTED configuration (Lambda@Edge)",{hasApiKey:!!c.publicApiKey,environment:c.environment,hasAppName:!!c.appName,hasLogo:!!c.logo,loginActionsCount:_optionalChain([c, 'access', _3 => _3.loginActions, 'optionalAccess', _4 => _4.length]),featureKeysCount:_optionalChain([c, 'access', _5 => _5.featureKeys, 'optionalAccess', _6 => _6.length]),hasTheme:!!c.theme});let p=L(c.environment)?c.environment:"prod";return{publicApiKey:c.publicApiKey,environment:p,appName:c.appName,logo:c.logo,loginActions:c.loginActions,featureKeys:c.featureKeys,theme:c.theme,enabledServices:c.enabledServices,configSource:"injected"}}return n?(d&&u.info("[TenantConfig] Using PROPS configuration (development)",{environment:r,hasAppName:!!t,hasLogo:!!i,loginActionsCount:_optionalChain([a, 'optionalAccess', _7 => _7.length]),featureKeysCount:_optionalChain([s, 'optionalAccess', _8 => _8.length]),hasTheme:!!l}),{publicApiKey:n,environment:r||"prod",appName:t,logo:i,loginActions:a,featureKeys:s,theme:l,enabledServices:g,configSource:"props"}):(d&&u.error("[TenantConfig] No configuration found! Ensure Lambda@Edge injects window.__TENANT_CONFIG__ (production) or provide props (development)."),{configSource:"none"})}function Q(e={}){return T(e)}function P(e){return e==="injected"?"cookies":e}function k(e={}){let n={publicApiKey:e.publicApiKey,env:e.env,appName:e.appName,logo:e.logo,loginActions:e.loginActions,featureKeys:e.featureKeys,enableDebug:e.enableDebug},r=T(n),t={publicApiKey:r.publicApiKey,env:r.environment,appName:r.appName,logo:r.logo,loginActions:r.loginActions,featureKeys:r.featureKeys,theme:r.theme,configSource:P(r.configSource)};return e.enableDebug&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=t),t}function X(e={}){return k(e)}var _=class e{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return e.instance||(e.instance=new e),e.instance}emit(n,r){let t=Date.now();if(this.isHandlingAuthError&&this.lastEventType===n&&t-this.lastErrorTime<this.DEBOUNCE_TIME){u.debug(`AuthEventBus: Ignoring duplicate ${n} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=t,this.lastEventType=n,u.debug(`AuthEventBus: Emitting ${n} event`,r?{details:r}:void 0);let i={type:n,details:r,timestamp:t};this.listeners.forEach(a=>{try{a(i)}catch(s){u.error("AuthEventBus: Error in listener",s instanceof Error?s:{message:String(s)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},ee= exports.f =_.getInstance();var K=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],V={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},F={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function f(e,n){let{translateFn:r,currentLanguage:t,enableDebug:i}=n;i&&u.debug(`[ErrorTranslation] Translating error code: ${e} (lang: ${t||"unknown"})`);let a=e.toUpperCase(),s=V[a],l=K.map(c=>c.replace("{category}",s||"general").replace("{code}",a));i&&u.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=r(c);if(i&&u.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return i&&u.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let g=F[a];if(g)return i&&u.debug(`[ErrorTranslation] Using default message: "${g}"`),g;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return i&&u.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function M(e,n){return e.map(r=>f(r,n))}function B(e,n){let{enableDebug:r}=n;r&&u.debug("[ErrorTranslation] Translating error:",{error:e});let t=f(e.code,n);return t!==e.code.toUpperCase()&&t!==e.code?(r&&u.debug(`[ErrorTranslation] Using hierarchical translation: "${t}"`),e.field?`${e.field}: ${t}`:t):e.message&&!e.message.includes("Error:")&&e.message.length>0&&e.message!==e.code?(r&&u.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${e.message}"`),e.message):(r&&u.debug(`[ErrorTranslation] Using final fallback: "${t}"`),e.field?`${e.field}: ${t}`:t)}function te(e,n={}){let r={translateFn:e,currentLanguage:n.currentLanguage,enableDebug:n.enableDebug||!1};return{translateErrorCode:t=>f(t,r),translateErrorCodes:t=>M(t,r),translateError:t=>B(t,r),translateApiError:t=>_optionalChain([t, 'optionalAccess', _9 => _9.data, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.status])?f(t.data.response.status,r):_optionalChain([t, 'optionalAccess', _12 => _12.status])?f(t.status,r):_optionalChain([t, 'optionalAccess', _13 => _13.code])?f(t.code,r):"Unknown error"}}var E=class E{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return E.instance||(E.instance=new E),E.instance}subscribe(n){return this.listeners.add(n),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(n)}}unsubscribe(n){this.listeners.delete(n),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let n=this;window.history.pushState=function(...r){let t=n.originalPushState.apply(this,r);return n.notifyListeners(),t},window.history.replaceState=function(...r){let t=n.originalReplaceState.apply(this,r);return n.notifyListeners(),t},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(n=>{try{n()}catch(r){u.error("NavigationTracker: Error in navigation listener",r instanceof Error?r:{message:String(r)})}})}static reset(){_optionalChain([E, 'access', _14 => _14.instance, 'optionalAccess', _15 => _15.isPatched])&&E.instance.removePatches(),E.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};E.instance=null;var v=E;var m=e=>{try{let n=e.split(".");if(n.length!==3)return u.warn("Invalid JWT format: token must have 3 parts"),null;let r=n[1],t=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(t))}catch(n){return u.warn("Failed to decode JWT token",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},ce= exports.s =()=>{try{let e=null;if(e=sessionStorage.getItem("authToken"),e||(e=sessionStorage.getItem("token")),e||(e=localStorage.getItem("authToken")||localStorage.getItem("token")),!e)return null;let n=m(e);return n&&(n.email||n["cognito:username"])||null}catch(e){return u.warn("Failed to get current user email",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},le= exports.t =e=>{try{let n=m(e);if(!n||!n.exp)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<r}catch (e2){return!0}};var o={INVALID_CREDENTIALS:"INVALID_CREDENTIALS",UNAUTHORIZED:"UNAUTHORIZED",INVALID_API_KEY:"INVALID_API_KEY",USER_NOT_FOUND:"USER_NOT_FOUND",USER_NOT_ACTIVE:"USER_NOT_ACTIVE",NO_PERMISSION:"NO_PERMISSION",ITEM_NOT_FOUND:"ITEM_NOT_FOUND",NOT_FOUND:"NOT_FOUND",IN_USE:"IN_USE",FIELD_ERROR:"FIELD_ERROR",BAD_REQUEST:"BAD_REQUEST",INVALID_EMAIL:"INVALID_EMAIL",INVALID_CODE:"INVALID_CODE",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"INVALID_CONFIGURATION",UNKNOWN_OPERATION:"UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"},N= exports.v ={[o.INVALID_CREDENTIALS]:"warning",[o.UNAUTHORIZED]:"warning",[o.INVALID_API_KEY]:"error",[o.USER_NOT_FOUND]:"warning",[o.USER_NOT_ACTIVE]:"warning",[o.NO_PERMISSION]:"warning",[o.ITEM_NOT_FOUND]:"info",[o.NOT_FOUND]:"info",[o.IN_USE]:"warning",[o.FIELD_ERROR]:"warning",[o.BAD_REQUEST]:"warning",[o.INVALID_EMAIL]:"warning",[o.INVALID_CODE]:"warning",[o.INTERNAL_SERVER_ERROR]:"error",[o.DATABASE_CONNECTION_ERROR]:"error",[o.INVALID_CONFIGURATION]:"error",[o.UNKNOWN_OPERATION]:"error",[o.TOO_MANY_REQUESTS]:"warning",[o.NETWORK_ERROR]:"error",[o.TIMEOUT_ERROR]:"error"};function C(e){let n=[];try{let r=e;if(r.data&&typeof r.data=="object"){let t=r.data;if(t.response){let{status:i,fieldsWarning:a}=t.response;if(a&&typeof a=="object"&&Object.entries(a).forEach(([s,l])=>{Array.isArray(l)&&l.length>0&&n.push({code:o.FIELD_ERROR,message:l[0],severity:"warning",field:s})}),i&&typeof i=="string"){let s=i;N[s]&&n.push({code:s,message:R(s),severity:N[s]})}}}if(r.errors){if(typeof r.errors=="string")n.push({code:o.BAD_REQUEST,message:r.errors,severity:"warning"});else if(typeof r.errors=="object"){let t=r.errors;Object.entries(t).forEach(([i,a])=>{Array.isArray(a)&&a.length>0&&(i==="_error"?a.forEach(s=>{let l=typeof s=="string"&&S(s)?s:o.BAD_REQUEST;n.push({code:l,message:typeof s=="string"?s:R(l),severity:N[l]||"warning"})}):i==="_graphql"?a.forEach(s=>{if(typeof s=="string"){let l=S(s)?s:o.BAD_REQUEST;n.push({code:l,message:R(l),severity:N[l]||"warning"})}}):n.push({code:o.FIELD_ERROR,message:typeof a[0]=="string"?a[0]:"Validation error",severity:"warning",field:i}))})}}n.length===0&&r.success===!1&&n.push({code:o.BAD_REQUEST,message:"Request failed",severity:"warning"})}catch(r){n.push({code:o.INTERNAL_SERVER_ERROR,message:"Failed to parse error response",severity:"error",details:{originalError:r}})}return n.length>0?n:[{code:o.INTERNAL_SERVER_ERROR,message:"Unknown error occurred",severity:"error"}]}function Y(e){try{let n=e;if(n.data&&Array.isArray(n.data)){let r=[];return n.data.forEach((t,i)=>{_optionalChain([t, 'access', _16 => _16.response, 'optionalAccess', _17 => _17.status])==="TOO_MANY_REQUESTS"?r.push({code:o.TOO_MANY_REQUESTS,message:R(o.TOO_MANY_REQUESTS),severity:"warning",details:{transactionIndex:i}}):(!t.response||t.response.status!=="OK")&&r.push({code:o.BAD_REQUEST,message:"Transaction failed",severity:"warning",details:{transactionIndex:i,response:t.response}})}),r}return C(e)}catch(n){return[{code:o.INTERNAL_SERVER_ERROR,message:"Failed to parse transaction error",severity:"error",details:{originalError:n}}]}}function S(e){return Object.values(o).includes(e)}function R(e){return{[o.INVALID_CREDENTIALS]:"Invalid email or password",[o.UNAUTHORIZED]:"You are not authorized to perform this action",[o.INVALID_API_KEY]:"Invalid API key",[o.USER_NOT_FOUND]:"User not found",[o.USER_NOT_ACTIVE]:"User account is not active",[o.NO_PERMISSION]:"You do not have permission to perform this action",[o.ITEM_NOT_FOUND]:"Item not found",[o.NOT_FOUND]:"Resource not found",[o.IN_USE]:"Resource is currently in use",[o.FIELD_ERROR]:"Validation error",[o.BAD_REQUEST]:"Invalid request",[o.INVALID_EMAIL]:"Please enter a valid email address",[o.INVALID_CODE]:"Invalid or expired code",[o.INTERNAL_SERVER_ERROR]:"Internal server error",[o.DATABASE_CONNECTION_ERROR]:"Database connection error",[o.INVALID_CONFIGURATION]:"Invalid configuration",[o.UNKNOWN_OPERATION]:"Unknown operation",[o.TOO_MANY_REQUESTS]:"Too many requests. Please try again later.",[o.NETWORK_ERROR]:"Network error. Please check your connection.",[o.TIMEOUT_ERROR]:"Request timed out. Please try again."}[e]||"An unknown error occurred"}function H(e){return e instanceof Error?e.name==="AbortError"?{code:o.TIMEOUT_ERROR,message:"Request was cancelled",severity:"info"}:e.message.includes("NetworkError")||e.message.includes("Failed to fetch")?{code:o.NETWORK_ERROR,message:R(o.NETWORK_ERROR),severity:"error"}:{code:o.INTERNAL_SERVER_ERROR,message:e.message||"An unexpected error occurred",severity:"error",details:{originalError:e}}:{code:o.INTERNAL_SERVER_ERROR,message:"An unknown error occurred",severity:"error",details:{originalError:e}}}function Ee(e){if(e instanceof Error)return[H(e)];if(typeof e=="object"&&e!==null){let n=e;return n.data&&Array.isArray(n.data)?Y(e):C(e)}return[{code:o.INTERNAL_SERVER_ERROR,message:"An unknown error occurred",severity:"error",details:{originalError:e}}]}var O="AES-GCM";async function de(e){let r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t)).map(a=>a.toString(16).padStart(2,"0")).join("")}async function $(e,n){let r=new TextEncoder,t=await crypto.subtle.importKey("raw",r.encode(e),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:n.buffer,iterations:1e5,hash:"SHA-256"},t,{name:O,length:256},!1,["encrypt","decrypt"])}async function pe(e,n,r){let t=new TextEncoder,i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:O,iv:i},n,t.encode(e)),s=A(i),l=A(r),g=A(new Uint8Array(a));return`v2:${s}:${l}:${g}`}async function fe(e,n){if(!e.startsWith("v2:"))return null;try{let r=e.slice(3).split(":");if(r.length!==3)return null;let[t,i,a]=r,s=I(t),l=I(i),g=I(a),d=await $(n,l),c=await crypto.subtle.decrypt({name:O,iv:s.buffer},d,g.buffer);return new TextDecoder().decode(c)}catch (e3){return null}}function Re(){return crypto.getRandomValues(new Uint8Array(16))}function Ne(e){return e.startsWith("v2:")}function A(e){let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}function I(e){let n=atob(e),r=new Uint8Array(n.length);for(let t=0;t<n.length;t++)r[t]=n.charCodeAt(t);return r}exports.a = u; exports.b = T; exports.c = Q; exports.d = k; exports.e = X; exports.f = ee; exports.g = de; exports.h = $; exports.i = pe; exports.j = fe; exports.k = Re; exports.l = Ne; exports.m = f; exports.n = M; exports.o = B; exports.p = te; exports.q = v; exports.r = m; exports.s = ce; exports.t = le; exports.u = o; exports.v = N; exports.w = C; exports.x = Y; exports.y = R; exports.z = H; exports.A = Ee;
@@ -0,0 +1 @@
1
+ import{g as z,l as b}from"./chunk-O4FUHIQG.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 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,N]=K(null),C=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),N(null),I(!1),e.current=0},[]),p=q(async()=>{let i=m();if(!i){f.current&&(N("No user email available from session data"),I(!1));return}if(!n){f.current&&(N("Session not initialized"),I(!1));return}C.current&&C.current.abort();let g=new AbortController;C.current=g;let O=++y.current;try{f.current&&(I(!0),N(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),N(null),e.current=0):(N("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)):(N("Failed to load user profile from database"),d(null))}}finally{O===y.current&&f.current&&I(!1),C.current===g&&(C.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,C.current&&(C.current.abort(),C.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:N}=b(),C=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:C,logout:l,refreshToken:E,login:u,isExpiringSoon:I,expiresIn:S,refreshExpiresIn:N,getTokenInfo:A,clearError:d}};import{useCallback as T}from"react";import 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]),N=T(async(f,y)=>(await l(),await P.transaction(f,y)),[l]),C=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:N,login:C,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 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]),N=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]),C=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:N,readItem:C,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]),N=L(i=>i.errorCode&&j[i.errorCode]?j[i.errorCode]:"error",[]),C=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:N,getSuccessMessage:C}),_=L((i,g)=>{if(!i.success&&t&&M(i)){let O=S(i),w=N(i);o(O,w,{autoHideDuration:u})}else i.success&&a&&g&&o(g,"success",{autoHideDuration:u});return i},[t,a,o,S,N,u]);return{createItem:f,updateItem:y,deleteItem:e,readItem:m,readItems:c,transaction:p,handleResponse:_,getErrorMessage:S,getErrorSeverity:N,shouldShowNotification:M}};export{ue as a,ye as b,Oe as c,ie as d};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var c="crudify_login_storage_version",d=2,g="crudify_login_encryption_salt",a=class{constructor(t="sessionStorage"){this.encryptionKey=null;this.salt=null;this.initPromise=null;this.initialized=!1;this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}async ensureInitialized(){if(!(this.initialized&&this.encryptionKey)){if(this.initPromise){await this.initPromise;return}this.initPromise=this.initialize(),await this.initPromise}}async initialize(){try{parseInt(this.storage.getItem(c)||"1")<d&&(this.clearLegacyData(),this.storage.setItem(c,d.toString()));let e=this.storage.getItem(g);e&&_chunkCR5KJUSTjs.l.call(void 0, `v2:x:${e}:x`)?this.salt=this.base64ToUint8Array(e):(this.salt=_chunkCR5KJUSTjs.k.call(void 0, ),this.storage.setItem(g,this.uint8ArrayToBase64(this.salt)));let i=await this.generateFingerprint();this.encryptionKey=await _chunkCR5KJUSTjs.h.call(void 0, i,this.salt),this.initialized=!0}catch(t){_chunkCR5KJUSTjs.a.error("SecureStorage initialization failed",t instanceof Error?t:{message:String(t)}),this.initialized=!1}}async generateFingerprint(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.colorDepth.toString(),screen.width.toString(),screen.height.toString(),"crudify-login"].join("|");return _chunkCR5KJUSTjs.g.call(void 0, t)}clearLegacyData(){let t=[];for(let e=0;e<this.storage.length;e++){let i=this.storage.key(e);i&&!i.startsWith(c)&&!i.startsWith(g)&&t.push(i)}t.forEach(e=>this.storage.removeItem(e))}async setItem(t,e,i){try{if(await this.ensureInitialized(),!this.encryptionKey||!this.salt){_chunkCR5KJUSTjs.a.error("SecureStorage not properly initialized");return}let r=await _chunkCR5KJUSTjs.i.call(void 0, e,this.encryptionKey,this.salt);if(this.storage.setItem(t,r),i){let o=Date.now()+i*60*1e3;this.storage.setItem(`${t}_expiry`,o.toString())}}catch(r){_chunkCR5KJUSTjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}async getItem(t){try{await this.ensureInitialized();let e=`${t}_expiry`,i=this.storage.getItem(e);if(i){let f=parseInt(i,10);if(Date.now()>f)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;if(!_chunkCR5KJUSTjs.l.call(void 0, r))return this.removeItem(t),null;let o=await this.generateFingerprint(),s=await _chunkCR5KJUSTjs.j.call(void 0, r,o);return s||(_chunkCR5KJUSTjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunkCR5KJUSTjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}clear(){this.storage.clear()}async setToken(t){try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=i.exp*1e3,o=Date.now(),s=Math.floor((r-o)/(60*1e3));if(s>0){await this.setItem("authToken",t,s);return}}}}catch (e2){_chunkCR5KJUSTjs.a.warn("Failed to parse token expiry, using default expiry")}await this.setItem("authToken",t,1440)}async getToken(){let t=await this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=Math.floor(Date.now()/1e3);if(i.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunkCR5KJUSTjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}async hasValidToken(){return await this.getToken()!==null}async migrateFromLocalStorage(t){let e=window.localStorage.getItem(t);e&&(window.localStorage.removeItem(t),t==="authToken"?await this.setToken(e):await this.setItem(t,e))}uint8ArrayToBase64(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return btoa(e)}base64ToUint8Array(t){let e=atob(t),i=new Uint8Array(e.length);for(let r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return i}},I= exports.a =new a("sessionStorage"),T= exports.b =new a("localStorage");exports.a = I; exports.b = T;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk4LMFQECSjs = require('./chunk-4LMFQECS.js');var c="crudify_login_storage_version",d=2,g="crudify_login_encryption_salt",a=class{constructor(t="sessionStorage"){this.encryptionKey=null;this.salt=null;this.initPromise=null;this.initialized=!1;this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}async ensureInitialized(){if(!(this.initialized&&this.encryptionKey)){if(this.initPromise){await this.initPromise;return}this.initPromise=this.initialize(),await this.initPromise}}async initialize(){try{parseInt(this.storage.getItem(c)||"1")<d&&(this.clearLegacyData(),this.storage.setItem(c,d.toString()));let e=this.storage.getItem(g);e&&_chunk4LMFQECSjs.l.call(void 0, `v2:x:${e}:x`)?this.salt=this.base64ToUint8Array(e):(this.salt=_chunk4LMFQECSjs.k.call(void 0, ),this.storage.setItem(g,this.uint8ArrayToBase64(this.salt)));let i=await this.generateFingerprint();this.encryptionKey=await _chunk4LMFQECSjs.h.call(void 0, i,this.salt),this.initialized=!0}catch(t){_chunk4LMFQECSjs.a.error("SecureStorage initialization failed",t instanceof Error?t:{message:String(t)}),this.initialized=!1}}async generateFingerprint(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.colorDepth.toString(),screen.width.toString(),screen.height.toString(),"crudify-login"].join("|");return _chunk4LMFQECSjs.g.call(void 0, t)}clearLegacyData(){let t=[];for(let e=0;e<this.storage.length;e++){let i=this.storage.key(e);i&&!i.startsWith(c)&&!i.startsWith(g)&&t.push(i)}t.forEach(e=>this.storage.removeItem(e))}async setItem(t,e,i){try{if(await this.ensureInitialized(),!this.encryptionKey||!this.salt){_chunk4LMFQECSjs.a.error("SecureStorage not properly initialized");return}let r=await _chunk4LMFQECSjs.i.call(void 0, e,this.encryptionKey,this.salt);if(this.storage.setItem(t,r),i){let o=Date.now()+i*60*1e3;this.storage.setItem(`${t}_expiry`,o.toString())}}catch(r){_chunk4LMFQECSjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}async getItem(t){try{await this.ensureInitialized();let e=`${t}_expiry`,i=this.storage.getItem(e);if(i){let f=parseInt(i,10);if(Date.now()>f)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;if(!_chunk4LMFQECSjs.l.call(void 0, r))return this.removeItem(t),null;let o=await this.generateFingerprint(),s=await _chunk4LMFQECSjs.j.call(void 0, r,o);return s||(_chunk4LMFQECSjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunk4LMFQECSjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}clear(){this.storage.clear()}async setToken(t){try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=i.exp*1e3,o=Date.now(),s=Math.floor((r-o)/(60*1e3));if(s>0){await this.setItem("authToken",t,s);return}}}}catch (e2){_chunk4LMFQECSjs.a.warn("Failed to parse token expiry, using default expiry")}await this.setItem("authToken",t,1440)}async getToken(){let t=await this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=Math.floor(Date.now()/1e3);if(i.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunk4LMFQECSjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}async hasValidToken(){return await this.getToken()!==null}async migrateFromLocalStorage(t){let e=window.localStorage.getItem(t);e&&(window.localStorage.removeItem(t),t==="authToken"?await this.setToken(e):await this.setItem(t,e))}uint8ArrayToBase64(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return btoa(e)}base64ToUint8Array(t){let e=atob(t),i=new Uint8Array(e.length);for(let r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return i}},I= exports.a =new a("sessionStorage"),T= exports.b =new a("localStorage");exports.a = I; exports.b = T;
@@ -1 +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 _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var Me="crudify_storage_version",He=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 _chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(t, () => ({message:"Unknown error"}))),t})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Me)||"1",10)<He){let t=a.getStorage();t&&t.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Me,He.toString()),_chunkCR5KJUSTjs.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=_chunkCR5KJUSTjs.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){_chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.g.call(void 0, t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunkCR5KJUSTjs.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]:(_chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.l.call(void 0, e)?_chunkCR5KJUSTjs.j.call(void 0, e,a.fingerprint):(_chunkCR5KJUSTjs.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),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.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?(_chunkCR5KJUSTjs.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunkCR5KJUSTjs.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 _chunkCR5KJUSTjs.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),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens cleared from storage")}catch(t){_chunkCR5KJUSTjs.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){}_chunkCR5KJUSTjs.a.info("Crudify: Encryption key rotated successfully")}catch(e){_chunkCR5KJUSTjs.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){_chunkCR5KJUSTjs.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){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens removed in another tab"),e(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunkCR5KJUSTjs.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=()=>{_chunkCR5KJUSTjs.a.warn("Crudify: CrossTabSync message error")},_chunkCR5KJUSTjs.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunkCR5KJUSTjs.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(e){_chunkCR5KJUSTjs.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),_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab broadcast ${e.type}`))}catch(t){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to broadcast cross-tab message",{message:t instanceof Error?t.message:String(t)})}}handleMessage(e){e.tabId!==this.tabId&&(_chunkCR5KJUSTjs.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){_chunkCR5KJUSTjs.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var Ee=K,$= exports.c =Ee.getInstance();var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var se="crudify_auth",Se=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"},Ot=(r,e,t)=>{if(typeof document>"u"){_chunkCR5KJUSTjs.a.debug("[CookieSync] No document available (SSR), skipping cookie set");return}if(!r){_chunkCR5KJUSTjs.a.warn("[CookieSync] Attempted to set cookie with empty token");return}try{let i=Se(t),n=Date.now(),s=Math.max(0,Math.floor((e-n)/1e3)),l=[`${se}=${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("; "),_chunkCR5KJUSTjs.a.debug("[CookieSync] Cookie set successfully",{domain:i||"(current host)",maxAgeSeconds:s,tokenLength:r.length})}catch(i){_chunkCR5KJUSTjs.a.error("[CookieSync] Failed to set cookie",i instanceof Error?i:{message:String(i)})}},Ft=r=>{if(typeof document>"u"){_chunkCR5KJUSTjs.a.debug("[CookieSync] No document available (SSR), skipping cookie clear");return}try{let e=Se(r),t=[`${se}=`,"path=/","max-age=0","expires=Thu, 01 Jan 1970 00:00:00 GMT"];e&&t.push(`domain=${e}`),document.cookie=t.join("; "),document.cookie=`${se}=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT`,_chunkCR5KJUSTjs.a.debug("[CookieSync] Cookie cleared successfully",{domain:e||"(current host)"})}catch(e){_chunkCR5KJUSTjs.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(`${se}=`));if(!e)return null;let t=e.split("=")[1];return t?decodeURIComponent(t):null}catch(r){return _chunkCR5KJUSTjs.a.error("[CookieSync] Failed to read cookie",r instanceof Error?r:{message:String(r)}),null}},j={setCrossSubdomainCookie:Ot,clearCrossSubdomainCookie:Ft,getCrossSubdomainCookie:zt,getCookieDomain:Se};var oe=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(),_crudifysdk2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkCR5KJUSTjs.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 _crudifysdk2.default.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,j.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 _chunkCR5KJUSTjs.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..."),_chunkCR5KJUSTjs.f.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),j.clearCrossSubdomainCookie(this.config.env),await _crudifysdk2.default.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(_crudifysdk2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifysdk2.default.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 _crudifysdk2.default.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 _crudifysdk2.default.logout(),this.isColdStartRestore=!1,!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=_crudifysdk2.default.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 _crudifysdk2.default.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"),j.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 _crudifysdk2.default.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"),j.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(){_crudifysdk2.default.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"),_chunkCR5KJUSTjs.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"),_chunkCR5KJUSTjs.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"),_chunkCR5KJUSTjs.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=_crudifysdk2.default.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";_crudifysdk2.default.config(t);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk2.default.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 _chunkCR5KJUSTjs.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(){j.clearCrossSubdomainCookie(this.config.env),await v.clearTokens(),await _crudifysdk2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkCR5KJUSTjs.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&&_chunkCR5KJUSTjs.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 Ge={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function _e(){let[r,e]=_react.useState.call(void 0, Ge),t=_react.useCallback.call(void 0, o=>{e(f=>({...f,isLoading:o}))},[]),i=_react.useCallback.call(void 0, (o,f)=>{e(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=_react.useCallback.call(void 0, o=>{e(f=>({...f,isLoggingOut:o}))},[]),s=_react.useCallback.call(void 0, o=>{e(f=>({...f,error:o}))},[]),l=_react.useCallback.call(void 0, o=>{e(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:e,setLoading:t,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}var ae={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},Te={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},Ve=.5;function $e(r){return r?r.expiresAt-Date.now()<3e5:!1}function Ye(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function We(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function Y(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function Be(r){let{sessionManager:e,stateManager:t}=r,i=_react.useCallback.call(void 0, async(o,f)=>{t.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await e.login(o,f);return E.success&&E.tokens?t.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):t.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";_chunkCR5KJUSTjs.a.error("[useSession] Login error",E instanceof Error?E:{message:b});let S=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return t.setState(m=>({...m,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(f=>({...f,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 f=await e.getTokenInfo();t.setState(E=>({...E,tokens:Y(f),error:null}))}else t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return t.setState(f=>({...f,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 _t(r){return r<Te.AGGRESSIVE?ae.AGGRESSIVE:r<Te.MODERATE?ae.MODERATE:ae.RELAXED}function Xe(r){let{isAuthenticated:e,tokens:t,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,f=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!e||!t)return;let b=_chunkCR5KJUSTjs.q.getInstance().subscribe(f);window.addEventListener("popstate",f);let S,m=!0,I=async()=>{if(!m)return;let k=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,R=_t(k);S=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*Ve;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n(Y(Z)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():m&&I()},R)};return I(),()=>{m=!1,clearTimeout(S),window.removeEventListener("popstate",f),b()}},[e,t,i,f,n,s,l,o])}function Ze(r){let{sessionManager:e,onTokensUpdated:t,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;_react.useEffect.call(void 0, ()=>{let l=_chunkCR5KJUSTjs.f.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(e.isRefreshing())return;n(!0);try{if(await e.refreshTokens()){let E=await e.getTokenInfo();t(Y(E)),n(!1)}else _chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:f instanceof Error?f.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 je(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&&(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),t(o))}catch(o){_chunkCR5KJUSTjs.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()||(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),t(null),e&&i())}catch(o){_chunkCR5KJUSTjs.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(f=>({...f,isAuthenticated:!1,tokens:null,error:o?"Session expired":null})),_optionalChain([t, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([t, 'access', _83 => _83.onSessionRestored, 'optionalCall', _84 => _84(o)])},onLoginSuccess:o=>{i.setState(f=>({...f,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:Y(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";_chunkCR5KJUSTjs.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function ve(r={}){let e=oe.getInstance(),t=_e(),{state:i}=t,{login:n,logout:s,refreshTokens:l,clearError:o}=Be({sessionManager:e,stateManager:t}),f=_react.useCallback.call(void 0, g=>{t.setAuthenticated(!!g,g)},[t]),E=_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, g=>{t.setLoading(g)},[t]),S=_react.useCallback.call(void 0, g=>{t.setError(g)},[t]);_react.useEffect.call(void 0, ()=>{Je({sessionManager:e,options:r,stateActions:t})},[]),Xe({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:e,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:s}),Ze({sessionManager:e,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:S}),je({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=_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:m,isExpiringSoon:$e(i.tokens),expiresIn:Ye(i.tokens),refreshExpiresIn:We(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 et=_react.createContext.call(void 0, null),ei=r=>_dompurify2.default.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),be= 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, []),f=_react.useCallback.call(void 0, (m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return _chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(_chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let k=_uuid.v4.call(void 0, ),R={id:k,message:m,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _87 => _87.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _88 => _88.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _89 => _89.allowHtml]), () => (s))};return o(x=>[...x.length>=e?x.slice(-(e-1)):x,R]),k},[e,t,n,s]),E=_react.useCallback.call(void 0, m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=_react.useCallback.call(void 0, ()=>{o([])},[]),S={showNotification:f,hideNotification:E,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, et.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(m=>_jsxruntime.jsx.call(void 0, ti,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},ti=({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:ei(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},tt= exports.g =()=>{let r=_react.useContext.call(void 0, et);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ie=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){_chunkCR5KJUSTjs.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}},ue= exports.h =Ie.getInstance();var it=_react.createContext.call(void 0, void 0),rt= 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),[f,E]=_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===f&&l){i(!1);return}(async()=>{i(!0),s(null),o(!1);try{_crudifysdk2.default.config(r.env||"prod");let k=await _crudifysdk2.default.init(r.publicApiKey,"none");if(S(k),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.login=="function")o(!0),E(I),k.apiEndpointAdmin&&k.apiKeyEndpointAdmin&&ue.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";_chunkCR5KJUSTjs.a.error("[CrudifyProvider] Initialization error",k instanceof Error?k:{message:String(k)}),s(R),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?_crudifysdk2.default:null,isLoading:t,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, it.Provider,{value:m,children:e})},nt= exports.j =()=>{let r=_react.useContext.call(void 0, it);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var ot=_react.createContext.call(void 0, void 0);function st({children:r,options:e={},config:t,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:g}=tt();s=g}catch (e10){}let l={};try{let g=nt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch (e11){}let o=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.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:g.publicApiKey,env:g.env||"prod"}},[t,_optionalChain([e, 'optionalAccess', _93 => _93.enableLogging])]),f=_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]),E=ve(f),b=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.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:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[t,_optionalChain([e, 'optionalAccess', _102 => _102.enableLogging])]),S=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([E, 'access', _103 => _103.tokens, 'optionalAccess', _104 => _104.accessToken])||!E.isAuthenticated)return null;try{let g=_chunkCR5KJUSTjs.r.call(void 0, E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let k={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(R=>{["sub","email","subscriber"].includes(R)||(k[R]=g[R])}),k}}catch(g){_chunkCR5KJUSTjs.a.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[_optionalChain([E, 'access', _105 => _105.tokens, 'optionalAccess', _106 => _106.accessToken]),E.isAuthenticated]),m={...E,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, ot.Provider,{value:m,children:r})}function Jr(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, rt,{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, be,{...e,children:_jsxruntime.jsx.call(void 0, st,{...r})})}):_jsxruntime.jsx.call(void 0, be,{...e,children:_jsxruntime.jsx.call(void 0, st,{...r})})}function ui(){let r=_react.useContext.call(void 0, ot);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qr(){let r=ui();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 on=(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),[f,E]=_react.useState.call(void 0, null),[b,S]=_react.useState.call(void 0, {}),m=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),k=_react.useRef.call(void 0, 0),R=_react.useCallback.call(void 0, ()=>{s(null),E(null),o(!1),S({})},[]),x=_react.useCallback.call(void 0, async()=>{let O=_chunkCR5KJUSTjs.s.call(void 0, );if(!O){I.current&&(E("No user email available"),o(!1));return}m.current&&m.current.abort();let C=new AbortController;m.current=C;let F=++g.current;try{I.current&&(o(!0),E(null));let z=await _crudifysdk2.default.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!C.signal.aborted){let L=z.data;if(z.success&&L&&L.length>0){let T=L[0];s(T);let Z={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(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,ne)=>({...V,[ne]:T[ne]}),{})}};S(Z),E(null),k.current=0}else E("User profile not found"),s(null),S({})}}catch(z){if(F===g.current&&I.current){let L=z;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&&x()},1e3*k.current)):(E("Failed to load user profile"),s(null),S({}))}}finally{F===g.current&&I.current&&o(!1),m.current===C&&(m.current=null)}},[t,i]);return _react.useEffect.call(void 0, ()=>{e&&x()},[e,x]),_react.useEffect.call(void 0, ()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:R}};var un=(r,e={})=>{let{autoFetch:t=!0,onSuccess:i,onError:n}=e,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, !1),[m,I]=_react.useState.call(void 0, null),g=_react.useRef.call(void 0, !1),k=_react.useCallback.call(void 0, C=>{let F=String(C).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),R=_react.useCallback.call(void 0, async()=>{S(!0),I(null);try{let C=await _crudifysdk2.default.getNextSequence(s),F=C.data;if(C.success&&_optionalChain([F, 'optionalAccess', _123 => _123.value])){let z=k(F.value);E(z),_optionalChain([i, 'optionalCall', _124 => _124(z)])}else{let z=_optionalChain([C, 'access', _125 => _125.errors, 'optionalAccess', _126 => _126._error, 'optionalAccess', _127 => _127[0]])||"Failed to generate code";I(z),_optionalChain([n, 'optionalCall', _128 => _128(z)])}}catch(C){let F=C instanceof Error?C.message:"Unknown error";I(F),_optionalChain([n, 'optionalCall', _129 => _129(F)])}finally{S(!1)}},[s,k,i,n]),x=_react.useCallback.call(void 0, async()=>{await R()},[R]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{t&&!f&&!g.current&&(g.current=!0,R())},[t,f,R]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};var Ce=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&&_chunkCR5KJUSTjs.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&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkCR5KJUSTjs.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&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkCR5KJUSTjs.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&&_chunkCR5KJUSTjs.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,_chunkCR5KJUSTjs.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&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(e,t,i){let n=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunkCR5KJUSTjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(t);let s=i?"debug":"none",l=await _crudifysdk2.default.init(e,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&ue.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}}},re= exports.q =Ce.getInstance();var ut=r=>{let e=new Uint8Array(r);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").substring(0,r)},ct=()=>`file_${Date.now()}_${ut(7)}`,yi=r=>{let e=r.lastIndexOf("."),t=e>0?r.substring(e):"",i=Date.now(),n=ut(6);return`${i}_${n}${t}`},we=(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},Tn= exports.r =(r={})=>{let{acceptedTypes:e,maxFileSize:t=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[S,m]=_react.useState.call(void 0, []),[I,g]=_react.useState.call(void 0, !1),[k,R]=_react.useState.call(void 0, !1),[x,O]=_react.useState.call(void 0, []),C=_react.useRef.call(void 0, new Map),F=_react.useCallback.call(void 0, ()=>{g(!0)},[]),z=_react.useCallback.call(void 0, ()=>{R(!0),g(!0)},[]),L=_react.useCallback.call(void 0, (u,p)=>{m(d=>d.map(y=>y.id===u?{...y,...p}:y))},[]),T=_react.useCallback.call(void 0, u=>{_optionalChain([E, 'optionalCall', _134 => _134(u)])},[E]),Z=_react.useCallback.call(void 0, u=>e&&e.length>0&&!e.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>t?{valid:!1,error:`File exceeds maximum size of ${(t/1048576).toFixed(1)}MB`}:{valid:!0},[e,t]),V=_react.useCallback.call(void 0, async(u,p)=>{try{if(!re.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=yi(p.name),h=await _crudifysdk2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:s});if(!h.success||!h.data)throw new Error("Failed to get upload URL");let y=h.data,{uploadUrl:w,s3Key:A,publicUrl:M}=y;if(!w||!A)throw new Error("Incomplete signed URL response");let W=A.indexOf("/"),Nt=W>0?A.substring(W+1):A;L(u.id,{status:"uploading",progress:0}),await new Promise((he,B)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Lt=Math.round(_.loaded/_.total*100);L(u.id,{progress:Lt})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?he():B(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{B(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),U.open("PUT",w),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Dt={status:"completed",progress:100,filePath:Nt,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};m(he=>{let B=he.map(_=>_.id===u.id?{..._,...Dt}:_);T(B);let U=B.find(_=>_.id===u.id);return U&&_optionalChain([l, 'optionalCall', _135 => _135(U)]),B})}catch(d){let h=d instanceof Error?d.message:"Unknown error";L(u.id,{status:"error",progress:0,errorMessage:h}),m(y=>{let w=y.find(A=>A.id===u.id);return w&&_optionalChain([o, 'optionalCall', _136 => _136(w,h)]),y})}},[L,l,o,s]),ne=_react.useCallback.call(void 0, async u=>{let p=Array.from(u),d=[];m(h=>{if(i!==void 0){let A=h.filter(W=>W.status!=="pendingDeletion"&&W.status!=="error").length,M=i-A;if(M<=0)return _chunkCR5KJUSTjs.a.warn(`File limit of ${i} already reached`),h;p.length>M&&(p=p.slice(0,M),_chunkCR5KJUSTjs.a.warn(`Only ${M} files will be added to not exceed limit`))}let y=[];for(let A of p){let M=Z(A),W={id:ct(),name:A.name,size:A.size,contentType:A.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?A:void 0,errorMessage:M.error,isExisting:!1};y.push(W)}d=y;let w=[...h,...y];return T(w),w}),setTimeout(()=>{let h=d.filter(y=>y.status==="pending"&&y.file);for(let y of h)if(y.file){let w=V(y,y.file);C.current.set(y.id,w),w.finally(()=>{C.current.delete(y.id)})}},0)},[i,Z,V,T]),dt=_react.useCallback.call(void 0, async u=>{let p=S.find(h=>h.id===u);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(h=>[...h,u]),m(h=>{let y=h.map(A=>A.id===u?{...A,status:"pendingDeletion"}:A),w=y.filter(A=>A.status!=="pendingDeletion");return T(w),y}),{needsConfirmation:!1,isExisting:d})},[S,b,T]),ft=_react.useCallback.call(void 0, async u=>{let p=S.find(d=>d.id===u);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let h=d.filter(y=>y.id!==u);return T(h),h}),{success:!0};try{if(!re.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=we(p.filePath);return(await _crudifysdk2.default.disableFile({filePath:d})).success?(m(y=>{let w=y.filter(A=>A.id!==u);return T(w),w}),_optionalChain([f, 'optionalCall', _137 => _137(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[S,T,f]),gt=_react.useCallback.call(void 0, u=>{let p=S.find(d=>d.id===u);return!p||!p.isExisting?!1:(O(d=>d.filter(h=>h!==u)),m(d=>{let h=d.map(y=>y.id===u?{...y,status:"completed"}:y);return T(h),h}),!0)},[S,T]),pt=_react.useCallback.call(void 0, ()=>{x.length!==0&&(m(u=>{let p=u.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return T(p),p}),O([]))},[x,T]),mt=_react.useCallback.call(void 0, async()=>{if(x.length===0)return{success:!0,errors:[]};let u=[],p=[];if(!re.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let h=S.find(y=>y.id===d);if(!_optionalChain([h, 'optionalAccess', _138 => _138.filePath])){p.push(d);continue}try{let y=we(h.filePath);(await _crudifysdk2.default.disableFile({filePath:y})).success?(p.push(d),_optionalChain([f, 'optionalCall', _139 => _139(h)])):u.push(`Failed to delete ${h.name}`)}catch(y){u.push(`Error deleting ${h.name}: ${y instanceof Error?y.message:"Unknown error"}`)}}return p.length>0&&(m(d=>d.filter(y=>!p.includes(y.id))),O(d=>d.filter(h=>!p.includes(h)))),{success:u.length===0,errors:u}},[S,x,f]),ht=_react.useCallback.call(void 0, ()=>{m([]),T([])},[T]),yt=_react.useCallback.call(void 0, async u=>{let p=S.find(h=>h.id===u);if(!p||p.status!=="error"||!p.file){_chunkCR5KJUSTjs.a.warn("Cannot retry: file not found or no original file");return}L(u,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);C.current.set(u,d),d.finally(()=>{C.current.delete(u)})},[S,L,V]),Et=_react.useCallback.call(void 0, async()=>{let u=Array.from(C.current.values());return u.length>0&&await Promise.allSettled(u),new Promise(p=>{setTimeout(()=>{m(d=>{let h=d.filter(y=>y.status==="completed"&&y.filePath).map(y=>y.filePath);return p(h),d})},0)})},[]),St=u=>{let p=_optionalChain([u, 'access', _140 => _140.split, 'call', _141 => _141("."), 'access', _142 => _142.pop, 'call', _143 => _143(), 'optionalAccess', _144 => _144.toLowerCase, 'call', _145 => _145()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[p]||"application/octet-stream"},Tt=_react.useCallback.call(void 0, (u,p)=>{let d=u.map(h=>{let y=we(h.filePath,p),w=y.includes("/public/")||y.startsWith("public/")?"public":"private",A=h.contentType||St(h.name);return{id:ct(),name:h.name,size:h.size||0,contentType:A,status:"completed",progress:100,filePath:y,visibility:w,createdAt:Date.now(),isExisting:!0}});m(d),T(d)},[T]),vt=_react.useCallback.call(void 0, async u=>{let p=S.find(d=>d.id===u);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!re.isInitialized())return null;let d=await _crudifysdk2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),h=d.data;return d.success&&_optionalChain([h, 'optionalAccess', _146 => _146.url])?h.url:null}catch (e13){return null}},[S]),bt=_react.useMemo.call(void 0, ()=>S.some(u=>u.status==="uploading"||u.status==="pending"),[S]),It=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="uploading"||u.status==="pending").length,[S]),kt=_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]),At=_react.useMemo.call(void 0, ()=>q.filter(u=>u.status==="completed"||u.status==="pending"||u.status==="uploading").length,[q]),{isValid:xt,validationError:Ct,validationErrorKey:wt,validationErrorParams:Rt}=_react.useMemo.call(void 0, ()=>{let u=q.filter(d=>d.status==="completed").length;if(u<n){let d=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:d,validationErrorKey:d,validationErrorParams:{count:n}}}return i!==void 0&&u>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),Pt=x.length>0;return{files:S,activeFiles:q,activeFileCount:At,isUploading:bt,pendingCount:It,addFiles:ne,removeFile:dt,deleteFileImmediately:ft,restoreFile:gt,clearFiles:ht,retryUpload:yt,isValid:xt,validationError:Ct,validationErrorKey:wt,validationErrorParams:Rt,waitForUploads:Et,completedFilePaths:kt,initializeFiles:Tt,isTouched:I,markAsTouched:F,isSubmitted:k,markAsSubmitted:z,getPreviewUrl:vt,pendingDeletions:x,hasPendingDeletions:Pt,commitDeletions:mt,restorePendingDeletions:pt}};exports.a = v; exports.b = Ee; exports.c = $; exports.d = oe; exports.e = ve; exports.f = be; exports.g = tt; exports.h = ue; exports.i = rt; exports.j = nt; exports.k = Jr; exports.l = ui; exports.m = Qr; exports.n = on; exports.o = un; exports.p = Ce; exports.q = re; exports.r = Tn;
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 _crudifysdk2 = _interopRequireDefault(_crudifysdk);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(),_crudifysdk2.default.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 _crudifysdk2.default.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 _crudifysdk2.default.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(_crudifysdk2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifysdk2.default.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 _crudifysdk2.default.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 _crudifysdk2.default.logout(),this.isColdStartRestore=!1,!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=_crudifysdk2.default.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 _crudifysdk2.default.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 _crudifysdk2.default.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(){_crudifysdk2.default.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=_crudifysdk2.default.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";_crudifysdk2.default.config(t);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk2.default.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 _crudifysdk2.default.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{_crudifysdk2.default.config(r.env||"prod");let k=await _crudifysdk2.default.init(r.publicApiKey,"none");if(S(k),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.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?_crudifysdk2.default: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 _crudifysdk2.default.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 _crudifysdk2.default.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=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunk4LMFQECSjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(t);let s=i?"debug":"none",l=await _crudifysdk2.default.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 _crudifysdk2.default.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 _crudifysdk2.default.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 _crudifysdk2.default.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
+ "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 _chunkH6XXWDUTjs = require('./chunk-H6XXWDUT.js');var _chunk4LMFQECSjs = require('./chunk-4LMFQECS.js');var _react = require('react');var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var ue=(r={})=>{let{autoFetch:o=!0,retryOnError:a=!1,maxRetries:t=3}=r,{isAuthenticated:s,isInitialized:n,sessionData:u,tokens:l}=_chunkH6XXWDUTjs.l.call(void 0, ),[E,d]=_react.useState.call(void 0, null),[A,I]=_react.useState.call(void 0, o&&s),[S,N]=_react.useState.call(void 0, null),C=_react.useRef.call(void 0, null),f=_react.useRef.call(void 0, !0),y=_react.useRef.call(void 0, 0),e=_react.useRef.call(void 0, 0),m=_react.useCallback.call(void 0, ()=>{if(!u)return null;let i=u["cognito:username"];return u.email||(typeof i=="string"?i:null)},[u]),c=_react.useCallback.call(void 0, ()=>{d(null),N(null),I(!1),e.current=0},[]),p=_react.useCallback.call(void 0, async()=>{let i=m();if(!i){f.current&&(N("No user email available from session data"),I(!1));return}if(!n){f.current&&(N("Session not initialized"),I(!1));return}C.current&&C.current.abort();let g=new AbortController;C.current=g;let O=++y.current;try{f.current&&(I(!0),N(null));let w=await _crudifysdk2.default.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)&&_optionalChain([R, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.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 (e2){}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)&&_optionalChain([R, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.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 (e3){}}h?(d(h),N(null),e.current=0):(N("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&&(_optionalChain([h, 'access', _7 => _7.message, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("Network Error")])||_optionalChain([h, 'access', _10 => _10.message, 'optionalAccess', _11 => _11.includes, 'call', _12 => _12("Failed to fetch")]))?(e.current++,setTimeout(()=>{f.current&&p()},1e3*e.current)):(N("Failed to load user profile from database"),d(null))}}finally{O===y.current&&f.current&&I(!1),C.current===g&&(C.current=null)}},[n,m,a,t]);return _react.useEffect.call(void 0, ()=>{o&&s&&n?p():s||c()},[o,s,n,p,c]),_react.useEffect.call(void 0, ()=>(f.current=!0,()=>{f.current=!1,C.current&&(C.current.abort(),C.current=null)}),[]),{user:{session:u,data:E},loading:A,error:S,refreshProfile:p,clearProfile:c}};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:N}=_chunkH6XXWDUTjs.l.call(void 0, ),C=_react.useCallback.call(void 0, y=>{y?_chunk4LMFQECSjs.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):l()},[l]),f=_optionalChain([t, 'optionalAccess', _13 => _13.expiresAt])?new Date(t.expiresAt):null;return{isAuthenticated:r,loading:o,error:s,token:_optionalChain([t, 'optionalAccess', _14 => _14.accessToken])||null,user:n,tokenExpiration:f,setToken:C,logout:l,refreshToken:E,login:u,isExpiringSoon:I,expiresIn:S,refreshExpiresIn:N,getTokenInfo:A,clearError:d}};var Oe=()=>{let{isInitialized:r,isLoading:o,error:a,isAuthenticated:t,login:s}=_chunkH6XXWDUTjs.l.call(void 0, ),n=_react.useCallback.call(void 0, ()=>r&&!o&&!a,[r,o,a]),u=_react.useCallback.call(void 0, async()=>new Promise((f,y)=>{let e=()=>{n()?f():a?y(new Error(a)):setTimeout(e,100)};e()}),[n,a]),l=_react.useCallback.call(void 0, async()=>{if(!n())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[n]),E=_react.useCallback.call(void 0, async(f,y,e)=>(await l(),await _crudifysdk2.default.readItems(f,y||{},e)),[l]),d=_react.useCallback.call(void 0, async(f,y,e)=>(await l(),await _crudifysdk2.default.readItem(f,y,e)),[l]),A=_react.useCallback.call(void 0, async(f,y,e)=>(await l(),await _crudifysdk2.default.createItem(f,y,e)),[l]),I=_react.useCallback.call(void 0, async(f,y,e)=>(await l(),await _crudifysdk2.default.updateItem(f,y,e)),[l]),S=_react.useCallback.call(void 0, async(f,y,e)=>(await l(),await _crudifysdk2.default.deleteItem(f,y,e)),[l]),N=_react.useCallback.call(void 0, async(f,y)=>(await l(),await _crudifysdk2.default.transaction(f,y)),[l]),C=_react.useCallback.call(void 0, 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:N,login:C,isInitialized:r,isInitializing:o,initializationError:a,isReady:n,waitForReady:u}};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")||_optionalChain([r, 'access', _15 => _15.errors, 'access', _16 => _16._transaction, 'optionalAccess', _17 => _17.includes, 'call', _18 => _18("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([r, 'access', _19 => _19.errors, 'access', _20 => _20._error, 'optionalAccess', _21 => _21.includes, 'call', _22 => _22("TOO_MANY_REQUESTS")])))return!1;let o=r.data;return!(!r.success&&_optionalChain([o, 'optionalAccess', _23 => _23.response, 'optionalAccess', _24 => _24.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(_optionalChain([r, 'optionalAccess', _25 => _25.includes, 'call', _26 => _26("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(_optionalChain([n, 'optionalAccess', _27 => _27.response, 'optionalAccess', _28 => _28.errorCode])){let u=n.response.errorCode;if(x[u])return o(x[u]);let l=J(u,o,a);if(l)return l}if(_optionalChain([n, 'optionalAccess', _29 => _29.response, 'optionalAccess', _30 => _30.data]))return n.response.data}if(_optionalChain([s, 'optionalAccess', _31 => _31.response, 'optionalAccess', _32 => _32.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 (e4){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=_optionalChain([a, 'optionalAccess', _33 => _33.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")}function ee(r){let{showErrorNotifications:o,showSuccessNotifications:a,autoHideDuration:t,appStructure:s,showNotification:n,getErrorMessage:u,getErrorSeverity:l,getSuccessMessage:E}=r,d=_react.useCallback.call(void 0, 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=_react.useCallback.call(void 0, (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=_react.useCallback.call(void 0, async(e,m,c)=>{let p=await _crudifysdk2.default.createItem(e,m,c);if(!(_optionalChain([c, 'optionalAccess', _34 => _34.skipNotifications])===!0)&&(d(p),p.success)){let i=_optionalChain([c, 'optionalAccess', _35 => _35.actionConfig]),g=_optionalChain([i, 'optionalAccess', _36 => _36.key])||"create",O=_optionalChain([i, 'optionalAccess', _37 => _37.moduleKey])||e;A(p,g,O,i)}return p},[d,A]),S=_react.useCallback.call(void 0, async(e,m,c)=>{let p=await _crudifysdk2.default.updateItem(e,m,c);if(!(_optionalChain([c, 'optionalAccess', _38 => _38.skipNotifications])===!0)&&(d(p),p.success)){let i=_optionalChain([c, 'optionalAccess', _39 => _39.actionConfig]),g=_optionalChain([i, 'optionalAccess', _40 => _40.key])||"update",O=_optionalChain([i, 'optionalAccess', _41 => _41.moduleKey])||e;A(p,g,O,i)}return p},[d,A]),N=_react.useCallback.call(void 0, async(e,m,c)=>{let p=await _crudifysdk2.default.deleteItem(e,m,c);if(!(_optionalChain([c, 'optionalAccess', _42 => _42.skipNotifications])===!0)&&(d(p),p.success)){let i=_optionalChain([c, 'optionalAccess', _43 => _43.actionConfig]),g=_optionalChain([i, 'optionalAccess', _44 => _44.key])||"delete",O=_optionalChain([i, 'optionalAccess', _45 => _45.moduleKey])||e;A(p,g,O,i)}return p},[d,A]),C=_react.useCallback.call(void 0, async(e,m,c)=>{let p=await _crudifysdk2.default.readItem(e,m,c);return _optionalChain([c, 'optionalAccess', _46 => _46.skipNotifications])===!0||d(p),p},[d]),f=_react.useCallback.call(void 0, async(e,m,c)=>{let p=await _crudifysdk2.default.readItems(e,m,c);return _optionalChain([c, 'optionalAccess', _47 => _47.skipNotifications])===!0||d(p),p},[d]),y=_react.useCallback.call(void 0, async(e,m)=>{let c=await _crudifysdk2.default.transaction(e,m);if(!(_optionalChain([m, 'optionalAccess', _48 => _48.skipNotifications])===!0)&&(d(c),c.success)){let _="transaction",i,g=null;if(_optionalChain([m, 'optionalAccess', _49 => _49.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,_nullishCoalesce(g, () => (void 0)))}return c},[d,A,s]);return{createItem:I,updateItem:S,deleteItem:N,readItem:C,readItems:f,transaction:y}}var ie=(r={})=>{let{showNotification:o}=_chunkH6XXWDUTjs.g.call(void 0, ),{showSuccessNotifications:a=!1,showErrorNotifications:t=!0,customErrorMessages:s={},defaultErrorMessage:n=G,autoHideDuration:u=Q,appStructure:l=[],translateFn:E=i=>i}=r,d=_react.useCallback.call(void 0, (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=_react.useCallback.call(void 0, i=>X(i,A),[s,n,E,d]),N=_react.useCallback.call(void 0, i=>i.errorCode&&_chunk4LMFQECSjs.v[i.errorCode]?_chunk4LMFQECSjs.v[i.errorCode]:"error",[]),C=_react.useCallback.call(void 0, (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:N,getSuccessMessage:C}),_=_react.useCallback.call(void 0, (i,g)=>{if(!i.success&&t&&M(i)){let O=S(i),w=N(i);o(O,w,{autoHideDuration:u})}else i.success&&a&&g&&o(g,"success",{autoHideDuration:u});return i},[t,a,o,S,N,u]);return{createItem:f,updateItem:y,deleteItem:e,readItem:m,readItems:c,transaction:p,handleResponse:_,getErrorMessage:S,getErrorSeverity:N,shouldShowNotification:M}};exports.a = ue; exports.b = ye; exports.c = Oe; exports.d = ie;