@skylabs-digital/react-identity-access 1.3.0 → 1.5.0

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 (40) hide show
  1. package/dist/components/FeatureFlag.d.ts +1 -0
  2. package/dist/components/LandingRoute.d.ts +9 -0
  3. package/dist/components/LandingRoute.d.ts.map +1 -0
  4. package/dist/components/LoginForm.d.ts +1 -0
  5. package/dist/components/PasswordRecoveryForm.d.ts +1 -0
  6. package/dist/components/Protected.d.ts +1 -0
  7. package/dist/components/ProtectedRoute.d.ts +1 -0
  8. package/dist/components/SignupForm.d.ts +1 -0
  9. package/dist/components/SubscriptionGuard.d.ts +1 -0
  10. package/dist/components/TenantRoute.d.ts +9 -0
  11. package/dist/components/TenantRoute.d.ts.map +1 -0
  12. package/dist/index.d.ts +5 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.es.js +721 -630
  15. package/dist/index.es.js.map +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/index.js.map +1 -1
  18. package/dist/providers/AppProvider.d.ts +1 -0
  19. package/dist/providers/AppProvider.d.ts.map +1 -1
  20. package/dist/providers/AuthProvider.d.ts +3 -2
  21. package/dist/providers/AuthProvider.d.ts.map +1 -1
  22. package/dist/providers/FeatureFlagProvider.d.ts +1 -0
  23. package/dist/providers/SubscriptionProvider.d.ts +1 -0
  24. package/dist/providers/TenantProvider.d.ts +1 -0
  25. package/dist/providers/TenantProvider.d.ts.map +1 -1
  26. package/dist/services/AppApiService.d.ts +1 -0
  27. package/dist/services/AuthApiService.d.ts +2 -0
  28. package/dist/services/AuthApiService.d.ts.map +1 -1
  29. package/dist/services/FeatureFlagApiService.d.ts +1 -0
  30. package/dist/services/HealthApiService.d.ts +1 -0
  31. package/dist/services/PermissionApiService.d.ts +1 -0
  32. package/dist/services/RoleApiService.d.ts +1 -0
  33. package/dist/services/SubscriptionApiService.d.ts +1 -0
  34. package/dist/services/SubscriptionPlanApiService.d.ts +1 -0
  35. package/dist/services/TenantApiService.d.ts +1 -0
  36. package/dist/services/UserApiService.d.ts +1 -0
  37. package/dist/types/api.d.ts +3 -0
  38. package/dist/types/api.d.ts.map +1 -1
  39. package/package.json +24 -23
  40. package/CHANGELOG.md +0 -32
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),a=require("react"),ee=require("react-router");class z{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,r,n){return this.executeRequest(e,t,r,n,!1)}async executeRequest(e,t,r,n,l=!1){const S=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,P=(n==null?void 0:n.timeout)||this.timeout;let k={"Content-Type":"application/json",...n==null?void 0:n.headers};if(!(n!=null&&n.skipAuth)&&this.sessionManager)try{const h=await this.sessionManager.getAuthHeaders();k={...k,...h}}catch(h){console.warn("Failed to inject auth headers:",h)}const A=new AbortController,g=setTimeout(()=>A.abort(),P);try{const h=await fetch(S,{method:e,headers:k,body:r?JSON.stringify(r):void 0,signal:A.signal});if(clearTimeout(g),h.status===401&&!(n!=null&&n.skipRetry)&&!l&&this.sessionManager)try{const p=this.sessionManager.getTokens();if(p!=null&&p.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,r,n,!0)}catch{throw new Error(`HTTP ${h.status}: ${h.statusText}`)}if(!h.ok)throw new Error(`HTTP ${h.status}: ${h.statusText}`);const b=h.headers.get("content-type");return!b||!b.includes("application/json")?{}:await h.json()}catch(h){throw clearTimeout(g),h instanceof Error&&h.name==="AbortError"?new Error(`Request timeout after ${P}ms`):h}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class oe{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/apps/${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{apps:l.data,meta:l.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:r})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:r})).data}async updateSettingsSchema(e,t,r){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:r},{headers:n})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const ae=a.createContext(null),xe=()=>s.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:s.jsx("div",{children:"Loading application..."})}),Se=({error:i,retry:e})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[s.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Application Error"}),s.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load application"}),s.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function be({config:i,children:e}){const[t,r]=a.useState(null),[n,l]=a.useState(!0),[S,P]=a.useState(null),k=a.useMemo(()=>{const g=()=>{A()};return{appId:i.appId,baseUrl:i.baseUrl,appInfo:t,isAppLoading:n,appError:S,retryApp:g}},[i,t,n,S]),A=a.useCallback(async()=>{try{l(!0),P(null);const g=new z(i.baseUrl),b=await new oe(g,{}).getPublicAppInfo(i.appId);r(b)}catch(g){const h=g instanceof Error?g:new Error("Failed to load app information");P(h),r(null)}finally{l(!1)}},[i.baseUrl,i.appId]);if(a.useEffect(()=>{A()},[A]),n)return s.jsx(s.Fragment,{children:i.loadingFallback||s.jsx(xe,{})});if(S){const g=typeof i.errorFallback=="function"?i.errorFallback(S,()=>A()):i.errorFallback||s.jsx(Se,{error:S,retry:()=>A()});return s.jsx(s.Fragment,{children:g})}return s.jsx(ae.Provider,{value:k,children:e})}function Y(){const i=a.useContext(ae);if(!i)throw new Error("useApp must be used within an AppProvider");return i}const ve=Y;class le{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.baseUrl=e.baseUrl||"",this.tokenStorage=e.tokenStorage||{get:()=>{try{const t=localStorage.getItem(this.storageKey);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(this.storageKey,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(this.storageKey)}catch{}}}}setTokens(e){const t={...e,expiresAt:e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)};this.tokenStorage.set(t)}getTokens(){return this.tokenStorage.get()}clearTokens(){this.tokenStorage.clear()}isTokenExpired(e){const t=e||this.getTokens();return t!=null&&t.expiresAt?Date.now()>=t.expiresAt:!1}shouldRefreshToken(e){const t=e||this.getTokens();return!(t!=null&&t.expiresAt)||!this.autoRefresh?!1:Date.now()>=t.expiresAt-this.refreshThreshold}getAccessToken(){const e=this.getTokens();return(e==null?void 0:e.accessToken)||null}async getAuthHeaders(){const e=this.getTokens();if(!(e!=null&&e.accessToken))return{};if(!this.shouldRefreshToken(e))return{Authorization:`Bearer ${e.accessToken}`};if(!e.refreshToken)return this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{};if(this.refreshPromise)return new Promise((t,r)=>{this.refreshQueue.push({resolve:t,reject:r})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),r=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:n})=>n(r)),this.refreshQueue=[],r}catch(t){const r=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:n})=>n(r)),this.refreshQueue=[],this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{}}finally{this.refreshPromise=null}}async performTokenRefresh(e){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const t=`${this.baseUrl}/auth/refresh`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status} ${r.statusText}`);const n=await r.json();this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||e,expiresIn:n.expiresIn})}setUser(e){const t=this.tokenStorage.get()||{};this.tokenStorage.set({...t,user:e})}getUser(){const e=this.tokenStorage.get();return(e==null?void 0:e.user)||null}clearUser(){const e=this.tokenStorage.get()||{};delete e.user,this.tokenStorage.set(e)}clearSession(){this.clearTokens(),this.clearUser()}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}}class ce{constructor(e){this.httpService=e}async login(e){const t=await this.httpService.post("/auth/login",e);return console.log(t),t}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class te{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:r})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const n=`/roles/app/${e}${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n);return{roles:l.data,meta:l.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:r})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:r})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const l=`/roles/user/${e}${n.toString()?`?${n.toString()}`:""}`,S=await this.httpService.get(l,{headers:r});return{roles:S.data,meta:S.meta}}}class de{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/users/${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{users:l.data,meta:l.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:r})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class se{constructor(e,t,r){this.httpService=e,this.appId=t,this.sessionManager=r}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/tenants/${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{tenants:l.data,meta:l.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:r})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:r})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:r})).data}}const ue=a.createContext(null),Ae=()=>s.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:s.jsx("div",{children:"Loading tenant..."})}),je=({error:i,retry:e})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[s.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Tenant Error"}),s.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load tenant"}),s.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Pe({config:i,children:e}){const{baseUrl:t,appInfo:r,appId:n}=Y(),[l,S]=a.useState(i.initialTenant||null),[P,k]=a.useState(!i.initialTenant),[A,g]=a.useState(null),[h,b]=a.useState(null),[p,v]=a.useState(!1),[E,f]=a.useState(null),I=a.useCallback(()=>{const d=i.tenantMode||"selector",w="tenant";if(typeof window>"u")return null;if(d==="subdomain"){const o=window.location.hostname.split(".");if(o.length>=3){const c=o[0];return localStorage.setItem(w,c),c}return localStorage.getItem(w)}else if(d==="selector"){const o=new URLSearchParams(window.location.search).get(i.selectorParam||"tenant");return o?(localStorage.setItem(w,o),o):localStorage.getItem(w)}return null},[i.tenantMode,i.selectorParam]),y=a.useMemo(()=>I(),[I]),m=(r==null?void 0:r.settingsSchema)||null,j=a.useCallback(async d=>{try{k(!0),g(null);const w=new z(t),o=await new se(w,n).getPublicTenantInfo(d);S(o)}catch(w){const u=w instanceof Error?w:new Error("Failed to load tenant information");g(u),S(null)}finally{k(!1)}},[t,n]),M=a.useCallback(async()=>{if(l!=null&&l.id)try{v(!0),f(null);const d=new z(t),u=await new se(d,l.appId).getTenantSettings(l.id);b(u)}catch(d){const w=d instanceof Error?d:new Error("Failed to load tenant settings");f(w),b(null)}finally{v(!1)}},[t,l]),H=a.useCallback(()=>{M()},[M]),T=a.useCallback(d=>{if(!m)return{isValid:!0,errors:[]};const w=[];try{return m.properties&&Object.entries(m.properties).forEach(([u,o])=>{var O;const c=d[u];if((O=m.required)!=null&&O.includes(u)&&c==null){w.push(`Field '${u}' is required`);return}if(c!=null){if(o.type){const F=o.type,B=typeof c;F==="string"&&B!=="string"?w.push(`Field '${u}' must be a string`):(F==="number"||F==="integer")&&B!=="number"?w.push(`Field '${u}' must be a number`):F==="boolean"&&B!=="boolean"?w.push(`Field '${u}' must be a boolean`):F==="array"&&!Array.isArray(c)&&w.push(`Field '${u}' must be an array`)}o.minLength!==void 0&&typeof c=="string"&&c.length<o.minLength&&w.push(`Field '${u}' must be at least ${o.minLength} characters long`),o.maxLength!==void 0&&typeof c=="string"&&c.length>o.maxLength&&w.push(`Field '${u}' must be no more than ${o.maxLength} characters long`),o.minimum!==void 0&&typeof c=="number"&&c<o.minimum&&w.push(`Field '${u}' must be at least ${o.minimum}`),o.maximum!==void 0&&typeof c=="number"&&c>o.maximum&&w.push(`Field '${u}' must be no more than ${o.maximum}`),o.pattern&&typeof c=="string"&&(new RegExp(o.pattern).test(c)||w.push(`Field '${u}' does not match the required pattern`)),o.enum&&!o.enum.includes(c)&&w.push(`Field '${u}' must be one of: ${o.enum.join(", ")}`)}}),{isValid:w.length===0,errors:w}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[m]);a.useEffect(()=>{!i.initialTenant&&y?j(y):!i.initialTenant&&!y&&(S(null),g(null),k(!1))},[i.initialTenant,y,j]),a.useEffect(()=>{l!=null&&l.id?M():(b(null),f(null),v(!1))},[l==null?void 0:l.id,M]);const $=a.useMemo(()=>({tenant:l,tenantSlug:y,isTenantLoading:P,tenantError:A,retryTenant:()=>{y&&j(y)},settings:h,settingsSchema:m,isSettingsLoading:p,settingsError:E,refreshSettings:H,validateSettings:T}),[l,y,P,A,h,m,p,E,H,T]);if(P)return s.jsx(s.Fragment,{children:i.loadingFallback||s.jsx(Ae,{})});if(A){const d=typeof i.errorFallback=="function"?i.errorFallback(A,()=>j(y||"")):i.errorFallback||s.jsx(je,{error:A,retry:()=>j(y||"")});return s.jsx(s.Fragment,{children:d})}return s.jsx(ue.Provider,{value:$,children:e})}function J(){const i=a.useContext(ue);if(!i)throw new Error("useTenant must be used within a TenantProvider");return i}const ke=J;function Te(){const{settings:i,settingsSchema:e,isSettingsLoading:t,settingsError:r,validateSettings:n}=J();return{settings:i,settingsSchema:e,isLoading:t,error:r,validateSettings:n}}function K(){const{tenant:i,tenantSlug:e,isTenantLoading:t,tenantError:r,retryTenant:n}=J();return{tenant:i,tenantSlug:e,isLoading:t,error:r,retry:n}}const he=a.createContext(null);function Me({config:i={},children:e}){const{appId:t,baseUrl:r}=Y(),n=K(),l=(n==null?void 0:n.tenantSlug)||null,[S,P]=a.useState(i.initialRoles||[]),[k,A]=a.useState(!i.initialRoles),[g,h]=a.useState(null),[b,p]=a.useState(!1),[v,E]=a.useState(null),f=a.useMemo(()=>{const d=l?`auth_tokens_${l}`:"auth_tokens",w={get:()=>{try{const u=localStorage.getItem(d);return u?JSON.parse(u):null}catch{return null}},set:u=>{try{localStorage.setItem(d,JSON.stringify(u))}catch{}},clear:()=>{try{localStorage.removeItem(d)}catch{}}};return new le({onRefreshFailed:i.onRefreshFailed,tokenStorage:w,baseUrl:r})},[l,r,i.onRefreshFailed]),I=a.useMemo(()=>{const d=new z(r);return d.setSessionManager(f),d},[r,f]),y=a.useMemo(()=>new ce(new z(r)),[r]),m=a.useMemo(()=>new de(I,f),[I,f]),j=a.useMemo(()=>new te(new z(r)),[r]),M=a.useMemo(()=>g||f.getUser(),[g,f]),H=a.useMemo(()=>M!=null&&M.roleId&&S.find(d=>d.id===M.roleId)||null,[M,S]),T=a.useMemo(()=>(H==null?void 0:H.permissions)||[],[H]);a.useEffect(()=>{console.log("AuthProvider - userPermissions changed:",T)},[T]);const $=a.useMemo(()=>{const d=async()=>{try{p(!0),E(null);const x=f.getUser();if(!(x!=null&&x.id))throw new Error("No user ID available in session");const C=await m.getUserById(x.id);h(C),f.setUser(C)}catch(x){const C=x instanceof Error?x:new Error("Failed to load user data");E(C),console.error("Failed to load user data:",C)}finally{p(!1)}},w=async()=>{await d()},u=async(x,C,_)=>{const N=await y.login({email:x,password:C,tenantId:_});if(f.setTokens({accessToken:N.accessToken,refreshToken:N.refreshToken,expiresIn:N.expiresIn}),N.user){f.setUser(N.user),h(N.user);try{await d()}catch(Z){console.warn("Failed to load complete user data after login:",Z)}}return N},o=async(x,C,_,N)=>await y.signup({email:x,name:C,password:_,tenantId:N}),c=async(x,C,_,N)=>await y.signupTenantAdmin({email:x,name:C,password:_,tenantName:N,appId:t}),O=async(x,C)=>{const _=await f.getAuthHeaders();await y.changePassword({currentPassword:x,newPassword:C},_)},F=async(x,C)=>{await y.requestPasswordReset({email:x,tenantId:C})},B=async(x,C)=>{await y.confirmPasswordReset({token:x,newPassword:C})},V=async()=>{const x=f.getTokens();if(!(x!=null&&x.refreshToken))throw new Error("No refresh token available");const C=await y.refreshToken({refreshToken:x.refreshToken});f.setTokens({accessToken:C.accessToken,refreshToken:C.refreshToken||x.refreshToken,expiresIn:C.expiresIn})},R=()=>{f.clearSession(),h(null),E(null)},D=x=>{f.setTokens(x)},G=()=>f.hasValidSession(),L=()=>{f.clearSession(),h(null),E(null)},U=async()=>{if(t)try{A(!0);const{roles:x}=await j.getRolesByApp(t);P(x)}catch(x){console.error("Failed to fetch roles:",x)}finally{A(!1)}},q=async()=>{await U()},X=x=>{if(!T||T.length===0)return!1;if(typeof x=="string")return T.includes(x);const C=`${x.resource}.${x.action}`;return T.includes(C)};return{sessionManager:f,authenticatedHttpService:I,login:u,signup:o,signupTenantAdmin:c,changePassword:O,requestPasswordReset:F,confirmPasswordReset:B,refreshToken:V,logout:R,setTokens:D,hasValidSession:G,clearSession:L,currentUser:g,isUserLoading:b,userError:v,refreshUser:w,userRole:H,userPermissions:T,availableRoles:S,rolesLoading:k,hasPermission:X,hasAnyPermission:x=>x.some(C=>X(C)),hasAllPermissions:x=>x.every(C=>X(C)),getUserPermissionStrings:()=>T||[],refreshRoles:q}},[f,I,y,m,j,t,S,g,b,v,H,T]);return a.useEffect(()=>{!i.initialRoles&&t&&(async()=>{try{A(!0);const w=new z(r),u=new te(w),{roles:o}=await u.getRolesByApp(t);P(o)}catch(w){console.error("Failed to fetch roles:",w)}finally{A(!1)}})()},[t,r,i.initialRoles]),a.useEffect(()=>{const d=f.getUser();d&&f.hasValidSession()&&h(d)},[f]),s.jsx(he.Provider,{value:$,children:e})}function Q(){const i=a.useContext(he);if(!i)throw new Error("useAuth must be used within an AuthProvider");return i}class ge{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/feature-flags/${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{featureFlags:l.data,meta:l.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:r})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const r=new URLSearchParams;r.append("tenantId",e),r.append("appId",t);const n=`/tenant-feature-flags${r.toString()?`?${r.toString()}`:""}`;return(await this.httpService.get(n,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,r){if(!e||!t||!r)throw new Error("Flag Key, Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",t),n.append("appId",r);const l=`/tenant-feature-flags/${e}${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(l,{headers:{"X-Tenant-ID":t}})).data}}const pe=a.createContext(null);function Ee({config:i={},children:e}){const{baseUrl:t,appId:r}=Y(),{tenant:n}=K(),[l,S]=a.useState([]),[P,k]=a.useState(!1),[A,g]=a.useState(null),h=a.useMemo(()=>{const v=new z(t);return new ge(v)},[t]),b=async()=>{if(!(n!=null&&n.id)){S([]);return}k(!0),g(null);try{const v=await h.getTenantFeatureFlags(n.id,r);S(v)}catch(v){const E=v instanceof Error?v.message:"Failed to fetch feature flags";g(E),i.onError&&i.onError(v instanceof Error?v:new Error(E))}finally{k(!1)}};a.useEffect(()=>{b();const v=i.refreshInterval||5*60*1e3,E=setInterval(b,v);return()=>clearInterval(E)},[n==null?void 0:n.id,i.refreshInterval]);const p=a.useMemo(()=>({featureFlags:l,loading:P,error:A,isEnabled:y=>{const m=l.find(j=>j.key===y);return(m==null?void 0:m.value)===!0},getFlag:y=>l.find(m=>m.key===y),getFlagState:y=>{const m=l.find(j=>j.key===y);return m?m.value?"enabled":"disabled":"not_found"},refresh:async()=>{await b()}}),[l,P,A]);return s.jsx(pe.Provider,{value:p,children:e})}function fe(){const i=a.useContext(pe);if(!i)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return i}class ye{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:r})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:r})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:r})).data}}const we=a.createContext(void 0);function Fe({config:i={},children:e}){const{baseUrl:t}=Y(),{tenant:r}=K(),[n,l]=a.useState(null),[S,P]=a.useState(!1),[k,A]=a.useState(null),g=a.useMemo(()=>{const p=new z(t);return new ye(p)},[t]),h=async()=>{if(!(r!=null&&r.id)){l(null);return}P(!0),A(null);try{const p=await g.getTenantSubscriptionFeatures(r.id);l(p)}catch(p){const v=p instanceof Error?p.message:"Failed to fetch subscription";A(v),i.onError&&i.onError(p instanceof Error?p:new Error(v))}finally{P(!1)}};a.useEffect(()=>{if(h(),!i.refreshInterval)return;const p=i.refreshInterval||10*60*1e3,v=setInterval(h,p);return()=>clearInterval(v)},[r==null?void 0:r.id,i.refreshInterval]);const b=a.useMemo(()=>{const p=(n==null?void 0:n.features)||[];return{subscription:n,features:p,loading:S,error:k,isFeatureEnabled:m=>{const j=p.find(M=>M.key===m);return j?j.type==="BOOLEAN"||j.type==="boolean"?j.value===!0:!!j.value:!1},getFeature:m=>p.find(j=>j.key===m),getFeatureValue:(m,j)=>{const M=p.find(H=>H.key===m);return M?M.value:j},hasAllowedPlan:m=>!n||!n.isActive?!1:m.includes(n.planId),refresh:async()=>{await h()}}},[n,S,k]);return s.jsx(we.Provider,{value:b,children:e})}function me(){const i=a.useContext(we);if(i===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return i}var W=(i=>(i.SUPERUSER="SUPERUSER",i.TENANT_ADMIN="TENANT_ADMIN",i.USER="USER",i))(W||{});const re=()=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[s.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),s.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),s.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),s.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),ne=({userType:i,minUserType:e,missingPermissions:t})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[s.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),s.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&i?s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",s.jsx("strong",{children:e})," access level or higher."]}),s.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",s.jsx("strong",{children:i})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&s.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",s.jsx("strong",{children:t.join(", ")})]})]})]}),Re=(i,e)=>{const t={[W.USER]:1,[W.TENANT_ADMIN]:2,[W.SUPERUSER]:3};return t[i]>=t[e]};function Ce({children:i,fallback:e,minUserType:t,requiredPermissions:r,requireAllPermissions:n=!1}){const{hasValidSession:l,sessionManager:S,hasPermission:P,hasAnyPermission:k,hasAllPermissions:A}=Q();if(!l())return s.jsx(s.Fragment,{children:e||s.jsx(re,{})});const g=S.getUser();if(!g)return s.jsx(s.Fragment,{children:e||s.jsx(re,{})});if(t&&!Re(g.userType,t))return s.jsx(ne,{userType:g.userType,minUserType:t});if(r&&r.length>0&&!(n?A(r):k(r))){const b=r.filter(p=>!P(p)).map(p=>typeof p=="string"?p:p.name);return s.jsx(ne,{missingPermissions:b})}return s.jsx(s.Fragment,{children:i})}const Ie=({redirectPath:i})=>s.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:s.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[s.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),s.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),s.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})}),ie=({userType:i,minUserType:e,missingPermissions:t})=>s.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:s.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[s.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),s.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&i?s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",s.jsx("strong",{children:e})," access level or higher."]}),s.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current access level: ",s.jsx("strong",{children:i})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&s.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",s.jsx("strong",{children:t.join(", ")})]})]})]})}),He=(i,e)=>{const t={[W.USER]:1,[W.TENANT_ADMIN]:2,[W.SUPERUSER]:3};return t[i]>=t[e]};function $e({children:i,redirectTo:e="/login",minUserType:t,requiredPermissions:r,requireAllPermissions:n=!1,fallback:l}){const{hasValidSession:S,sessionManager:P,hasPermission:k,hasAnyPermission:A,hasAllPermissions:g}=Q(),h=ee.useLocation();if(!S())return l?s.jsx(s.Fragment,{children:l}):s.jsxs(s.Fragment,{children:[s.jsx(Ie,{redirectPath:e}),s.jsx(ee.Navigate,{to:e,state:{from:h.pathname},replace:!0})]});const b=P.getUser();if(!b)return s.jsx(ee.Navigate,{to:e,state:{from:h.pathname},replace:!0});if(t&&!He(b.userType,t))return s.jsx(ie,{userType:b.userType,minUserType:t});if(r&&r.length>0&&!(n?g(r):A(r))){const v=r.filter(E=>!k(E)).map(E=>typeof E=="string"?E:E.name);return s.jsx(ie,{missingPermissions:v})}return s.jsx(s.Fragment,{children:i})}const Le=()=>s.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[s.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),s.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function De({children:i,fallback:e=s.jsx(Le,{}),allowedPlans:t,requiredFeature:r}){const{subscription:n,hasAllowedPlan:l,isFeatureEnabled:S,loading:P}=me();return P?s.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):n?n.isActive?t&&t.length>0&&!l(t)?s.jsx(s.Fragment,{children:e}):r&&!S(r)?s.jsx(s.Fragment,{children:e}):s.jsx(s.Fragment,{children:i}):s.jsx(s.Fragment,{children:e}):s.jsx(s.Fragment,{children:e})}const Be=({flagName:i})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[s.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),s.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),s.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',i,'" is disabled']})]});function Ue({name:i,children:e,fallback:t}){const{isEnabled:r,loading:n}=fe();return n?s.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):(console.log(i,r(i)),r(i)?s.jsx(s.Fragment,{children:e}):s.jsx(s.Fragment,{children:t||s.jsx(Be,{flagName:i})}))}const qe=()=>s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),Ne=()=>s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[s.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),Oe={showPassword:s.jsx(qe,{}),hidePassword:s.jsx(Ne,{})},ze={title:"Sign In",emailLabel:"Email",emailPlaceholder:"Enter your email",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",errorMessage:"Invalid email or password",loadingText:"Signing in..."},Ve={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},inputContainer:{position:"relative",display:"flex",alignItems:"center"},passwordToggle:{position:"absolute",right:"0.75rem",background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"#6b7280",display:"flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",borderRadius:"4px",transition:"background-color 0.15s ease-in-out"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function We({copy:i={},styles:e={},icons:t={},onSuccess:r,onError:n,onForgotPassword:l,onSignupClick:S,showForgotPassword:P=!0,showSignupLink:k=!0,className:A}){const[g,h]=a.useState(""),[b,p]=a.useState(""),[v,E]=a.useState(!1),[f,I]=a.useState(!1),[y,m]=a.useState(""),[j,M]=a.useState({}),{login:H}=Q(),{tenant:T}=K(),$={...ze,...i},d={...Ve,...e},w={...Oe,...t},u=()=>{const F={};return g.trim()||(F.email=!0),b.trim()||(F.password=!0),M(F),Object.keys(F).length===0},o=async F=>{if(F.preventDefault(),!!u()){if(!(T!=null&&T.id)){m("Tenant not found");return}I(!0),m("");try{const B=await H(g,b,T.id);r==null||r(B)}catch(B){const V=B.message||$.errorMessage;m(V),n==null||n(V)}finally{I(!1)}}},c=F=>({...d.input,...j[F]?d.inputError:{}}),O=()=>({...d.button,...f?d.buttonLoading:{},...!g||!b||f?d.buttonDisabled:{}});return s.jsxs("div",{className:A,style:d.container,children:[s.jsx("h2",{style:d.title,children:$.title}),s.jsxs("form",{onSubmit:o,style:d.form,children:[s.jsxs("div",{style:d.fieldGroup,children:[s.jsx("label",{style:d.label,children:$.emailLabel}),s.jsx("input",{id:"email",name:"email",type:"email",value:g,onChange:F=>{h(F.target.value),j.email&&M(B=>({...B,email:!1}))},placeholder:$.emailPlaceholder,style:c("email"),disabled:f})]}),s.jsxs("div",{style:d.fieldGroup,children:[s.jsx("label",{style:d.label,children:$.passwordLabel}),s.jsxs("div",{style:d.inputContainer,children:[s.jsx("input",{id:"password",name:"password",type:v?"text":"password",value:b,onChange:F=>{p(F.target.value),j.password&&M(B=>({...B,password:!1}))},placeholder:$.passwordPlaceholder,style:{...c("password"),paddingRight:"2.5rem"},disabled:f}),s.jsx("button",{type:"button",onClick:()=>E(!v),style:d.passwordToggle,disabled:f,"aria-label":v?"Hide password":"Show password",children:v?w.hidePassword:w.showPassword})]})]}),s.jsx("button",{type:"submit",disabled:!g||!b||f,style:O(),children:f?$.loadingText:$.submitButton}),y&&s.jsx("div",{style:d.errorText,children:y})]}),(P||k)&&s.jsxs("div",{style:d.linkContainer,children:[P&&s.jsx("a",{onClick:l,style:d.link,children:$.forgotPasswordLink}),P&&k&&s.jsx("div",{style:d.divider,children:"•"}),k&&s.jsxs("div",{children:[s.jsxs("span",{style:d.divider,children:[$.signupText," "]}),s.jsx("a",{onClick:S,style:d.link,children:$.signupLink})]})]})]})}const Ge={title:"Create Account",nameLabel:"Full Name",namePlaceholder:"Enter your full name",emailLabel:"Email",emailPlaceholder:"Enter your email",passwordLabel:"Password",passwordPlaceholder:"Enter your password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm your password",tenantNameLabel:"Organization Name",tenantNamePlaceholder:"Enter your organization name",submitButton:"Create Account",loginLink:"Sign in here",loginText:"Already have an account?",errorMessage:"Failed to create account",loadingText:"Creating account...",passwordMismatchError:"Passwords do not match",isAdminLabel:"Create new organization",isAdminDescription:"Check this if you want to create a new organization"},_e={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function Ke({copy:i={},styles:e={},signupType:t="user",onSuccess:r,onError:n,onLoginClick:l,showLoginLink:S=!0,className:P}){const[k,A]=a.useState(""),[g,h]=a.useState(""),[b,p]=a.useState(""),[v,E]=a.useState(""),[f,I]=a.useState(""),[y,m]=a.useState(!1),[j,M]=a.useState(""),[H,T]=a.useState({}),{signup:$,signupTenantAdmin:d}=Q(),{tenant:w}=K(),u={...Ge,...i},o={..._e,...e},c=()=>{const R={};return k.trim()||(R.name=!0),g.trim()||(R.email=!0),b.trim()||(R.password=!0),v.trim()||(R.confirmPassword=!0),t==="tenant"&&!f.trim()&&(R.tenantName=!0),T(R),Object.keys(R).length===0},O=async R=>{if(R.preventDefault(),!!c()){if(b!==v){M(u.passwordMismatchError),T({confirmPassword:!0});return}if(t==="user"&&!(w!=null&&w.id)){M("Tenant not found");return}m(!0),M("");try{let D;t==="tenant"?D=await d(g,k,b,f):D=await $(g,k,b,w.id),r==null||r(D)}catch(D){const G=D.message||u.errorMessage;M(G),n==null||n(G)}finally{m(!1)}}},F=R=>({...o.input,...H[R]?o.inputError:{}}),B=()=>({...o.button,...y?o.buttonLoading:{},...!k||!g||!b||!v||y||t==="tenant"&&!f?o.buttonDisabled:{}}),V=k&&g&&b&&v&&(t==="user"||f);return s.jsxs("div",{className:P,style:o.container,children:[s.jsx("h2",{style:o.title,children:u.title}),s.jsxs("form",{onSubmit:O,style:o.form,children:[s.jsxs("div",{style:o.fieldGroup,children:[s.jsx("label",{style:o.label,children:u.nameLabel}),s.jsx("input",{id:"name",name:"name",type:"text",value:k,onChange:R=>{A(R.target.value),H.name&&T(D=>({...D,name:!1}))},placeholder:u.namePlaceholder,style:F("name"),disabled:y})]}),s.jsxs("div",{style:o.fieldGroup,children:[s.jsx("label",{style:o.label,children:u.emailLabel}),s.jsx("input",{id:"email",name:"email",type:"email",value:g,onChange:R=>{h(R.target.value),H.email&&T(D=>({...D,email:!1}))},placeholder:u.emailPlaceholder,style:F("email"),disabled:y})]}),s.jsxs("div",{style:o.fieldGroup,children:[s.jsx("label",{style:o.label,children:u.passwordLabel}),s.jsx("input",{id:"password",name:"password",type:"password",value:b,onChange:R=>{p(R.target.value),H.password&&T(D=>({...D,password:!1}))},placeholder:u.passwordPlaceholder,style:F("password"),disabled:y})]}),s.jsxs("div",{style:o.fieldGroup,children:[s.jsx("label",{style:o.label,children:u.confirmPasswordLabel}),s.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:v,onChange:R=>{E(R.target.value),H.confirmPassword&&T(D=>({...D,confirmPassword:!1})),j===u.passwordMismatchError&&M("")},placeholder:u.confirmPasswordPlaceholder,style:F("confirmPassword"),disabled:y})]}),t==="tenant"&&s.jsxs("div",{style:o.fieldGroup,children:[s.jsx("label",{style:o.label,children:u.tenantNameLabel}),s.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:f,onChange:R=>{I(R.target.value),H.tenantName&&T(D=>({...D,tenantName:!1}))},placeholder:u.tenantNamePlaceholder,style:F("tenantName"),disabled:y})]}),s.jsx("button",{type:"submit",disabled:!V||y,style:B(),children:y?u.loadingText:u.submitButton}),j&&s.jsx("div",{style:o.errorText,children:j})]}),S&&s.jsxs("div",{style:o.linkContainer,children:[s.jsxs("span",{style:o.divider,children:[u.loginText," "]}),s.jsx("a",{onClick:l,style:o.link,children:u.loginLink})]})]})}const Ye={title:"Reset Password",subtitle:"Enter your email address and we'll send you a link to reset your password.",emailLabel:"Email",emailPlaceholder:"Enter your email",submitButton:"Send Reset Link",backToLoginLink:"Back to Sign In",successMessage:"Password reset link sent! Check your email.",errorMessage:"Failed to send reset link",loadingText:"Sending...",resetTitle:"Set New Password",resetSubtitle:"Enter your reset token and new password.",tokenLabel:"Reset Token",tokenPlaceholder:"Enter reset token from email",newPasswordLabel:"New Password",newPasswordPlaceholder:"Enter new password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm new password",resetSubmitButton:"Reset Password",resetLoadingText:"Resetting...",resetSuccessMessage:"Password reset successfully!",passwordMismatchError:"Passwords do not match"},Qe={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"}};function Je({copy:i={},styles:e={},mode:t="request",token:r="",onSuccess:n,onError:l,onBackToLogin:S,onModeChange:P,className:k}){const[A,g]=a.useState(""),[h,b]=a.useState(r),[p,v]=a.useState(""),[E,f]=a.useState(""),[I,y]=a.useState(!1),[m,j]=a.useState(""),[M,H]=a.useState(""),[T,$]=a.useState({}),{requestPasswordReset:d,confirmPasswordReset:w}=Q(),{tenant:u}=K(),o={...Ye,...i},c={...Qe,...e},O=()=>{const L={};return A.trim()||(L.email=!0),$(L),Object.keys(L).length===0},F=()=>{const L={};return h.trim()||(L.token=!0),p.trim()||(L.newPassword=!0),E.trim()||(L.confirmPassword=!0),$(L),Object.keys(L).length===0},B=async L=>{if(L.preventDefault(),!!O()){if(!(u!=null&&u.id)){j("Tenant not found");return}y(!0),j(""),H("");try{await d(A,u.id),H(o.successMessage),n==null||n()}catch(U){const q=U.message||o.errorMessage;j(q),l==null||l(q)}finally{y(!1)}}},V=async L=>{if(L.preventDefault(),!!F()){if(p!==E){j(o.passwordMismatchError),$({confirmPassword:!0});return}y(!0),j(""),H("");try{await w(h,p),H(o.resetSuccessMessage),n==null||n()}catch(U){const q=U.message||o.errorMessage;j(q),l==null||l(q)}finally{y(!1)}}},R=L=>({...c.input,...T[L]?c.inputError:{}}),D=()=>({...c.button,...I?c.buttonLoading:{}});if(t==="reset"){const L=h&&p&&E;return s.jsxs("div",{className:k,style:c.container,children:[s.jsx("h2",{style:c.title,children:o.resetTitle}),s.jsx("p",{style:c.subtitle,children:o.resetSubtitle}),s.jsxs("form",{onSubmit:V,style:c.form,children:[s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:o.tokenLabel}),s.jsx("input",{type:"text",value:h,onChange:U=>{b(U.target.value),T.token&&$(q=>({...q,token:!1}))},placeholder:o.tokenPlaceholder,style:R("token"),disabled:I})]}),s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:o.newPasswordLabel}),s.jsx("input",{type:"password",value:p,onChange:U=>{v(U.target.value),T.newPassword&&$(q=>({...q,newPassword:!1}))},placeholder:o.newPasswordPlaceholder,style:R("newPassword"),disabled:I})]}),s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:o.confirmPasswordLabel}),s.jsx("input",{type:"password",value:E,onChange:U=>{f(U.target.value),T.confirmPassword&&$(q=>({...q,confirmPassword:!1})),m===o.passwordMismatchError&&j("")},placeholder:o.confirmPasswordPlaceholder,style:R("confirmPassword"),disabled:I})]}),s.jsx("button",{type:"submit",disabled:!L||I,style:{...D(),...!L||I?c.buttonDisabled:{}},children:I?o.resetLoadingText:o.resetSubmitButton}),m&&s.jsx("div",{style:c.errorText,children:m}),M&&s.jsx("div",{style:c.successText,children:M})]}),s.jsxs("div",{style:c.linkContainer,children:[s.jsx("a",{onClick:S,style:c.link,children:o.backToLoginLink}),P&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),s.jsx("a",{onClick:()=>P("request"),style:c.link,children:"Request New Link"})]})]})]})}const G=A;return s.jsxs("div",{className:k,style:c.container,children:[s.jsx("h2",{style:c.title,children:o.title}),s.jsx("p",{style:c.subtitle,children:o.subtitle}),s.jsxs("form",{onSubmit:B,style:c.form,children:[s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:o.emailLabel}),s.jsx("input",{type:"email",value:A,onChange:L=>{g(L.target.value),T.email&&$(U=>({...U,email:!1}))},placeholder:o.emailPlaceholder,style:R("email"),disabled:I})]}),s.jsx("button",{type:"submit",disabled:!G||I,style:{...D(),...!G||I?c.buttonDisabled:{}},children:I?o.loadingText:o.submitButton}),m&&s.jsx("div",{style:c.errorText,children:m}),M&&s.jsx("div",{style:c.successText,children:M})]}),s.jsxs("div",{style:c.linkContainer,children:[s.jsx("a",{onClick:S,style:c.link,children:o.backToLoginLink}),P&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),s.jsx("a",{onClick:()=>P("reset"),style:c.link,children:"I have a token"})]})]})]})}class Xe{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/permissions/${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{permissions:l.data,meta:l.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:r})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const n=`/permissions/apps/${e}${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n);return{permissions:l.data,meta:l.meta}}}class Ze{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder),e!=null&&e.appId&&r.append("appId",e.appId);const n=`/subscription-plans/${r.toString()?`?${r.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{plans:l.data,meta:l.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:r})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class et{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class tt{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([r,n])=>{n!=null&&n!==""&&t.append(r,String(n))}),t}}exports.ApiMappers=tt;exports.AppApiService=oe;exports.AppProvider=be;exports.AuthApiService=ce;exports.AuthProvider=Me;exports.FeatureFlag=Ue;exports.FeatureFlagApiService=ge;exports.FeatureFlagProvider=Ee;exports.HealthApiService=et;exports.HttpService=z;exports.LoginForm=We;exports.PasswordRecoveryForm=Je;exports.PermissionApiService=Xe;exports.Protected=Ce;exports.ProtectedRoute=$e;exports.RoleApiService=te;exports.SessionManager=le;exports.SignupForm=Ke;exports.SubscriptionApiService=ye;exports.SubscriptionGuard=De;exports.SubscriptionPlanApiService=Ze;exports.SubscriptionProvider=Fe;exports.TenantApiService=se;exports.TenantProvider=Pe;exports.UserApiService=de;exports.UserType=W;exports.useApi=ve;exports.useApp=Y;exports.useAuth=Q;exports.useFeatureFlags=fe;exports.useSettings=Te;exports.useSubscription=me;exports.useTenant=J;exports.useTenantInfo=K;exports.useTenantSettings=ke;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),l=require("react"),K=require("react-router");class z{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,r,n){return this.executeRequest(e,t,r,n,!1)}async executeRequest(e,t,r,n,o=!1){const x=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,P=(n==null?void 0:n.timeout)||this.timeout;let k={"Content-Type":"application/json",...n==null?void 0:n.headers};if(!(n!=null&&n.skipAuth)&&this.sessionManager)try{const h=await this.sessionManager.getAuthHeaders();k={...k,...h}}catch(h){console.warn("Failed to inject auth headers:",h)}const A=new AbortController,g=setTimeout(()=>A.abort(),P);try{const h=await fetch(x,{method:e,headers:k,body:r?JSON.stringify(r):void 0,signal:A.signal});if(clearTimeout(g),h.status===401&&!(n!=null&&n.skipRetry)&&!o&&this.sessionManager)try{const p=this.sessionManager.getTokens();if(p!=null&&p.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,r,n,!0)}catch{throw new Error(`HTTP ${h.status}: ${h.statusText}`)}if(!h.ok)throw new Error(`HTTP ${h.status}: ${h.statusText}`);const b=h.headers.get("content-type");return!b||!b.includes("application/json")?{}:await h.json()}catch(h){throw clearTimeout(g),h instanceof Error&&h.name==="AbortError"?new Error(`Request timeout after ${P}ms`):h}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class oe{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/apps/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n,{headers:t});return{apps:o.data,meta:o.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:r})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:r})).data}async updateSettingsSchema(e,t,r){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:r},{headers:n})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const ae=l.createContext(null),Se=()=>s.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:s.jsx("div",{children:"Loading application..."})}),be=({error:i,retry:e})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[s.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Application Error"}),s.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load application"}),s.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function ve({config:i,children:e}){const[t,r]=l.useState(null),[n,o]=l.useState(!0),[x,P]=l.useState(null),k=l.useMemo(()=>{const g=()=>{A()};return{appId:i.appId,baseUrl:i.baseUrl,appInfo:t,isAppLoading:n,appError:x,retryApp:g}},[i,t,n,x]),A=l.useCallback(async()=>{try{o(!0),P(null);const g=new z(i.baseUrl),b=await new oe(g,{}).getPublicAppInfo(i.appId);r(b)}catch(g){const h=g instanceof Error?g:new Error("Failed to load app information");P(h),r(null)}finally{o(!1)}},[i.baseUrl,i.appId]);if(l.useEffect(()=>{A()},[A]),n)return s.jsx(s.Fragment,{children:i.loadingFallback||s.jsx(Se,{})});if(x){const g=typeof i.errorFallback=="function"?i.errorFallback(x,()=>A()):i.errorFallback||s.jsx(be,{error:x,retry:()=>A()});return s.jsx(s.Fragment,{children:g})}return s.jsx(ae.Provider,{value:k,children:e})}function Q(){const i=l.useContext(ae);if(!i)throw new Error("useApp must be used within an AppProvider");return i}const Ae=Q;class le{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.baseUrl=e.baseUrl||"",this.tokenStorage=e.tokenStorage||{get:()=>{try{const t=localStorage.getItem(this.storageKey);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(this.storageKey,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(this.storageKey)}catch{}}}}setTokens(e){const t={...e,expiresAt:e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)};this.tokenStorage.set(t)}getTokens(){return this.tokenStorage.get()}clearTokens(){this.tokenStorage.clear()}isTokenExpired(e){const t=e||this.getTokens();return t!=null&&t.expiresAt?Date.now()>=t.expiresAt:!1}shouldRefreshToken(e){const t=e||this.getTokens();return!(t!=null&&t.expiresAt)||!this.autoRefresh?!1:Date.now()>=t.expiresAt-this.refreshThreshold}getAccessToken(){const e=this.getTokens();return(e==null?void 0:e.accessToken)||null}async getAuthHeaders(){const e=this.getTokens();if(!(e!=null&&e.accessToken))return{};if(!this.shouldRefreshToken(e))return{Authorization:`Bearer ${e.accessToken}`};if(!e.refreshToken)return this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{};if(this.refreshPromise)return new Promise((t,r)=>{this.refreshQueue.push({resolve:t,reject:r})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),r=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:n})=>n(r)),this.refreshQueue=[],r}catch(t){const r=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:n})=>n(r)),this.refreshQueue=[],this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{}}finally{this.refreshPromise=null}}async performTokenRefresh(e){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const t=`${this.baseUrl}/auth/refresh`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status} ${r.statusText}`);const n=await r.json();this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||e,expiresIn:n.expiresIn})}setUser(e){const t=this.tokenStorage.get()||{};this.tokenStorage.set({...t,user:e})}getUser(){const e=this.tokenStorage.get();return(e==null?void 0:e.user)||null}clearUser(){const e=this.tokenStorage.get()||{};delete e.user,this.tokenStorage.set(e)}clearSession(){this.clearTokens(),this.clearUser()}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}}class ce{constructor(e){this.httpService=e}async login(e){const t=await this.httpService.post("/auth/login",e);return console.log(t),t}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class te{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:r})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const n=`/roles/app/${e}${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:r})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:r})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const o=`/roles/user/${e}${n.toString()?`?${n.toString()}`:""}`,x=await this.httpService.get(o,{headers:r});return{roles:x.data,meta:x.meta}}}class de{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/users/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n,{headers:t});return{users:o.data,meta:o.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:r})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class se{constructor(e,t,r){this.httpService=e,this.appId=t,this.sessionManager=r}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/tenants/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n,{headers:t});return{tenants:o.data,meta:o.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:r})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:r})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:r})).data}}const ue=l.createContext(null),je=()=>s.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:s.jsx("div",{children:"Loading tenant..."})}),Pe=({error:i,retry:e})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[s.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Tenant Error"}),s.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load tenant"}),s.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function ke({config:i,children:e}){const{baseUrl:t,appInfo:r,appId:n}=Q(),[o,x]=l.useState(i.initialTenant||null),[P,k]=l.useState(!i.initialTenant),[A,g]=l.useState(null),[h,b]=l.useState(null),[p,v]=l.useState(!1),[F,f]=l.useState(null),I=l.useCallback(()=>{const d=i.tenantMode||"selector",y="tenant";if(typeof window>"u")return null;if(d==="subdomain"){const a=window.location.hostname.split(".");if(a.length>=3){const c=a[0];return localStorage.setItem(y,c),c}return localStorage.getItem(y)}else if(d==="selector"){const a=new URLSearchParams(window.location.search).get(i.selectorParam||"tenant");return a?(localStorage.setItem(y,a),a):localStorage.getItem(y)}return null},[i.tenantMode,i.selectorParam]),m=l.useMemo(()=>I(),[I]),w=(r==null?void 0:r.settingsSchema)||null,j=l.useCallback(async d=>{try{k(!0),g(null);const y=new z(t),a=await new se(y,n).getPublicTenantInfo(d);x(a)}catch(y){const u=y instanceof Error?y:new Error("Failed to load tenant information");g(u),x(null)}finally{k(!1)}},[t,n]),M=l.useCallback(async()=>{if(o!=null&&o.id)try{v(!0),f(null);const d=new z(t),u=await new se(d,o.appId).getTenantSettings(o.id);b(u)}catch(d){const y=d instanceof Error?d:new Error("Failed to load tenant settings");f(y),b(null)}finally{v(!1)}},[t,o]),H=l.useCallback(()=>{M()},[M]),T=l.useCallback(d=>{if(!w)return{isValid:!0,errors:[]};const y=[];try{return w.properties&&Object.entries(w.properties).forEach(([u,a])=>{var O;const c=d[u];if((O=w.required)!=null&&O.includes(u)&&c==null){y.push(`Field '${u}' is required`);return}if(c!=null){if(a.type){const E=a.type,B=typeof c;E==="string"&&B!=="string"?y.push(`Field '${u}' must be a string`):(E==="number"||E==="integer")&&B!=="number"?y.push(`Field '${u}' must be a number`):E==="boolean"&&B!=="boolean"?y.push(`Field '${u}' must be a boolean`):E==="array"&&!Array.isArray(c)&&y.push(`Field '${u}' must be an array`)}a.minLength!==void 0&&typeof c=="string"&&c.length<a.minLength&&y.push(`Field '${u}' must be at least ${a.minLength} characters long`),a.maxLength!==void 0&&typeof c=="string"&&c.length>a.maxLength&&y.push(`Field '${u}' must be no more than ${a.maxLength} characters long`),a.minimum!==void 0&&typeof c=="number"&&c<a.minimum&&y.push(`Field '${u}' must be at least ${a.minimum}`),a.maximum!==void 0&&typeof c=="number"&&c>a.maximum&&y.push(`Field '${u}' must be no more than ${a.maximum}`),a.pattern&&typeof c=="string"&&(new RegExp(a.pattern).test(c)||y.push(`Field '${u}' does not match the required pattern`)),a.enum&&!a.enum.includes(c)&&y.push(`Field '${u}' must be one of: ${a.enum.join(", ")}`)}}),{isValid:y.length===0,errors:y}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[w]);l.useEffect(()=>{!i.initialTenant&&m?j(m):!i.initialTenant&&!m&&(x(null),g(null),k(!1))},[i.initialTenant,m,j]),l.useEffect(()=>{o!=null&&o.id?M():(b(null),f(null),v(!1))},[o==null?void 0:o.id,M]);const $=l.useMemo(()=>({tenant:o,tenantSlug:m,isTenantLoading:P,tenantError:A,retryTenant:()=>{m&&j(m)},settings:h,settingsSchema:w,isSettingsLoading:p,settingsError:F,refreshSettings:H,validateSettings:T}),[o,m,P,A,h,w,p,F,H,T]);if(P)return s.jsx(s.Fragment,{children:i.loadingFallback||s.jsx(je,{})});if(A){const d=typeof i.errorFallback=="function"?i.errorFallback(A,()=>j(m||"")):i.errorFallback||s.jsx(Pe,{error:A,retry:()=>j(m||"")});return s.jsx(s.Fragment,{children:d})}return s.jsx(ue.Provider,{value:$,children:e})}function Z(){const i=l.useContext(ue);if(!i)throw new Error("useTenant must be used within a TenantProvider");return i}const Te=Z;function Me(){const{settings:i,settingsSchema:e,isSettingsLoading:t,settingsError:r,validateSettings:n}=Z();return{settings:i,settingsSchema:e,isLoading:t,error:r,validateSettings:n}}function V(){const{tenant:i,tenantSlug:e,isTenantLoading:t,tenantError:r,retryTenant:n}=Z();return{tenant:i,tenantSlug:e,isLoading:t,error:r,retry:n}}const he=l.createContext(null);function Fe({config:i={},children:e}){const{appId:t,baseUrl:r}=Q(),n=V(),o=(n==null?void 0:n.tenantSlug)||null,[x,P]=l.useState(i.initialRoles||[]),[k,A]=l.useState(!i.initialRoles),[g,h]=l.useState(null),[b,p]=l.useState(!1),[v,F]=l.useState(null),f=l.useMemo(()=>{const d=o?`auth_tokens_${o}`:"auth_tokens",y={get:()=>{try{const u=localStorage.getItem(d);return u?JSON.parse(u):null}catch{return null}},set:u=>{try{localStorage.setItem(d,JSON.stringify(u))}catch{}},clear:()=>{try{localStorage.removeItem(d)}catch{}}};return new le({onRefreshFailed:i.onRefreshFailed,tokenStorage:y,baseUrl:r})},[o,r,i.onRefreshFailed]),I=l.useMemo(()=>{const d=new z(r);return d.setSessionManager(f),d},[r,f]),m=l.useMemo(()=>new ce(new z(r)),[r]),w=l.useMemo(()=>new de(I,f),[I,f]),j=l.useMemo(()=>new te(new z(r)),[r]),M=l.useMemo(()=>g||f.getUser(),[g,f]),H=l.useMemo(()=>M!=null&&M.roleId&&x.find(d=>d.id===M.roleId)||null,[M,x]),T=l.useMemo(()=>(H==null?void 0:H.permissions)||[],[H]);l.useEffect(()=>{console.log("AuthProvider - userPermissions changed:",T)},[T]);const $=l.useMemo(()=>{const d=async()=>{try{p(!0),F(null);const S=f.getUser();if(!(S!=null&&S.id))throw new Error("No user ID available in session");const C=await w.getUserById(S.id);h(C),f.setUser(C)}catch(S){const C=S instanceof Error?S:new Error("Failed to load user data");F(C),console.error("Failed to load user data:",C)}finally{p(!1)}},y=async()=>{await d()},u=async(S,C,Y)=>{const N=await m.login({email:S,password:C,tenantId:Y});if(f.setTokens({accessToken:N.accessToken,refreshToken:N.refreshToken,expiresIn:N.expiresIn}),N.user){f.setUser(N.user),h(N.user);try{await d()}catch(X){console.warn("Failed to load complete user data after login:",X)}}return N},a=async(S,C,Y,N,X)=>await m.signup({email:S,name:C,password:Y,tenantId:N,lastName:X}),c=async(S,C,Y,N,X)=>await m.signupTenantAdmin({email:S,name:C,password:Y,tenantName:N,appId:t,lastName:X}),O=async(S,C)=>{const Y=await f.getAuthHeaders();await m.changePassword({currentPassword:S,newPassword:C},Y)},E=async(S,C)=>{await m.requestPasswordReset({email:S,tenantId:C})},B=async(S,C)=>{await m.confirmPasswordReset({token:S,newPassword:C})},W=async()=>{const S=f.getTokens();if(!(S!=null&&S.refreshToken))throw new Error("No refresh token available");const C=await m.refreshToken({refreshToken:S.refreshToken});f.setTokens({accessToken:C.accessToken,refreshToken:C.refreshToken||S.refreshToken,expiresIn:C.expiresIn})},R=()=>{f.clearSession(),h(null),F(null)},D=S=>{f.setTokens(S)},_=()=>f.hasValidSession(),L=()=>{f.clearSession(),h(null),F(null)},q=async()=>{if(t)try{A(!0);const{roles:S}=await j.getRolesByApp(t);P(S)}catch(S){console.error("Failed to fetch roles:",S)}finally{A(!1)}},U=async()=>{await q()},ee=S=>{if(!T||T.length===0)return!1;if(typeof S=="string")return T.includes(S);const C=`${S.resource}.${S.action}`;return T.includes(C)};return{sessionManager:f,authenticatedHttpService:I,login:u,signup:a,signupTenantAdmin:c,changePassword:O,requestPasswordReset:E,confirmPasswordReset:B,refreshToken:W,logout:R,setTokens:D,hasValidSession:_,clearSession:L,currentUser:g,isUserLoading:b,userError:v,refreshUser:y,userRole:H,userPermissions:T,availableRoles:x,rolesLoading:k,hasPermission:ee,hasAnyPermission:S=>S.some(C=>ee(C)),hasAllPermissions:S=>S.every(C=>ee(C)),getUserPermissionStrings:()=>T||[],refreshRoles:U}},[f,I,m,w,j,t,x,g,b,v,H,T]);return l.useEffect(()=>{!i.initialRoles&&t&&(async()=>{try{A(!0);const y=new z(r),u=new te(y),{roles:a}=await u.getRolesByApp(t);P(a)}catch(y){console.error("Failed to fetch roles:",y)}finally{A(!1)}})()},[t,r,i.initialRoles]),l.useEffect(()=>{const d=f.getUser();d&&f.hasValidSession()&&h(d)},[f]),s.jsx(he.Provider,{value:$,children:e})}function J(){const i=l.useContext(he);if(!i)throw new Error("useAuth must be used within an AuthProvider");return i}class ge{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/feature-flags/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n,{headers:t});return{featureFlags:o.data,meta:o.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:r})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const r=new URLSearchParams;r.append("tenantId",e),r.append("appId",t);const n=`/tenant-feature-flags${r.toString()?`?${r.toString()}`:""}`;return(await this.httpService.get(n,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,r){if(!e||!t||!r)throw new Error("Flag Key, Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",t),n.append("appId",r);const o=`/tenant-feature-flags/${e}${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const pe=l.createContext(null);function Ee({config:i={},children:e}){const{baseUrl:t,appId:r}=Q(),{tenant:n}=V(),[o,x]=l.useState([]),[P,k]=l.useState(!1),[A,g]=l.useState(null),h=l.useMemo(()=>{const v=new z(t);return new ge(v)},[t]),b=async()=>{if(!(n!=null&&n.id)){x([]);return}k(!0),g(null);try{const v=await h.getTenantFeatureFlags(n.id,r);x(v)}catch(v){const F=v instanceof Error?v.message:"Failed to fetch feature flags";g(F),i.onError&&i.onError(v instanceof Error?v:new Error(F))}finally{k(!1)}};l.useEffect(()=>{b();const v=i.refreshInterval||5*60*1e3,F=setInterval(b,v);return()=>clearInterval(F)},[n==null?void 0:n.id,i.refreshInterval]);const p=l.useMemo(()=>({featureFlags:o,loading:P,error:A,isEnabled:m=>{const w=o.find(j=>j.key===m);return(w==null?void 0:w.value)===!0},getFlag:m=>o.find(w=>w.key===m),getFlagState:m=>{const w=o.find(j=>j.key===m);return w?w.value?"enabled":"disabled":"not_found"},refresh:async()=>{await b()}}),[o,P,A]);return s.jsx(pe.Provider,{value:p,children:e})}function fe(){const i=l.useContext(pe);if(!i)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return i}class me{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:r})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:r})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:r})).data}}const ye=l.createContext(void 0);function Re({config:i={},children:e}){const{baseUrl:t}=Q(),{tenant:r}=V(),[n,o]=l.useState(null),[x,P]=l.useState(!1),[k,A]=l.useState(null),g=l.useMemo(()=>{const p=new z(t);return new me(p)},[t]),h=async()=>{if(!(r!=null&&r.id)){o(null);return}P(!0),A(null);try{const p=await g.getTenantSubscriptionFeatures(r.id);o(p)}catch(p){const v=p instanceof Error?p.message:"Failed to fetch subscription";A(v),i.onError&&i.onError(p instanceof Error?p:new Error(v))}finally{P(!1)}};l.useEffect(()=>{if(h(),!i.refreshInterval)return;const p=i.refreshInterval||10*60*1e3,v=setInterval(h,p);return()=>clearInterval(v)},[r==null?void 0:r.id,i.refreshInterval]);const b=l.useMemo(()=>{const p=(n==null?void 0:n.features)||[];return{subscription:n,features:p,loading:x,error:k,isFeatureEnabled:w=>{const j=p.find(M=>M.key===w);return j?j.type==="BOOLEAN"||j.type==="boolean"?j.value===!0:!!j.value:!1},getFeature:w=>p.find(j=>j.key===w),getFeatureValue:(w,j)=>{const M=p.find(H=>H.key===w);return M?M.value:j},hasAllowedPlan:w=>!n||!n.isActive?!1:w.includes(n.planId),refresh:async()=>{await h()}}},[n,x,k]);return s.jsx(ye.Provider,{value:b,children:e})}function xe(){const i=l.useContext(ye);if(i===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return i}var G=(i=>(i.SUPERUSER="SUPERUSER",i.TENANT_ADMIN="TENANT_ADMIN",i.USER="USER",i))(G||{});const re=()=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[s.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),s.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),s.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),s.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),ne=({userType:i,minUserType:e,missingPermissions:t})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[s.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),s.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&i?s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",s.jsx("strong",{children:e})," access level or higher."]}),s.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",s.jsx("strong",{children:i})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&s.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",s.jsx("strong",{children:t.join(", ")})]})]})]}),Ce=(i,e)=>{const t={[G.USER]:1,[G.TENANT_ADMIN]:2,[G.SUPERUSER]:3};return t[i]>=t[e]};function Ie({children:i,fallback:e,minUserType:t,requiredPermissions:r,requireAllPermissions:n=!1}){const{hasValidSession:o,sessionManager:x,hasPermission:P,hasAnyPermission:k,hasAllPermissions:A}=J();if(!o())return s.jsx(s.Fragment,{children:e||s.jsx(re,{})});const g=x.getUser();if(!g)return s.jsx(s.Fragment,{children:e||s.jsx(re,{})});if(t&&!Ce(g.userType,t))return s.jsx(ne,{userType:g.userType,minUserType:t});if(r&&r.length>0&&!(n?A(r):k(r))){const b=r.filter(p=>!P(p)).map(p=>typeof p=="string"?p:p.name);return s.jsx(ne,{missingPermissions:b})}return s.jsx(s.Fragment,{children:i})}const He=({redirectPath:i})=>s.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:s.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[s.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),s.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),s.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})}),ie=({userType:i,minUserType:e,missingPermissions:t})=>s.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:s.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[s.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),s.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&i?s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",s.jsx("strong",{children:e})," access level or higher."]}),s.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current access level: ",s.jsx("strong",{children:i})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&s.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",s.jsx("strong",{children:t.join(", ")})]})]})]})}),$e=(i,e)=>{const t={[G.USER]:1,[G.TENANT_ADMIN]:2,[G.SUPERUSER]:3};return t[i]>=t[e]};function Le({children:i,redirectTo:e="/login",minUserType:t,requiredPermissions:r,requireAllPermissions:n=!1,fallback:o}){const{hasValidSession:x,sessionManager:P,hasPermission:k,hasAnyPermission:A,hasAllPermissions:g}=J(),h=K.useLocation();if(!x())return o?s.jsx(s.Fragment,{children:o}):s.jsxs(s.Fragment,{children:[s.jsx(He,{redirectPath:e}),s.jsx(K.Navigate,{to:e,state:{from:h.pathname},replace:!0})]});const b=P.getUser();if(!b)return s.jsx(K.Navigate,{to:e,state:{from:h.pathname},replace:!0});if(t&&!$e(b.userType,t))return s.jsx(ie,{userType:b.userType,minUserType:t});if(r&&r.length>0&&!(n?g(r):A(r))){const v=r.filter(F=>!k(F)).map(F=>typeof F=="string"?F:F.name);return s.jsx(ie,{missingPermissions:v})}return s.jsx(s.Fragment,{children:i})}const De=({redirectPath:i})=>s.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:s.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[s.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),s.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),s.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})});function Be({children:i,redirectTo:e="/",fallback:t}){const{tenant:r,isLoading:n,error:o}=V(),x=K.useLocation();return n||o?null:r?s.jsx(s.Fragment,{children:i}):t?s.jsx(s.Fragment,{children:t}):s.jsxs(s.Fragment,{children:[s.jsx(De,{redirectPath:e}),s.jsx(K.Navigate,{to:e,state:{from:x.pathname},replace:!0})]})}const qe=({redirectPath:i})=>s.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:s.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[s.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),s.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),s.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})});function Ue({children:i,redirectTo:e="/dashboard",fallback:t}){const{tenant:r,isLoading:n,error:o}=V(),x=K.useLocation();return n||o?null:r?t?s.jsx(s.Fragment,{children:t}):s.jsxs(s.Fragment,{children:[s.jsx(qe,{redirectPath:e}),s.jsx(K.Navigate,{to:e,state:{from:x.pathname},replace:!0})]}):s.jsx(s.Fragment,{children:i})}const Ne=()=>s.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[s.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),s.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function Oe({children:i,fallback:e=s.jsx(Ne,{}),allowedPlans:t,requiredFeature:r}){const{subscription:n,hasAllowedPlan:o,isFeatureEnabled:x,loading:P}=xe();return P?s.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):n?n.isActive?t&&t.length>0&&!o(t)?s.jsx(s.Fragment,{children:e}):r&&!x(r)?s.jsx(s.Fragment,{children:e}):s.jsx(s.Fragment,{children:i}):s.jsx(s.Fragment,{children:e}):s.jsx(s.Fragment,{children:e})}const ze=({flagName:i})=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[s.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),s.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),s.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',i,'" is disabled']})]});function Ve({name:i,children:e,fallback:t}){const{isEnabled:r,loading:n}=fe();return n?s.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):(console.log(i,r(i)),r(i)?s.jsx(s.Fragment,{children:e}):s.jsx(s.Fragment,{children:t||s.jsx(ze,{flagName:i})}))}const We=()=>s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),Ge=()=>s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[s.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),_e={showPassword:s.jsx(We,{}),hidePassword:s.jsx(Ge,{})},Ye={title:"Sign In",emailLabel:"Email",emailPlaceholder:"Enter your email",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",errorMessage:"Invalid email or password",loadingText:"Signing in..."},Ke={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},inputContainer:{position:"relative",display:"flex",alignItems:"center"},passwordToggle:{position:"absolute",right:"0.75rem",background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"#6b7280",display:"flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",borderRadius:"4px",transition:"background-color 0.15s ease-in-out"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function Qe({copy:i={},styles:e={},icons:t={},onSuccess:r,onError:n,onForgotPassword:o,onSignupClick:x,showForgotPassword:P=!0,showSignupLink:k=!0,className:A}){const[g,h]=l.useState(""),[b,p]=l.useState(""),[v,F]=l.useState(!1),[f,I]=l.useState(!1),[m,w]=l.useState(""),[j,M]=l.useState({}),{login:H}=J(),{tenant:T}=V(),$={...Ye,...i},d={...Ke,...e},y={..._e,...t},u=()=>{const E={};return g.trim()||(E.email=!0),b.trim()||(E.password=!0),M(E),Object.keys(E).length===0},a=async E=>{if(E.preventDefault(),!!u()){if(!(T!=null&&T.id)){w("Tenant not found");return}I(!0),w("");try{const B=await H(g,b,T.id);r==null||r(B)}catch(B){const W=B.message||$.errorMessage;w(W),n==null||n(W)}finally{I(!1)}}},c=E=>({...d.input,...j[E]?d.inputError:{}}),O=()=>({...d.button,...f?d.buttonLoading:{},...!g||!b||f?d.buttonDisabled:{}});return s.jsxs("div",{className:A,style:d.container,children:[s.jsx("h2",{style:d.title,children:$.title}),s.jsxs("form",{onSubmit:a,style:d.form,children:[s.jsxs("div",{style:d.fieldGroup,children:[s.jsx("label",{style:d.label,children:$.emailLabel}),s.jsx("input",{id:"email",name:"email",type:"email",value:g,onChange:E=>{h(E.target.value),j.email&&M(B=>({...B,email:!1}))},placeholder:$.emailPlaceholder,style:c("email"),disabled:f})]}),s.jsxs("div",{style:d.fieldGroup,children:[s.jsx("label",{style:d.label,children:$.passwordLabel}),s.jsxs("div",{style:d.inputContainer,children:[s.jsx("input",{id:"password",name:"password",type:v?"text":"password",value:b,onChange:E=>{p(E.target.value),j.password&&M(B=>({...B,password:!1}))},placeholder:$.passwordPlaceholder,style:{...c("password"),paddingRight:"2.5rem"},disabled:f}),s.jsx("button",{type:"button",onClick:()=>F(!v),style:d.passwordToggle,disabled:f,"aria-label":v?"Hide password":"Show password",children:v?y.hidePassword:y.showPassword})]})]}),s.jsx("button",{type:"submit",disabled:!g||!b||f,style:O(),children:f?$.loadingText:$.submitButton}),m&&s.jsx("div",{style:d.errorText,children:m})]}),(P||k)&&s.jsxs("div",{style:d.linkContainer,children:[P&&s.jsx("a",{onClick:o,style:d.link,children:$.forgotPasswordLink}),P&&k&&s.jsx("div",{style:d.divider,children:"•"}),k&&s.jsxs("div",{children:[s.jsxs("span",{style:d.divider,children:[$.signupText," "]}),s.jsx("a",{onClick:x,style:d.link,children:$.signupLink})]})]})]})}const Je={title:"Create Account",nameLabel:"Full Name",namePlaceholder:"Enter your full name",emailLabel:"Email",emailPlaceholder:"Enter your email",passwordLabel:"Password",passwordPlaceholder:"Enter your password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm your password",tenantNameLabel:"Organization Name",tenantNamePlaceholder:"Enter your organization name",submitButton:"Create Account",loginLink:"Sign in here",loginText:"Already have an account?",errorMessage:"Failed to create account",loadingText:"Creating account...",passwordMismatchError:"Passwords do not match",isAdminLabel:"Create new organization",isAdminDescription:"Check this if you want to create a new organization"},Xe={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function Ze({copy:i={},styles:e={},signupType:t="user",onSuccess:r,onError:n,onLoginClick:o,showLoginLink:x=!0,className:P}){const[k,A]=l.useState(""),[g,h]=l.useState(""),[b,p]=l.useState(""),[v,F]=l.useState(""),[f,I]=l.useState(""),[m,w]=l.useState(!1),[j,M]=l.useState(""),[H,T]=l.useState({}),{signup:$,signupTenantAdmin:d}=J(),{tenant:y}=V(),u={...Je,...i},a={...Xe,...e},c=()=>{const R={};return k.trim()||(R.name=!0),g.trim()||(R.email=!0),b.trim()||(R.password=!0),v.trim()||(R.confirmPassword=!0),t==="tenant"&&!f.trim()&&(R.tenantName=!0),T(R),Object.keys(R).length===0},O=async R=>{if(R.preventDefault(),!!c()){if(b!==v){M(u.passwordMismatchError),T({confirmPassword:!0});return}if(t==="user"&&!(y!=null&&y.id)){M("Tenant not found");return}w(!0),M("");try{let D;t==="tenant"?D=await d(g,k,b,f):D=await $(g,k,b,y.id),r==null||r(D)}catch(D){const _=D.message||u.errorMessage;M(_),n==null||n(_)}finally{w(!1)}}},E=R=>({...a.input,...H[R]?a.inputError:{}}),B=()=>({...a.button,...m?a.buttonLoading:{},...!k||!g||!b||!v||m||t==="tenant"&&!f?a.buttonDisabled:{}}),W=k&&g&&b&&v&&(t==="user"||f);return s.jsxs("div",{className:P,style:a.container,children:[s.jsx("h2",{style:a.title,children:u.title}),s.jsxs("form",{onSubmit:O,style:a.form,children:[s.jsxs("div",{style:a.fieldGroup,children:[s.jsx("label",{style:a.label,children:u.nameLabel}),s.jsx("input",{id:"name",name:"name",type:"text",value:k,onChange:R=>{A(R.target.value),H.name&&T(D=>({...D,name:!1}))},placeholder:u.namePlaceholder,style:E("name"),disabled:m})]}),s.jsxs("div",{style:a.fieldGroup,children:[s.jsx("label",{style:a.label,children:u.emailLabel}),s.jsx("input",{id:"email",name:"email",type:"email",value:g,onChange:R=>{h(R.target.value),H.email&&T(D=>({...D,email:!1}))},placeholder:u.emailPlaceholder,style:E("email"),disabled:m})]}),s.jsxs("div",{style:a.fieldGroup,children:[s.jsx("label",{style:a.label,children:u.passwordLabel}),s.jsx("input",{id:"password",name:"password",type:"password",value:b,onChange:R=>{p(R.target.value),H.password&&T(D=>({...D,password:!1}))},placeholder:u.passwordPlaceholder,style:E("password"),disabled:m})]}),s.jsxs("div",{style:a.fieldGroup,children:[s.jsx("label",{style:a.label,children:u.confirmPasswordLabel}),s.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:v,onChange:R=>{F(R.target.value),H.confirmPassword&&T(D=>({...D,confirmPassword:!1})),j===u.passwordMismatchError&&M("")},placeholder:u.confirmPasswordPlaceholder,style:E("confirmPassword"),disabled:m})]}),t==="tenant"&&s.jsxs("div",{style:a.fieldGroup,children:[s.jsx("label",{style:a.label,children:u.tenantNameLabel}),s.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:f,onChange:R=>{I(R.target.value),H.tenantName&&T(D=>({...D,tenantName:!1}))},placeholder:u.tenantNamePlaceholder,style:E("tenantName"),disabled:m})]}),s.jsx("button",{type:"submit",disabled:!W||m,style:B(),children:m?u.loadingText:u.submitButton}),j&&s.jsx("div",{style:a.errorText,children:j})]}),x&&s.jsxs("div",{style:a.linkContainer,children:[s.jsxs("span",{style:a.divider,children:[u.loginText," "]}),s.jsx("a",{onClick:o,style:a.link,children:u.loginLink})]})]})}const et={title:"Reset Password",subtitle:"Enter your email address and we'll send you a link to reset your password.",emailLabel:"Email",emailPlaceholder:"Enter your email",submitButton:"Send Reset Link",backToLoginLink:"Back to Sign In",successMessage:"Password reset link sent! Check your email.",errorMessage:"Failed to send reset link",loadingText:"Sending...",resetTitle:"Set New Password",resetSubtitle:"Enter your reset token and new password.",tokenLabel:"Reset Token",tokenPlaceholder:"Enter reset token from email",newPasswordLabel:"New Password",newPasswordPlaceholder:"Enter new password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm new password",resetSubmitButton:"Reset Password",resetLoadingText:"Resetting...",resetSuccessMessage:"Password reset successfully!",passwordMismatchError:"Passwords do not match"},tt={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"}};function st({copy:i={},styles:e={},mode:t="request",token:r="",onSuccess:n,onError:o,onBackToLogin:x,onModeChange:P,className:k}){const[A,g]=l.useState(""),[h,b]=l.useState(r),[p,v]=l.useState(""),[F,f]=l.useState(""),[I,m]=l.useState(!1),[w,j]=l.useState(""),[M,H]=l.useState(""),[T,$]=l.useState({}),{requestPasswordReset:d,confirmPasswordReset:y}=J(),{tenant:u}=V(),a={...et,...i},c={...tt,...e},O=()=>{const L={};return A.trim()||(L.email=!0),$(L),Object.keys(L).length===0},E=()=>{const L={};return h.trim()||(L.token=!0),p.trim()||(L.newPassword=!0),F.trim()||(L.confirmPassword=!0),$(L),Object.keys(L).length===0},B=async L=>{if(L.preventDefault(),!!O()){if(!(u!=null&&u.id)){j("Tenant not found");return}m(!0),j(""),H("");try{await d(A,u.id),H(a.successMessage),n==null||n()}catch(q){const U=q.message||a.errorMessage;j(U),o==null||o(U)}finally{m(!1)}}},W=async L=>{if(L.preventDefault(),!!E()){if(p!==F){j(a.passwordMismatchError),$({confirmPassword:!0});return}m(!0),j(""),H("");try{await y(h,p),H(a.resetSuccessMessage),n==null||n()}catch(q){const U=q.message||a.errorMessage;j(U),o==null||o(U)}finally{m(!1)}}},R=L=>({...c.input,...T[L]?c.inputError:{}}),D=()=>({...c.button,...I?c.buttonLoading:{}});if(t==="reset"){const L=h&&p&&F;return s.jsxs("div",{className:k,style:c.container,children:[s.jsx("h2",{style:c.title,children:a.resetTitle}),s.jsx("p",{style:c.subtitle,children:a.resetSubtitle}),s.jsxs("form",{onSubmit:W,style:c.form,children:[s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:a.tokenLabel}),s.jsx("input",{type:"text",value:h,onChange:q=>{b(q.target.value),T.token&&$(U=>({...U,token:!1}))},placeholder:a.tokenPlaceholder,style:R("token"),disabled:I})]}),s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:a.newPasswordLabel}),s.jsx("input",{type:"password",value:p,onChange:q=>{v(q.target.value),T.newPassword&&$(U=>({...U,newPassword:!1}))},placeholder:a.newPasswordPlaceholder,style:R("newPassword"),disabled:I})]}),s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:a.confirmPasswordLabel}),s.jsx("input",{type:"password",value:F,onChange:q=>{f(q.target.value),T.confirmPassword&&$(U=>({...U,confirmPassword:!1})),w===a.passwordMismatchError&&j("")},placeholder:a.confirmPasswordPlaceholder,style:R("confirmPassword"),disabled:I})]}),s.jsx("button",{type:"submit",disabled:!L||I,style:{...D(),...!L||I?c.buttonDisabled:{}},children:I?a.resetLoadingText:a.resetSubmitButton}),w&&s.jsx("div",{style:c.errorText,children:w}),M&&s.jsx("div",{style:c.successText,children:M})]}),s.jsxs("div",{style:c.linkContainer,children:[s.jsx("a",{onClick:x,style:c.link,children:a.backToLoginLink}),P&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),s.jsx("a",{onClick:()=>P("request"),style:c.link,children:"Request New Link"})]})]})]})}const _=A;return s.jsxs("div",{className:k,style:c.container,children:[s.jsx("h2",{style:c.title,children:a.title}),s.jsx("p",{style:c.subtitle,children:a.subtitle}),s.jsxs("form",{onSubmit:B,style:c.form,children:[s.jsxs("div",{style:c.fieldGroup,children:[s.jsx("label",{style:c.label,children:a.emailLabel}),s.jsx("input",{type:"email",value:A,onChange:L=>{g(L.target.value),T.email&&$(q=>({...q,email:!1}))},placeholder:a.emailPlaceholder,style:R("email"),disabled:I})]}),s.jsx("button",{type:"submit",disabled:!_||I,style:{...D(),...!_||I?c.buttonDisabled:{}},children:I?a.loadingText:a.submitButton}),w&&s.jsx("div",{style:c.errorText,children:w}),M&&s.jsx("div",{style:c.successText,children:M})]}),s.jsxs("div",{style:c.linkContainer,children:[s.jsx("a",{onClick:x,style:c.link,children:a.backToLoginLink}),P&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),s.jsx("a",{onClick:()=>P("reset"),style:c.link,children:"I have a token"})]})]})]})}class rt{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const n=`/permissions/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n,{headers:t});return{permissions:o.data,meta:o.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:r})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const n=`/permissions/apps/${e}${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n);return{permissions:o.data,meta:o.meta}}}class nt{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder),e!=null&&e.appId&&r.append("appId",e.appId);const n=`/subscription-plans/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(n,{headers:t});return{plans:o.data,meta:o.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:r})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class it{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class ot{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.lastName?`${e.name} ${e.lastName}`:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([r,n])=>{n!=null&&n!==""&&t.append(r,String(n))}),t}}exports.ApiMappers=ot;exports.AppApiService=oe;exports.AppProvider=ve;exports.AuthApiService=ce;exports.AuthProvider=Fe;exports.FeatureFlag=Ve;exports.FeatureFlagApiService=ge;exports.FeatureFlagProvider=Ee;exports.HealthApiService=it;exports.HttpService=z;exports.LandingRoute=Ue;exports.LoginForm=Qe;exports.PasswordRecoveryForm=st;exports.PermissionApiService=rt;exports.Protected=Ie;exports.ProtectedRoute=Le;exports.RoleApiService=te;exports.SessionManager=le;exports.SignupForm=Ze;exports.SubscriptionApiService=me;exports.SubscriptionGuard=Oe;exports.SubscriptionPlanApiService=nt;exports.SubscriptionProvider=Re;exports.TenantApiService=se;exports.TenantProvider=ke;exports.TenantRoute=Be;exports.UserApiService=de;exports.UserType=G;exports.useApi=Ae;exports.useApp=Q;exports.useAuth=J;exports.useFeatureFlags=fe;exports.useSettings=Me;exports.useSubscription=xe;exports.useTenant=Z;exports.useTenantInfo=V;exports.useTenantSettings=Te;
2
2
  //# sourceMappingURL=index.js.map