@skylabs-digital/react-identity-access 3.0.0 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +439 -352
- package/dist/errors/SessionErrors.d.ts +10 -0
- package/dist/errors/SessionErrors.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +1083 -934
- package/dist/index.es.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/services/AuthApiService.d.ts +1 -0
- package/dist/services/AuthApiService.d.ts.map +1 -1
- package/dist/services/SessionManager.d.ts +10 -3
- package/dist/services/SessionManager.d.ts.map +1 -1
- package/dist/utils/configValidation.d.ts +39 -0
- package/dist/utils/configValidation.d.ts.map +1 -0
- package/dist/utils/jwt.d.ts +25 -0
- package/dist/utils/jwt.d.ts.map +1 -0
- package/package.json +15 -16
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),o=require("react"),re=require("react-router-dom");class oe{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async executeRequest(e,t,s,i){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,c=(i==null?void 0:i.timeout)||this.timeout;let h={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const u=await this.sessionManager.getValidAccessToken();h={...h,Authorization:`Bearer ${u}`}}const v=new AbortController,j=setTimeout(()=>v.abort(),c);try{const u=await fetch(l,{method:e,headers:h,body:s?JSON.stringify(s):void 0,signal:v.signal});if(clearTimeout(j),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);const S=u.headers.get("content-type");return!S||!S.includes("application/json")?{}:await u.json()}catch(u){throw clearTimeout(j),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${c}ms`):u}}async get(e,t){return this.executeRequest("GET",e,void 0,t)}async post(e,t,s){return this.executeRequest("POST",e,t,s)}async put(e,t,s){return this.executeRequest("PUT",e,t,s)}async delete(e,t){return this.executeRequest("DELETE",e,void 0,t)}}function ne(n){if(!n)return"";const e=new URLSearchParams;for(const[s,i]of Object.entries(n))i!=null&&i!==""&&e.append(s,String(i));const t=e.toString();return t?`?${t}`:""}class Ee{constructor(e){this.httpService=e}async createApp(e){return(await this.httpService.post("/apps/",e)).data}async getApps(e){const t=await this.httpService.get(`/apps/${ne(e)}`);return{apps:t.data,meta:t.meta}}async getAppById(e){return(await this.httpService.get(`/apps/${e}`)).data}async updateApp(e,t){return(await this.httpService.put(`/apps/${e}`,t)).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`,{skipAuth:!0})).data}async setDefaultSubscriptionPlan(e,t){return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t})).data}async updateSettingsSchema(e,t,s){return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s})).data}async exportConfig(e){return(await this.httpService.get(`/apps/${e}/export-config`)).data}}const je=o.createContext(null),pt=5*60*1e3;function ft({config:n,children:e}){var T,m,g;const{appId:t,baseUrl:s}=n,i=((T=n.cache)==null?void 0:T.enabled)??!0,l=((m=n.cache)==null?void 0:m.ttl)??pt,c=((g=n.cache)==null?void 0:g.storageKey)??`app_cache_${t}`,[h,v]=o.useState(()=>{if(!i)return null;try{const b=localStorage.getItem(c);if(!b)return null;const L=JSON.parse(b);return Date.now()-L.timestamp<l&&L.appId===t?L.data:(localStorage.removeItem(c),null)}catch{return null}}),[j,u]=o.useState(!h),[S,p]=o.useState(null),E=o.useRef(h);E.current=h;const P=o.useCallback(async(b=!1)=>{if(!(!b&&i&&E.current))try{u(!0),p(null);const a=await new Ee(new oe(s)).getPublicAppInfo(t);if(v(a),i)try{const f={data:a,timestamp:Date.now(),appId:t};localStorage.setItem(c,JSON.stringify(f))}catch(f){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",f)}}catch(L){const a=L instanceof Error?L:new Error("Failed to load app information");p(a),v(null)}finally{u(!1)}},[s,t,i,c]),R=o.useCallback(async()=>{if(!(!i||!E.current))try{const b=localStorage.getItem(c);if(!b)return;const L=JSON.parse(b);if(Date.now()-L.timestamp<=l*.5)return;const f=await new Ee(new oe(s)).getPublicAppInfo(t);v(f);const k={data:f,timestamp:Date.now(),appId:t};localStorage.setItem(c,JSON.stringify(k))}catch(b){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",b)}},[s,t,i,l,c]),A=o.useMemo(()=>({appId:t,baseUrl:s,appInfo:h,isAppLoading:j,appError:S,retryApp:()=>{P(!0)}}),[t,s,h,j,S,P]);return o.useEffect(()=>{E.current?R():P()},[]),r.jsx(je.Provider,{value:A,children:e})}function de(){const n=o.useContext(je);if(!n)throw new Error("useApp must be used within an AppProvider");return n}function Ae(){return o.useContext(je)}const mt=de;class H extends Error{constructor(e,t){const s={token_expired:"Refresh token has expired",token_invalid:"Refresh token is invalid",user_inactive:"User account is inactive"};super(t||s[e]),this.name="SessionExpiredError",this.reason=e}}class Ge extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class Ze extends Error{constructor(e,t){super(`Token refresh failed after ${e} attempts: ${(t==null?void 0:t.message)||"Unknown error"}`),this.name="TokenRefreshError",this.attempts=e,this.lastError=t}}const Q=class Q{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,this.consecutiveBackgroundFailures=0,this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.onSessionExpired=e.onSessionExpired,this.baseUrl=e.baseUrl||"",this.enableCookieSession=e.enableCookieSession??!1,this.proactiveRefreshMargin=e.proactiveRefreshMargin??6e4,this.refreshQueueTimeout=e.refreshQueueTimeout??1e4,this.maxRefreshRetries=e.maxRefreshRetries??3,this.retryBackoffBase=e.retryBackoffBase??1e3,this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey),this.scheduleProactiveRefresh()}static getInstance(e={}){const t=Q.resolveStorageKey(e),s=Q.instances.get(t);if(s)return s.updateConfig(e),s;const i=new Q(e);return Q.instances.set(t,i),i}static resetAllInstances(){for(const e of Q.instances.values())e.destroy();Q.instances.clear()}static resolveStorageKey(e){return e.storageKey||"auth_tokens"}updateConfig(e){e.onSessionExpired!==void 0&&(this.onSessionExpired=e.onSessionExpired),e.onRefreshFailed!==void 0&&(this.onRefreshFailed=e.onRefreshFailed),e.baseUrl&&(this.baseUrl=e.baseUrl),e.enableCookieSession!==void 0&&(this.enableCookieSession=e.enableCookieSession)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}static decodeJwtPayload(e){try{const t=e.split(".");return t.length!==3?null:JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}static extractJwtExpiry(e){const t=Q.decodeJwtPayload(e);return typeof(t==null?void 0:t.exp)=="number"?t.exp*1e3:void 0}static extractJwtClaim(e,t){const s=Q.decodeJwtPayload(e),i=s==null?void 0:s[t];return typeof i=="string"?i:void 0}setTokens(e){const t=e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)||Q.extractJwtExpiry(e.accessToken),s={...e,expiresAt:t},i=this.tokenStorage.get()||{};this.tokenStorage.set({...i,...s}),this.scheduleProactiveRefresh()}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:i,tokenType:l}=this.tokenStorage.get()||{};if(!e)return null;const c=s||Q.extractJwtExpiry(e);return{accessToken:e,refreshToken:t,expiresAt:c,expiresIn:i,tokenType:l}}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}scheduleProactiveRefresh(){if(this.cancelProactiveTimer(),!this.autoRefresh||this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.expiresAt)||!e.refreshToken)return;const s=e.expiresAt-this.proactiveRefreshMargin-Date.now();if(s<=0){this.backgroundRefresh();return}this.proactiveTimerId=setTimeout(()=>{this.backgroundRefresh()},s)}cancelProactiveTimer(){this.proactiveTimerId!==null&&(clearTimeout(this.proactiveTimerId),this.proactiveTimerId=null),this.backgroundRetryTimerId!==null&&(clearTimeout(this.backgroundRetryTimerId),this.backgroundRetryTimerId=null)}backgroundRefresh(){if(this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.refreshToken)||this.refreshPromise)return;const t=this.sessionGeneration;this.startRefreshAndResolveQueue(e.refreshToken).then(()=>{this.consecutiveBackgroundFailures=0}).catch(s=>{if(!(s instanceof H)){if(this.sessionGeneration===t){if(this.consecutiveBackgroundFailures++,this.consecutiveBackgroundFailures>=Q.MAX_BACKGROUND_FAILURES){process.env.NODE_ENV==="development"&&console.error(`[SessionManager] Background refresh failed ${this.consecutiveBackgroundFailures} consecutive times — expiring session`),this.consecutiveBackgroundFailures=0,this.handleSessionExpired(new H("token_invalid","Background refresh failed repeatedly"));return}process.env.NODE_ENV==="development"&&console.warn("[SessionManager] Background refresh failed, retrying in 30s:",s.message),this.backgroundRetryTimerId=setTimeout(()=>{this.backgroundRefresh()},3e4)}}})}async waitForPendingRefresh(){if(!this.refreshPromise)return!1;try{return await this.refreshPromise,!0}catch{return!1}}async attemptCookieSessionRestore(){if(!this.enableCookieSession||!this.baseUrl)return!1;const e=`${this.baseUrl}/auth/refresh`;try{const t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),credentials:"include"});if(!t.ok)return!1;const s=await t.json();return s.accessToken?(this.setTokens({accessToken:s.accessToken,refreshToken:s.refreshToken||"",expiresIn:s.expiresIn}),!0):!1}catch{return!1}}async getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new H("token_invalid","No tokens available");throw this.handleSessionExpired(t),t}if(!this.shouldRefreshToken(e)&&!this.isTokenExpired(e))return e.accessToken;if(!e.refreshToken){const t=new H("token_invalid","No refresh token available");throw this.handleSessionExpired(t),t}return this.refreshPromise?this.enqueueForToken():this.startRefreshAndResolveQueue(e.refreshToken)}async getAuthHeaders(){try{return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}catch(e){return e instanceof H&&this.onRefreshFailed&&this.onRefreshFailed(),{}}}enqueueForToken(){return new Promise((e,t)=>{const s=setTimeout(()=>{const i=this.refreshQueue.findIndex(l=>l.timeoutId===s);i!==-1&&this.refreshQueue.splice(i,1),t(new Ge(this.refreshQueueTimeout))},this.refreshQueueTimeout);this.refreshQueue.push({resolve:e,reject:t,timeoutId:s})})}async startRefreshAndResolveQueue(e){this.refreshPromise=this.executeRefreshWithRetry(e);try{await this.refreshPromise;const t=this.getTokens(),s=(t==null?void 0:t.accessToken)||"";return this.resolveQueue(s),s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");throw s instanceof H?(this.rejectQueue(s),this.handleSessionExpired(s)):this.rejectQueue(s),s}finally{this.refreshPromise=null}}resolveQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const s of t)clearTimeout(s.timeoutId),s.resolve(e)}rejectQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const s of t)clearTimeout(s.timeoutId),s.reject(e)}async executeRefreshWithRetry(e){let t;const s=this.sessionGeneration;for(let i=0;i<=this.maxRefreshRetries;i++){if(this.sessionGeneration!==s)throw new H("token_invalid","Session cleared during refresh");try{await this.performTokenRefresh(e,s);return}catch(l){const c=l instanceof Error?l:new Error(String(l));if(c instanceof H)throw c;if(t=c,i<this.maxRefreshRetries){const h=this.retryBackoffBase*Math.pow(2,i);await this.sleep(h)}}}throw new Ze(this.maxRefreshRetries+1,t)}async performTokenRefresh(e,t){return typeof navigator<"u"&&navigator.locks?navigator.locks.request(`session-refresh:${this.storageKey}`,()=>this.performTokenRefreshInner(e,t)):this.performTokenRefreshInner(e,t)}async performTokenRefreshInner(e,t){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const s=this.getTokens();if(s!=null&&s.accessToken&&!this.isTokenExpired(s)&&!this.shouldRefreshToken(s))return;const i=(s==null?void 0:s.refreshToken)||e,l=`${this.baseUrl}/auth/refresh`,c=Q.extractJwtClaim(i,"deviceId"),h={refreshToken:i};c&&(h.deviceId=c);let v;try{v=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),...this.enableCookieSession&&{credentials:"include"}})}catch(u){throw u instanceof Error?u:new Error("Network error during token refresh")}if(!v.ok){let u="";try{const S=await v.json();u=(S.message||S.error||"").toLowerCase()}catch{u=v.statusText.toLowerCase()}throw v.status===401?u.includes("expired")?new H("token_expired"):u.includes("invalid")?new H("token_invalid"):new H("token_invalid",`Unauthorized: ${u}`):v.status===400?u.includes("inactive")?new H("user_inactive"):u.includes("expired")||u.includes("invalid")?new H("token_invalid",u):u.includes("reuse")||u.includes("revoked")?new H("token_invalid",u):new Error(`Token refresh failed (400): ${u}`):new Error(`Token refresh failed: ${v.status} ${u}`)}if(this.sessionGeneration!==t)throw new H("token_invalid","Session cleared during refresh");const j=await v.json();this.setTokens({accessToken:j.accessToken,refreshToken:j.refreshToken||i,expiresIn:j.expiresIn})}handleSessionExpired(e){this.cancelProactiveTimer(),this.clearSession(),this.onSessionExpired?this.onSessionExpired(e):this.onRefreshFailed&&this.onRefreshFailed()}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.sessionGeneration++,this.cancelProactiveTimer(),this.clearTokens();const e=new H("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,Q.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new H("token_invalid","SessionManager destroyed");this.rejectQueue(e)}getTokenPayload(){var t;const e=(t=this.getTokens())==null?void 0:t.accessToken;return e?Q.decodeJwtPayload(e)??null:null}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};Q.instances=new Map,Q.MAX_BACKGROUND_FAILURES=3;let me=Q;class He{constructor(e){this.httpService=e,this.pendingVerifications=new Map}async login(e){return await this.httpService.post("/auth/login",e)}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 switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(){return this.httpService.get("/auth/tenants")}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){const t=e.token,s=this.pendingVerifications.get(t);if(s)return s;const i=this.httpService.post("/auth/magic-link/verify",e).finally(()=>{this.pendingVerifications.delete(t)});return this.pendingVerifications.set(t,i),i}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e){await this.httpService.post("/auth/change-password",e)}}class Qe{constructor(e){this.httpService=e}async createRole(e){return(await this.httpService.post("/roles/",e)).data}async getRoleById(e){return(await this.httpService.get(`/roles/${e}`)).data}async updateRole(e,t){return(await this.httpService.put(`/roles/${e}`,t)).data}async deleteRole(e){await this.httpService.delete(`/roles/${e}`)}async getRolesByApp(e,t){const s=await this.httpService.get(`/roles/app/${e}${ne(t)}`,{skipAuth:!0});return{roles:s.data,meta:s.meta}}async assignRole(e,t){await this.httpService.post(`/roles/${e}/assign`,t)}async revokeRole(e,t){await this.httpService.post(`/roles/${e}/revoke`,t)}async getUserRoles(e,t){const s=await this.httpService.get(`/roles/user/${e}${ne(t)}`);return{roles:s.data,meta:s.meta}}}class Je{constructor(e){this.httpService=e}async createUser(e){return(await this.httpService.post("/users/",e)).data}async getUsers(e){const t=await this.httpService.get(`/users/${ne(e)}`);return{users:t.data,meta:t.meta}}async getUserById(e){return(await this.httpService.get(`/users/${e}`)).data}async updateUser(e,t){return(await this.httpService.put(`/users/${e}`,t)).data}async deleteUser(e){await this.httpService.delete(`/users/${e}`)}}class le{constructor(e,t){this.httpService=e,this.appId=t}async createTenant(e){return(await this.httpService.post("/tenants/",e)).data}async getTenants(e){const t=await this.httpService.get(`/tenants/${ne(e)}`);return{tenants:t.data,meta:t.meta}}async getTenantById(e){return(await this.httpService.get(`/tenants/${e}`)).data}async updateTenant(e,t){return(await this.httpService.put(`/tenants/${e}`,t)).data}async adminUpdateTenant(e,t){return(await this.httpService.put(`/tenants/${e}/admin-update`,t)).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`,{skipAuth:!0})).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`,{skipAuth:!0})).data}async updateTenantSettings(e,t){return(await this.httpService.put(`/tenants/${e}/settings`,t)).data}}function gt(n,e){if(n==="localhost"||n.startsWith("127.")||n.startsWith("192.168."))return null;if(e){const i=e.toLowerCase(),l=n.toLowerCase();if(l===i||l===`www.${i}`)return null;if(l.endsWith(`.${i}`)){const c=l.slice(0,-(i.length+1));return c==="www"?null:c}return null}const s=n.split(".");return s.length>=3&&s[0]!=="www"?s[0]:null}function yt(n,e="tenant",t){const i=new URLSearchParams(n).get(e);return i?(t&&t.setItem("tenant",i),i):t?t.getItem("tenant"):null}function bt(n,e,t){const{tenantMode:s,baseDomain:i,selectorParam:l,fixedTenantSlug:c}=n;return s==="fixed"?c||null:s==="subdomain"?gt(e.hostname,i):s==="selector"?yt(e.search,l,t):null}function xt(n,e,t){if(t)return`${n}.${t}`;const s=e.split(".");return s.length===2?`${n}.${e}`:s.length>=3?(s[0]=n,s.join(".")):null}const Pe=o.createContext(null);function wt({config:n,children:e}){var _,Z,M;const{baseUrl:t,appInfo:s,appId:i}=de(),l=o.useCallback(()=>typeof window>"u"?null:bt({tenantMode:n.tenantMode||"selector",baseDomain:n.baseDomain,selectorParam:n.selectorParam,fixedTenantSlug:n.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[n.tenantMode,n.baseDomain,n.selectorParam,n.fixedTenantSlug]),[c,h]=o.useState(()=>l()),v=((_=n.cache)==null?void 0:_.enabled)??!0,j=((Z=n.cache)==null?void 0:Z.ttl)??5*60*1e3,u=((M=n.cache)==null?void 0:M.storageKey)??`tenant_cache_${c||"default"}`,S=o.useMemo(()=>({enabled:v,ttl:j,storageKey:u}),[v,j,u]),[p,E]=o.useState(()=>{if(n.initialTenant)return n.initialTenant;if(!S.enabled||!c)return null;try{const D=localStorage.getItem(S.storageKey);if(!D)return null;const F=JSON.parse(D);return Date.now()-F.timestamp<S.ttl&&F.tenantSlug===c?F.data:(localStorage.removeItem(S.storageKey),null)}catch{return null}}),[P,R]=o.useState(!p&&!n.initialTenant),[A,T]=o.useState(null),[m,g]=o.useState(null),[b,L]=o.useState(!1),[a,f]=o.useState(null);o.useEffect(()=>{if(n.tenantMode==="fixed")return;const D=l();h(D)},[l,n.tenantMode]);const k=(s==null?void 0:s.settingsSchema)||null,y=o.useCallback(async(D,F=!1)=>{if(!(!F&&S.enabled&&p&&p.subdomain===D))try{R(!0),T(null);const B=new oe(t),q=await new le(B,i).getPublicTenantInfo(D);if(E(q),S.enabled)try{const J={data:q,timestamp:Date.now(),tenantSlug:D};localStorage.setItem(S.storageKey,JSON.stringify(J))}catch(J){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",J)}}catch(B){const U=B instanceof Error?B:new Error("Failed to load tenant information");T(U),E(null)}finally{R(!1)}},[t,i,S,p]),d=o.useCallback(async()=>{if(!(!S.enabled||!p||!c))try{const D=localStorage.getItem(S.storageKey);if(!D)return;const F=JSON.parse(D);if(Date.now()-F.timestamp>S.ttl*.5){const U=new oe(t),J=await new le(U,i).getPublicTenantInfo(c);E(J);const K={data:J,timestamp:Date.now(),tenantSlug:c};localStorage.setItem(S.storageKey,JSON.stringify(K))}}catch(D){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",D)}},[t,i,S,p,c]),w=o.useCallback(async()=>{if(p!=null&&p.id)try{L(!0),f(null);const D=new oe(t),B=await new le(D,p.appId).getTenantSettings(p.id);g(B)}catch(D){const F=D instanceof Error?D:new Error("Failed to load tenant settings");f(F),g(null)}finally{L(!1)}},[t,p]),N=o.useCallback(()=>{w()},[w]),X=o.useCallback(D=>{if(!k)return{isValid:!0,errors:[]};const F=[];try{return k.properties&&Object.entries(k.properties).forEach(([B,U])=>{var J;const q=D[B];if((J=k.required)!=null&&J.includes(B)&&q==null){F.push(`Field '${B}' is required`);return}if(q!=null){if(U.type){const K=U.type,te=typeof q;K==="string"&&te!=="string"?F.push(`Field '${B}' must be a string`):(K==="number"||K==="integer")&&te!=="number"?F.push(`Field '${B}' must be a number`):K==="boolean"&&te!=="boolean"?F.push(`Field '${B}' must be a boolean`):K==="array"&&!Array.isArray(q)&&F.push(`Field '${B}' must be an array`)}U.minLength!==void 0&&typeof q=="string"&&q.length<U.minLength&&F.push(`Field '${B}' must be at least ${U.minLength} characters long`),U.maxLength!==void 0&&typeof q=="string"&&q.length>U.maxLength&&F.push(`Field '${B}' must be no more than ${U.maxLength} characters long`),U.minimum!==void 0&&typeof q=="number"&&q<U.minimum&&F.push(`Field '${B}' must be at least ${U.minimum}`),U.maximum!==void 0&&typeof q=="number"&&q>U.maximum&&F.push(`Field '${B}' must be no more than ${U.maximum}`),U.pattern&&typeof q=="string"&&(new RegExp(U.pattern).test(q)||F.push(`Field '${B}' does not match the required pattern`)),U.enum&&!U.enum.includes(q)&&F.push(`Field '${B}' must be one of: ${U.enum.join(", ")}`)}}),{isValid:F.length===0,errors:F}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[k]);o.useEffect(()=>{!n.initialTenant&&c?p?d():y(c):!n.initialTenant&&!c&&(E(null),T(null),R(!1))},[n.initialTenant,c,p,y,d]),o.useEffect(()=>{p!=null&&p.id?w():(g(null),f(null),L(!1))},[p==null?void 0:p.id,w]);const I=o.useCallback((D,F)=>{const{mode:B="reload",redirectPath:U}=F||{},q=n.tenantMode||"selector";if(q==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",n.fixedTenantSlug),U&&(window.location.href=U);return}if(localStorage.setItem("tenant",D),q==="subdomain"){const J=window.location.hostname,K=xt(D,J,n.baseDomain);if(!K){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",J);return}const te=U||window.location.pathname,he=new URL(`${window.location.protocol}//${K}${te}`);new URLSearchParams(window.location.search).forEach((ve,Se)=>{he.searchParams.set(Se,ve)}),window.location.href=he.toString()}else if(q==="selector"){const J=U||window.location.pathname,K=new URLSearchParams(window.location.search);if(K.set(n.selectorParam||"tenant",D),B==="reload"){const te=`${J}?${K.toString()}${window.location.hash}`;window.location.href=te}else{const te=`${J}?${K.toString()}${window.location.hash}`;window.history.pushState({},"",te),h(D),y(D)}}},[n.tenantMode,n.selectorParam,n.baseDomain,n.fixedTenantSlug,y]),z=o.useMemo(()=>({tenant:p,tenantSlug:c,isTenantLoading:P,tenantError:A,retryTenant:()=>{c&&y(c)},settings:m,settingsSchema:k,isSettingsLoading:b,settingsError:a,refreshSettings:N,switchTenant:I,validateSettings:X}),[p,c,P,A,m,k,b,a,N,I,X]);return r.jsx(Pe.Provider,{value:z,children:e})}function ce(){const n=o.useContext(Pe);if(!n)throw new Error("useTenant must be used within a TenantProvider");return n}function ae(){return o.useContext(Pe)}const vt=ce;function St(){const{settings:n,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:i}=ce();return{settings:n,settingsSchema:e,isLoading:t,error:s,validateSettings:i}}function Re(){const{tenant:n,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:i}=ce();return{tenant:n,tenantSlug:e,isLoading:t,error:s,retry:i}}const Fe="userTenants";function Tt(){try{const n=localStorage.getItem(Fe);return n?JSON.parse(n):[]}catch{return[]}}function Be(n){try{localStorage.setItem(Fe,JSON.stringify(n))}catch{}}function Oe(){try{localStorage.removeItem(Fe)}catch{}}const ge=o.createContext(null),ye=o.createContext(null);function kt({config:n={},children:e}){const t=Ae(),s=ae(),i=(t==null?void 0:t.baseUrl)??n.baseUrl??"",l=(t==null?void 0:t.appId)??n.appId,c=(s==null?void 0:s.tenant)??null,h=(s==null?void 0:s.tenantSlug)??null,v=(s==null?void 0:s.switchTenant)??(()=>{});if(!i)throw new Error("[AuthProvider] baseUrl is required. Provide it via AppProvider or AuthConfig.baseUrl.");const[j,u]=o.useState(n.initialRoles||[]),[S,p]=o.useState(!n.initialRoles),[E,P]=o.useState(null),[R,A]=o.useState(!1),[T,m]=o.useState(null),[g,b]=o.useState(()=>Tt()),L=o.useRef({done:!1});L.current.done||(L.current.done=!0);const a=o.useMemo(()=>me.getInstance({baseUrl:i,enableCookieSession:n.enableCookieSession,refreshQueueTimeout:n.refreshQueueTimeout,proactiveRefreshMargin:n.proactiveRefreshMargin,onSessionExpired:x=>{P(null),m(null),b([]),Oe(),n.onSessionExpired?n.onSessionExpired(x):n.onRefreshFailed&&n.onRefreshFailed()}}),[i,n.enableCookieSession,n.refreshQueueTimeout,n.proactiveRefreshMargin]),[f,k]=o.useState(()=>{const x=a.getTokens();return x?a.hasValidSession()||!!x.refreshToken:!!n.enableCookieSession}),y=L.current.done&&!f,d=o.useMemo(()=>{const x=new oe(i);return x.setSessionManager(a),x},[i,a]),w=o.useMemo(()=>new He(d),[d]),N=o.useMemo(()=>new Je(d),[d]),X=o.useMemo(()=>new Qe(d),[d]),I=o.useMemo(()=>E!=null&&E.roleId&&j.find(x=>x.id===E.roleId)||null,[E,j]),z=o.useMemo(()=>(I==null?void 0:I.permissions)||[],[I]),_=o.useMemo(()=>a.hasValidSession()&&E!==null,[a,E]),Z=o.useMemo(()=>(E==null?void 0:E.tenantId)!=null,[E]),M=o.useRef(null),D=async(x=!1)=>{try{if(!a.hasValidSession()||!x&&E)return;const C=a.getUserId();if(!C){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}A(!0),m(null);const O=await N.getUserById(C);P(O),a.setUser(O)}catch(C){const O=C instanceof Error?C:new Error("Failed to load user data");m(O),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",O)}finally{A(!1)}},F=async x=>{var Ue;const{username:C,password:O,tenantSlug:$,redirectPath:W}=x;let Y=c==null?void 0:c.id,G=h;$&&(Y=(await new le(d,l).getPublicTenantInfo($)).id,G=$);const V=await w.login({username:C,password:O,appId:l,tenantId:Y}),pe=$&&$!==h;if(a.setTokens({accessToken:V.accessToken,refreshToken:V.refreshToken,expiresIn:V.expiresIn}),V.user){a.setUser(V.user),P(V.user);try{await D()}catch(fe){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",fe)}}V.tenants&&V.tenants.length>0&&(b(V.tenants),Be(V.tenants));const De=((Ue=V.user)==null?void 0:Ue.tenantId)!==null;if(pe&&G)return v(G,{redirectPath:W}),V;if(W&&W!==window.location.pathname)return v(G||h||"",{redirectPath:W}),V;if(!De&&V.tenants&&V.tenants.length>0){const fe=x.autoSwitch!==!1&&n.autoSwitchSingleTenant!==!1;if(V.tenants.length===1&&fe){const $e=V.tenants[0];return v($e.subdomain,{redirectPath:W}),V}else V.tenants.length>1&&n.onTenantSelectionRequired&&n.onTenantSelectionRequired(V.tenants)}return V},B=async x=>{const{email:C,phoneNumber:O,name:$,password:W,lastName:Y,tenantId:G}=x;if(!C&&!O)throw new Error("Either email or phoneNumber is required");if(!$||!W)throw new Error("Name and password are required");return w.signup({email:C,phoneNumber:O,name:$,password:W,tenantId:G??(c==null?void 0:c.id),lastName:Y,appId:l})},U=async x=>{const{email:C,phoneNumber:O,name:$,password:W,tenantName:Y,lastName:G}=x;if(!C&&!O)throw new Error("Either email or phoneNumber is required");if(!$||!W||!Y)throw new Error("Name, password, and tenantName are required");return w.signupTenantAdmin({email:C,phoneNumber:O,name:$,password:W,tenantName:Y,appId:l,lastName:G})},q=async x=>{await w.changePassword(x)},J=async x=>{const{email:C,tenantId:O}=x,$=O??(c==null?void 0:c.id);if(!$)throw new Error("tenantId is required for password reset");await w.requestPasswordReset({email:C,tenantId:$})},K=async x=>{await w.confirmPasswordReset(x)},te=async x=>{const{email:C,frontendUrl:O,name:$,lastName:W,tenantId:Y}=x,G=Y??(c==null?void 0:c.id);if(!G)throw new Error("tenantId is required for magic link authentication");return w.sendMagicLink({email:C,tenantId:G,frontendUrl:O,name:$,lastName:W,appId:l})},he=async x=>{const{token:C,email:O,tenantSlug:$}=x;let W=c==null?void 0:c.id,Y=h;$&&(W=(await new le(d,l).getPublicTenantInfo($)).id,Y=$);const G=await w.verifyMagicLink({token:C,email:O,appId:l,tenantId:W}),V=$&&$!==h;if(a.setTokens({accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn}),G.user){a.setUser(G.user),P(G.user);try{await D()}catch(pe){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",pe)}}return V&&Y&&Y!==h&&v(Y),G},Me=async()=>{const x=a.getTokens();if(!(x!=null&&x.refreshToken))throw new Error("No refresh token available");const C=await w.refreshToken({refreshToken:x.refreshToken});a.setTokens({accessToken:C.accessToken,refreshToken:C.refreshToken||x.refreshToken,expiresIn:C.expiresIn})},ve=()=>{a.clearSession(),P(null),m(null),b([]),Oe()},Se=x=>{a.setTokens(x)},ot=()=>a.hasValidSession(),at=()=>{a.clearSession(),P(null),m(null)},lt=async()=>{if(l)try{p(!0);const{roles:x}=await X.getRolesByApp(l);u(x)}catch(x){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",x)}finally{p(!1)}},ct=async(x,C)=>{const{redirectPath:O}=C||{},$=a.getTokens();if(!($!=null&&$.refreshToken))throw new Error("No refresh token available for tenant switch");const W=await w.switchTenant({refreshToken:$.refreshToken,tenantId:x});a.setTokens({accessToken:W.accessToken,refreshToken:$.refreshToken,expiresIn:W.expiresIn}),P(W.user),a.setUser(W.user);const Y=g.find(G=>G.id===x);Y&&v(Y.subdomain,{redirectPath:O})},ut=async()=>{const x=await w.getUserTenants();return b(x),Be(x),x};M.current={login:F,signup:B,signupTenantAdmin:U,sendMagicLink:te,verifyMagicLink:he,changePassword:q,requestPasswordReset:J,confirmPasswordReset:K,refreshToken:Me,logout:ve,setTokens:Se,hasValidSession:ot,clearSession:at,loadUserData:D,refreshUser:()=>D(),refreshRoles:lt,switchToTenant:ct,refreshUserTenants:ut};const dt=o.useMemo(()=>({login:x=>M.current.login(x),signup:x=>M.current.signup(x),signupTenantAdmin:x=>M.current.signupTenantAdmin(x),sendMagicLink:x=>M.current.sendMagicLink(x),verifyMagicLink:x=>M.current.verifyMagicLink(x),changePassword:x=>M.current.changePassword(x),requestPasswordReset:x=>M.current.requestPasswordReset(x),confirmPasswordReset:x=>M.current.confirmPasswordReset(x),refreshToken:()=>M.current.refreshToken(),logout:()=>M.current.logout(),setTokens:x=>M.current.setTokens(x),hasValidSession:()=>M.current.hasValidSession(),clearSession:()=>M.current.clearSession(),loadUserData:x=>M.current.loadUserData(x),refreshUser:()=>M.current.refreshUser(),refreshRoles:()=>M.current.refreshRoles(),switchToTenant:(x,C)=>M.current.switchToTenant(x,C),refreshUserTenants:()=>M.current.refreshUserTenants()}),[]),ht=o.useMemo(()=>{const x=C=>!z||z.length===0?!1:typeof C=="string"?z.includes(C):z.includes(`${C.resource}.${C.action}`);return{isAuthenticated:_,isAuthInitializing:!y,isAuthReady:y,currentUser:E,isUserLoading:R,userError:T,userRole:I,userPermissions:z,availableRoles:j,rolesLoading:S,userTenants:g,hasTenantContext:Z,sessionManager:a,authenticatedHttpService:d,hasPermission:x,hasAnyPermission:C=>C.some(O=>x(O)),hasAllPermissions:C=>C.every(O=>x(O)),getUserPermissionStrings:()=>z||[]}},[_,y,E,R,T,I,z,j,S,g,Z,a,d]);return o.useEffect(()=>{if(n.initialRoles||!l)return;let x=!1;return p(!0),X.getRolesByApp(l).then(({roles:C})=>{x||u(C)}).catch(C=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",C)}).finally(()=>{x||p(!1)}),()=>{x=!0}},[l,n.initialRoles,X]),o.useEffect(()=>{let x=!1;return(async()=>{var $;if(!a.hasValidSession()&&(($=a.getTokens())!=null&&$.refreshToken)&&await a.waitForPendingRefresh(),x||!a.hasValidSession()&&!a.getTokens()&&n.enableCookieSession&&(await a.attemptCookieSessionRestore(),x))return;const O=a.getUser();O&&a.hasValidSession()&&P(O),k(!1)})(),()=>{x=!0}},[a,n.enableCookieSession]),o.useEffect(()=>{!E&&!R&&!T&&a.hasValidSession()?M.current.loadUserData().catch(()=>{}).finally(()=>{k(!1)}):k(!1)},[E,R,T,a]),r.jsx(ye.Provider,{value:dt,children:r.jsx(ge.Provider,{value:ht,children:e})})}function Et(){const n=o.useContext(ge);if(!n)throw new Error("useAuthState must be used within an AuthProvider");return n}function jt(){const n=o.useContext(ye);if(!n)throw new Error("useAuthActions must be used within an AuthProvider");return n}function ie(){const n=o.useContext(ge),e=o.useContext(ye);if(!n||!e)throw new Error("useAuth must be used within an AuthProvider");return o.useMemo(()=>({...n,...e}),[n,e])}function be(){const n=o.useContext(ge),e=o.useContext(ye);return o.useMemo(()=>!n||!e?null:{...n,...e},[n,e])}class Ke{constructor(e){this.httpService=e}async createFeatureFlag(e){return(await this.httpService.post("/feature-flags/",e)).data}async getFeatureFlags(e){const t=await this.httpService.get(`/feature-flags/${ne(e)}`);return{featureFlags:t.data,meta:t.meta}}async getFeatureFlagById(e){return(await this.httpService.get(`/feature-flags/${e}`)).data}async updateFeatureFlag(e,t){return(await this.httpService.put(`/feature-flags/${e}`,t)).data}async deleteFeatureFlag(e){await this.httpService.delete(`/feature-flags/${e}`)}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const s=ne({tenantId:e,appId:t});return(await this.httpService.get(`/tenant-feature-flags${s}`,{headers:{"X-Tenant-ID":e},skipAuth:!0})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const i=ne({tenantId:t,appId:s});return(await this.httpService.get(`/tenant-feature-flags/${e}${i}`,{headers:{"X-Tenant-ID":t},skipAuth:!0})).data}}const Ie=o.createContext(null);function At({config:n={},children:e}){const t=Ae(),s=ae(),i=(t==null?void 0:t.baseUrl)??"",l=(t==null?void 0:t.appId)??"",c=(s==null?void 0:s.tenant)??null,[h,v]=o.useState([]),[j,u]=o.useState(!1),[S,p]=o.useState(null),[E,P]=o.useState(!1),R=o.useMemo(()=>{const m=new oe(i);return new Ke(m)},[i]),A=async()=>{if(!(c!=null&&c.id)){v([]);return}u(!0),p(null);try{const m=await R.getTenantFeatureFlags(c.id,l);v(m)}catch(m){const g=m instanceof Error?m.message:"Failed to fetch feature flags";p(g),n.onError&&n.onError(m instanceof Error?m:new Error(g))}finally{u(!1)}};o.useEffect(()=>{if(!i||!l)return;A().finally(()=>P(!0));const m=n.refreshInterval||5*60*1e3,g=setInterval(A,m);return()=>clearInterval(g)},[c==null?void 0:c.id,i,l,n.refreshInterval]);const T=o.useMemo(()=>{const m=f=>{const k=h.find(y=>y.key===f);return(k==null?void 0:k.value)===!0},g=f=>h.find(k=>k.key===f),b=f=>{const k=h.find(y=>y.key===f);return k?k.value?"enabled":"disabled":"not_found"},L=async()=>{await A()},a=!!(i&&l)&&(E||!(c!=null&&c.id));return{featureFlags:h,loading:j,error:S,isReady:a,isEnabled:m,getFlag:g,getFlagState:b,refresh:L}},[h,j,S,i,l,c==null?void 0:c.id,E]);return r.jsx(Ie.Provider,{value:T,children:e})}function Ye(){const n=o.useContext(Ie);if(!n)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return n}function Xe(){return o.useContext(Ie)}class et{constructor(e){this.httpService=e}async createSubscription(e){return(await this.httpService.post("/subscriptions/",e)).data}async getSubscriptionById(e){return(await this.httpService.get(`/subscriptions/subscriptions/${e}`)).data}async updateSubscription(e,t){return(await this.httpService.put(`/subscriptions/${e}`,t)).data}async changeSubscriptionPlan(e,t){return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`,{skipAuth:!0})).data}async processPayment(e,t){return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t)).data}}const Le=o.createContext(void 0);function Pt({config:n={},children:e}){const t=Ae(),s=ae(),i=(t==null?void 0:t.baseUrl)??"",l=(s==null?void 0:s.tenant)??null,[c,h]=o.useState(null),[v,j]=o.useState(!1),[u,S]=o.useState(null),[p,E]=o.useState(!1),P=o.useMemo(()=>{const T=new oe(i);return new et(T)},[i]),R=async()=>{if(!(l!=null&&l.id)){h(null);return}j(!0),S(null);try{const T=await P.getTenantSubscriptionFeatures(l.id);h(T)}catch(T){const m=T instanceof Error?T.message:"Failed to fetch subscription";S(m),n.onError&&n.onError(T instanceof Error?T:new Error(m))}finally{j(!1)}};o.useEffect(()=>{if(!i||(R().finally(()=>E(!0)),!n.refreshInterval))return;const T=n.refreshInterval||10*60*1e3,m=setInterval(R,T);return()=>clearInterval(m)},[l==null?void 0:l.id,i,n.refreshInterval]);const A=o.useMemo(()=>{const T=(c==null?void 0:c.features)||[],m=k=>{const y=T.find(d=>d.key===k);return y?y.type==="BOOLEAN"||y.type==="boolean"?y.value===!0:!!y.value:!1},g=k=>T.find(y=>y.key===k),b=(k,y)=>{const d=T.find(w=>w.key===k);return d?d.value:y},L=k=>!c||!c.isActive?!1:k.includes(c.planId),a=async()=>{await R()},f=!!i&&(p||!(l!=null&&l.id));return{subscription:c,features:T,loading:v,error:u,isReady:f,isFeatureEnabled:m,getFeature:g,getFeatureValue:b,hasAllowedPlan:L,refresh:a}},[c,v,u,i,l==null?void 0:l.id,p]);return r.jsx(Le.Provider,{value:A,children:e})}function tt(){const n=o.useContext(Le);if(n===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return n}function rt(){return o.useContext(Le)??null}var ee=(n=>(n.SUPERUSER="SUPERUSER",n.TENANT_ADMIN="TENANT_ADMIN",n.USER="USER",n))(ee||{});const xe={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},Ne={landing:{tenant:"forbidden",auth:"optional"},publicOnly:{tenant:"forbidden",auth:"forbidden"},login:{tenant:"required",auth:"forbidden"},guest:{auth:"forbidden"},authenticated:{auth:"required"},tenant:{tenant:"required"},tenantOpen:{tenant:"required",auth:"optional"},tenantAuth:{tenant:"required",auth:"required"},user:{tenant:"required",auth:"required",userType:ee.USER},admin:{tenant:"required",auth:"required",userType:ee.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ce=o.createContext(null),Rt={zoneRoots:xe,presets:Ne,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"};function Ft({config:n={},children:e}){const t=o.useMemo(()=>{const s={...xe,...n.zoneRoots},i={...Ne,...n.presets};return{zoneRoots:s,presets:i,loadingFallback:n.loadingFallback??null,accessDeniedFallback:n.accessDeniedFallback??null,onAccessDenied:n.onAccessDenied,returnToParam:n.returnToParam??"returnTo",returnToStorage:n.returnToStorage??"url"}},[n]);return r.jsx(Ce.Provider,{value:t,children:e})}function It(){const n=o.useContext(Ce);if(!n)throw new Error("useRouting must be used within a RoutingProvider");return n}function nt(){return o.useContext(Ce)??Rt}const _e=()=>r.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:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.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"})]}),qe=({userType:n,minUserType:e,missingPermissions:t})=>r.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:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&n?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:n})]})]}):r.jsxs(r.Fragment,{children:[r.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&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),Lt=(n,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[n]>=t[e]};function Nt({children:n,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:i=!1}){const{hasValidSession:l,sessionManager:c,hasPermission:h,hasAnyPermission:v,hasAllPermissions:j}=ie();if(!l())return r.jsx(r.Fragment,{children:e||r.jsx(_e,{})});const u=c.getUser();if(!u)return r.jsx(r.Fragment,{children:e||r.jsx(_e,{})});if(t&&!Lt(u.userType,t))return r.jsx(qe,{userType:u.userType,minUserType:t});if(s&&s.length>0&&!(i?j(s):v(s))){const p=s.filter(E=>!h(E)).map(E=>typeof E=="string"?E:E.name);return r.jsx(qe,{missingPermissions:p})}return r.jsx(r.Fragment,{children:n})}const Ct=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})}),Ve=({userType:n,requiredUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&n?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",r.jsx("strong",{children:n})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),Mt=(n,e)=>n===e;function Dt({children:n,redirectTo:e="/login",requiredUserType:t,requiredPermissions:s,requireAllPermissions:i=!1,fallback:l}){const{hasValidSession:c,sessionManager:h,hasPermission:v,hasAnyPermission:j,hasAllPermissions:u}=ie(),S=re.useLocation();if(o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!c())return l?r.jsx(r.Fragment,{children:l}):r.jsxs(r.Fragment,{children:[r.jsx(Ct,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:S.pathname},replace:!0})]});const p=h.getUser();if(!p)return r.jsx(re.Navigate,{to:e,state:{from:S.pathname},replace:!0});if(t&&!Mt(p.userType,t))return r.jsx(Ve,{userType:p.userType,requiredUserType:t});if(s&&s.length>0&&!(i?u(s):j(s))){const P=s.filter(R=>!v(R)).map(R=>typeof R=="string"?R:R.name);return r.jsx(Ve,{missingPermissions:P})}return r.jsx(r.Fragment,{children:n})}const Ut=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})});function $t({children:n,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:i,error:l}=Re(),c=re.useLocation();return o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),i||l?null:s?r.jsx(r.Fragment,{children:n}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Ut,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:c.pathname},replace:!0})]})}const Bt=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})});function Ot({children:n,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:i,error:l}=Re(),c=re.useLocation();return o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),i||l?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Bt,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:c.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:n})}function _t(n,e){return e?n?Array.isArray(e)?e.includes(n):n===e:!1:!0}function ze(n,e){return!n||n==="optional"?"skip":n==="required"?e?"pass":"fail":n==="forbidden"?e?"fail":"pass":"skip"}function qt(n,e){return ze(n.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":ze(n.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":n.userType&&e.isAuthenticated&&!_t(e.userType,n.userType)?"wrong_user_type":n.permissions&&n.permissions.length>0&&!(n.requireAllPermissions!==!1?l=>l.every(c=>e.permissions.includes(c)):l=>l.some(c=>e.permissions.includes(c)))(n.permissions)?"missing_permissions":null}function Vt(n,e){return n.hasTenant?n.isAuthenticated?n.userType===ee.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:n.isAuthenticated?n.userType===ee.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function zt(n,e,t,s,i){if(!e||i!=="url")return n;const l=typeof e=="string"?e:t,c=n.includes("?")?"&":"?";return`${n}${c}${s}=${encodeURIComponent(l)}`}function Wt(n,e,t){if(!n||t==="url")return;const s=typeof n=="string"?n:e,i="zone_return_to";t==="session"?sessionStorage.setItem(i,s):t==="local"&&localStorage.setItem(i,s)}const se=({children:n,preset:e,tenant:t,auth:s,userType:i,requiredPermissions:l,requireAllPermissions:c=!0,returnTo:h,onAccessDenied:v,redirectTo:j,loadingFallback:u,accessDeniedFallback:S})=>{const p=re.useLocation(),{isAuthenticated:E,isAuthInitializing:P,currentUser:R,userPermissions:A}=ie(),{tenant:T,isTenantLoading:m}=ce(),g=nt(),b=o.useMemo(()=>{if(e)return g.presets[e]},[e,g.presets]),L=o.useMemo(()=>({tenant:t??(b==null?void 0:b.tenant),auth:s??(b==null?void 0:b.auth),userType:i??(b==null?void 0:b.userType),permissions:l??(b==null?void 0:b.requiredPermissions),requireAllPermissions:c}),[t,s,i,l,b,c]),a=o.useMemo(()=>({hasTenant:!!T,isAuthenticated:E,userType:R==null?void 0:R.userType,permissions:A,isLoading:P||m}),[T,E,R==null?void 0:R.userType,A,P,m]),f=o.useMemo(()=>a.isLoading?null:qt(L,a),[L,a]),k=o.useMemo(()=>f?j||Vt(a,g.zoneRoots):null,[f,j,a,g.zoneRoots]),y=o.useMemo(()=>!f||!k?null:{type:f,required:{tenant:L.tenant,auth:L.auth,userType:L.userType,permissions:L.permissions},current:{hasTenant:a.hasTenant,isAuthenticated:a.isAuthenticated,userType:a.userType,permissions:a.permissions},redirectTo:k},[f,k,L,a]);if(o.useEffect(()=>{y&&(v?v(y):g.onAccessDenied&&g.onAccessDenied(y))},[y,v,g]),o.useEffect(()=>{y&&h&&Wt(h,p.pathname+p.search,g.returnToStorage)},[y,h,p.pathname,p.search,g.returnToStorage]),a.isLoading)return r.jsx(r.Fragment,{children:u??g.loadingFallback??null});if(y&&k){const d=S??g.accessDeniedFallback;if(d)return r.jsx(r.Fragment,{children:d});const w=zt(k,h,p.pathname+p.search,g.returnToParam,g.returnToStorage);return r.jsx(re.Navigate,{to:w,replace:!0})}return r.jsx(r.Fragment,{children:n})},Gt=n=>r.jsx(se,{tenant:"required",...n}),Zt=n=>r.jsx(se,{tenant:"forbidden",...n}),Ht=n=>r.jsx(se,{auth:"required",...n}),Qt=n=>r.jsx(se,{auth:"forbidden",...n}),Jt=n=>r.jsx(se,{auth:"required",userType:ee.TENANT_ADMIN,...n}),Kt=n=>r.jsx(se,{auth:"required",userType:ee.USER,...n}),Yt=n=>r.jsx(se,{tenant:"optional",auth:"optional",...n}),Xt=n=>r.jsx(se,{tenant:"required",auth:"required",...n}),er=n=>r.jsx(se,{tenant:"required",auth:"optional",...n}),tr=n=>r.jsx(se,{tenant:"required",auth:"forbidden",...n}),rr=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function nr({children:n,fallback:e=r.jsx(rr,{}),allowedPlans:t,requiredFeature:s}){const{subscription:i,hasAllowedPlan:l,isFeatureEnabled:c,loading:h}=tt();return h?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):i?i.isActive?t&&t.length>0&&!l(t)?r.jsx(r.Fragment,{children:e}):s&&!c(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:n}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const sr=({flagName:n})=>r.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:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',n,'" is disabled']})]});function ir({name:n,children:e,fallback:t}){const{isEnabled:s,loading:i}=Ye();return i?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):s(n)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(sr,{flagName:n})})}function ue(n){const{submit:e,defaultErrorMessage:t,validate:s,onSuccess:i,onError:l}=n,[c,h]=o.useState(!1),[v,j]=o.useState(""),[u,S]=o.useState({}),p=o.useCallback((A,T)=>{S(m=>({...m,[A]:T}))},[]),E=o.useCallback(A=>{S(T=>{if(!T[A])return T;const m={...T};return delete m[A],m})},[]),P=o.useCallback(()=>{j(""),S({})},[]),R=o.useCallback(async A=>{if(A&&A.preventDefault(),!(s&&!s())){h(!0),j("");try{const T=await e();return i==null||i(T),T}catch(T){const m=T instanceof Error?T.message:t;j(m),l==null||l(m);return}finally{h(!1)}}},[e,s,t,i,l]);return{loading:c,error:v,setError:j,fieldErrors:u,setFieldError:p,clearFieldError:E,resetErrors:P,handleSubmit:R}}const We={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"},inputWithIcon:{paddingRight:"2.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},hintText:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},verifyingContainer:{textAlign:"center",padding:"2rem"},verifyingText:{fontSize:"1rem",color:"#6b7280"},toggleContainer:{textAlign:"center",marginTop:"0.5rem"},toggleLink:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},modeSwitchDivider:{margin:"0 0.5rem",color:"#6b7280"}};function we(n,e){return{...We,...e,button:{...We.button,backgroundColor:n,...(e==null?void 0:e.button)||{}}}}const or=()=>o.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0}},o.createElement("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),o.createElement("circle",{cx:"12",cy:"12",r:"3"})),ar=()=>o.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0}},o.createElement("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"}),o.createElement("line",{x1:"1",y1:"1",x2:"23",y2:"23"})),lr={showPassword:r.jsx(or,{}),hidePassword:r.jsx(ar,{})},cr={title:"Sign In",usernameLabel:"Email or Phone",usernamePlaceholder:"Enter your email or phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Invalid credentials",loadingText:"Signing in...",tenantNotFoundError:"Tenant not found",dividerBullet:"•",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password"};function ur({copy:n={},styles:e={},icons:t={},onSuccess:s,onError:i,onForgotPassword:l,onSignupClick:c,onMagicLinkClick:h,showForgotPassword:v=!0,showSignupLink:j=!0,showMagicLinkOption:u=!0,className:S}){const[p,E]=o.useState(""),[P,R]=o.useState(""),[A,T]=o.useState(!1),{login:m}=ie(),g={...cr,...n},b=we("#3b82f6",e),L={...lr,...t},a=ue({defaultErrorMessage:g.errorMessage,validate:()=>{const d=[];return p.trim()||d.push("username"),P.trim()||d.push("password"),d.forEach(w=>a.setFieldError(w,!0)),d.length===0},submit:()=>m({username:p,password:P}),onSuccess:s,onError:i}),f=d=>({...b.input,...a.fieldErrors[d]?b.inputError:{}}),k=!p||!P||a.loading,y={...b.button,...a.loading?b.buttonLoading:{},...k?b.buttonDisabled:{}};return r.jsxs("div",{className:S,style:b.container,children:[r.jsx("h2",{style:b.title,children:g.title}),r.jsxs("form",{onSubmit:a.handleSubmit,style:b.form,children:[r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:g.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:p,onChange:d=>{E(d.target.value),a.clearFieldError("username")},placeholder:g.usernamePlaceholder,style:f("username"),disabled:a.loading})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:g.passwordLabel}),r.jsxs("div",{style:b.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:A?"text":"password",value:P,onChange:d=>{R(d.target.value),a.clearFieldError("password")},placeholder:g.passwordPlaceholder,style:{...f("password"),...b.inputWithIcon},disabled:a.loading}),r.jsx("button",{type:"button",onClick:()=>T(!A),style:b.passwordToggle,disabled:a.loading,"aria-label":A?g.hidePasswordAriaLabel:g.showPasswordAriaLabel,children:A?L.hidePassword:L.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:k,style:y,children:a.loading?g.loadingText:g.submitButton}),a.error&&r.jsx("div",{style:b.errorText,children:a.error})]}),(v||j||u)&&r.jsxs("div",{style:b.linkContainer,children:[u&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[g.magicLinkText," "]}),r.jsx("a",{onClick:h,style:b.link,children:g.magicLinkLink})]}),u&&(v||j)&&r.jsx("div",{style:b.divider,children:g.dividerBullet}),v&&r.jsx("a",{onClick:l,style:b.link,children:g.forgotPasswordLink}),v&&j&&r.jsx("div",{style:b.divider,children:g.dividerBullet}),j&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[g.signupText," "]}),r.jsx("a",{onClick:c,style:b.link,children:g.signupLink})]})]})]})}const dr={title:"Create Account",nameLabel:"First Name",namePlaceholder:"Enter your first name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",emailLabel:"Email",emailPlaceholder:"Enter your email",phoneNumberLabel:"Phone Number",phoneNumberPlaceholder:"Enter your phone number",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?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",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",contactMethodHint:"At least one contact method (email or phone) is required",tenantNotFoundError:"Tenant not found",dividerBullet:"•"};function hr({copy:n={},styles:e={},signupType:t="user",onSuccess:s,onError:i,onLoginClick:l,onMagicLinkClick:c,showLoginLink:h=!0,showMagicLinkOption:v=!0,className:j}){var D;const[u,S]=o.useState(""),[p,E]=o.useState(""),[P,R]=o.useState(""),[A,T]=o.useState(""),[m,g]=o.useState(""),[b,L]=o.useState(""),[a,f]=o.useState(""),{signup:k,signupTenantAdmin:y}=ie(),d=((D=ae())==null?void 0:D.tenant)??null,w={...dr,...n},N=we("#10b981",e),X=!!u&&(!!P||!!A)&&!!m&&!!b&&(t==="user"||!!a),I=ue({defaultErrorMessage:w.errorMessage,validate:()=>{const F=[];return u.trim()||F.push("name"),!P.trim()&&!A.trim()&&(F.push("email"),F.push("phoneNumber")),m.trim()||F.push("password"),b.trim()||F.push("confirmPassword"),t==="tenant"&&!a.trim()&&F.push("tenantName"),F.forEach(B=>I.setFieldError(B,!0)),F.length>0?!1:m!==b?(I.setError(w.passwordMismatchError),I.setFieldError("confirmPassword",!0),!1):t==="user"&&!(d!=null&&d.id)?(I.setError(w.tenantNotFoundError),!1):!0},submit:async()=>t==="tenant"?y({email:P||void 0,phoneNumber:A||void 0,name:u,password:m,tenantName:a,lastName:p||void 0}):k({email:P||void 0,phoneNumber:A||void 0,name:u,password:m,tenantId:d.id,lastName:p||void 0}),onSuccess:s,onError:i}),z=F=>({...N.input,...I.fieldErrors[F]?N.inputError:{}}),_=!X||I.loading,Z={...N.button,...I.loading?N.buttonLoading:{},..._?N.buttonDisabled:{}},M=()=>{I.clearFieldError("email"),I.clearFieldError("phoneNumber")};return r.jsxs("div",{className:j,style:N.container,children:[r.jsx("h2",{style:N.title,children:w.title}),r.jsxs("form",{onSubmit:I.handleSubmit,style:N.form,children:[r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:u,onChange:F=>{S(F.target.value),I.clearFieldError("name")},placeholder:w.namePlaceholder,style:z("name"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:p,onChange:F=>E(F.target.value),placeholder:w.lastNamePlaceholder,style:N.input,disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:P,onChange:F=>{R(F.target.value),M()},placeholder:w.emailPlaceholder,style:z("email"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:A,onChange:F=>{T(F.target.value),M()},placeholder:w.phoneNumberPlaceholder,style:z("phoneNumber"),disabled:I.loading})]}),r.jsx("div",{style:N.hintText,children:w.contactMethodHint}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:m,onChange:F=>{g(F.target.value),I.clearFieldError("password")},placeholder:w.passwordPlaceholder,style:z("password"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:b,onChange:F=>{L(F.target.value),I.clearFieldError("confirmPassword"),I.error===w.passwordMismatchError&&I.setError("")},placeholder:w.confirmPasswordPlaceholder,style:z("confirmPassword"),disabled:I.loading})]}),t==="tenant"&&r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:a,onChange:F=>{f(F.target.value),I.clearFieldError("tenantName")},placeholder:w.tenantNamePlaceholder,style:z("tenantName"),disabled:I.loading})]}),r.jsx("button",{type:"submit",disabled:_,style:Z,children:I.loading?w.loadingText:w.submitButton}),I.error&&r.jsx("div",{style:N.errorText,children:I.error})]}),(h||v)&&r.jsxs("div",{style:N.linkContainer,children:[v&&r.jsxs("div",{children:[r.jsxs("span",{style:N.divider,children:[w.magicLinkText," "]}),r.jsx("a",{onClick:c,style:N.link,children:w.magicLinkLink})]}),v&&h&&r.jsx("div",{style:N.divider,children:w.dividerBullet}),h&&r.jsxs("div",{children:[r.jsxs("span",{style:N.divider,children:[w.loginText," "]}),r.jsx("a",{onClick:l,style:N.link,children:w.loginLink})]})]})]})}const pr={title:"Sign In with Magic Link",emailLabel:"Email",emailPlaceholder:"Enter your email",nameLabel:"Name",namePlaceholder:"Enter your name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",submitButton:"Send Magic Link",loginLink:"Sign in with password",signupLink:"Sign up with password",loginText:"Already have an account?",signupText:"Prefer traditional signup?",successMessage:"Magic link sent! Check your email and click the link to sign in.",errorMessage:"Failed to send magic link. Please try again.",loadingText:"Sending magic link...",verifyingText:"Verifying magic link...",verifyingDescription:"Please wait while we verify your magic link...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you.",showNameToggle:"New user? Add your name",hideNameToggle:"Existing user? Hide name fields",tenantNotFoundError:"Tenant not found",missingTenantOrEmailError:"Missing tenant or email",dividerBullet:"•"};function fr({copy:n={},styles:e={},onSuccess:t,onError:s,onLoginClick:i,onSignupClick:l,showTraditionalLinks:c=!0,className:h,verifyToken:v,frontendUrl:j}){var z;const[u,S]=o.useState(""),[p,E]=o.useState(""),[P,R]=o.useState(""),[A,T]=o.useState(!1),[m,g]=o.useState(""),[b,L]=o.useState(!1),{sendMagicLink:a,verifyMagicLink:f}=ie(),k=((z=ae())==null?void 0:z.tenant)??null,y={...pr,...n},d=we("#3b82f6",e),w=ue({defaultErrorMessage:y.errorMessage,validate:()=>{const _=[];return u.trim()||_.push("email"),b&&!p.trim()&&_.push("name"),_.forEach(Z=>w.setFieldError(Z,!0)),_.length>0?!1:k!=null&&k.id?!0:(w.setError(y.tenantNotFoundError),!1)},submit:async()=>{g("");const _=j||(typeof window<"u"?window.location.origin:""),Z=await a({email:u,tenantId:k.id,frontendUrl:_,name:b?p:void 0,lastName:b?P:void 0});return g(y.successMessage),Z},onSuccess:t,onError:s});o.useEffect(()=>{if(!v)return;(async()=>{if(!k||!u){w.setError(y.missingTenantOrEmailError);return}T(!0),w.setError("");try{const Z=await f({token:v,email:u});t==null||t(Z)}catch(Z){const M=Z instanceof Error?Z.message:"Failed to verify magic link";w.setError(M),s==null||s(M)}finally{T(!1)}})()},[v]);const N=_=>({...d.input,...w.fieldErrors[_]?d.inputError:{}}),X=!u||w.loading||A,I={...d.button,...w.loading||A?d.buttonLoading:{},...X?d.buttonDisabled:{}};return A?r.jsxs("div",{className:h,style:d.container,children:[r.jsx("h2",{style:d.title,children:y.verifyingText}),r.jsx("div",{style:d.verifyingContainer,children:r.jsx("div",{style:d.verifyingText,children:y.verifyingDescription})})]}):r.jsxs("div",{className:h,style:d.container,children:[r.jsx("h2",{style:d.title,children:y.title}),r.jsx("p",{style:d.description,children:y.description}),r.jsxs("form",{onSubmit:w.handleSubmit,style:d.form,children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:u,onChange:_=>{S(_.target.value),w.clearFieldError("email")},placeholder:y.emailPlaceholder,style:N("email"),disabled:w.loading||A})]}),!b&&r.jsx("div",{style:d.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>L(!0),style:d.toggleLink,children:y.showNameToggle})}),b&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:p,onChange:_=>{E(_.target.value),w.clearFieldError("name")},placeholder:y.namePlaceholder,style:N("name"),disabled:w.loading||A})]}),r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:P,onChange:_=>R(_.target.value),placeholder:y.lastNamePlaceholder,style:d.input,disabled:w.loading||A})]}),r.jsx("div",{style:d.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{L(!1),E(""),R("")},style:d.toggleLink,children:y.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:X,style:I,children:w.loading?y.loadingText:y.submitButton}),w.error&&r.jsx("div",{style:d.errorText,children:w.error}),m&&r.jsx("div",{style:d.successText,children:m})]}),c&&r.jsxs("div",{style:d.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[y.loginText," "]}),r.jsx("a",{onClick:i,style:d.link,children:y.loginLink})]}),r.jsx("div",{style:d.divider,children:y.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[y.signupText," "]}),r.jsx("a",{onClick:l,style:d.link,children:y.signupLink})]})]})]})}const mr={title:"Verifying Magic Link",verifyingMessage:"Please wait while we verify your magic link...",successMessage:"Magic link verified successfully! You are now logged in.",errorMessage:"Failed to verify magic link. The link may be expired or invalid.",redirectingMessage:"Redirecting you to the dashboard...",retryButton:"Try Again",backToLoginButton:"Back to Login",missingParamsError:"Missing required parameters: token or email"},st={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},card:{backgroundColor:"transparent",padding:"0",borderRadius:"0",boxShadow:"none",maxWidth:"100%",width:"100%",textAlign:"center"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},message:{fontSize:"1rem",color:"#6b7280",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},successMessage:{fontSize:"1rem",color:"#059669",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},errorMessage:{fontSize:"0.875rem",color:"#ef4444",textAlign:"center",marginBottom:"1rem",lineHeight:"1.5"},spinner:{display:"inline-block",width:"20px",height:"20px",border:"2px solid #e5e7eb",borderTop:"2px solid #3b82f6",borderRadius:"50%",animation:"spin 1s linear infinite",marginRight:"0.5rem"},buttonContainer:{display:"flex",gap:"0.75rem",justifyContent:"center",flexWrap:"wrap",marginTop:"1rem"},retryButton:{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"},backButton:{padding:"0.75rem 1rem",backgroundColor:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"all 0.15s ease-in-out"},retryButtonHover:{backgroundColor:"#2563eb"},backButtonHover:{backgroundColor:"#e5e7eb"}},gr=()=>r.jsx("div",{style:st.spinner}),yr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),br=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),xr={loading:r.jsx(gr,{}),success:r.jsx(yr,{}),error:r.jsx(br,{})};function wr({copy:n={},styles:e={},icons:t={},onSuccess:s,onError:i,onRetry:l,onBackToLogin:c,className:h,token:v,email:j,appId:u,tenantSlug:S,autoRedirectDelay:p=3e3}){const[E,P]=o.useState("verifying"),[R,A]=o.useState(""),{verifyMagicLink:T}=ie(),m={...mr,...n},g={...st,...e},b={...xr,...t},L=()=>{if(typeof window>"u")return{};const d=new URLSearchParams(window.location.search);return{token:v||d.get("token")||"",email:j||d.get("email")||"",appId:u||d.get("appId")||"",tenantSlug:S||d.get("tenantSlug")||void 0}},a=async()=>{P("verifying"),A("");try{const d=L();if(!d.token||!d.email)throw new Error(m.missingParamsError);const w=await T({token:d.token,email:d.email,tenantSlug:d.tenantSlug});P("success"),s==null||s(w),p>0&&setTimeout(()=>{P("redirecting")},p)}catch(d){const w=d.message||m.errorMessage;A(w),P("error"),i==null||i(w)}},f=()=>{l==null||l(),a()},k=()=>{c==null||c()};o.useEffect(()=>{a()},[]);const y=()=>{switch(E){case"verifying":return r.jsxs("div",{style:g.message,children:[b.loading,m.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[b.success,r.jsx("div",{style:g.successMessage,children:m.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[b.loading,r.jsx("div",{style:g.message,children:m.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[b.error,r.jsx("div",{style:g.errorMessage,children:R||m.errorMessage}),r.jsxs("div",{style:g.buttonContainer,children:[r.jsx("button",{onClick:f,style:g.retryButton,onMouseOver:d=>{Object.assign(d.currentTarget.style,g.retryButtonHover)},onMouseOut:d=>{const w=g.retryButton||{};Object.keys(g.retryButtonHover||{}).forEach(N=>{d.currentTarget.style[N]=w[N]??""})},children:m.retryButton}),r.jsx("button",{onClick:k,style:g.backButton,onMouseOver:d=>{Object.assign(d.currentTarget.style,g.backButtonHover)},onMouseOut:d=>{const w=g.backButton||{};Object.keys(g.backButtonHover||{}).forEach(N=>{d.currentTarget.style[N]=w[N]??""})},children:m.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:g.container,className:h,children:[r.jsx("style",{children:`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),o=require("react"),ne=require("react-router-dom");class ae{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async executeRequest(e,t,s,i){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,c=(i==null?void 0:i.timeout)||this.timeout;let h={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const u=await this.sessionManager.getValidAccessToken();h={...h,Authorization:`Bearer ${u}`}}const w=new AbortController,j=setTimeout(()=>w.abort(),c);try{const u=await fetch(l,{method:e,headers:h,body:s?JSON.stringify(s):void 0,signal:w.signal});if(clearTimeout(j),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);const S=u.headers.get("content-type");return!S||!S.includes("application/json")?{}:await u.json()}catch(u){throw clearTimeout(j),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${c}ms`):u}}async get(e,t){return this.executeRequest("GET",e,void 0,t)}async post(e,t,s){return this.executeRequest("POST",e,t,s)}async put(e,t,s){return this.executeRequest("PUT",e,t,s)}async delete(e,t){return this.executeRequest("DELETE",e,void 0,t)}}function se(n){if(!n)return"";const e=new URLSearchParams;for(const[s,i]of Object.entries(n))i!=null&&i!==""&&e.append(s,String(i));const t=e.toString();return t?`?${t}`:""}class Re{constructor(e){this.httpService=e}async createApp(e){return(await this.httpService.post("/apps/",e)).data}async getApps(e){const t=await this.httpService.get(`/apps/${se(e)}`);return{apps:t.data,meta:t.meta}}async getAppById(e){return(await this.httpService.get(`/apps/${e}`)).data}async updateApp(e,t){return(await this.httpService.put(`/apps/${e}`,t)).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`,{skipAuth:!0})).data}async setDefaultSubscriptionPlan(e,t){return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t})).data}async updateSettingsSchema(e,t,s){return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s})).data}async exportConfig(e){return(await this.httpService.get(`/apps/${e}/export-config`)).data}}const Pe=o.createContext(null),xt=5*60*1e3;function vt({config:n,children:e}){var T,m,g;const{appId:t,baseUrl:s}=n,i=((T=n.cache)==null?void 0:T.enabled)??!0,l=((m=n.cache)==null?void 0:m.ttl)??xt,c=((g=n.cache)==null?void 0:g.storageKey)??`app_cache_${t}`,[h,w]=o.useState(()=>{if(!i)return null;try{const b=localStorage.getItem(c);if(!b)return null;const L=JSON.parse(b);return Date.now()-L.timestamp<l&&L.appId===t?L.data:(localStorage.removeItem(c),null)}catch{return null}}),[j,u]=o.useState(!h),[S,p]=o.useState(null),E=o.useRef(h);E.current=h;const R=o.useCallback(async(b=!1)=>{if(!(!b&&i&&E.current))try{u(!0),p(null);const a=await new Re(new ae(s)).getPublicAppInfo(t);if(w(a),i)try{const f={data:a,timestamp:Date.now(),appId:t};localStorage.setItem(c,JSON.stringify(f))}catch(f){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",f)}}catch(L){const a=L instanceof Error?L:new Error("Failed to load app information");p(a),w(null)}finally{u(!1)}},[s,t,i,c]),P=o.useCallback(async()=>{if(!(!i||!E.current))try{const b=localStorage.getItem(c);if(!b)return;const L=JSON.parse(b);if(Date.now()-L.timestamp<=l*.5)return;const f=await new Re(new ae(s)).getPublicAppInfo(t);w(f);const k={data:f,timestamp:Date.now(),appId:t};localStorage.setItem(c,JSON.stringify(k))}catch(b){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",b)}},[s,t,i,l,c]),A=o.useMemo(()=>({appId:t,baseUrl:s,appInfo:h,isAppLoading:j,appError:S,retryApp:()=>{R(!0)}}),[t,s,h,j,S,R]);return o.useEffect(()=>{E.current?P():R()},[]),r.jsx(Pe.Provider,{value:A,children:e})}function pe(){const n=o.useContext(Pe);if(!n)throw new Error("useApp must be used within an AppProvider");return n}function Fe(){return o.useContext(Pe)}const wt=pe;class Z extends Error{constructor(e,t){const s={token_expired:"Refresh token has expired",token_invalid:"Refresh token is invalid",user_inactive:"User account is inactive"};super(t||s[e]),this.name="SessionExpiredError",this.reason=e}}class Ye extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class Xe extends Error{constructor(e,t){super(`Token refresh failed after ${e} attempts: ${(t==null?void 0:t.message)||"Unknown error"}`),this.name="TokenRefreshError",this.attempts=e,this.lastError=t}}class ee extends Error{constructor(e,t,s){super(`Invalid configuration "${e}": ${s} (received: ${St(t)})`),this.name="ConfigurationError",this.field=e,this.received=t}}function St(n){if(n===void 0)return"undefined";try{const e=JSON.stringify(n);return e===void 0?typeof n:e.length>50?`${e.slice(0,47)}...`:e}catch{return typeof n}}function Ve(n){return JSON.parse(atob(n.replace(/-/g,"+").replace(/_/g,"/")))}function be(n){const e=n.split(".");if(e.length!==3)return null;try{return{header:Ve(e[0]),payload:Ve(e[1])}}catch{return null}}function qe(n){const e=be(n),t=e==null?void 0:e.payload.exp;return typeof t=="number"?t*1e3:void 0}function Tt(n,e){var s;const t=(s=be(n))==null?void 0:s.payload[e];return typeof t=="string"?t:void 0}const kt=/^(javascript|data|vbscript|file):/i,Et=/^https?:\/\//i;function jt(n,e="baseUrl"){if(!(n==null||n==="")){if(typeof n!="string")throw new ee(e,n,"must be a string");if(kt.test(n))throw new ee(e,n,"dangerous URL scheme is not allowed");if(!Et.test(n))throw new ee(e,n,"must start with http:// or https://")}}function de(n,e,t={}){if(e===void 0)return;if(typeof e!="number"||!Number.isFinite(e))throw new ee(n,e,"must be a finite number");const{min:s=0,max:i=Number.MAX_SAFE_INTEGER}=t;if(e<s)throw new ee(n,e,`must be >= ${s}`);if(e>i)throw new ee(n,e,`must be <= ${i}`)}function ze(n,e){if(e!==void 0&&typeof e!="boolean")throw new ee(n,e,"must be a boolean")}function At(n,e="accessToken"){if(typeof n!="string"||n.length===0)throw new ee(e,n,"must be a non-empty string");if(!n.includes("."))return;const t=n.split(".");if(t.length!==3)throw new ee(e,`<${t.length}-segment token>`,"JWT must have exactly 3 segments (header.payload.signature)");if(be(n)===null)throw new ee(e,"<malformed JWT>","JWT header or payload is not valid base64url-encoded JSON")}function Rt(n){if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<=0))throw new ee("expiresIn",n,"must be a finite positive number (seconds)")}function Pt(n){if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<=0))throw new ee("expiresAt",n,"must be a finite positive timestamp (ms since epoch)")}const X=class X{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,this.consecutiveBackgroundFailures=0,this.memoryStore=null,this.visibilityListener=null,X.validateConfig(e),this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.onSessionExpired=e.onSessionExpired,this.baseUrl=e.baseUrl||"",this.enableCookieSession=e.enableCookieSession??!1,this.proactiveRefreshMargin=e.proactiveRefreshMargin??6e4,this.refreshQueueTimeout=e.refreshQueueTimeout??1e4,this.maxRefreshRetries=e.maxRefreshRetries??3,this.retryBackoffBase=e.retryBackoffBase??1e3,this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey),this.attachVisibilityListener(),this.scheduleProactiveRefresh()}static getInstance(e={}){const t=X.resolveStorageKey(e),s=X.instances.get(t);if(s)return s.updateConfig(e),s;const i=new X(e);return X.instances.set(t,i),i}static resetAllInstances(){for(const e of X.instances.values())e.destroy();X.instances.clear()}static resolveStorageKey(e){return e.storageKey||"auth_tokens"}static validateConfig(e){jt(e.baseUrl),ze("enableCookieSession",e.enableCookieSession),ze("autoRefresh",e.autoRefresh),de("refreshThreshold",e.refreshThreshold,{min:0}),de("proactiveRefreshMargin",e.proactiveRefreshMargin,{min:0}),de("refreshQueueTimeout",e.refreshQueueTimeout,{min:1}),de("maxRefreshRetries",e.maxRefreshRetries,{min:0}),de("retryBackoffBase",e.retryBackoffBase,{min:1})}updateConfig(e){e.onSessionExpired!==void 0&&(this.onSessionExpired=e.onSessionExpired),e.onRefreshFailed!==void 0&&(this.onRefreshFailed=e.onRefreshFailed),e.baseUrl&&(this.baseUrl=e.baseUrl),e.enableCookieSession!==void 0&&(this.enableCookieSession=e.enableCookieSession)}createTokenStorage(e){return X.probeLocalStorage()||this.activateMemoryFallback(),{get:()=>{const t=this.storageGet(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},set:t=>{this.storageSet(e,JSON.stringify(t))},clear:()=>{this.storageRemove(e)}}}static probeLocalStorage(){if(typeof localStorage>"u")return!1;try{return localStorage.setItem("__sm_probe__","1"),localStorage.removeItem("__sm_probe__"),!0}catch{return!1}}activateMemoryFallback(){return this.memoryStore||(this.memoryStore=new Map,process.env.NODE_ENV==="development"&&console.warn("[SessionManager] localStorage unavailable — falling back to in-memory session. Cross-tab and reload persistence are lost.")),this.memoryStore}storageGet(e){if(this.memoryStore)return this.memoryStore.get(e)??null;try{return localStorage.getItem(e)}catch{return this.activateMemoryFallback().get(e)??null}}storageSet(e,t){if(this.memoryStore){this.memoryStore.set(e,t);return}try{localStorage.setItem(e,t)}catch{this.activateMemoryFallback().set(e,t)}}storageRemove(e){if(this.memoryStore){this.memoryStore.delete(e);return}try{localStorage.removeItem(e)}catch{}}setTokens(e){if(At(e.accessToken,"accessToken"),e.refreshToken!==void 0&&typeof e.refreshToken!="string")throw new ee("refreshToken",e.refreshToken,"must be a string");Rt(e.expiresIn),Pt(e.expiresAt);const t=e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)||qe(e.accessToken),s={...e,expiresAt:t},i=this.tokenStorage.get()||{};this.tokenStorage.set({...i,...s}),this.scheduleProactiveRefresh()}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:i,tokenType:l}=this.tokenStorage.get()||{};if(!e)return null;const c=s||qe(e);return{accessToken:e,refreshToken:t,expiresAt:c,expiresIn:i,tokenType:l}}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}scheduleProactiveRefresh(){if(this.cancelProactiveTimer(),!this.autoRefresh||this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.expiresAt)||!e.refreshToken)return;const s=e.expiresAt-this.proactiveRefreshMargin-Date.now();if(s<=0){this.backgroundRefresh();return}this.proactiveTimerId=setTimeout(()=>{this.backgroundRefresh()},s)}cancelProactiveTimer(){this.proactiveTimerId!==null&&(clearTimeout(this.proactiveTimerId),this.proactiveTimerId=null),this.backgroundRetryTimerId!==null&&(clearTimeout(this.backgroundRetryTimerId),this.backgroundRetryTimerId=null)}attachVisibilityListener(){if(!this.visibilityListener&&!(typeof document>"u"||typeof document.addEventListener!="function")){this.visibilityListener=()=>{document.visibilityState!=="visible"||this.isDestroyed||this.scheduleProactiveRefresh()};try{document.addEventListener("visibilitychange",this.visibilityListener)}catch{this.visibilityListener=null}}}detachVisibilityListener(){if(this.visibilityListener&&typeof document<"u")try{document.removeEventListener("visibilitychange",this.visibilityListener)}catch{}this.visibilityListener=null}backgroundRefresh(){if(this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.refreshToken)||this.refreshPromise)return;const t=this.sessionGeneration;this.startRefreshAndResolveQueue(e.refreshToken).then(()=>{this.consecutiveBackgroundFailures=0}).catch(s=>{if(!(s instanceof Z)){if(this.sessionGeneration===t){if(this.consecutiveBackgroundFailures++,this.consecutiveBackgroundFailures>=X.MAX_BACKGROUND_FAILURES){process.env.NODE_ENV==="development"&&console.error(`[SessionManager] Background refresh failed ${this.consecutiveBackgroundFailures} consecutive times — expiring session`),this.consecutiveBackgroundFailures=0,this.handleSessionExpired(new Z("token_invalid","Background refresh failed repeatedly"));return}process.env.NODE_ENV==="development"&&console.warn("[SessionManager] Background refresh failed, retrying in 30s:",s.message),this.backgroundRetryTimerId=setTimeout(()=>{this.backgroundRefresh()},3e4)}}})}async waitForPendingRefresh(){if(!this.refreshPromise)return!1;try{return await this.refreshPromise,!0}catch{return!1}}async attemptCookieSessionRestore(){if(!this.enableCookieSession||!this.baseUrl)return!1;const e=`${this.baseUrl}/auth/refresh`;try{const t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),credentials:"include"});if(!t.ok)return!1;const s=await t.json();return s.accessToken?(this.setTokens({accessToken:s.accessToken,refreshToken:s.refreshToken||"",expiresIn:s.expiresIn}),!0):!1}catch{return!1}}async getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new Z("token_invalid","No tokens available");throw this.handleSessionExpired(t),t}if(!this.shouldRefreshToken(e)&&!this.isTokenExpired(e))return e.accessToken;if(!e.refreshToken){const t=new Z("token_invalid","No refresh token available");throw this.handleSessionExpired(t),t}return this.refreshPromise?this.enqueueForToken():this.startRefreshAndResolveQueue(e.refreshToken)}async getAuthHeaders(){try{return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}catch(e){return e instanceof Z&&this.onRefreshFailed&&this.onRefreshFailed(),{}}}enqueueForToken(){return new Promise((e,t)=>{const s=setTimeout(()=>{const i=this.refreshQueue.findIndex(l=>l.timeoutId===s);i!==-1&&this.refreshQueue.splice(i,1),t(new Ye(this.refreshQueueTimeout))},this.refreshQueueTimeout);this.refreshQueue.push({resolve:e,reject:t,timeoutId:s})})}async startRefreshAndResolveQueue(e){this.refreshPromise=this.executeRefreshWithRetry(e);try{await this.refreshPromise;const t=this.getTokens(),s=(t==null?void 0:t.accessToken)||"";return this.resolveQueue(s),s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");throw s instanceof Z?(this.rejectQueue(s),this.handleSessionExpired(s)):this.rejectQueue(s),s}finally{this.refreshPromise=null}}resolveQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const s of t)clearTimeout(s.timeoutId),s.resolve(e)}rejectQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const s of t)clearTimeout(s.timeoutId),s.reject(e)}async executeRefreshWithRetry(e){let t;const s=this.sessionGeneration;for(let i=0;i<=this.maxRefreshRetries;i++){if(this.sessionGeneration!==s)throw new Z("token_invalid","Session cleared during refresh");try{await this.performTokenRefresh(e,s);return}catch(l){const c=l instanceof Error?l:new Error(String(l));if(c instanceof Z)throw c;if(t=c,i<this.maxRefreshRetries){const h=this.retryBackoffBase*Math.pow(2,i);await this.sleep(h)}}}throw new Xe(this.maxRefreshRetries+1,t)}async performTokenRefresh(e,t){return typeof navigator<"u"&&navigator.locks?navigator.locks.request(`session-refresh:${this.storageKey}`,()=>this.performTokenRefreshInner(e,t)):this.performTokenRefreshInner(e,t)}async performTokenRefreshInner(e,t){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const s=this.getTokens();if(s!=null&&s.accessToken&&!this.isTokenExpired(s)&&!this.shouldRefreshToken(s))return;const i=(s==null?void 0:s.refreshToken)||e,l=`${this.baseUrl}/auth/refresh`,c=Tt(i,"deviceId"),h={refreshToken:i};c&&(h.deviceId=c);let w;try{w=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),...this.enableCookieSession&&{credentials:"include"}})}catch(u){throw u instanceof Error?u:new Error("Network error during token refresh")}if(!w.ok){let u="";try{const S=await w.json();u=(S.message||S.error||"").toLowerCase()}catch{u=w.statusText.toLowerCase()}throw w.status===401?u.includes("expired")?new Z("token_expired"):u.includes("invalid")?new Z("token_invalid"):new Z("token_invalid",`Unauthorized: ${u}`):w.status===400?u.includes("inactive")?new Z("user_inactive"):u.includes("expired")||u.includes("invalid")?new Z("token_invalid",u):u.includes("reuse")||u.includes("revoked")?new Z("token_invalid",u):new Error(`Token refresh failed (400): ${u}`):new Error(`Token refresh failed: ${w.status} ${u}`)}if(this.sessionGeneration!==t)throw new Z("token_invalid","Session cleared during refresh");const j=await w.json();this.setTokens({accessToken:j.accessToken,refreshToken:j.refreshToken||i,expiresIn:j.expiresIn})}handleSessionExpired(e){this.cancelProactiveTimer(),this.clearSession(),this.onSessionExpired?this.onSessionExpired(e):this.onRefreshFailed&&this.onRefreshFailed()}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.sessionGeneration++,this.cancelProactiveTimer(),this.clearTokens();const e=new Z("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,X.instances.delete(this.storageKey),this.cancelProactiveTimer(),this.detachVisibilityListener();const e=new Z("token_invalid","SessionManager destroyed");this.rejectQueue(e)}getTokenPayload(){var t,s;const e=(t=this.getTokens())==null?void 0:t.accessToken;return e?((s=be(e))==null?void 0:s.payload)??null:null}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};X.instances=new Map,X.MAX_BACKGROUND_FAILURES=3;let ye=X;class et{constructor(e){this.httpService=e,this.pendingVerifications=new Map,this.pendingMagicLinks=new Map}async login(e){return this.httpService.post("/auth/login",e,{skipAuth:!0})}async signup(e){return this.httpService.post("/auth/signup",e,{skipAuth:!0})}async signupTenantAdmin(e){return this.httpService.post("/auth/signup/tenant-admin",e,{skipAuth:!0})}async refreshToken(e){return this.httpService.post("/auth/refresh",e,{skipAuth:!0})}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(){return this.httpService.get("/auth/tenants")}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e,{skipAuth:!0})}async sendMagicLink(e){const t=JSON.stringify([e.email,e.tenantId,e.appId??"",e.frontendUrl??""]),s=this.pendingMagicLinks.get(t);if(s)return s;const i=this.httpService.post("/auth/magic-link/send",e,{skipAuth:!0}).finally(()=>{this.pendingMagicLinks.delete(t)});return this.pendingMagicLinks.set(t,i),i}async verifyMagicLink(e){const t=e.token,s=this.pendingVerifications.get(t);if(s)return s;const i=this.httpService.post("/auth/magic-link/verify",e,{skipAuth:!0}).finally(()=>{this.pendingVerifications.delete(t)});return this.pendingVerifications.set(t,i),i}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e,{skipAuth:!0})}async changePassword(e){await this.httpService.post("/auth/change-password",e)}}class tt{constructor(e){this.httpService=e}async createRole(e){return(await this.httpService.post("/roles/",e)).data}async getRoleById(e){return(await this.httpService.get(`/roles/${e}`)).data}async updateRole(e,t){return(await this.httpService.put(`/roles/${e}`,t)).data}async deleteRole(e){await this.httpService.delete(`/roles/${e}`)}async getRolesByApp(e,t){const s=await this.httpService.get(`/roles/app/${e}${se(t)}`,{skipAuth:!0});return{roles:s.data,meta:s.meta}}async assignRole(e,t){await this.httpService.post(`/roles/${e}/assign`,t)}async revokeRole(e,t){await this.httpService.post(`/roles/${e}/revoke`,t)}async getUserRoles(e,t){const s=await this.httpService.get(`/roles/user/${e}${se(t)}`);return{roles:s.data,meta:s.meta}}}class rt{constructor(e){this.httpService=e}async createUser(e){return(await this.httpService.post("/users/",e)).data}async getUsers(e){const t=await this.httpService.get(`/users/${se(e)}`);return{users:t.data,meta:t.meta}}async getUserById(e){return(await this.httpService.get(`/users/${e}`)).data}async updateUser(e,t){return(await this.httpService.put(`/users/${e}`,t)).data}async deleteUser(e){await this.httpService.delete(`/users/${e}`)}}class ce{constructor(e,t){this.httpService=e,this.appId=t}async createTenant(e){return(await this.httpService.post("/tenants/",e)).data}async getTenants(e){const t=await this.httpService.get(`/tenants/${se(e)}`);return{tenants:t.data,meta:t.meta}}async getTenantById(e){return(await this.httpService.get(`/tenants/${e}`)).data}async updateTenant(e,t){return(await this.httpService.put(`/tenants/${e}`,t)).data}async adminUpdateTenant(e,t){return(await this.httpService.put(`/tenants/${e}/admin-update`,t)).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`,{skipAuth:!0})).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`,{skipAuth:!0})).data}async updateTenantSettings(e,t){return(await this.httpService.put(`/tenants/${e}/settings`,t)).data}}function Ft(n,e){if(n==="localhost"||n.startsWith("127.")||n.startsWith("192.168."))return null;if(e){const i=e.toLowerCase(),l=n.toLowerCase();if(l===i||l===`www.${i}`)return null;if(l.endsWith(`.${i}`)){const c=l.slice(0,-(i.length+1));return c==="www"?null:c}return null}const s=n.split(".");return s.length>=3&&s[0]!=="www"?s[0]:null}function It(n,e="tenant",t){const i=new URLSearchParams(n).get(e);return i?(t&&t.setItem("tenant",i),i):t?t.getItem("tenant"):null}function Lt(n,e,t){const{tenantMode:s,baseDomain:i,selectorParam:l,fixedTenantSlug:c}=n;return s==="fixed"?c||null:s==="subdomain"?Ft(e.hostname,i):s==="selector"?It(e.search,l,t):null}function Nt(n,e,t){if(t)return`${n}.${t}`;const s=e.split(".");return s.length===2?`${n}.${e}`:s.length>=3?(s[0]=n,s.join(".")):null}const Ie=o.createContext(null);function Ct({config:n,children:e}){var O,H,M;const{baseUrl:t,appInfo:s,appId:i}=pe(),l=o.useCallback(()=>typeof window>"u"?null:Lt({tenantMode:n.tenantMode||"selector",baseDomain:n.baseDomain,selectorParam:n.selectorParam,fixedTenantSlug:n.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[n.tenantMode,n.baseDomain,n.selectorParam,n.fixedTenantSlug]),[c,h]=o.useState(()=>l()),w=((O=n.cache)==null?void 0:O.enabled)??!0,j=((H=n.cache)==null?void 0:H.ttl)??5*60*1e3,u=((M=n.cache)==null?void 0:M.storageKey)??`tenant_cache_${c||"default"}`,S=o.useMemo(()=>({enabled:w,ttl:j,storageKey:u}),[w,j,u]),[p,E]=o.useState(()=>{if(n.initialTenant)return n.initialTenant;if(!S.enabled||!c)return null;try{const D=localStorage.getItem(S.storageKey);if(!D)return null;const F=JSON.parse(D);return Date.now()-F.timestamp<S.ttl&&F.tenantSlug===c?F.data:(localStorage.removeItem(S.storageKey),null)}catch{return null}}),[R,P]=o.useState(!p&&!n.initialTenant),[A,T]=o.useState(null),[m,g]=o.useState(null),[b,L]=o.useState(!1),[a,f]=o.useState(null);o.useEffect(()=>{if(n.tenantMode==="fixed")return;const D=l();h(D)},[l,n.tenantMode]);const k=(s==null?void 0:s.settingsSchema)||null,y=o.useCallback(async(D,F=!1)=>{if(!(!F&&S.enabled&&p&&p.subdomain===D))try{P(!0),T(null);const B=new ae(t),V=await new ce(B,i).getPublicTenantInfo(D);if(E(V),S.enabled)try{const Q={data:V,timestamp:Date.now(),tenantSlug:D};localStorage.setItem(S.storageKey,JSON.stringify(Q))}catch(Q){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",Q)}}catch(B){const $=B instanceof Error?B:new Error("Failed to load tenant information");T($),E(null)}finally{P(!1)}},[t,i,S,p]),d=o.useCallback(async()=>{if(!(!S.enabled||!p||!c))try{const D=localStorage.getItem(S.storageKey);if(!D)return;const F=JSON.parse(D);if(Date.now()-F.timestamp>S.ttl*.5){const $=new ae(t),Q=await new ce($,i).getPublicTenantInfo(c);E(Q);const J={data:Q,timestamp:Date.now(),tenantSlug:c};localStorage.setItem(S.storageKey,JSON.stringify(J))}}catch(D){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",D)}},[t,i,S,p,c]),v=o.useCallback(async()=>{if(p!=null&&p.id)try{L(!0),f(null);const D=new ae(t),B=await new ce(D,p.appId).getTenantSettings(p.id);g(B)}catch(D){const F=D instanceof Error?D:new Error("Failed to load tenant settings");f(F),g(null)}finally{L(!1)}},[t,p]),N=o.useCallback(()=>{v()},[v]),Y=o.useCallback(D=>{if(!k)return{isValid:!0,errors:[]};const F=[];try{return k.properties&&Object.entries(k.properties).forEach(([B,$])=>{var Q;const V=D[B];if((Q=k.required)!=null&&Q.includes(B)&&V==null){F.push(`Field '${B}' is required`);return}if(V!=null){if($.type){const J=$.type,re=typeof V;J==="string"&&re!=="string"?F.push(`Field '${B}' must be a string`):(J==="number"||J==="integer")&&re!=="number"?F.push(`Field '${B}' must be a number`):J==="boolean"&&re!=="boolean"?F.push(`Field '${B}' must be a boolean`):J==="array"&&!Array.isArray(V)&&F.push(`Field '${B}' must be an array`)}$.minLength!==void 0&&typeof V=="string"&&V.length<$.minLength&&F.push(`Field '${B}' must be at least ${$.minLength} characters long`),$.maxLength!==void 0&&typeof V=="string"&&V.length>$.maxLength&&F.push(`Field '${B}' must be no more than ${$.maxLength} characters long`),$.minimum!==void 0&&typeof V=="number"&&V<$.minimum&&F.push(`Field '${B}' must be at least ${$.minimum}`),$.maximum!==void 0&&typeof V=="number"&&V>$.maximum&&F.push(`Field '${B}' must be no more than ${$.maximum}`),$.pattern&&typeof V=="string"&&(new RegExp($.pattern).test(V)||F.push(`Field '${B}' does not match the required pattern`)),$.enum&&!$.enum.includes(V)&&F.push(`Field '${B}' must be one of: ${$.enum.join(", ")}`)}}),{isValid:F.length===0,errors:F}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[k]);o.useEffect(()=>{!n.initialTenant&&c?p?d():y(c):!n.initialTenant&&!c&&(E(null),T(null),P(!1))},[n.initialTenant,c,p,y,d]),o.useEffect(()=>{p!=null&&p.id?v():(g(null),f(null),L(!1))},[p==null?void 0:p.id,v]);const I=o.useCallback((D,F)=>{const{mode:B="reload",redirectPath:$}=F||{},V=n.tenantMode||"selector";if(V==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",n.fixedTenantSlug),$&&(window.location.href=$);return}if(localStorage.setItem("tenant",D),V==="subdomain"){const Q=window.location.hostname,J=Nt(D,Q,n.baseDomain);if(!J){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",Q);return}const re=$||window.location.pathname,fe=new URL(`${window.location.protocol}//${J}${re}`);new URLSearchParams(window.location.search).forEach((ke,Ee)=>{fe.searchParams.set(Ee,ke)}),window.location.href=fe.toString()}else if(V==="selector"){const Q=$||window.location.pathname,J=new URLSearchParams(window.location.search);if(J.set(n.selectorParam||"tenant",D),B==="reload"){const re=`${Q}?${J.toString()}${window.location.hash}`;window.location.href=re}else{const re=`${Q}?${J.toString()}${window.location.hash}`;window.history.pushState({},"",re),h(D),y(D)}}},[n.tenantMode,n.selectorParam,n.baseDomain,n.fixedTenantSlug,y]),z=o.useMemo(()=>({tenant:p,tenantSlug:c,isTenantLoading:R,tenantError:A,retryTenant:()=>{c&&y(c)},settings:m,settingsSchema:k,isSettingsLoading:b,settingsError:a,refreshSettings:N,switchTenant:I,validateSettings:Y}),[p,c,R,A,m,k,b,a,N,I,Y]);return r.jsx(Ie.Provider,{value:z,children:e})}function ue(){const n=o.useContext(Ie);if(!n)throw new Error("useTenant must be used within a TenantProvider");return n}function le(){return o.useContext(Ie)}const Mt=ue;function Dt(){const{settings:n,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:i}=ue();return{settings:n,settingsSchema:e,isLoading:t,error:s,validateSettings:i}}function Le(){const{tenant:n,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:i}=ue();return{tenant:n,tenantSlug:e,isLoading:t,error:s,retry:i}}const Ne="userTenants";function $t(){try{const n=localStorage.getItem(Ne);return n?JSON.parse(n):[]}catch{return[]}}function Ge(n){try{localStorage.setItem(Ne,JSON.stringify(n))}catch{}}function We(){try{localStorage.removeItem(Ne)}catch{}}const xe=o.createContext(null),ve=o.createContext(null);function Ut({config:n={},children:e}){const t=Fe(),s=le(),i=(t==null?void 0:t.baseUrl)??n.baseUrl??"",l=(t==null?void 0:t.appId)??n.appId,c=(s==null?void 0:s.tenant)??null,h=(s==null?void 0:s.tenantSlug)??null,w=(s==null?void 0:s.switchTenant)??(()=>{});if(!i)throw new Error("[AuthProvider] baseUrl is required. Provide it via AppProvider or AuthConfig.baseUrl.");const[j,u]=o.useState(n.initialRoles||[]),[S,p]=o.useState(!n.initialRoles),[E,R]=o.useState(null),[P,A]=o.useState(!1),[T,m]=o.useState(null),[g,b]=o.useState(()=>$t()),L=o.useRef({done:!1});L.current.done||(L.current.done=!0);const a=o.useMemo(()=>ye.getInstance({baseUrl:i,enableCookieSession:n.enableCookieSession,refreshQueueTimeout:n.refreshQueueTimeout,proactiveRefreshMargin:n.proactiveRefreshMargin,onSessionExpired:x=>{R(null),m(null),b([]),We(),n.onSessionExpired?n.onSessionExpired(x):n.onRefreshFailed&&n.onRefreshFailed()}}),[i,n.enableCookieSession,n.refreshQueueTimeout,n.proactiveRefreshMargin]),[f,k]=o.useState(()=>{const x=a.getTokens();return x?a.hasValidSession()||!!x.refreshToken:!!n.enableCookieSession}),y=L.current.done&&!f,d=o.useMemo(()=>{const x=new ae(i);return x.setSessionManager(a),x},[i,a]),v=o.useMemo(()=>new et(d),[d]),N=o.useMemo(()=>new rt(d),[d]),Y=o.useMemo(()=>new tt(d),[d]),I=o.useMemo(()=>E!=null&&E.roleId&&j.find(x=>x.id===E.roleId)||null,[E,j]),z=o.useMemo(()=>(I==null?void 0:I.permissions)||[],[I]),O=o.useMemo(()=>a.hasValidSession()&&E!==null,[a,E]),H=o.useMemo(()=>(E==null?void 0:E.tenantId)!=null,[E]),M=o.useRef(null),D=async(x=!1)=>{try{if(!a.hasValidSession()||!x&&E)return;const C=a.getUserId();if(!C){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}A(!0),m(null);const _=await N.getUserById(C);R(_),a.setUser(_)}catch(C){const _=C instanceof Error?C:new Error("Failed to load user data");m(_),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",_)}finally{A(!1)}},F=async x=>{var _e;const{username:C,password:_,tenantSlug:U,redirectPath:G}=x;let K=c==null?void 0:c.id,W=h;U&&(K=(await new ce(d,l).getPublicTenantInfo(U)).id,W=U);const q=await v.login({username:C,password:_,appId:l,tenantId:K}),me=U&&U!==h;if(a.setTokens({accessToken:q.accessToken,refreshToken:q.refreshToken,expiresIn:q.expiresIn}),q.user){a.setUser(q.user),R(q.user);try{await D()}catch(ge){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",ge)}}q.tenants&&q.tenants.length>0&&(b(q.tenants),Ge(q.tenants));const Be=((_e=q.user)==null?void 0:_e.tenantId)!==null;if(me&&W)return w(W,{redirectPath:G}),q;if(G&&G!==window.location.pathname)return w(W||h||"",{redirectPath:G}),q;if(!Be&&q.tenants&&q.tenants.length>0){const ge=x.autoSwitch!==!1&&n.autoSwitchSingleTenant!==!1;if(q.tenants.length===1&&ge){const Oe=q.tenants[0];return w(Oe.subdomain,{redirectPath:G}),q}else q.tenants.length>1&&n.onTenantSelectionRequired&&n.onTenantSelectionRequired(q.tenants)}return q},B=async x=>{const{email:C,phoneNumber:_,name:U,password:G,lastName:K,tenantId:W}=x;if(!C&&!_)throw new Error("Either email or phoneNumber is required");if(!U||!G)throw new Error("Name and password are required");return v.signup({email:C,phoneNumber:_,name:U,password:G,tenantId:W??(c==null?void 0:c.id),lastName:K,appId:l})},$=async x=>{const{email:C,phoneNumber:_,name:U,password:G,tenantName:K,lastName:W}=x;if(!C&&!_)throw new Error("Either email or phoneNumber is required");if(!U||!G||!K)throw new Error("Name, password, and tenantName are required");return v.signupTenantAdmin({email:C,phoneNumber:_,name:U,password:G,tenantName:K,appId:l,lastName:W})},V=async x=>{await v.changePassword(x)},Q=async x=>{const{email:C,tenantId:_}=x,U=_??(c==null?void 0:c.id);if(!U)throw new Error("tenantId is required for password reset");await v.requestPasswordReset({email:C,tenantId:U})},J=async x=>{await v.confirmPasswordReset(x)},re=async x=>{const{email:C,frontendUrl:_,name:U,lastName:G,tenantId:K}=x,W=K??(c==null?void 0:c.id);if(!W)throw new Error("tenantId is required for magic link authentication");return v.sendMagicLink({email:C,tenantId:W,frontendUrl:_,name:U,lastName:G,appId:l})},fe=async x=>{const{token:C,email:_,tenantSlug:U}=x;let G=c==null?void 0:c.id,K=h;U&&(G=(await new ce(d,l).getPublicTenantInfo(U)).id,K=U);const W=await v.verifyMagicLink({token:C,email:_,appId:l,tenantId:G}),q=U&&U!==h;if(a.setTokens({accessToken:W.accessToken,refreshToken:W.refreshToken,expiresIn:W.expiresIn}),W.user){a.setUser(W.user),R(W.user);try{await D()}catch(me){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",me)}}return q&&K&&K!==h&&w(K),W},Ue=async()=>{const x=a.getTokens();if(!(x!=null&&x.refreshToken))throw new Error("No refresh token available");const C=await v.refreshToken({refreshToken:x.refreshToken});a.setTokens({accessToken:C.accessToken,refreshToken:C.refreshToken||x.refreshToken,expiresIn:C.expiresIn})},ke=()=>{a.clearSession(),R(null),m(null),b([]),We()},Ee=x=>{a.setTokens(x)},ht=()=>a.hasValidSession(),pt=()=>{a.clearSession(),R(null),m(null)},ft=async()=>{if(l)try{p(!0);const{roles:x}=await Y.getRolesByApp(l);u(x)}catch(x){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",x)}finally{p(!1)}},mt=async(x,C)=>{const{redirectPath:_}=C||{},U=a.getTokens();if(!(U!=null&&U.refreshToken))throw new Error("No refresh token available for tenant switch");const G=await v.switchTenant({refreshToken:U.refreshToken,tenantId:x});a.setTokens({accessToken:G.accessToken,refreshToken:U.refreshToken,expiresIn:G.expiresIn}),R(G.user),a.setUser(G.user);const K=g.find(W=>W.id===x);K&&w(K.subdomain,{redirectPath:_})},gt=async()=>{const x=await v.getUserTenants();return b(x),Ge(x),x};M.current={login:F,signup:B,signupTenantAdmin:$,sendMagicLink:re,verifyMagicLink:fe,changePassword:V,requestPasswordReset:Q,confirmPasswordReset:J,refreshToken:Ue,logout:ke,setTokens:Ee,hasValidSession:ht,clearSession:pt,loadUserData:D,refreshUser:()=>D(),refreshRoles:ft,switchToTenant:mt,refreshUserTenants:gt};const yt=o.useMemo(()=>({login:x=>M.current.login(x),signup:x=>M.current.signup(x),signupTenantAdmin:x=>M.current.signupTenantAdmin(x),sendMagicLink:x=>M.current.sendMagicLink(x),verifyMagicLink:x=>M.current.verifyMagicLink(x),changePassword:x=>M.current.changePassword(x),requestPasswordReset:x=>M.current.requestPasswordReset(x),confirmPasswordReset:x=>M.current.confirmPasswordReset(x),refreshToken:()=>M.current.refreshToken(),logout:()=>M.current.logout(),setTokens:x=>M.current.setTokens(x),hasValidSession:()=>M.current.hasValidSession(),clearSession:()=>M.current.clearSession(),loadUserData:x=>M.current.loadUserData(x),refreshUser:()=>M.current.refreshUser(),refreshRoles:()=>M.current.refreshRoles(),switchToTenant:(x,C)=>M.current.switchToTenant(x,C),refreshUserTenants:()=>M.current.refreshUserTenants()}),[]),bt=o.useMemo(()=>{const x=C=>!z||z.length===0?!1:typeof C=="string"?z.includes(C):z.includes(`${C.resource}.${C.action}`);return{isAuthenticated:O,isAuthInitializing:!y,isAuthReady:y,currentUser:E,isUserLoading:P,userError:T,userRole:I,userPermissions:z,availableRoles:j,rolesLoading:S,userTenants:g,hasTenantContext:H,sessionManager:a,authenticatedHttpService:d,hasPermission:x,hasAnyPermission:C=>C.some(_=>x(_)),hasAllPermissions:C=>C.every(_=>x(_)),getUserPermissionStrings:()=>z||[]}},[O,y,E,P,T,I,z,j,S,g,H,a,d]);return o.useEffect(()=>{if(n.initialRoles||!l)return;let x=!1;return p(!0),Y.getRolesByApp(l).then(({roles:C})=>{x||u(C)}).catch(C=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",C)}).finally(()=>{x||p(!1)}),()=>{x=!0}},[l,n.initialRoles,Y]),o.useEffect(()=>{let x=!1;return(async()=>{var U;if(!a.hasValidSession()&&((U=a.getTokens())!=null&&U.refreshToken)&&await a.waitForPendingRefresh(),x||!a.hasValidSession()&&!a.getTokens()&&n.enableCookieSession&&(await a.attemptCookieSessionRestore(),x))return;const _=a.getUser();_&&a.hasValidSession()&&R(_),k(!1)})(),()=>{x=!0}},[a,n.enableCookieSession]),o.useEffect(()=>{!E&&!P&&!T&&a.hasValidSession()?M.current.loadUserData().catch(()=>{}).finally(()=>{k(!1)}):k(!1)},[E,P,T,a]),r.jsx(ve.Provider,{value:yt,children:r.jsx(xe.Provider,{value:bt,children:e})})}function Bt(){const n=o.useContext(xe);if(!n)throw new Error("useAuthState must be used within an AuthProvider");return n}function _t(){const n=o.useContext(ve);if(!n)throw new Error("useAuthActions must be used within an AuthProvider");return n}function oe(){const n=o.useContext(xe),e=o.useContext(ve);if(!n||!e)throw new Error("useAuth must be used within an AuthProvider");return o.useMemo(()=>({...n,...e}),[n,e])}function we(){const n=o.useContext(xe),e=o.useContext(ve);return o.useMemo(()=>!n||!e?null:{...n,...e},[n,e])}class nt{constructor(e){this.httpService=e}async createFeatureFlag(e){return(await this.httpService.post("/feature-flags/",e)).data}async getFeatureFlags(e){const t=await this.httpService.get(`/feature-flags/${se(e)}`);return{featureFlags:t.data,meta:t.meta}}async getFeatureFlagById(e){return(await this.httpService.get(`/feature-flags/${e}`)).data}async updateFeatureFlag(e,t){return(await this.httpService.put(`/feature-flags/${e}`,t)).data}async deleteFeatureFlag(e){await this.httpService.delete(`/feature-flags/${e}`)}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const s=se({tenantId:e,appId:t});return(await this.httpService.get(`/tenant-feature-flags${s}`,{headers:{"X-Tenant-ID":e},skipAuth:!0})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const i=se({tenantId:t,appId:s});return(await this.httpService.get(`/tenant-feature-flags/${e}${i}`,{headers:{"X-Tenant-ID":t},skipAuth:!0})).data}}const Ce=o.createContext(null);function Ot({config:n={},children:e}){const t=Fe(),s=le(),i=(t==null?void 0:t.baseUrl)??"",l=(t==null?void 0:t.appId)??"",c=(s==null?void 0:s.tenant)??null,[h,w]=o.useState([]),[j,u]=o.useState(!1),[S,p]=o.useState(null),[E,R]=o.useState(!1),P=o.useMemo(()=>{const m=new ae(i);return new nt(m)},[i]),A=async()=>{if(!(c!=null&&c.id)){w([]);return}u(!0),p(null);try{const m=await P.getTenantFeatureFlags(c.id,l);w(m)}catch(m){const g=m instanceof Error?m.message:"Failed to fetch feature flags";p(g),n.onError&&n.onError(m instanceof Error?m:new Error(g))}finally{u(!1)}};o.useEffect(()=>{if(!i||!l)return;A().finally(()=>R(!0));const m=n.refreshInterval||5*60*1e3,g=setInterval(A,m);return()=>clearInterval(g)},[c==null?void 0:c.id,i,l,n.refreshInterval]);const T=o.useMemo(()=>{const m=f=>{const k=h.find(y=>y.key===f);return(k==null?void 0:k.value)===!0},g=f=>h.find(k=>k.key===f),b=f=>{const k=h.find(y=>y.key===f);return k?k.value?"enabled":"disabled":"not_found"},L=async()=>{await A()},a=!!(i&&l)&&(E||!(c!=null&&c.id));return{featureFlags:h,loading:j,error:S,isReady:a,isEnabled:m,getFlag:g,getFlagState:b,refresh:L}},[h,j,S,i,l,c==null?void 0:c.id,E]);return r.jsx(Ce.Provider,{value:T,children:e})}function st(){const n=o.useContext(Ce);if(!n)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return n}function it(){return o.useContext(Ce)}class ot{constructor(e){this.httpService=e}async createSubscription(e){return(await this.httpService.post("/subscriptions/",e)).data}async getSubscriptionById(e){return(await this.httpService.get(`/subscriptions/subscriptions/${e}`)).data}async updateSubscription(e,t){return(await this.httpService.put(`/subscriptions/${e}`,t)).data}async changeSubscriptionPlan(e,t){return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`,{skipAuth:!0})).data}async processPayment(e,t){return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t)).data}}const Me=o.createContext(void 0);function Vt({config:n={},children:e}){const t=Fe(),s=le(),i=(t==null?void 0:t.baseUrl)??"",l=(s==null?void 0:s.tenant)??null,[c,h]=o.useState(null),[w,j]=o.useState(!1),[u,S]=o.useState(null),[p,E]=o.useState(!1),R=o.useMemo(()=>{const T=new ae(i);return new ot(T)},[i]),P=async()=>{if(!(l!=null&&l.id)){h(null);return}j(!0),S(null);try{const T=await R.getTenantSubscriptionFeatures(l.id);h(T)}catch(T){const m=T instanceof Error?T.message:"Failed to fetch subscription";S(m),n.onError&&n.onError(T instanceof Error?T:new Error(m))}finally{j(!1)}};o.useEffect(()=>{if(!i||(P().finally(()=>E(!0)),!n.refreshInterval))return;const T=n.refreshInterval||10*60*1e3,m=setInterval(P,T);return()=>clearInterval(m)},[l==null?void 0:l.id,i,n.refreshInterval]);const A=o.useMemo(()=>{const T=(c==null?void 0:c.features)||[],m=k=>{const y=T.find(d=>d.key===k);return y?y.type==="BOOLEAN"||y.type==="boolean"?y.value===!0:!!y.value:!1},g=k=>T.find(y=>y.key===k),b=(k,y)=>{const d=T.find(v=>v.key===k);return d?d.value:y},L=k=>!c||!c.isActive?!1:k.includes(c.planId),a=async()=>{await P()},f=!!i&&(p||!(l!=null&&l.id));return{subscription:c,features:T,loading:w,error:u,isReady:f,isFeatureEnabled:m,getFeature:g,getFeatureValue:b,hasAllowedPlan:L,refresh:a}},[c,w,u,i,l==null?void 0:l.id,p]);return r.jsx(Me.Provider,{value:A,children:e})}function at(){const n=o.useContext(Me);if(n===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return n}function lt(){return o.useContext(Me)??null}var te=(n=>(n.SUPERUSER="SUPERUSER",n.TENANT_ADMIN="TENANT_ADMIN",n.USER="USER",n))(te||{});const Se={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},De={landing:{tenant:"forbidden",auth:"optional"},publicOnly:{tenant:"forbidden",auth:"forbidden"},login:{tenant:"required",auth:"forbidden"},guest:{auth:"forbidden"},authenticated:{auth:"required"},tenant:{tenant:"required"},tenantOpen:{tenant:"required",auth:"optional"},tenantAuth:{tenant:"required",auth:"required"},user:{tenant:"required",auth:"required",userType:te.USER},admin:{tenant:"required",auth:"required",userType:te.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},$e=o.createContext(null),qt={zoneRoots:Se,presets:De,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"};function zt({config:n={},children:e}){const t=o.useMemo(()=>{const s={...Se,...n.zoneRoots},i={...De,...n.presets};return{zoneRoots:s,presets:i,loadingFallback:n.loadingFallback??null,accessDeniedFallback:n.accessDeniedFallback??null,onAccessDenied:n.onAccessDenied,returnToParam:n.returnToParam??"returnTo",returnToStorage:n.returnToStorage??"url"}},[n]);return r.jsx($e.Provider,{value:t,children:e})}function Gt(){const n=o.useContext($e);if(!n)throw new Error("useRouting must be used within a RoutingProvider");return n}function ct(){return o.useContext($e)??qt}const He=()=>r.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:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.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"})]}),Ze=({userType:n,minUserType:e,missingPermissions:t})=>r.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:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&n?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:n})]})]}):r.jsxs(r.Fragment,{children:[r.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&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),Wt=(n,e)=>{const t={[te.USER]:1,[te.TENANT_ADMIN]:2,[te.SUPERUSER]:3};return t[n]>=t[e]};function Ht({children:n,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:i=!1}){const{hasValidSession:l,sessionManager:c,hasPermission:h,hasAnyPermission:w,hasAllPermissions:j}=oe();if(!l())return r.jsx(r.Fragment,{children:e||r.jsx(He,{})});const u=c.getUser();if(!u)return r.jsx(r.Fragment,{children:e||r.jsx(He,{})});if(t&&!Wt(u.userType,t))return r.jsx(Ze,{userType:u.userType,minUserType:t});if(s&&s.length>0&&!(i?j(s):w(s))){const p=s.filter(E=>!h(E)).map(E=>typeof E=="string"?E:E.name);return r.jsx(Ze,{missingPermissions:p})}return r.jsx(r.Fragment,{children:n})}const Zt=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})}),Qe=({userType:n,requiredUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&n?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",r.jsx("strong",{children:n})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),Qt=(n,e)=>n===e;function Jt({children:n,redirectTo:e="/login",requiredUserType:t,requiredPermissions:s,requireAllPermissions:i=!1,fallback:l}){const{hasValidSession:c,sessionManager:h,hasPermission:w,hasAnyPermission:j,hasAllPermissions:u}=oe(),S=ne.useLocation();if(o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!c())return l?r.jsx(r.Fragment,{children:l}):r.jsxs(r.Fragment,{children:[r.jsx(Zt,{redirectPath:e}),r.jsx(ne.Navigate,{to:e,state:{from:S.pathname},replace:!0})]});const p=h.getUser();if(!p)return r.jsx(ne.Navigate,{to:e,state:{from:S.pathname},replace:!0});if(t&&!Qt(p.userType,t))return r.jsx(Qe,{userType:p.userType,requiredUserType:t});if(s&&s.length>0&&!(i?u(s):j(s))){const R=s.filter(P=>!w(P)).map(P=>typeof P=="string"?P:P.name);return r.jsx(Qe,{missingPermissions:R})}return r.jsx(r.Fragment,{children:n})}const Kt=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})});function Yt({children:n,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:i,error:l}=Le(),c=ne.useLocation();return o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),i||l?null:s?r.jsx(r.Fragment,{children:n}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Kt,{redirectPath:e}),r.jsx(ne.Navigate,{to:e,state:{from:c.pathname},replace:!0})]})}const Xt=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})});function er({children:n,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:i,error:l}=Le(),c=ne.useLocation();return o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),i||l?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Xt,{redirectPath:e}),r.jsx(ne.Navigate,{to:e,state:{from:c.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:n})}function tr(n,e){return e?n?Array.isArray(e)?e.includes(n):n===e:!1:!0}function Je(n,e){return!n||n==="optional"?"skip":n==="required"?e?"pass":"fail":n==="forbidden"?e?"fail":"pass":"skip"}function rr(n,e){return Je(n.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":Je(n.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":n.userType&&e.isAuthenticated&&!tr(e.userType,n.userType)?"wrong_user_type":n.permissions&&n.permissions.length>0&&!(n.requireAllPermissions!==!1?l=>l.every(c=>e.permissions.includes(c)):l=>l.some(c=>e.permissions.includes(c)))(n.permissions)?"missing_permissions":null}function nr(n,e){return n.hasTenant?n.isAuthenticated?n.userType===te.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:n.isAuthenticated?n.userType===te.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function sr(n,e,t,s,i){if(!e||i!=="url")return n;const l=typeof e=="string"?e:t,c=n.includes("?")?"&":"?";return`${n}${c}${s}=${encodeURIComponent(l)}`}function ir(n,e,t){if(!n||t==="url")return;const s=typeof n=="string"?n:e,i="zone_return_to";t==="session"?sessionStorage.setItem(i,s):t==="local"&&localStorage.setItem(i,s)}const ie=({children:n,preset:e,tenant:t,auth:s,userType:i,requiredPermissions:l,requireAllPermissions:c=!0,returnTo:h,onAccessDenied:w,redirectTo:j,loadingFallback:u,accessDeniedFallback:S})=>{const p=ne.useLocation(),{isAuthenticated:E,isAuthInitializing:R,currentUser:P,userPermissions:A}=oe(),{tenant:T,isTenantLoading:m}=ue(),g=ct(),b=o.useMemo(()=>{if(e)return g.presets[e]},[e,g.presets]),L=o.useMemo(()=>({tenant:t??(b==null?void 0:b.tenant),auth:s??(b==null?void 0:b.auth),userType:i??(b==null?void 0:b.userType),permissions:l??(b==null?void 0:b.requiredPermissions),requireAllPermissions:c}),[t,s,i,l,b,c]),a=o.useMemo(()=>({hasTenant:!!T,isAuthenticated:E,userType:P==null?void 0:P.userType,permissions:A,isLoading:R||m}),[T,E,P==null?void 0:P.userType,A,R,m]),f=o.useMemo(()=>a.isLoading?null:rr(L,a),[L,a]),k=o.useMemo(()=>f?j||nr(a,g.zoneRoots):null,[f,j,a,g.zoneRoots]),y=o.useMemo(()=>!f||!k?null:{type:f,required:{tenant:L.tenant,auth:L.auth,userType:L.userType,permissions:L.permissions},current:{hasTenant:a.hasTenant,isAuthenticated:a.isAuthenticated,userType:a.userType,permissions:a.permissions},redirectTo:k},[f,k,L,a]);if(o.useEffect(()=>{y&&(w?w(y):g.onAccessDenied&&g.onAccessDenied(y))},[y,w,g]),o.useEffect(()=>{y&&h&&ir(h,p.pathname+p.search,g.returnToStorage)},[y,h,p.pathname,p.search,g.returnToStorage]),a.isLoading)return r.jsx(r.Fragment,{children:u??g.loadingFallback??null});if(y&&k){const d=S??g.accessDeniedFallback;if(d)return r.jsx(r.Fragment,{children:d});const v=sr(k,h,p.pathname+p.search,g.returnToParam,g.returnToStorage);return r.jsx(ne.Navigate,{to:v,replace:!0})}return r.jsx(r.Fragment,{children:n})},or=n=>r.jsx(ie,{tenant:"required",...n}),ar=n=>r.jsx(ie,{tenant:"forbidden",...n}),lr=n=>r.jsx(ie,{auth:"required",...n}),cr=n=>r.jsx(ie,{auth:"forbidden",...n}),ur=n=>r.jsx(ie,{auth:"required",userType:te.TENANT_ADMIN,...n}),dr=n=>r.jsx(ie,{auth:"required",userType:te.USER,...n}),hr=n=>r.jsx(ie,{tenant:"optional",auth:"optional",...n}),pr=n=>r.jsx(ie,{tenant:"required",auth:"required",...n}),fr=n=>r.jsx(ie,{tenant:"required",auth:"optional",...n}),mr=n=>r.jsx(ie,{tenant:"required",auth:"forbidden",...n}),gr=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function yr({children:n,fallback:e=r.jsx(gr,{}),allowedPlans:t,requiredFeature:s}){const{subscription:i,hasAllowedPlan:l,isFeatureEnabled:c,loading:h}=at();return h?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):i?i.isActive?t&&t.length>0&&!l(t)?r.jsx(r.Fragment,{children:e}):s&&!c(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:n}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const br=({flagName:n})=>r.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:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',n,'" is disabled']})]});function xr({name:n,children:e,fallback:t}){const{isEnabled:s,loading:i}=st();return i?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):s(n)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(br,{flagName:n})})}function he(n){const{submit:e,defaultErrorMessage:t,validate:s,onSuccess:i,onError:l}=n,[c,h]=o.useState(!1),[w,j]=o.useState(""),[u,S]=o.useState({}),p=o.useCallback((A,T)=>{S(m=>({...m,[A]:T}))},[]),E=o.useCallback(A=>{S(T=>{if(!T[A])return T;const m={...T};return delete m[A],m})},[]),R=o.useCallback(()=>{j(""),S({})},[]),P=o.useCallback(async A=>{if(A&&A.preventDefault(),!(s&&!s())){h(!0),j("");try{const T=await e();return i==null||i(T),T}catch(T){const m=T instanceof Error?T.message:t;j(m),l==null||l(m);return}finally{h(!1)}}},[e,s,t,i,l]);return{loading:c,error:w,setError:j,fieldErrors:u,setFieldError:p,clearFieldError:E,resetErrors:R,handleSubmit:P}}const 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"},inputWithIcon:{paddingRight:"2.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},hintText:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},verifyingContainer:{textAlign:"center",padding:"2rem"},verifyingText:{fontSize:"1rem",color:"#6b7280"},toggleContainer:{textAlign:"center",marginTop:"0.5rem"},toggleLink:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},modeSwitchDivider:{margin:"0 0.5rem",color:"#6b7280"}};function Te(n,e){return{...Ke,...e,button:{...Ke.button,backgroundColor:n,...(e==null?void 0:e.button)||{}}}}const vr=()=>o.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0}},o.createElement("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),o.createElement("circle",{cx:"12",cy:"12",r:"3"})),wr=()=>o.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0}},o.createElement("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"}),o.createElement("line",{x1:"1",y1:"1",x2:"23",y2:"23"})),Sr={showPassword:r.jsx(vr,{}),hidePassword:r.jsx(wr,{})},Tr={title:"Sign In",usernameLabel:"Email or Phone",usernamePlaceholder:"Enter your email or phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Invalid credentials",loadingText:"Signing in...",tenantNotFoundError:"Tenant not found",dividerBullet:"•",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password"};function kr({copy:n={},styles:e={},icons:t={},onSuccess:s,onError:i,onForgotPassword:l,onSignupClick:c,onMagicLinkClick:h,showForgotPassword:w=!0,showSignupLink:j=!0,showMagicLinkOption:u=!0,className:S}){const[p,E]=o.useState(""),[R,P]=o.useState(""),[A,T]=o.useState(!1),{login:m}=oe(),g={...Tr,...n},b=Te("#3b82f6",e),L={...Sr,...t},a=he({defaultErrorMessage:g.errorMessage,validate:()=>{const d=[];return p.trim()||d.push("username"),R.trim()||d.push("password"),d.forEach(v=>a.setFieldError(v,!0)),d.length===0},submit:()=>m({username:p,password:R}),onSuccess:s,onError:i}),f=d=>({...b.input,...a.fieldErrors[d]?b.inputError:{}}),k=!p||!R||a.loading,y={...b.button,...a.loading?b.buttonLoading:{},...k?b.buttonDisabled:{}};return r.jsxs("div",{className:S,style:b.container,children:[r.jsx("h2",{style:b.title,children:g.title}),r.jsxs("form",{onSubmit:a.handleSubmit,style:b.form,children:[r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:g.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:p,onChange:d=>{E(d.target.value),a.clearFieldError("username")},placeholder:g.usernamePlaceholder,style:f("username"),disabled:a.loading})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:g.passwordLabel}),r.jsxs("div",{style:b.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:A?"text":"password",value:R,onChange:d=>{P(d.target.value),a.clearFieldError("password")},placeholder:g.passwordPlaceholder,style:{...f("password"),...b.inputWithIcon},disabled:a.loading}),r.jsx("button",{type:"button",onClick:()=>T(!A),style:b.passwordToggle,disabled:a.loading,"aria-label":A?g.hidePasswordAriaLabel:g.showPasswordAriaLabel,children:A?L.hidePassword:L.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:k,style:y,children:a.loading?g.loadingText:g.submitButton}),a.error&&r.jsx("div",{style:b.errorText,children:a.error})]}),(w||j||u)&&r.jsxs("div",{style:b.linkContainer,children:[u&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[g.magicLinkText," "]}),r.jsx("a",{onClick:h,style:b.link,children:g.magicLinkLink})]}),u&&(w||j)&&r.jsx("div",{style:b.divider,children:g.dividerBullet}),w&&r.jsx("a",{onClick:l,style:b.link,children:g.forgotPasswordLink}),w&&j&&r.jsx("div",{style:b.divider,children:g.dividerBullet}),j&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[g.signupText," "]}),r.jsx("a",{onClick:c,style:b.link,children:g.signupLink})]})]})]})}const Er={title:"Create Account",nameLabel:"First Name",namePlaceholder:"Enter your first name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",emailLabel:"Email",emailPlaceholder:"Enter your email",phoneNumberLabel:"Phone Number",phoneNumberPlaceholder:"Enter your phone number",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?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",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",contactMethodHint:"At least one contact method (email or phone) is required",tenantNotFoundError:"Tenant not found",dividerBullet:"•"};function jr({copy:n={},styles:e={},signupType:t="user",onSuccess:s,onError:i,onLoginClick:l,onMagicLinkClick:c,showLoginLink:h=!0,showMagicLinkOption:w=!0,className:j}){var D;const[u,S]=o.useState(""),[p,E]=o.useState(""),[R,P]=o.useState(""),[A,T]=o.useState(""),[m,g]=o.useState(""),[b,L]=o.useState(""),[a,f]=o.useState(""),{signup:k,signupTenantAdmin:y}=oe(),d=((D=le())==null?void 0:D.tenant)??null,v={...Er,...n},N=Te("#10b981",e),Y=!!u&&(!!R||!!A)&&!!m&&!!b&&(t==="user"||!!a),I=he({defaultErrorMessage:v.errorMessage,validate:()=>{const F=[];return u.trim()||F.push("name"),!R.trim()&&!A.trim()&&(F.push("email"),F.push("phoneNumber")),m.trim()||F.push("password"),b.trim()||F.push("confirmPassword"),t==="tenant"&&!a.trim()&&F.push("tenantName"),F.forEach(B=>I.setFieldError(B,!0)),F.length>0?!1:m!==b?(I.setError(v.passwordMismatchError),I.setFieldError("confirmPassword",!0),!1):t==="user"&&!(d!=null&&d.id)?(I.setError(v.tenantNotFoundError),!1):!0},submit:async()=>t==="tenant"?y({email:R||void 0,phoneNumber:A||void 0,name:u,password:m,tenantName:a,lastName:p||void 0}):k({email:R||void 0,phoneNumber:A||void 0,name:u,password:m,tenantId:d.id,lastName:p||void 0}),onSuccess:s,onError:i}),z=F=>({...N.input,...I.fieldErrors[F]?N.inputError:{}}),O=!Y||I.loading,H={...N.button,...I.loading?N.buttonLoading:{},...O?N.buttonDisabled:{}},M=()=>{I.clearFieldError("email"),I.clearFieldError("phoneNumber")};return r.jsxs("div",{className:j,style:N.container,children:[r.jsx("h2",{style:N.title,children:v.title}),r.jsxs("form",{onSubmit:I.handleSubmit,style:N.form,children:[r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:u,onChange:F=>{S(F.target.value),I.clearFieldError("name")},placeholder:v.namePlaceholder,style:z("name"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:p,onChange:F=>E(F.target.value),placeholder:v.lastNamePlaceholder,style:N.input,disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:R,onChange:F=>{P(F.target.value),M()},placeholder:v.emailPlaceholder,style:z("email"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:A,onChange:F=>{T(F.target.value),M()},placeholder:v.phoneNumberPlaceholder,style:z("phoneNumber"),disabled:I.loading})]}),r.jsx("div",{style:N.hintText,children:v.contactMethodHint}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:m,onChange:F=>{g(F.target.value),I.clearFieldError("password")},placeholder:v.passwordPlaceholder,style:z("password"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:b,onChange:F=>{L(F.target.value),I.clearFieldError("confirmPassword"),I.error===v.passwordMismatchError&&I.setError("")},placeholder:v.confirmPasswordPlaceholder,style:z("confirmPassword"),disabled:I.loading})]}),t==="tenant"&&r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:v.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:a,onChange:F=>{f(F.target.value),I.clearFieldError("tenantName")},placeholder:v.tenantNamePlaceholder,style:z("tenantName"),disabled:I.loading})]}),r.jsx("button",{type:"submit",disabled:O,style:H,children:I.loading?v.loadingText:v.submitButton}),I.error&&r.jsx("div",{style:N.errorText,children:I.error})]}),(h||w)&&r.jsxs("div",{style:N.linkContainer,children:[w&&r.jsxs("div",{children:[r.jsxs("span",{style:N.divider,children:[v.magicLinkText," "]}),r.jsx("a",{onClick:c,style:N.link,children:v.magicLinkLink})]}),w&&h&&r.jsx("div",{style:N.divider,children:v.dividerBullet}),h&&r.jsxs("div",{children:[r.jsxs("span",{style:N.divider,children:[v.loginText," "]}),r.jsx("a",{onClick:l,style:N.link,children:v.loginLink})]})]})]})}const Ar={title:"Sign In with Magic Link",emailLabel:"Email",emailPlaceholder:"Enter your email",nameLabel:"Name",namePlaceholder:"Enter your name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",submitButton:"Send Magic Link",loginLink:"Sign in with password",signupLink:"Sign up with password",loginText:"Already have an account?",signupText:"Prefer traditional signup?",successMessage:"Magic link sent! Check your email and click the link to sign in.",errorMessage:"Failed to send magic link. Please try again.",loadingText:"Sending magic link...",verifyingText:"Verifying magic link...",verifyingDescription:"Please wait while we verify your magic link...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you.",showNameToggle:"New user? Add your name",hideNameToggle:"Existing user? Hide name fields",tenantNotFoundError:"Tenant not found",missingTenantOrEmailError:"Missing tenant or email",dividerBullet:"•"};function Rr({copy:n={},styles:e={},onSuccess:t,onError:s,onLoginClick:i,onSignupClick:l,showTraditionalLinks:c=!0,className:h,verifyToken:w,frontendUrl:j}){var z;const[u,S]=o.useState(""),[p,E]=o.useState(""),[R,P]=o.useState(""),[A,T]=o.useState(!1),[m,g]=o.useState(""),[b,L]=o.useState(!1),{sendMagicLink:a,verifyMagicLink:f}=oe(),k=((z=le())==null?void 0:z.tenant)??null,y={...Ar,...n},d=Te("#3b82f6",e),v=he({defaultErrorMessage:y.errorMessage,validate:()=>{const O=[];return u.trim()||O.push("email"),b&&!p.trim()&&O.push("name"),O.forEach(H=>v.setFieldError(H,!0)),O.length>0?!1:k!=null&&k.id?!0:(v.setError(y.tenantNotFoundError),!1)},submit:async()=>{g("");const O=j||(typeof window<"u"?window.location.origin:""),H=await a({email:u,tenantId:k.id,frontendUrl:O,name:b?p:void 0,lastName:b?R:void 0});return g(y.successMessage),H},onSuccess:t,onError:s});o.useEffect(()=>{if(!w)return;(async()=>{if(!k||!u){v.setError(y.missingTenantOrEmailError);return}T(!0),v.setError("");try{const H=await f({token:w,email:u});t==null||t(H)}catch(H){const M=H instanceof Error?H.message:"Failed to verify magic link";v.setError(M),s==null||s(M)}finally{T(!1)}})()},[w]);const N=O=>({...d.input,...v.fieldErrors[O]?d.inputError:{}}),Y=!u||v.loading||A,I={...d.button,...v.loading||A?d.buttonLoading:{},...Y?d.buttonDisabled:{}};return A?r.jsxs("div",{className:h,style:d.container,children:[r.jsx("h2",{style:d.title,children:y.verifyingText}),r.jsx("div",{style:d.verifyingContainer,children:r.jsx("div",{style:d.verifyingText,children:y.verifyingDescription})})]}):r.jsxs("div",{className:h,style:d.container,children:[r.jsx("h2",{style:d.title,children:y.title}),r.jsx("p",{style:d.description,children:y.description}),r.jsxs("form",{onSubmit:v.handleSubmit,style:d.form,children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:u,onChange:O=>{S(O.target.value),v.clearFieldError("email")},placeholder:y.emailPlaceholder,style:N("email"),disabled:v.loading||A})]}),!b&&r.jsx("div",{style:d.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>L(!0),style:d.toggleLink,children:y.showNameToggle})}),b&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:p,onChange:O=>{E(O.target.value),v.clearFieldError("name")},placeholder:y.namePlaceholder,style:N("name"),disabled:v.loading||A})]}),r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:R,onChange:O=>P(O.target.value),placeholder:y.lastNamePlaceholder,style:d.input,disabled:v.loading||A})]}),r.jsx("div",{style:d.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{L(!1),E(""),P("")},style:d.toggleLink,children:y.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:Y,style:I,children:v.loading?y.loadingText:y.submitButton}),v.error&&r.jsx("div",{style:d.errorText,children:v.error}),m&&r.jsx("div",{style:d.successText,children:m})]}),c&&r.jsxs("div",{style:d.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[y.loginText," "]}),r.jsx("a",{onClick:i,style:d.link,children:y.loginLink})]}),r.jsx("div",{style:d.divider,children:y.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[y.signupText," "]}),r.jsx("a",{onClick:l,style:d.link,children:y.signupLink})]})]})]})}const Pr={title:"Verifying Magic Link",verifyingMessage:"Please wait while we verify your magic link...",successMessage:"Magic link verified successfully! You are now logged in.",errorMessage:"Failed to verify magic link. The link may be expired or invalid.",redirectingMessage:"Redirecting you to the dashboard...",retryButton:"Try Again",backToLoginButton:"Back to Login",missingParamsError:"Missing required parameters: token or email"},ut={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},card:{backgroundColor:"transparent",padding:"0",borderRadius:"0",boxShadow:"none",maxWidth:"100%",width:"100%",textAlign:"center"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},message:{fontSize:"1rem",color:"#6b7280",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},successMessage:{fontSize:"1rem",color:"#059669",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},errorMessage:{fontSize:"0.875rem",color:"#ef4444",textAlign:"center",marginBottom:"1rem",lineHeight:"1.5"},spinner:{display:"inline-block",width:"20px",height:"20px",border:"2px solid #e5e7eb",borderTop:"2px solid #3b82f6",borderRadius:"50%",animation:"spin 1s linear infinite",marginRight:"0.5rem"},buttonContainer:{display:"flex",gap:"0.75rem",justifyContent:"center",flexWrap:"wrap",marginTop:"1rem"},retryButton:{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"},backButton:{padding:"0.75rem 1rem",backgroundColor:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"all 0.15s ease-in-out"},retryButtonHover:{backgroundColor:"#2563eb"},backButtonHover:{backgroundColor:"#e5e7eb"}},Fr=()=>r.jsx("div",{style:ut.spinner}),Ir=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),Lr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),Nr={loading:r.jsx(Fr,{}),success:r.jsx(Ir,{}),error:r.jsx(Lr,{})};function Cr({copy:n={},styles:e={},icons:t={},onSuccess:s,onError:i,onRetry:l,onBackToLogin:c,className:h,token:w,email:j,appId:u,tenantSlug:S,autoRedirectDelay:p=3e3}){const[E,R]=o.useState("verifying"),[P,A]=o.useState(""),{verifyMagicLink:T}=oe(),m={...Pr,...n},g={...ut,...e},b={...Nr,...t},L=()=>{if(typeof window>"u")return{};const d=new URLSearchParams(window.location.search);return{token:w||d.get("token")||"",email:j||d.get("email")||"",appId:u||d.get("appId")||"",tenantSlug:S||d.get("tenantSlug")||void 0}},a=async()=>{R("verifying"),A("");try{const d=L();if(!d.token||!d.email)throw new Error(m.missingParamsError);const v=await T({token:d.token,email:d.email,tenantSlug:d.tenantSlug});R("success"),s==null||s(v),p>0&&setTimeout(()=>{R("redirecting")},p)}catch(d){const v=d.message||m.errorMessage;A(v),R("error"),i==null||i(v)}},f=()=>{l==null||l(),a()},k=()=>{c==null||c()};o.useEffect(()=>{a()},[]);const y=()=>{switch(E){case"verifying":return r.jsxs("div",{style:g.message,children:[b.loading,m.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[b.success,r.jsx("div",{style:g.successMessage,children:m.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[b.loading,r.jsx("div",{style:g.message,children:m.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[b.error,r.jsx("div",{style:g.errorMessage,children:P||m.errorMessage}),r.jsxs("div",{style:g.buttonContainer,children:[r.jsx("button",{onClick:f,style:g.retryButton,onMouseOver:d=>{Object.assign(d.currentTarget.style,g.retryButtonHover)},onMouseOut:d=>{const v=g.retryButton||{};Object.keys(g.retryButtonHover||{}).forEach(N=>{d.currentTarget.style[N]=v[N]??""})},children:m.retryButton}),r.jsx("button",{onClick:k,style:g.backButton,onMouseOver:d=>{Object.assign(d.currentTarget.style,g.backButtonHover)},onMouseOut:d=>{const v=g.backButton||{};Object.keys(g.backButtonHover||{}).forEach(N=>{d.currentTarget.style[N]=v[N]??""})},children:m.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:g.container,className:h,children:[r.jsx("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`}),r.jsx("h1",{style:g.title,children:m.title}),y()]})}const vr={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",requestNewLinkLink:"Request New Link",haveTokenLink:"I have a token",tenantNotFoundError:"Tenant not found",dividerBullet:"•"};function Sr({copy:n={},styles:e={},mode:t="request",token:s="",onSuccess:i,onError:l,onBackToLogin:c,onModeChange:h,className:v}){var X;const[j,u]=o.useState(""),[S,p]=o.useState(s),[E,P]=o.useState(""),[R,A]=o.useState(""),[T,m]=o.useState(""),{requestPasswordReset:g,confirmPasswordReset:b}=ie(),L=((X=ae())==null?void 0:X.tenant)??null,a={...vr,...n},f=we("#f59e0b",e),k=ue({defaultErrorMessage:a.errorMessage,validate:()=>j.trim()?L!=null&&L.id?!0:(k.setError(a.tenantNotFoundError),!1):(k.setFieldError("email",!0),!1),submit:async()=>{m(""),await g({email:j,tenantId:L.id}),m(a.successMessage)},onSuccess:()=>i==null?void 0:i(),onError:l}),y=ue({defaultErrorMessage:a.errorMessage,validate:()=>{const I=[];return S.trim()||I.push("token"),E.trim()||I.push("newPassword"),R.trim()||I.push("confirmPassword"),I.forEach(z=>y.setFieldError(z,!0)),I.length>0?!1:E!==R?(y.setError(a.passwordMismatchError),y.setFieldError("confirmPassword",!0),!1):!0},submit:async()=>{m(""),await b({token:S,newPassword:E}),m(a.resetSuccessMessage)},onSuccess:()=>i==null?void 0:i(),onError:l});if(t==="reset"){const I=M=>({...f.input,...y.fieldErrors[M]?f.inputError:{}}),_=!(!!S&&!!E&&!!R)||y.loading,Z={...f.button,...y.loading?f.buttonLoading:{},..._?f.buttonDisabled:{}};return r.jsxs("div",{className:v,style:f.container,children:[r.jsx("h2",{style:f.title,children:a.resetTitle}),r.jsx("p",{style:f.subtitle,children:a.resetSubtitle}),r.jsxs("form",{onSubmit:y.handleSubmit,style:f.form,children:[r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.tokenLabel}),r.jsx("input",{type:"text",value:S,onChange:M=>{p(M.target.value),y.clearFieldError("token")},placeholder:a.tokenPlaceholder,style:I("token"),disabled:y.loading})]}),r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.newPasswordLabel}),r.jsx("input",{type:"password",value:E,onChange:M=>{P(M.target.value),y.clearFieldError("newPassword")},placeholder:a.newPasswordPlaceholder,style:I("newPassword"),disabled:y.loading})]}),r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.confirmPasswordLabel}),r.jsx("input",{type:"password",value:R,onChange:M=>{A(M.target.value),y.clearFieldError("confirmPassword"),y.error===a.passwordMismatchError&&y.setError("")},placeholder:a.confirmPasswordPlaceholder,style:I("confirmPassword"),disabled:y.loading})]}),r.jsx("button",{type:"submit",disabled:_,style:Z,children:y.loading?a.resetLoadingText:a.resetSubmitButton}),y.error&&r.jsx("div",{style:f.errorText,children:y.error}),T&&r.jsx("div",{style:f.successText,children:T})]}),r.jsxs("div",{style:f.linkContainer,children:[r.jsx("a",{onClick:c,style:f.link,children:a.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:f.modeSwitchDivider,children:a.dividerBullet}),r.jsx("a",{onClick:()=>h("request"),style:f.link,children:a.requestNewLinkLink})]})]})]})}const d=I=>({...f.input,...k.fieldErrors[I]?f.inputError:{}}),w=!j||k.loading,N={...f.button,...k.loading?f.buttonLoading:{},...w?f.buttonDisabled:{}};return r.jsxs("div",{className:v,style:f.container,children:[r.jsx("h2",{style:f.title,children:a.title}),r.jsx("p",{style:f.subtitle,children:a.subtitle}),r.jsxs("form",{onSubmit:k.handleSubmit,style:f.form,children:[r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.emailLabel}),r.jsx("input",{type:"email",value:j,onChange:I=>{u(I.target.value),k.clearFieldError("email")},placeholder:a.emailPlaceholder,style:d("email"),disabled:k.loading})]}),r.jsx("button",{type:"submit",disabled:w,style:N,children:k.loading?a.loadingText:a.submitButton}),k.error&&r.jsx("div",{style:f.errorText,children:k.error}),T&&r.jsx("div",{style:f.successText,children:T})]}),r.jsxs("div",{style:f.linkContainer,children:[r.jsx("a",{onClick:c,style:f.link,children:a.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:f.modeSwitchDivider,children:a.dividerBullet}),r.jsx("a",{onClick:()=>h("reset"),style:f.link,children:a.haveTokenLink})]})]})]})}const Tr=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),kr=({error:n,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:n.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Er({children:n,loadingFallback:e,errorFallback:t,requireTenant:s=!0}){const{isAppLoading:i,appError:l,retryApp:c}=de(),h=ae(),v=be(),j=Xe(),u=rt(),S=(h==null?void 0:h.isTenantLoading)??!1,p=(h==null?void 0:h.tenantError)??null,E=(h==null?void 0:h.tenantSlug)??null,P=(h==null?void 0:h.retryTenant)??(()=>{}),R=(v==null?void 0:v.isAuthReady)??!0,A=(j==null?void 0:j.isReady)??!0,T=(u==null?void 0:u.isReady)??!0,m=s&&h&&E,a=i||m&&S||v&&!R||j&&!A||u&&!T,f=l||(m?p:null),k=()=>{l&&c(),p&&h&&P()};if(a)return r.jsx(r.Fragment,{children:e||r.jsx(Tr,{})});if(f){const y=typeof t=="function"?t(f,k):t||r.jsx(kr,{error:f,retry:k});return r.jsx(r.Fragment,{children:y})}return r.jsx(r.Fragment,{children:n})}function jr(n=!0){const{isAppLoading:e,appError:t,retryApp:s,appInfo:i}=de(),l=ae(),c=be(),h=Xe(),v=rt(),j=(l==null?void 0:l.isTenantLoading)??!1,u=(l==null?void 0:l.tenantError)??null,S=(l==null?void 0:l.tenant)??null,p=(l==null?void 0:l.tenantSlug)??null,E=(l==null?void 0:l.retryTenant)??(()=>{}),P=(c==null?void 0:c.isAuthReady)??!0,R=(h==null?void 0:h.isReady)??!0,A=(v==null?void 0:v.isReady)??!0,T=n&&l&&p,L=e||T&&j||c&&!P||h&&!R||v&&!A,a=t||(T?u:null);return{isLoading:L,error:a,isReady:!L&&!a&&i!==null&&(!T||S!==null),retry:()=>{t&&s(),u&&l&&E()},app:{isLoading:e,error:t,data:i},tenant:l?{isLoading:j,error:u,data:S}:null,auth:c?{isReady:P}:null,featureFlags:h?{isReady:R}:null,subscription:v?{isReady:A}:null}}const Ar={wrapper:{position:"relative"},button:{cursor:"pointer",opacity:1},buttonDisabled:{cursor:"not-allowed",opacity:.6},dropdown:{position:"absolute",top:"100%",left:0,right:0,zIndex:1e3,backgroundColor:"white",border:"1px solid #ccc",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",maxHeight:300,overflowY:"auto"},item:{padding:"8px 12px",cursor:"pointer",backgroundColor:"transparent"},itemSelected:{backgroundColor:"#f0f0f0"},itemHover:{backgroundColor:"#f5f5f5"},itemRole:{opacity:.7,marginLeft:8},arrow:{marginLeft:8}};function Pr({tenants:n,currentTenantId:e,onSelect:t,styles:s={},className:i="",dropdownClassName:l="",itemClassName:c="",renderItem:h,placeholder:v="Select tenant",disabled:j=!1,showCurrentTenant:u=!0}){var L;const S={...Ar,...s},p=be(),[E,P]=o.useState(!1),R=o.useRef(null),A=n??(p==null?void 0:p.userTenants)??[],T=e??((L=p==null?void 0:p.currentUser)==null?void 0:L.tenantId)??null,m=async a=>{P(!1),t?t(a):p!=null&&p.switchToTenant&&await p.switchToTenant(a)};o.useEffect(()=>{const a=f=>{R.current&&!R.current.contains(f.target)&&P(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const g=A.find(a=>a.id===T);if(A.length===0)return null;if(A.length===1&&u)return r.jsx("div",{className:i,children:r.jsx("span",{children:A[0].name})});const b=(a,f)=>r.jsxs("span",{style:{fontWeight:f?"bold":"normal"},children:[a.name,a.role&&r.jsxs("span",{style:S.itemRole,children:["(",a.role,")"]})]});return r.jsxs("div",{ref:R,className:i,style:S.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!j&&P(!E),disabled:j,style:{...S.button,...j?S.buttonDisabled:{}},children:[g?g.name:v,r.jsx("span",{style:S.arrow,children:E?"▲":"▼"})]}),E&&r.jsx("div",{className:l,style:S.dropdown,children:A.map(a=>{const f=a.id===T;return r.jsx("div",{className:c,onClick:()=>m(a.id),style:{...S.item,...f?S.itemSelected:{}},onMouseEnter:k=>{f||Object.assign(k.currentTarget.style,S.itemHover)},onMouseLeave:k=>{if(!f){const y=S.item||{};Object.keys(S.itemHover||{}).forEach(d=>{k.currentTarget.style[d]=y[d]??""})}},children:h?h(a,f):b(a,f)},a.id)})})]})}class Rr{constructor(e){this.httpService=e}async createPermission(e){return(await this.httpService.post("/permissions/",e)).data}async getPermissions(e){const t=await this.httpService.get(`/permissions/${ne(e)}`);return{permissions:t.data,meta:t.meta}}async getPermissionById(e){return(await this.httpService.get(`/permissions/${e}`)).data}async updatePermission(e,t){return(await this.httpService.put(`/permissions/${e}`,t)).data}async deletePermission(e){await this.httpService.delete(`/permissions/${e}`)}async getAppPermissions(e,t){const s=await this.httpService.get(`/permissions/apps/${e}${ne(t)}`,{skipAuth:!0});return{permissions:s.data,meta:s.meta}}}class Fr{constructor(e){this.httpService=e}async createSubscriptionPlan(e){return(await this.httpService.post("/subscription-plans/",e)).data}async getSubscriptionPlans(e){const t=await this.httpService.get(`/subscription-plans/${ne(e)}`);return{plans:t.data,meta:t.meta}}async getSubscriptionPlanById(e){return(await this.httpService.get(`/subscription-plans/${e}`)).data}async updateSubscriptionPlan(e,t){return(await this.httpService.put(`/subscription-plans/${e}`,t)).data}async deleteSubscriptionPlan(e){await this.httpService.delete(`/subscription-plans/${e}`)}}class Ir{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}const it="returnTo",Te="zone_return_to",ke="zone_return_to";function Lr(n={}){const{zoneRoots:e={},returnToParam:t=it,returnToStorage:s="url"}=n,i=re.useNavigate(),[l,c]=re.useSearchParams(),{isAuthenticated:h,currentUser:v}=ie(),{tenant:j}=ce(),u=o.useMemo(()=>({...xe,...e}),[e]),S=!!j,p=v==null?void 0:v.userType,E=o.useMemo(()=>{switch(s){case"url":return l.get(t);case"session":return sessionStorage.getItem(Te);case"local":return localStorage.getItem(ke);default:return null}},[s,l,t]),P=o.useCallback(()=>{switch(s){case"url":{const m=new URLSearchParams(l);m.delete(t),c(m,{replace:!0});break}case"session":sessionStorage.removeItem(Te);break;case"local":localStorage.removeItem(ke);break}},[s,l,t,c]),R=o.useCallback(m=>{switch(s){case"url":{const g=new URLSearchParams(l);g.set(t,m),c(g,{replace:!0});break}case"session":sessionStorage.setItem(Te,m);break;case"local":localStorage.setItem(ke,m);break}},[s,l,t,c]),A=o.useCallback(m=>{const g=u[m]||u.default;i(g)},[i,u]),T=o.useCallback(()=>S?h?p===ee.TENANT_ADMIN?u.tenantAdmin:u.tenantUser:u.tenantGuest:h?p===ee.TENANT_ADMIN?u.publicAdmin:u.publicUser:u.publicGuest,[S,h,p,u]);return{returnToUrl:E,clearReturnTo:P,setReturnTo:R,navigateToZone:A,getSmartRedirect:T}}function Nr(n,e,t=it,s="url"){if(!e||s!=="url")return n;const i=new URL(n,window.location.origin);return i.searchParams.set(t,e),i.pathname+i.search}exports.AdminZone=Jt;exports.AppApiService=Ee;exports.AppLoader=Er;exports.AppProvider=ft;exports.AuthApiService=He;exports.AuthProvider=kt;exports.AuthenticatedZone=Ht;exports.DEFAULT_ZONE_PRESETS=Ne;exports.DEFAULT_ZONE_ROOTS=xe;exports.FeatureFlag=ir;exports.FeatureFlagApiService=Ke;exports.FeatureFlagProvider=At;exports.GuestZone=Qt;exports.HealthApiService=Ir;exports.HttpService=oe;exports.LandingRoute=Ot;exports.LoginForm=ur;exports.MagicLinkForm=fr;exports.MagicLinkVerify=wr;exports.OpenZone=Yt;exports.PasswordRecoveryForm=Sr;exports.PermissionApiService=Rr;exports.Protected=Nt;exports.ProtectedRoute=Dt;exports.PublicZone=Zt;exports.RoleApiService=Qe;exports.RoutingProvider=Ft;exports.SessionExpiredError=H;exports.SessionManager=me;exports.SignupForm=hr;exports.SubscriptionApiService=et;exports.SubscriptionGuard=nr;exports.SubscriptionPlanApiService=Fr;exports.SubscriptionProvider=Pt;exports.TenantApiService=le;exports.TenantAuthenticatedZone=Xt;exports.TenantGuestZone=tr;exports.TenantOpenZone=er;exports.TenantProvider=wt;exports.TenantRoute=$t;exports.TenantSelector=Pr;exports.TenantZone=Gt;exports.TokenRefreshError=Ze;exports.TokenRefreshTimeoutError=Ge;exports.UserApiService=Je;exports.UserType=ee;exports.UserZone=Kt;exports.ZoneRoute=se;exports.buildRedirectUrl=Nr;exports.useApi=mt;exports.useApp=de;exports.useAppLoaderState=jr;exports.useAuth=ie;exports.useAuthActions=jt;exports.useAuthOptional=be;exports.useAuthState=Et;exports.useFeatureFlags=Ye;exports.useRouting=It;exports.useRoutingOptional=nt;exports.useSettings=St;exports.useSubscription=tt;exports.useTenant=ce;exports.useTenantInfo=Re;exports.useTenantOptional=ae;exports.useTenantSettings=vt;exports.useZoneNavigation=Lr;
|
|
6
|
+
`}),r.jsx("h1",{style:g.title,children:m.title}),y()]})}const Mr={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",requestNewLinkLink:"Request New Link",haveTokenLink:"I have a token",tenantNotFoundError:"Tenant not found",dividerBullet:"•"};function Dr({copy:n={},styles:e={},mode:t="request",token:s="",onSuccess:i,onError:l,onBackToLogin:c,onModeChange:h,className:w}){var Y;const[j,u]=o.useState(""),[S,p]=o.useState(s),[E,R]=o.useState(""),[P,A]=o.useState(""),[T,m]=o.useState(""),{requestPasswordReset:g,confirmPasswordReset:b}=oe(),L=((Y=le())==null?void 0:Y.tenant)??null,a={...Mr,...n},f=Te("#f59e0b",e),k=he({defaultErrorMessage:a.errorMessage,validate:()=>j.trim()?L!=null&&L.id?!0:(k.setError(a.tenantNotFoundError),!1):(k.setFieldError("email",!0),!1),submit:async()=>{m(""),await g({email:j,tenantId:L.id}),m(a.successMessage)},onSuccess:()=>i==null?void 0:i(),onError:l}),y=he({defaultErrorMessage:a.errorMessage,validate:()=>{const I=[];return S.trim()||I.push("token"),E.trim()||I.push("newPassword"),P.trim()||I.push("confirmPassword"),I.forEach(z=>y.setFieldError(z,!0)),I.length>0?!1:E!==P?(y.setError(a.passwordMismatchError),y.setFieldError("confirmPassword",!0),!1):!0},submit:async()=>{m(""),await b({token:S,newPassword:E}),m(a.resetSuccessMessage)},onSuccess:()=>i==null?void 0:i(),onError:l});if(t==="reset"){const I=M=>({...f.input,...y.fieldErrors[M]?f.inputError:{}}),O=!(!!S&&!!E&&!!P)||y.loading,H={...f.button,...y.loading?f.buttonLoading:{},...O?f.buttonDisabled:{}};return r.jsxs("div",{className:w,style:f.container,children:[r.jsx("h2",{style:f.title,children:a.resetTitle}),r.jsx("p",{style:f.subtitle,children:a.resetSubtitle}),r.jsxs("form",{onSubmit:y.handleSubmit,style:f.form,children:[r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.tokenLabel}),r.jsx("input",{type:"text",value:S,onChange:M=>{p(M.target.value),y.clearFieldError("token")},placeholder:a.tokenPlaceholder,style:I("token"),disabled:y.loading})]}),r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.newPasswordLabel}),r.jsx("input",{type:"password",value:E,onChange:M=>{R(M.target.value),y.clearFieldError("newPassword")},placeholder:a.newPasswordPlaceholder,style:I("newPassword"),disabled:y.loading})]}),r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.confirmPasswordLabel}),r.jsx("input",{type:"password",value:P,onChange:M=>{A(M.target.value),y.clearFieldError("confirmPassword"),y.error===a.passwordMismatchError&&y.setError("")},placeholder:a.confirmPasswordPlaceholder,style:I("confirmPassword"),disabled:y.loading})]}),r.jsx("button",{type:"submit",disabled:O,style:H,children:y.loading?a.resetLoadingText:a.resetSubmitButton}),y.error&&r.jsx("div",{style:f.errorText,children:y.error}),T&&r.jsx("div",{style:f.successText,children:T})]}),r.jsxs("div",{style:f.linkContainer,children:[r.jsx("a",{onClick:c,style:f.link,children:a.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:f.modeSwitchDivider,children:a.dividerBullet}),r.jsx("a",{onClick:()=>h("request"),style:f.link,children:a.requestNewLinkLink})]})]})]})}const d=I=>({...f.input,...k.fieldErrors[I]?f.inputError:{}}),v=!j||k.loading,N={...f.button,...k.loading?f.buttonLoading:{},...v?f.buttonDisabled:{}};return r.jsxs("div",{className:w,style:f.container,children:[r.jsx("h2",{style:f.title,children:a.title}),r.jsx("p",{style:f.subtitle,children:a.subtitle}),r.jsxs("form",{onSubmit:k.handleSubmit,style:f.form,children:[r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.emailLabel}),r.jsx("input",{type:"email",value:j,onChange:I=>{u(I.target.value),k.clearFieldError("email")},placeholder:a.emailPlaceholder,style:d("email"),disabled:k.loading})]}),r.jsx("button",{type:"submit",disabled:v,style:N,children:k.loading?a.loadingText:a.submitButton}),k.error&&r.jsx("div",{style:f.errorText,children:k.error}),T&&r.jsx("div",{style:f.successText,children:T})]}),r.jsxs("div",{style:f.linkContainer,children:[r.jsx("a",{onClick:c,style:f.link,children:a.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:f.modeSwitchDivider,children:a.dividerBullet}),r.jsx("a",{onClick:()=>h("reset"),style:f.link,children:a.haveTokenLink})]})]})]})}const $r=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),Ur=({error:n,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:n.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Br({children:n,loadingFallback:e,errorFallback:t,requireTenant:s=!0}){const{isAppLoading:i,appError:l,retryApp:c}=pe(),h=le(),w=we(),j=it(),u=lt(),S=(h==null?void 0:h.isTenantLoading)??!1,p=(h==null?void 0:h.tenantError)??null,E=(h==null?void 0:h.tenantSlug)??null,R=(h==null?void 0:h.retryTenant)??(()=>{}),P=(w==null?void 0:w.isAuthReady)??!0,A=(j==null?void 0:j.isReady)??!0,T=(u==null?void 0:u.isReady)??!0,m=s&&h&&E,a=i||m&&S||w&&!P||j&&!A||u&&!T,f=l||(m?p:null),k=()=>{l&&c(),p&&h&&R()};if(a)return r.jsx(r.Fragment,{children:e||r.jsx($r,{})});if(f){const y=typeof t=="function"?t(f,k):t||r.jsx(Ur,{error:f,retry:k});return r.jsx(r.Fragment,{children:y})}return r.jsx(r.Fragment,{children:n})}function _r(n=!0){const{isAppLoading:e,appError:t,retryApp:s,appInfo:i}=pe(),l=le(),c=we(),h=it(),w=lt(),j=(l==null?void 0:l.isTenantLoading)??!1,u=(l==null?void 0:l.tenantError)??null,S=(l==null?void 0:l.tenant)??null,p=(l==null?void 0:l.tenantSlug)??null,E=(l==null?void 0:l.retryTenant)??(()=>{}),R=(c==null?void 0:c.isAuthReady)??!0,P=(h==null?void 0:h.isReady)??!0,A=(w==null?void 0:w.isReady)??!0,T=n&&l&&p,L=e||T&&j||c&&!R||h&&!P||w&&!A,a=t||(T?u:null);return{isLoading:L,error:a,isReady:!L&&!a&&i!==null&&(!T||S!==null),retry:()=>{t&&s(),u&&l&&E()},app:{isLoading:e,error:t,data:i},tenant:l?{isLoading:j,error:u,data:S}:null,auth:c?{isReady:R}:null,featureFlags:h?{isReady:P}:null,subscription:w?{isReady:A}:null}}const Or={wrapper:{position:"relative"},button:{cursor:"pointer",opacity:1},buttonDisabled:{cursor:"not-allowed",opacity:.6},dropdown:{position:"absolute",top:"100%",left:0,right:0,zIndex:1e3,backgroundColor:"white",border:"1px solid #ccc",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",maxHeight:300,overflowY:"auto"},item:{padding:"8px 12px",cursor:"pointer",backgroundColor:"transparent"},itemSelected:{backgroundColor:"#f0f0f0"},itemHover:{backgroundColor:"#f5f5f5"},itemRole:{opacity:.7,marginLeft:8},arrow:{marginLeft:8}};function Vr({tenants:n,currentTenantId:e,onSelect:t,styles:s={},className:i="",dropdownClassName:l="",itemClassName:c="",renderItem:h,placeholder:w="Select tenant",disabled:j=!1,showCurrentTenant:u=!0}){var L;const S={...Or,...s},p=we(),[E,R]=o.useState(!1),P=o.useRef(null),A=n??(p==null?void 0:p.userTenants)??[],T=e??((L=p==null?void 0:p.currentUser)==null?void 0:L.tenantId)??null,m=async a=>{R(!1),t?t(a):p!=null&&p.switchToTenant&&await p.switchToTenant(a)};o.useEffect(()=>{const a=f=>{P.current&&!P.current.contains(f.target)&&R(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const g=A.find(a=>a.id===T);if(A.length===0)return null;if(A.length===1&&u)return r.jsx("div",{className:i,children:r.jsx("span",{children:A[0].name})});const b=(a,f)=>r.jsxs("span",{style:{fontWeight:f?"bold":"normal"},children:[a.name,a.role&&r.jsxs("span",{style:S.itemRole,children:["(",a.role,")"]})]});return r.jsxs("div",{ref:P,className:i,style:S.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!j&&R(!E),disabled:j,style:{...S.button,...j?S.buttonDisabled:{}},children:[g?g.name:w,r.jsx("span",{style:S.arrow,children:E?"▲":"▼"})]}),E&&r.jsx("div",{className:l,style:S.dropdown,children:A.map(a=>{const f=a.id===T;return r.jsx("div",{className:c,onClick:()=>m(a.id),style:{...S.item,...f?S.itemSelected:{}},onMouseEnter:k=>{f||Object.assign(k.currentTarget.style,S.itemHover)},onMouseLeave:k=>{if(!f){const y=S.item||{};Object.keys(S.itemHover||{}).forEach(d=>{k.currentTarget.style[d]=y[d]??""})}},children:h?h(a,f):b(a,f)},a.id)})})]})}class qr{constructor(e){this.httpService=e}async createPermission(e){return(await this.httpService.post("/permissions/",e)).data}async getPermissions(e){const t=await this.httpService.get(`/permissions/${se(e)}`);return{permissions:t.data,meta:t.meta}}async getPermissionById(e){return(await this.httpService.get(`/permissions/${e}`)).data}async updatePermission(e,t){return(await this.httpService.put(`/permissions/${e}`,t)).data}async deletePermission(e){await this.httpService.delete(`/permissions/${e}`)}async getAppPermissions(e,t){const s=await this.httpService.get(`/permissions/apps/${e}${se(t)}`,{skipAuth:!0});return{permissions:s.data,meta:s.meta}}}class zr{constructor(e){this.httpService=e}async createSubscriptionPlan(e){return(await this.httpService.post("/subscription-plans/",e)).data}async getSubscriptionPlans(e){const t=await this.httpService.get(`/subscription-plans/${se(e)}`);return{plans:t.data,meta:t.meta}}async getSubscriptionPlanById(e){return(await this.httpService.get(`/subscription-plans/${e}`)).data}async updateSubscriptionPlan(e,t){return(await this.httpService.put(`/subscription-plans/${e}`,t)).data}async deleteSubscriptionPlan(e){await this.httpService.delete(`/subscription-plans/${e}`)}}class Gr{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}const dt="returnTo",je="zone_return_to",Ae="zone_return_to";function Wr(n={}){const{zoneRoots:e={},returnToParam:t=dt,returnToStorage:s="url"}=n,i=ne.useNavigate(),[l,c]=ne.useSearchParams(),{isAuthenticated:h,currentUser:w}=oe(),{tenant:j}=ue(),u=o.useMemo(()=>({...Se,...e}),[e]),S=!!j,p=w==null?void 0:w.userType,E=o.useMemo(()=>{switch(s){case"url":return l.get(t);case"session":return sessionStorage.getItem(je);case"local":return localStorage.getItem(Ae);default:return null}},[s,l,t]),R=o.useCallback(()=>{switch(s){case"url":{const m=new URLSearchParams(l);m.delete(t),c(m,{replace:!0});break}case"session":sessionStorage.removeItem(je);break;case"local":localStorage.removeItem(Ae);break}},[s,l,t,c]),P=o.useCallback(m=>{switch(s){case"url":{const g=new URLSearchParams(l);g.set(t,m),c(g,{replace:!0});break}case"session":sessionStorage.setItem(je,m);break;case"local":localStorage.setItem(Ae,m);break}},[s,l,t,c]),A=o.useCallback(m=>{const g=u[m]||u.default;i(g)},[i,u]),T=o.useCallback(()=>S?h?p===te.TENANT_ADMIN?u.tenantAdmin:u.tenantUser:u.tenantGuest:h?p===te.TENANT_ADMIN?u.publicAdmin:u.publicUser:u.publicGuest,[S,h,p,u]);return{returnToUrl:E,clearReturnTo:R,setReturnTo:P,navigateToZone:A,getSmartRedirect:T}}function Hr(n,e,t=dt,s="url"){if(!e||s!=="url")return n;const i=new URL(n,window.location.origin);return i.searchParams.set(t,e),i.pathname+i.search}exports.AdminZone=ur;exports.AppApiService=Re;exports.AppLoader=Br;exports.AppProvider=vt;exports.AuthApiService=et;exports.AuthProvider=Ut;exports.AuthenticatedZone=lr;exports.ConfigurationError=ee;exports.DEFAULT_ZONE_PRESETS=De;exports.DEFAULT_ZONE_ROOTS=Se;exports.FeatureFlag=xr;exports.FeatureFlagApiService=nt;exports.FeatureFlagProvider=Ot;exports.GuestZone=cr;exports.HealthApiService=Gr;exports.HttpService=ae;exports.LandingRoute=er;exports.LoginForm=kr;exports.MagicLinkForm=Rr;exports.MagicLinkVerify=Cr;exports.OpenZone=hr;exports.PasswordRecoveryForm=Dr;exports.PermissionApiService=qr;exports.Protected=Ht;exports.ProtectedRoute=Jt;exports.PublicZone=ar;exports.RoleApiService=tt;exports.RoutingProvider=zt;exports.SessionExpiredError=Z;exports.SessionManager=ye;exports.SignupForm=jr;exports.SubscriptionApiService=ot;exports.SubscriptionGuard=yr;exports.SubscriptionPlanApiService=zr;exports.SubscriptionProvider=Vt;exports.TenantApiService=ce;exports.TenantAuthenticatedZone=pr;exports.TenantGuestZone=mr;exports.TenantOpenZone=fr;exports.TenantProvider=Ct;exports.TenantRoute=Yt;exports.TenantSelector=Vr;exports.TenantZone=or;exports.TokenRefreshError=Xe;exports.TokenRefreshTimeoutError=Ye;exports.UserApiService=rt;exports.UserType=te;exports.UserZone=dr;exports.ZoneRoute=ie;exports.buildRedirectUrl=Hr;exports.useApi=wt;exports.useApp=pe;exports.useAppLoaderState=_r;exports.useAuth=oe;exports.useAuthActions=_t;exports.useAuthOptional=we;exports.useAuthState=Bt;exports.useFeatureFlags=st;exports.useRouting=Gt;exports.useRoutingOptional=ct;exports.useSettings=Dt;exports.useSubscription=at;exports.useTenant=ue;exports.useTenantInfo=Le;exports.useTenantOptional=le;exports.useTenantSettings=Mt;exports.useZoneNavigation=Wr;
|
|
7
7
|
//# sourceMappingURL=index.js.map
|