@trieoh/identityx-sdk-ts 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # IdentityX SDK - Typescript
2
+
3
+ SDK for integrating with the TrieOH authentication ecosystem.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @trieoh/identityx-sdk-ts
9
+ # or
10
+ yarn add @trieoh/identityx-sdk-ts
11
+ # or
12
+ bun add @trieoh/identityx-sdk-ts
13
+ ```
14
+
15
+ ## Configuration (Vite / React)
16
+
17
+ To use the SDK in a React project (Vite, Next.js, or CRA), wrap your application with `AuthProvider`.
18
+
19
+ ### Option 1: Environment Variables (Recommended)
20
+
21
+ The SDK automatically looks for these variables:
22
+
23
+ - `VITE_TRIEOH_AUTH_PROJECT_ID` (Vite)
24
+ - `NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID` (Next.js)
25
+ - `PUBLIC_TRIEOH_AUTH_PROJECT_ID` (General)
26
+
27
+ ```tsx
28
+ import { AuthProvider } from '@trieoh/identityx-sdk-ts/react';
29
+
30
+ function App() {
31
+ return (
32
+ <AuthProvider>
33
+ <YourRoutes />
34
+ </AuthProvider>
35
+ );
36
+ }
37
+ ```
38
+
39
+ ### Option 2: Passing via Props
40
+
41
+ Useful if you load the project ID dynamically or want to avoid environment issues.
42
+
43
+ ```tsx
44
+ <AuthProvider projectId="your-project-id-here">
45
+ <YourApp />
46
+ </AuthProvider>
47
+ ```
48
+
49
+ ### Option 3: Global Configuration via Code
50
+
51
+ ```tsx
52
+ import { configure } from '@trieoh/identityx-sdk-ts';
53
+
54
+ configure({
55
+ PROJECT_ID: 'your-id',
56
+ BASE_URL: 'https://your-api.com'
57
+ });
58
+ ```
59
+
60
+ ## Components
61
+
62
+ The SDK provides ready-to-use components:
63
+
64
+ ```tsx
65
+ import { SignIn, SignUp } from '@trieoh/identityx-sdk-ts/react';
66
+
67
+ // Example usage
68
+ const LoginPage = () => <SignIn />;
69
+ const RegisterPage = () => <SignUp />;
70
+ ```
71
+
72
+ ## Hooks
73
+
74
+ You can access the authentication state anywhere in your application:
75
+
76
+ ```tsx
77
+ import { useAuth } from '@trieoh/identityx-sdk-ts/react';
78
+
79
+ function Header() {
80
+ const { isAuthenticated, auth } = useAuth();
81
+
82
+ return (
83
+ <nav>
84
+ {isAuthenticated ? (
85
+ <button onClick={() => auth.logout()}>Logout</button>
86
+ ) : (
87
+ <span>Not logged in</span>
88
+ )}
89
+ </nav>
90
+ );
91
+ }
92
+
93
+ ---
@@ -0,0 +1,3 @@
1
+ 'use strict';var nodeFetchSdk=require('@soramux/node-fetch-sdk');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function w(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var g={isAuthenticated:false,isInitializing:true},S=new Set,U=()=>S.forEach(t=>t()),T={subscribe:t=>(S.add(t),()=>S.delete(t)),getSnapshot:()=>g,getServerSnapshot:()=>g,set:t=>{g={...g,...t},U();},reset:()=>{g={isAuthenticated:false,isInitializing:false},U();}};typeof window<"u"&&window.addEventListener("storage",t=>{if(t.key==="trieoh_access_expiry")if(!t.newValue)T.reset();else {let e=parseInt(t.newValue,10),r=!isNaN(e)&&e>Date.now();T.set({isAuthenticated:r,isInitializing:false});}});var o={getItem:t=>typeof window<"u"?localStorage.getItem(t):null,setItem:(t,e)=>{typeof window<"u"&&localStorage.setItem(t,e);},removeItem:t=>{typeof window<"u"&&localStorage.removeItem(t);}},R={getItem:t=>typeof window<"u"?sessionStorage.getItem(t):null,setItem:(t,e)=>{typeof window<"u"&&sessionStorage.setItem(t,e);},removeItem:t=>{typeof window<"u"&&sessionStorage.removeItem(t);}},l={get:t=>{if(typeof window>"u")return null;let e=t+"=",r=document.cookie.split(";");for(let n=0;n<r.length;n++){let s=r[n];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return s.substring(e.length,s.length)}return null},set:(t,e,r={})=>{if(typeof window>"u")return;let{expires:n,path:s="/",domain:u,secure:h=window.location.protocol==="https:",sameSite:d=h?"None":"Lax"}=r,m=[`${t}=${e}`,u?`Domain=${u}`:"",`Path=${s}`,`SameSite=${d}`,h?"Secure":"",n?`expires=${n}`:""];document.cookie=m.filter(Boolean).join("; ");},remove:(t,e)=>{l.set(t,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:e});}};var y="trieoh_access_token",a={getAccessToken:()=>R.getItem(y),setAccessToken:t=>{t?R.setItem(y,t):R.removeItem(y);},clear:()=>{R.removeItem(y);}};var p=null,b="trieoh_access_expiry",v="trieoh_refresh_expiry";function F(){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost")return null;if(t.endsWith("univents.com.br"))return "univents.com.br";if(t.endsWith("identityx.com.br"))return "identityx.com.br";let e=t.split(".");return t.endsWith("trieoh.com")&&e.length>=3?`${e[e.length-3]}.trieoh.com`:t}function C(t){try{let e=t.split(".")[1];return JSON.parse(atob(e))}catch{return null}}function q(t,e){let r=C(t),n=C(e);if(!r||!n){nodeFetchSdk.logger.error("Failed to decode tokens");return}a.setAccessToken(t);let s=n.exp*1e3,u=r.exp*1e3;l.set("refresh_token",e,{expires:new Date(s).toUTCString(),domain:F()}),p={access_data:r,refresh_expiry_date:s},o.setItem(b,String(u)),o.setItem(v,String(s)),T.set({isAuthenticated:true,isInitializing:false}),nodeFetchSdk.logger.log("Auth session saved");}function L(){if(p)return p;let t=a.getAccessToken();if(!t)return null;let e=C(t);if(!e||e.exp*1e3<=Date.now())return null;let r=o.getItem(v);return r?(p={access_data:e,refresh_expiry_date:parseInt(r,10)},p):null}function D(t,e){try{let r=o.getItem(t);if(!r)return !0;let n=parseInt(r,10);return isNaN(n)?!0:n-Date.now()<=e*1e3}catch(r){return nodeFetchSdk.logger.warn("Error reading expiry:",r),true}}var B=(t=30)=>D(b,t),H=(t=10)=>D(v,t);function E(){p=null,a.clear(),o.removeItem(b),o.removeItem(v);let t=F();l.remove("refresh_token",t),T.reset(),nodeFetchSdk.logger.log("Auth tokens and claims cleared");}function N(){let t=typeof window>"u",e=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},r=typeof process<"u"?process.env:{},n=e.VITE_TRIEOH_AUTH_PROJECT_ID||r.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||r.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",s=t&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:n,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var I=null,P={};function $(t){P={...P,...t},I=null;}function O(){return I||(I={...N(),...P}),I}var J={get BASE_URL(){return O().BASE_URL}};var f=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||J.BASE_URL,this.authBaseURL=e?.authBaseURL||this.baseURL,this.onTokenRefreshed=e?.onTokenRefreshed,this.onRefreshFailed=e?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=await nodeFetchSdk.simpleFetch(w(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(e.code!==200||!e.data)throw e.code!==503&&E(),new Error(e.message||"Failed to refresh token");let{access_token:r,refresh_token:n}=e.data;q(r,n);let s=L();s&&this.onTokenRefreshed?.(s),nodeFetchSdk.logger.log("Token refreshed successfully");}catch(e){throw nodeFetchSdk.logger.warn("Failed to refresh token:",e),E(),this.onRefreshFailed?.(e),e}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(H()){E();return}let e=!!a.getAccessToken(),r=!!l.get("refresh_token");if(!e&&r||e&&B(30))try{await this.refreshToken();}catch(n){nodeFetchSdk.logger.warn("Proactive refresh failed:",n);}}async fetch(e,r){let n=r?.requiresAuth!==false,s=e.includes("/auth/refresh");n&&!s&&!r?.skipRefresh&&await this.beforeRequest();let u=w(this.baseURL,e),h=async()=>{let m=a.getAccessToken(),k=new Headers(r?.headers);return n&&m&&k.set("Authorization",`Bearer ${m}`),k.has("Content-Type")||k.set("Content-Type","application/json"),fetch(u,{...r,headers:k,credentials:"include"})},d=await h();if(d.status===401&&n&&!s){nodeFetchSdk.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),d=await h();}catch{nodeFetchSdk.logger.error("Retry failed after refresh error");}}return d}},ge=t=>new f(t),Te=t=>{let e=new f(t);return (r,n)=>e.fetch(r,n)};function c(t){if(!t)return;let{requiresAuth:e,skipRefresh:r,...n}=t,s={};return e!==void 0&&(s.requiresAuth=e),r!==void 0&&(s.skipRefresh=r),{...n,adapterInit:{...n.adapterInit,...s}}}var _=class{constructor(e,r,n,s){this.interceptor=new f({baseURL:e,authBaseURL:r,onTokenRefreshed:n}),this.client=nodeFetchSdk.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(e,r){return this.client.request(e,c(r))}get(e,r){return this.client.get(e,c(r))}post(e,r,n){return this.client.post(e,r,c(n))}put(e,r,n){return this.client.put(e,r,c(n))}patch(e,r,n){return this.client.patch(e,r,c(n))}delete(e,r,n){return this.client.delete(e,r,c(n))}query(e,r){return this.client.query(e,c(r))}};function j(t){let e=new _(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return {request:e.request.bind(e),get:e.get.bind(e),post:e.post.bind(e),put:e.put.bind(e),patch:e.patch.bind(e),delete:e.delete.bind(e),query:e.query.bind(e)}}function z(t){let e=new _(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return (r,n)=>e.query(r,n)}
2
+ Object.defineProperty(exports,"ApiError",{enumerable:true,get:function(){return nodeFetchSdk.FetchClientError}});exports.AuthInterceptor=f;exports.configure=$;exports.createAuthInterceptor=ge;exports.createAuthenticatedFetch=Te;exports.createFetcher=j;exports.createQueryFetcher=z;//# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/store/token-store.ts","../../src/utils/token-utils.ts","../../src/core/env.ts","../../src/core/interceptor.ts","../../src/core/api.ts"],"names":["joinUrl","base","path","cleanBase","cleanPath","_state","_listeners","notify","l","authStore","cb","partial","event","expiry","isAuthenticated","browserStorage","key","value","sessionBrowserStorage","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","getCookieDomain","hostname","parts","decodeJwt","payload","saveAuthSession","access_token","refresh_token","claims","refreshClaims","logger","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","isExpiringSoon","thresholdSeconds","expiryStr","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","error","hasAccessToken","hasRefreshToken","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"sJAAO,SAASA,EAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,WAAW,MAAM,CAAA,CAAG,OAAOA,CAAAA,CAEpC,IAAMC,EAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAClCG,EAAYF,CAAAA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OAAUvB,CAAAA,CAAciG,CAAAA,CAAgB1E,EAA6B,CACnE,OAAO,KAAK,MAAA,CAAO,MAAA,CAAUvB,EAAMiG,CAAAA,CAAMX,CAAAA,CAAe/D,CAAO,CAAC,CAClE,CAEA,KAAA,CAASvB,CAAAA,CAAcuB,EAA6B,CAClD,OAAO,KAAK,MAAA,CAAO,KAAA,CAASvB,EAAMsF,CAAAA,CAAe/D,CAAO,CAAC,CAC3D,CACF,CAAA,CAEO,SAAS2E,EAAchC,CAAAA,CAI3B,CACD,IAAMiC,CAAAA,CAAM,IAAIR,EACdzB,CAAAA,EAAQ,OAAA,CACRA,GAAQ,WAAA,CACR,MAAA,CACAA,GAAQ,YACV,CAAA,CAEA,OAAO,CACL,OAAA,CAASiC,EAAI,OAAA,CAAQ,IAAA,CAAKA,CAAG,CAAA,CAC7B,IAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,KAAMA,CAAAA,CAAI,IAAA,CAAK,KAAKA,CAAG,CAAA,CACvB,IAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,MAAOA,CAAAA,CAAI,KAAA,CAAM,IAAA,CAAKA,CAAG,EACzB,MAAA,CAAQA,CAAAA,CAAI,OAAO,IAAA,CAAKA,CAAG,EAC3B,KAAA,CAAOA,CAAAA,CAAI,MAAM,IAAA,CAAKA,CAAG,CAC3B,CACF,CAEO,SAASC,CAAAA,CAAmBlC,CAAAA,CAIhC,CACD,IAAMiC,CAAAA,CAAM,IAAIR,CAAAA,CACdzB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,OACAA,CAAAA,EAAQ,YACV,EAEA,OAAO,CAAQlE,EAAcuB,CAAAA,GAC3B4E,CAAAA,CAAI,MAAanG,CAAAA,CAAMuB,CAAO,CAClC","file":"index.js","sourcesContent":["export function joinUrl(base: string, path: string): string {\n if (path.startsWith(\"http\")) return path;\n \n const cleanBase = base.replace(/\\/$/, \"\");\n const cleanPath = path.replace(/^\\//, \"\");\n \n return `${cleanBase}/${cleanPath}`;\n}\n","type AuthState = {\n isAuthenticated: boolean;\n isInitializing: boolean;\n};\n\nlet _state: AuthState = {\n isAuthenticated: false,\n isInitializing: true,\n};\nconst _listeners = new Set<() => void>();\n\nconst notify = () => _listeners.forEach((l) => l());\n\nexport const authStore = {\n subscribe: (cb: () => void) => {\n _listeners.add(cb);\n return () => _listeners.delete(cb);\n },\n getSnapshot: () => _state,\n getServerSnapshot: () => _state,\n set: (partial: Partial<AuthState>) => {\n _state = { ..._state, ...partial };\n notify();\n },\n reset: () => {\n _state = {\n isAuthenticated: false,\n isInitializing: false,\n };\n notify();\n },\n};\n\n// Sync between tabs\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"trieoh_access_expiry\") {\n if (!event.newValue) authStore.reset();\n else {\n const expiry = parseInt(event.newValue, 10);\n const isAuthenticated = !isNaN(expiry) && expiry > Date.now();\n authStore.set({ isAuthenticated, isInitializing: false });\n }\n }\n });\n}\n","export interface StorageAdapter {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const browserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") localStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") localStorage.removeItem(key);\n },\n};\n\nexport const sessionBrowserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? sessionStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") sessionStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") sessionStorage.removeItem(key);\n },\n};\n\nexport interface CookieOptions {\n expires?: string;\n path?: string;\n domain?: string | null;\n secure?: boolean;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n}\n\nexport const cookieStorage = {\n get: (name: string): string | null => {\n if (typeof window === \"undefined\") return null;\n const nameEQ = name + \"=\";\n const ca = document.cookie.split(\";\");\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === \" \") c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n },\n\n set: (name: string, value: string, options: CookieOptions = {}) => {\n if (typeof window === \"undefined\") return;\n\n const {\n expires,\n path = \"/\",\n domain,\n secure = window.location.protocol === \"https:\",\n sameSite = secure ? \"None\" : \"Lax\",\n } = options;\n\n const cookieParts = [\n `${name}=${value}`,\n domain ? `Domain=${domain}` : \"\",\n `Path=${path}`,\n `SameSite=${sameSite}`,\n secure ? \"Secure\" : \"\",\n expires ? `expires=${expires}` : \"\",\n ];\n\n document.cookie = cookieParts.filter(Boolean).join(\"; \");\n },\n\n remove: (name: string, domain?: string | null) => {\n cookieStorage.set(name, \"\", {\n expires: \"Thu, 01 Jan 1970 00:00:00 GMT\",\n domain,\n });\n },\n};\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, token);\n else sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n },\n clear: () => {\n sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n }\n};\n","import { authStore } from \"../store/auth-store\";\nimport { tokenStore } from \"../store/token-store\";\nimport { logger } from \"@soramux/node-fetch-sdk\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n access_token: string;\n refresh_token: string;\n}\n\nexport interface TokenClaims {\n sub: {\n id: string;\n email: string;\n session_id: string;\n user_agent: string;\n user_ip: string;\n project_id: string | null;\n verified_at: string | null;\n is_verified: boolean;\n user_type: \"client\" | \"project\";\n metadata: Record<string, unknown> | null;\n };\n iss: string;\n exp: number;\n iat: number;\n jti: string;\n}\n\nexport interface AuthTokenClaims {\n access_data: TokenClaims;\n refresh_expiry_date: string | number;\n}\n\n// Stored only in memory\nlet memoryClaims: AuthTokenClaims | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\n\nexport function getCookieDomain() {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n if (hostname === 'localhost') return null;\n if (hostname.endsWith('univents.com.br')) return 'univents.com.br';\n if (hostname.endsWith('identityx.com.br')) return 'identityx.com.br';\n\n const parts = hostname.split('.');\n if (hostname.endsWith('trieoh.com') && parts.length >= 3) {\n const appName = parts[parts.length - 3];\n return `${appName}.trieoh.com`;\n }\n\n return hostname;\n}\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n return JSON.parse(atob(payload));\n } catch {\n return null;\n }\n}\n\nexport function saveAuthSession(\n access_token: string,\n refresh_token: string,\n): void {\n const claims = decodeJwt<TokenClaims>(access_token);\n const refreshClaims = decodeJwt<{ exp: number }>(refresh_token);\n\n if (!claims || !refreshClaims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token);\n\n const refreshExpiry = refreshClaims.exp * 1000;\n const accessExpiry = claims.exp * 1000;\n\n cookieStorage.set(\"refresh_token\", refresh_token, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain: getCookieDomain()\n });\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, String(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, String(refreshExpiry));\n\n authStore.set({\n isAuthenticated: true,\n isInitializing: false,\n });\n\n logger.log(\"Auth session saved\");\n}\n\nexport function getTokenClaims(): AuthTokenClaims | null {\n if (memoryClaims) return memoryClaims;\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: parseInt(refreshExpiryStr, 10),\n };\n\n return memoryClaims;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const expiryStr = browserStorage.getItem(key);\n if (!expiryStr) return true;\n const expiry = parseInt(expiryStr, 10);\n if (isNaN(expiry)) return true;\n return (expiry - Date.now()) <= thresholdSeconds * 1000;\n } catch (e) {\n logger.warn(\"Error reading expiry:\", e);\n return true;\n }\n}\n\nexport const isTokenExpiringSoon = (t = 30) => isExpiringSoon(ACCESS_EXPIRY_KEY, t);\nexport const isRefreshSessionExpired = (t = 10) => isExpiringSoon(REFRESH_EXPIRY_KEY, t);\n\nexport function isAuthenticated(): boolean {\n if (!tokenStore.getAccessToken()) return false;\n const expiryStr = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!expiryStr) return false;\n const accessExpiryTimestamp = parseInt(expiryStr, 10);\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n memoryClaims = null;\n tokenStore.clear();\n browserStorage.removeItem(ACCESS_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_EXPIRY_KEY);\n\n const domain = getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\n\n authStore.reset();\n\n logger.log(\"Auth tokens and claims cleared\");\n}\n\nexport function getUserInfo() {\n const claims = getTokenClaims();\n if (!claims) return null;\n\n return claims.access_data.sub\n}\n\nexport function decodeJwtExp(token: string): number | null {\n const decoded = decodeJwt<{ exp: number }>(token);\n return decoded?.exp ?? null;\n}\n","export interface TrieOHEnv {\n PROJECT_ID: string;\n API_KEY: string;\n BASE_URL: string;\n}\n\nexport function resolveEnv(): TrieOHEnv {\n const isServer = typeof window === \"undefined\";\n\n const viteEnv = (\n typeof import.meta !== \"undefined\" && import.meta.env\n ? import.meta.env\n : {}\n ) as Partial<ImportMetaEnv>;\n\n const safeProcessEnv: NodeJS.ProcessEnv =\n typeof process !== \"undefined\" ? process.env : {};\n\n const resolvedProjectId =\n viteEnv.VITE_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n \"\";\n\n const resolvedApiKey = isServer\n ? (safeProcessEnv.TRIEOH_AUTH_API_KEY || \"\")\n : \"\";\n\n return {\n PROJECT_ID: resolvedProjectId,\n API_KEY: resolvedApiKey,\n BASE_URL: \"https://api.trieauth.trieoh.com\",\n };\n}\nlet memoizedEnv: TrieOHEnv | null = null;\nlet overrides: Partial<TrieOHEnv> = {};\n\n/**\n * Configure the SDK manually. This will override any environment variables.\n */\nexport function configure(config: Partial<TrieOHEnv>) {\n overrides = { ...overrides, ...config };\n memoizedEnv = null; // Reset memoization to apply new config\n}\n\nfunction getEnv(): TrieOHEnv {\n if (!memoizedEnv) {\n const resolved = resolveEnv();\n memoizedEnv = {\n ...resolved,\n ...overrides,\n };\n }\n return memoizedEnv;\n}\nexport const env: TrieOHEnv = {\n get PROJECT_ID() {\n return getEnv().PROJECT_ID;\n },\n get API_KEY() {\n return getEnv().API_KEY;\n },\n get BASE_URL() {\n return getEnv().BASE_URL;\n },\n};\n","import { joinUrl } from \"../utils/url-utils\";\nimport {\n clearAuthTokens,\n isRefreshSessionExpired,\n isTokenExpiringSoon,\n saveAuthSession,\n getTokenClaims,\n type AuthTokenClaims,\n type AuthTokens\n} from \"../utils/token-utils\";\nimport { env } from \"./env\";\nimport { logger, simpleFetch } from \"@soramux/node-fetch-sdk\";\nimport { cookieStorage } from \"../utils/storage-adapter\";\nimport { tokenStore } from \"../store/token-store\";\n\nexport interface RequestOptions extends RequestInit {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\ninterface InterceptorConfig {\n baseURL?: string;\n authBaseURL?: string;\n onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n onRefreshFailed?: (error: Error) => void;\n}\n\nexport class AuthInterceptor {\n private baseURL: string;\n private authBaseURL: string;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n private onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n private onRefreshFailed?: (error: Error) => void;\n\n constructor(config?: InterceptorConfig) {\n this.baseURL = config?.baseURL || env.BASE_URL;\n this.authBaseURL = config?.authBaseURL || this.baseURL;\n this.onTokenRefreshed = config?.onTokenRefreshed;\n this.onRefreshFailed = config?.onRefreshFailed;\n }\n\n private async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\n try {\n const res = await simpleFetch<{ code: number; data?: AuthTokens; message?: string }>(\n joinUrl(this.authBaseURL, \"/auth/refresh\"),\n { method: \"POST\", credentials: \"include\" }\n );\n\n if (res.code !== 200 || !res.data) {\n if (res.code !== 503) clearAuthTokens();\n throw new Error(res.message || \"Failed to refresh token\");\n }\n\n const { access_token, refresh_token } = res.data;\n saveAuthSession(access_token, refresh_token);\n\n const claims = getTokenClaims();\n if (claims) this.onTokenRefreshed?.(claims);\n\n logger.log(\"Token refreshed successfully\");\n } catch (error) {\n logger.warn(\"Failed to refresh token:\", error);\n clearAuthTokens();\n this.onRefreshFailed?.(error as Error);\n throw error;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n return this.refreshPromise;\n }\n\n async beforeRequest(): Promise<void> {\n if (isRefreshSessionExpired()) {\n clearAuthTokens();\n return;\n }\n\n const hasAccessToken = !!tokenStore.getAccessToken();\n const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n\n if ((!hasAccessToken && hasRefreshToken) || (hasAccessToken && isTokenExpiringSoon(30))) {\n try {\n await this.refreshToken();\n } catch (error) {\n logger.warn(\"Proactive refresh failed:\", error);\n }\n }\n }\n\n async fetch(url: string, options?: RequestOptions): Promise<Response> {\n const shouldAuth = options?.requiresAuth !== false;\n const isRefreshReq = url.includes(\"/auth/refresh\");\n\n if (shouldAuth && !isRefreshReq && !options?.skipRefresh) {\n await this.beforeRequest();\n }\n\n const finalUrl = joinUrl(this.baseURL, url);\n\n const executeFetch = async (): Promise<Response> => {\n const accessToken = tokenStore.getAccessToken();\n const headers = new Headers(options?.headers);\n\n if (shouldAuth && accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n return fetch(finalUrl, {\n ...options,\n headers,\n credentials: \"include\",\n });\n };\n\n let response = await executeFetch();\n\n if (response.status === 401 && shouldAuth && !isRefreshReq) {\n logger.log(\"401 detected, attempting one-time retry after refresh...\");\n try {\n await this.refreshToken();\n response = await executeFetch();\n } catch (e) {\n logger.error(\"Retry failed after refresh error\");\n }\n }\n\n return response;\n }\n}\n\nexport const createAuthInterceptor = (config?: InterceptorConfig) => new AuthInterceptor(config);\n\nexport const createAuthenticatedFetch = (config?: InterceptorConfig) => {\n const interceptor = new AuthInterceptor(config);\n return (url: string, options?: RequestOptions) => interceptor.fetch(url, options);\n};\n","import { AuthInterceptor, type RequestOptions as InterceptorOptions } from \"./interceptor\";\nimport type { AuthTokenClaims } from \"../utils/token-utils\";\nimport {\n createDefaultFetchClient,\n type DefaultFetchClientConfig,\n type DefaultFetchResult,\n type DefaultSuccessEnvelope,\n type DefaultFailureEnvelope,\n type FetchClient,\n type FetchClientOptions\n} from \"@soramux/node-fetch-sdk\";\n\nexport type { DefaultFetchResult as ApiResponse };\n\nexport interface ApiRequestOptions extends FetchClientOptions {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\nfunction toFetchOptions(options?: ApiRequestOptions): FetchClientOptions | undefined {\n if (!options) return undefined;\n\n const { requiresAuth, skipRefresh, ...rest } = options;\n\n const interceptorFields: Partial<InterceptorOptions> = {};\n if (requiresAuth !== undefined) interceptorFields.requiresAuth = requiresAuth;\n if (skipRefresh !== undefined) interceptorFields.skipRefresh = skipRefresh;\n\n return {\n ...rest,\n adapterInit: {\n ...rest.adapterInit,\n ...interceptorFields,\n },\n };\n}\n\nexport class Api {\n readonly interceptor: AuthInterceptor;\n private readonly client: FetchClient<DefaultSuccessEnvelope, DefaultFailureEnvelope>;\n\n constructor(\n baseURL?: string,\n authBaseURL?: string,\n onTokenRefreshed?: (claims: AuthTokenClaims) => void,\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">,\n ) {\n this.interceptor = new AuthInterceptor({\n baseURL,\n authBaseURL,\n onTokenRefreshed,\n });\n\n this.client = createDefaultFetchClient({\n ...clientConfig,\n adapter: this.interceptor.fetch.bind(this.interceptor),\n });\n }\n\n request<T>(path: string, options?: ApiRequestOptions) {\n return this.client.request<T>(path, toFetchOptions(options));\n }\n\n get<T>(path: string, options?: ApiRequestOptions) {\n return this.client.get<T>(path, toFetchOptions(options));\n }\n\n post<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.post<T>(path, body, toFetchOptions(options));\n }\n\n put<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.put<T>(path, body, toFetchOptions(options));\n }\n\n patch<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.patch<T>(path, body, toFetchOptions(options));\n }\n\n delete<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.delete<T>(path, body, toFetchOptions(options));\n }\n\n query<T>(path: string, options?: ApiRequestOptions) {\n return this.client.query<T>(path, toFetchOptions(options));\n }\n}\n\nexport function createFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return {\n request: api.request.bind(api),\n get: api.get.bind(api),\n post: api.post.bind(api),\n put: api.put.bind(api),\n patch: api.patch.bind(api),\n delete: api.delete.bind(api),\n query: api.query.bind(api),\n };\n}\n\nexport function createQueryFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return <TData>(path: string, options?: ApiRequestOptions): Promise<TData> =>\n api.query<TData>(path, options);\n}\n"]}
@@ -0,0 +1,6 @@
1
+ 'use strict';var react=require('react'),nodeFetchSdk=require('@soramux/node-fetch-sdk'),jsxRuntime=require('react/jsx-runtime'),ri=require('react-icons/ri'),go=require('react-icons/go'),im=require('react-icons/im'),fa=require('react-icons/fa'),uaParserJs=require('ua-parser-js');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function fe(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var V={isAuthenticated:false,isInitializing:true},ge=new Set,Ee=()=>ge.forEach(e=>e()),v={subscribe:e=>(ge.add(e),()=>ge.delete(e)),getSnapshot:()=>V,getServerSnapshot:()=>V,set:e=>{V={...V,...e},Ee();},reset:()=>{V={isAuthenticated:false,isInitializing:false},Ee();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)v.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();v.set({isAuthenticated:r,isInitializing:false});}});var P={getItem:e=>typeof window<"u"?localStorage.getItem(e):null,setItem:(e,t)=>{typeof window<"u"&&localStorage.setItem(e,t);},removeItem:e=>{typeof window<"u"&&localStorage.removeItem(e);}},K={getItem:e=>typeof window<"u"?sessionStorage.getItem(e):null,setItem:(e,t)=>{typeof window<"u"&&sessionStorage.setItem(e,t);},removeItem:e=>{typeof window<"u"&&sessionStorage.removeItem(e);}},A={get:e=>{if(typeof window>"u")return null;let t=e+"=",r=document.cookie.split(";");for(let o=0;o<r.length;o++){let s=r[o];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return s.substring(t.length,s.length)}return null},set:(e,t,r={})=>{if(typeof window>"u")return;let{expires:o,path:s="/",domain:i,secure:n=window.location.protocol==="https:",sameSite:l=n?"None":"Lax"}=r,c=[`${e}=${t}`,i?`Domain=${i}`:"",`Path=${s}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=c.filter(Boolean).join("; ");},remove:(e,t)=>{A.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t});}};var oe="trieoh_access_token",D={getAccessToken:()=>K.getItem(oe),setAccessToken:e=>{e?K.setItem(oe,e):K.removeItem(oe);},clear:()=>{K.removeItem(oe);}};var F=null,_e="trieoh_access_expiry",ie="trieoh_refresh_expiry";function Ae(){if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost")return null;if(e.endsWith("univents.com.br"))return "univents.com.br";if(e.endsWith("identityx.com.br"))return "identityx.com.br";let t=e.split(".");return e.endsWith("trieoh.com")&&t.length>=3?`${t[t.length-3]}.trieoh.com`:e}function ve(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function Y(e,t){let r=ve(e),o=ve(t);if(!r||!o){nodeFetchSdk.logger.error("Failed to decode tokens");return}D.setAccessToken(e);let s=o.exp*1e3,i=r.exp*1e3;A.set("refresh_token",t,{expires:new Date(s).toUTCString(),domain:Ae()}),F={access_data:r,refresh_expiry_date:s},P.setItem(_e,String(i)),P.setItem(ie,String(s)),v.set({isAuthenticated:true,isInitializing:false}),nodeFetchSdk.logger.log("Auth session saved");}function j(){if(F)return F;let e=D.getAccessToken();if(!e)return null;let t=ve(e);if(!t||t.exp*1e3<=Date.now())return null;let r=P.getItem(ie);return r?(F={access_data:t,refresh_expiry_date:parseInt(r,10)},F):null}function Ce(e,t){try{let r=P.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return nodeFetchSdk.logger.warn("Error reading expiry:",r),true}}var Ie=(e=30)=>Ce(_e,e),ne=(e=10)=>Ce(ie,e);function U(){F=null,D.clear(),P.removeItem(_e),P.removeItem(ie);let e=Ae();A.remove("refresh_token",e),v.reset(),nodeFetchSdk.logger.log("Auth tokens and claims cleared");}function ke(){let e=j();return e?e.access_data.sub:null}function Ye(){let e=typeof window>"u",t=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('react.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},r=typeof process<"u"?process.env:{},o=t.VITE_TRIEOH_AUTH_PROJECT_ID||r.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||r.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",s=e&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var ae=null,xe={};function Pe(e){xe={...xe,...e},ae=null;}function ye(){return ae||(ae={...Ye(),...xe}),ae}var _={get PROJECT_ID(){return ye().PROJECT_ID},get BASE_URL(){return ye().BASE_URL}};var le=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||_.BASE_URL,this.authBaseURL=t?.authBaseURL||this.baseURL,this.onTokenRefreshed=t?.onTokenRefreshed,this.onRefreshFailed=t?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let t=await nodeFetchSdk.simpleFetch(fe(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&U(),new Error(t.message||"Failed to refresh token");let{access_token:r,refresh_token:o}=t.data;Y(r,o);let s=j();s&&this.onTokenRefreshed?.(s),nodeFetchSdk.logger.log("Token refreshed successfully");}catch(t){throw nodeFetchSdk.logger.warn("Failed to refresh token:",t),U(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ne()){U();return}let t=!!D.getAccessToken(),r=!!A.get("refresh_token");if(!t&&r||t&&Ie(30))try{await this.refreshToken();}catch(o){nodeFetchSdk.logger.warn("Proactive refresh failed:",o);}}async fetch(t,r){let o=r?.requiresAuth!==false,s=t.includes("/auth/refresh");o&&!s&&!r?.skipRefresh&&await this.beforeRequest();let i=fe(this.baseURL,t),n=async()=>{let c=D.getAccessToken(),h=new Headers(r?.headers);return o&&c&&h.set("Authorization",`Bearer ${c}`),h.has("Content-Type")||h.set("Content-Type","application/json"),fetch(i,{...r,headers:h,credentials:"include"})},l=await n();if(l.status===401&&o&&!s){nodeFetchSdk.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),l=await n();}catch{nodeFetchSdk.logger.error("Retry failed after refresh error");}}return l}};function O(e){if(!e)return;let{requiresAuth:t,skipRefresh:r,...o}=e,s={};return t!==void 0&&(s.requiresAuth=t),r!==void 0&&(s.skipRefresh=r),{...o,adapterInit:{...o.adapterInit,...s}}}var ce=class{constructor(t,r,o,s){this.interceptor=new le({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=nodeFetchSdk.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(t,r){return this.client.request(t,O(r))}get(t,r){return this.client.get(t,O(r))}post(t,r,o){return this.client.post(t,r,O(o))}put(t,r,o){return this.client.put(t,r,O(o))}patch(t,r,o){return this.client.patch(t,r,O(o))}delete(t,r,o){return this.client.delete(t,r,O(o))}query(t,r){return this.client.query(t,O(r))}};var z=()=>{if(!_.PROJECT_ID||_.PROJECT_ID.trim()==="")throw new Error("[TRIEOH SDK] Project ID is missing. Please set PUBLIC_TRIEOH_AUTH_PROJECT_ID, NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID or VITE_TRIEOH_AUTH_PROJECT_ID.")};var De=(e,t)=>({login:async(r,o)=>{_.PROJECT_ID&&z();let s=`/auth/login${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`,i=await e.post(s,{email:r,password:o},{requiresAuth:false});return i.success&&(Y(i.data.access_token,i.data.refresh_token),t?.onLogin?.()),i},register:async(r,o)=>{let s={requiresAuth:false},i=`/auth/register${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`;_.PROJECT_ID&&z();let n=await e.post(i,{email:r,password:o},s);return n.success&&t?.onRegister?.(),n},logout:async r=>{let o=`/auth/logout${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`,s=await e.post(o);return (s.success||r?.forceLogout)&&U(),s},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(Y(r.data.access_token,r.data.refresh_token),t?.onRefresh?.()),r},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async r=>e.delete(`/sessions/${r}`),revokeSessions:async(r=false)=>{let o=r?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>ke(),sendForgotPassword:async r=>{let o={requiresAuth:false},s=await(async()=>_.PROJECT_ID?(z(),e.post("/account/forgot-password",{email:r,project_id:_.PROJECT_ID},o)):e.post("/account/forgot-password",{email:r},o))();return s.success&&t?.onForgotPassword?.(),s},resetPassword:async(r,o)=>e.post(`/account/reset-password?token=${r}`,{new_password:o},{requiresAuth:false}),verifyEmail:async()=>{let r=await e.get("/account/verify",{requiresAuth:false});return r.success&&t?.onVerify?.(),r},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var Le=react.createContext(null);function xr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:s,waitSession:i=true,clientConfig:n,onLogin:l,onForgotPassword:c,onRegister:h,onVerify:p,onRefresh:u}){let f=react.useRef(false),{isAuthenticated:d,isInitializing:m}=react.useSyncExternalStore(v.subscribe,v.getSnapshot,v.getServerSnapshot);react.useEffect(()=>{Pe({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let x=react.useCallback(I=>{v.set({isAuthenticated:!!I.access_data,isInitializing:false}),u?.();},[u]),b=react.useMemo(()=>new ce(t,void 0,x,n),[t,x,n]),y=react.useMemo(()=>De(b,{onLogin:l,onForgotPassword:c,onRegister:h,onVerify:p,onRefresh:u}),[b,l,c,h,p,u]);react.useEffect(()=>{o&&z(),(async()=>{if(f.current)return;if(f.current=true,j()){v.set({isAuthenticated:true,isInitializing:false});return}if(!!!A.get("refresh_token")||ne()){v.reset(),v.set({isInitializing:false});return}nodeFetchSdk.logger.log("No cached claims, attempting silent refresh...");try{(await y.refresh()).success?(v.set({isAuthenticated:!0,isInitializing:!1}),nodeFetchSdk.logger.log("Session restored.")):(v.reset(),nodeFetchSdk.logger.warn("No active session."));}catch{v.reset(),nodeFetchSdk.logger.warn("Could not restore session (offline?).");}finally{v.set({isInitializing:false});}})();},[y,o]);let E=react.useMemo(()=>({auth:y,isAuthenticated:d,isInitializing:m,isProjectMode:o}),[y,d,m,o]);return i&&m?s??null:jsxRuntime.jsx(Le.Provider,{value:E,children:e})}function S(){let e=react.useContext(Le);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function W(e,{insertAt:t}={}){if(!e||typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}W(`@import"https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap";:root{--trieoh-primary: oklch(.1139 .0789 264.05);--trieoh-secondary: oklch(.7975 .1018 262.7);--trieoh-neutral1: oklch(.9702 0 0);--trieoh-neutral2: oklch(.1944 .0051 248.09);--trieoh-radius-full: 50%;--trieoh-text-sm: .75rem;--trieoh-text-base: .875rem;--trieoh-text-xl: 1.25rem;--trieoh-text-2xl: 1.5rem;--trieoh-text-3xl: 1.875rem;--trieoh-text-6xl: 3.75rem}
2
+ `);W(`.trieoh{font-family:Inter,sans-serif}.trieoh-input{position:relative;width:100%;display:flex;flex-direction:column;gap:.25rem;color:var(--trieoh-neutral2)}.trieoh-input__label{font-size:1rem;font-weight:600}.trieoh-input__container{display:flex;justify-content:space-between;align-items:center;padding:.0625rem .625rem;gap:.625rem;border-bottom:solid .125rem var(--trieoh-neutral2)}.trieoh-input__container--error{border-color:#e53935!important}.trieoh-input__container-field{min-width:10rem;flex:1;font-size:var(--trieoh-text-base);font-weight:300;color:var(--trieoh-neutral2);-webkit-appearance:none;background:none;outline:none;border:none;box-shadow:none!important;padding:.125rem 0}.trieoh-input__container-icon{cursor:pointer;flex-shrink:0;-webkit-user-select:none;user-select:none}.trieoh-input__hint{font-size:.75rem;color:#6b7280;transition:opacity .2s ease-in-out}.trieoh-input__hint .hint-part{transition:color .12s ease,text-decoration .12s ease,opacity .12s ease;opacity:.95;margin:.125rem}.trieoh-input__hint .hint-part.passed{text-decoration:line-through;opacity:.6;color:#10b981}.trieoh-input__hint .hint-part.failed-on-submit{color:#e53935;font-weight:600;opacity:1}.trieoh-button{--trieoh-button-color: var(--trieoh-neutral2);width:100%;height:3.25rem;font-size:var(--trieoh-text-xl);font-weight:600;color:var(--trieoh-button-color);outline:none;background:none;position:relative;overflow:hidden;min-width:10rem;flex-shrink:0;border:.125rem solid var(--trieoh-button-color);cursor:pointer;padding:0 1.5rem;transition:transform .5s}.trieoh-button--all-rounded{border-radius:.25rem}.trieoh-button:hover{transform:scale(102%)}.trieoh-button:active{transform:scale(99%)}.trieoh-button[disabled],.trieoh-button--logout[disabled]{opacity:.6;cursor:not-allowed;transform:none!important}.trieoh-button--loading:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-button-color) 40%,white 15%) 40%,transparent 80%);animation:trieoh-shine 1.5s infinite}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}.trieoh-button--logout{border:none;background:none;cursor:pointer;--trieoh-button-color: oklch(.628 .2577 29.23);display:flex;align-items:end;gap:.25rem;font-size:var(--trieoh-text-base);font-weight:500;color:var(--trieoh-button-color);transition:transform .2s}.trieoh-button--logout:hover{transform:scale(1.05)}.trieoh-button--logout:active{transform:scale(.98)}.trieoh-avacard{display:flex;flex-direction:column;align-items:center}.trieoh-avacard__container{display:flex;justify-content:center;align-items:center;padding:.5rem;background-color:#d9d9d94d;border-radius:var(--trieoh-radius-full);margin-bottom:.625rem}.trieoh-avacard__content{width:64px;height:64px;padding:.625rem;background-color:var(--trieoh-neutral1);border-radius:var(--trieoh-radius-full);box-shadow:0 .25rem 1rem #00000040}.trieoh-avacard__title{text-align:center;font-size:var(--trieoh-text-xl);font-weight:500;margin:0}.trieoh-avacard__sub-title{text-align:center;font-size:.875rem;font-weight:300;opacity:.6}.trieoh-card{display:flex;flex-direction:column;width:100%;max-width:30rem;min-width:15rem;max-height:max(75dvh,32rem);overflow:hidden;gap:1.25rem;align-items:center;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.25rem 1.5rem;box-shadow:0 .25rem .25rem #00000040;transition:transform .15s ease}.trieoh-card--full-rounded{border-radius:.25rem}.trieoh-card__fields{width:100%;display:flex;flex-direction:column;gap:.625rem;flex:1 1 auto;overflow-y:auto;margin-bottom:.5rem}.trieoh-card__divider{display:flex;align-items:center;gap:.625rem;width:100%;font-size:var(--trieoh-text-base);font-weight:600;opacity:.6}.trieoh-card__divider hr{flex:1}.trieoh-card__other{font-size:var(--trieoh-text-sm);font-weight:600}.trieoh-card__other span{cursor:pointer;color:var(--trieoh-secondary);transition:color .2s}.trieoh-card__other span:hover{color:var(--trieoh-primary)}.trieoh-copyright{font-size:var(--trieoh-text-xl);font-weight:500}.trieoh-copyright--xs{font-size:var(--trieoh-text-sm)}.trieoh-copyright--sm{font-size:var(--trieoh-text-base)}.trieoh-copyright--md{font-size:var(--trieoh-text-xl)}.trieoh-copyright--lg{font-size:var(--trieoh-text-2xl)}.trieoh-copyright--xl{font-size:var(--trieoh-text-3xl)}.trieoh-copyright--2xl{font-size:var(--trieoh-text-6xl)}.trieoh-sessions{width:100%;min-width:20rem;margin:.5rem;container-type:inline-size;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.5rem .5rem;border-radius:.5rem}.trieoh-sessions__header{width:100%;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;text-align:center;gap:1rem;box-sizing:border-box;padding:0 .75rem}.trieoh-sessions__header div{flex:0 1 auto;max-width:25rem}.trieoh-sessions__header div h3{font-weight:600;font-size:var(--trieoh-text-2xl);margin:0;margin-bottom:.25rem}.trieoh-sessions__header div p{font-weight:200;font-size:var(--trieoh-text-base);margin:0}.trieoh-sessions__header button{max-width:14rem;padding:1rem 0;height:auto;font-size:var(--trieoh-text-base)}.trieoh-sessions__content{margin-top:1rem}.trieoh-sessions__empty{display:block;border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;text-align:center;font-weight:600}.trieoh-session{border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;color:var(--trieoh-neutral2)}.trieoh-session__content{position:relative;display:flex;flex-direction:column;align-items:center;gap:.5rem;flex:1;text-align:center}.trieoh-session__info{display:flex;flex-direction:column;min-width:0}.trieoh-session__meta{display:inline-flex;flex-direction:column;font-size:var(--trieoh-text-sm);font-weight:200}.trieoh-session h3{font-size:var(--trieoh-text-base);font-weight:600;margin:0}.trieoh-session span strong{color:var(--trieoh-primary);font-weight:400}.trieoh-session__content svg:last-child{position:absolute;top:0;right:0;cursor:pointer;opacity:.6;transition:opacity .2s,transform .15s}.trieoh-session__content svg:last-child:hover{opacity:1;transform:scale(1.05)}.trieoh-session__content svg:last-child:active{transform:scale(.95)}@container (min-width: 640px){.trieoh-sessions__header{justify-content:space-between;text-align:left;gap:2rem}.trieoh-session{flex-direction:row;text-align:left}.trieoh-session__content{flex-direction:row;align-items:center;gap:1rem;text-align:left}.trieoh-session__meta{flex-direction:row;gap:.5rem;align-items:center}}
3
+ `);function w({name:e,label:t,placeholder:r,type:o="text",value:s,onValueChange:i,onBlur:n,autoComplete:l,rulesStatus:c=[],submitted:h=false,inputRef:p}){let[u,f]=react.useState(false),d=c.some(m=>!m.passed);return jsxRuntime.jsxs("div",{className:"trieoh trieoh-input",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"trieoh-input__label",children:t}),jsxRuntime.jsxs("div",{className:(d&&h?"trieoh-input__container--error ":"")+"trieoh-input__container",children:[jsxRuntime.jsx("input",{type:u?"text":o,name:e,id:e,placeholder:r,value:s,onChange:m=>i&&i(m.target.value),onBlur:n,autoComplete:l,"aria-invalid":d&&h,ref:p,className:"trieoh-input__container-field"}),o==="password"&&(u?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>f(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>f(true)}))]}),jsxRuntime.jsx("div",{className:"trieoh-input__hint",children:c.map((m,x)=>{let b=["hint-part",m.passed?"passed":"",!m.passed&&h?"failed-on-submit":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:b,children:m.message},m.id??x)})})]})}function L({label:e,onSubmit:t,loading:r}){return jsxRuntime.jsx("button",{type:"submit",onClick:t,disabled:r,className:`trieoh trieoh-button trieoh-button--all-rounded
4
+ ${r?"trieoh-button--loading":""}`,children:e})}function N({mainText:e,subText:t}){return jsxRuntime.jsxs("div",{className:"trieoh trieoh-avacard",children:[jsxRuntime.jsx("div",{className:"trieoh-avacard__container",children:jsxRuntime.jsx(go.GoPerson,{className:"trieoh-avacard__content",size:70})}),jsxRuntime.jsx("h3",{className:"trieoh-avacard__title",children:e}),jsxRuntime.jsx("span",{className:"trieoh-avacard__sub-title",children:t})]})}function R(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function lt({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:s}){let[i,n]=react.useState(""),[l,c]=react.useState(""),[h,p]=react.useState(false),[u,f]=react.useState(false),d=react.useRef(null),m=react.useRef(null),{auth:x}=S(),b={email:s||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:k=>/\S+@\S+\.\S+/.test(k)}],password:[]},y=R(b.email,i),E=R(b.password,l);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(N,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(w,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:d,rulesStatus:y,submitted:h}),jsxRuntime.jsx(w,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:c,inputRef:m,rulesStatus:E,submitted:h})]}),jsxRuntime.jsx(L,{label:"Entrar",onSubmit:async k=>{k.preventDefault(),p(true);let q=y.some(g=>!g.passed),te=E.some(g=>!g.passed);if(q){d.current?.focus();return}if(te){m.current?.focus();return}f(true);let $=await x.login(i,l);$.success?e&&await e($.message):t&&await t($.message,$.trace),f(false);},loading:u}),o&&jsxRuntime.jsx("span",{className:"trieoh-card__other",style:{textAlign:"center",cursor:"pointer"},children:jsxRuntime.jsx("span",{onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{onClick:r,children:"Cadastra-se"})]})]})]})}function ut({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:s}){let[i,n]=react.useState(""),[l,c]=react.useState(""),[h,p]=react.useState(""),[u,f]=react.useState(false),[d,m]=react.useState(false),x=react.useRef(null),b=react.useRef(null),y=react.useRef(null),{auth:E}=S(),I={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:s||[{message:"M\xEDnimo de 8 caracteres.",test:g=>g.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:g=>/[A-Z]/.test(g)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:g=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(g)},{message:"Deve conter um n\xFAmero.",test:g=>/\d/.test(g)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:g=>g===l}]},k=R(I.email,i),q=R(I.password,l),te=R(I.confirmPassword,h);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(N,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(w,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:x,rulesStatus:k,submitted:u}),jsxRuntime.jsx(w,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:c,inputRef:b,rulesStatus:q,submitted:u}),jsxRuntime.jsx(w,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:h,onValueChange:p,inputRef:y,rulesStatus:te,submitted:u})]}),jsxRuntime.jsx(L,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),f(true);let Je=k.some(J=>!J.passed),Ve=q.some(J=>!J.passed),Ke=te.some(J=>!J.passed);if(Je){x.current?.focus();return}if(Ve){b.current?.focus();return}if(Ke){y.current?.focus();return}m(true);let re=await E.register(i,l);re.success?e&&await e(re.message):t&&await t(re.message,re.trace),m(false);},loading:d}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{onClick:r,children:"Entre"})]})]})]})}function mt({size:e}){let t=e?`trieoh-copyright--${e}`:"";return jsxRuntime.jsxs("span",{className:`trieoh trieoh-copyright ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function gt({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=S(),[s,i]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async l=>{if(l.preventDefault(),s)return;i(true);let c=await o.logout({forceLogout:r});c.success?e&&await e(c.message):t&&await t(c.message,c.trace),i(false);},type:"button",disabled:s,className:"trieoh trieoh-button--logout",children:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Ue={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function ze(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function He(e){let t=ze(e);return {device:wt(t.deviceType),os:t.os,browser:t.browser}}function wt(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Me(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),s=Math.floor(o/60),i=Math.floor(s/24),n=Math.floor(i/7);return r<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:s<24?`${s} horas atr\xE1s`:i<7?`${i} dias atr\xE1s`:`${n} semanas atr\xE1s`}function Se({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:s,onClick:i}){let n=He(r),l=Ue[n.device];return jsxRuntime.jsx("div",{className:"trieoh-session",children:jsxRuntime.jsxs("div",{className:"trieoh-session__content",children:[jsxRuntime.jsx(l,{size:40}),jsxRuntime.jsxs("div",{className:"trieoh-session__info",children:[jsxRuntime.jsxs("h3",{children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"trieoh-session__meta",children:[e&&jsxRuntime.jsx("strong",{children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${s} - ${Me(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.FaTrashAlt,{size:20,color:"red",onClick:c=>i(c,t)})]})})}function Tt({revokeAll:e=false,onSuccess:t}){let{auth:r}=S(),[o,s]=react.useState(false),[i,n]=react.useState([]),l=async()=>{let p=await r.sessions();if(p.success){let u=r.profile()?.session_id,f=p.data.sort((d,m)=>d.session_id===u?-1:m.session_id===u?1:0);n(f);}};react.useEffect(()=>{l();},[]);let c=async(p,u)=>{p.preventDefault();let f=i.find(d=>d.session_id===u);if(f){n(i.filter(d=>d.session_id!==u));try{(await r.revokeASession(u)).success||n(m=>[...m,f]);}catch{n(d=>[...d,f]);}}};return jsxRuntime.jsxs("div",{className:"trieoh trieoh-sessions",children:[jsxRuntime.jsxs("div",{className:"trieoh-sessions__header",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsxRuntime.jsx("button",{type:"submit",onClick:async p=>{if(p.preventDefault(),o)return;s(true);let u=await r.revokeSessions(e),f=r.profile()?.session_id;u.success&&(n(e?[]:i.filter(d=>d.session_id===f)),t&&t(u.message)),s(false);},disabled:o,className:`trieoh trieoh-button trieoh-button--all-rounded
5
+ ${o?"trieoh-button--loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"trieoh-sessions__content",children:i.length>0?i.map(p=>jsxRuntime.jsx(Se,{...p,is_current:r.profile()?.session_id===p.session_id,onClick:c},p.session_id)):jsxRuntime.jsx("span",{className:"trieoh-sessions__empty",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function $e({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[s,i]=react.useState(""),[n,l]=react.useState(false),[c,h]=react.useState(false),p=react.useRef(null),{auth:u}=S(),d=R({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:x=>/\S+@\S+\.\S+/.test(x)}]}.email,s);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(N,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"trieoh-card__fields",children:jsxRuntime.jsx(w,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:i,inputRef:p,rulesStatus:d,submitted:n})}),jsxRuntime.jsx(L,{label:c?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async x=>{if(x.preventDefault(),l(true),d.some(E=>!E.passed)){p.current?.focus();return}h(true);let y=await u.sendForgotPassword(s);y.success?e&&await e(y.message):t&&await t(y.message,y.trace),h(false);},loading:c}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{onClick:r,children:"Login"})]})]})]})}exports.AuthProvider=xr;exports.BasicInputField=w;exports.BasicLogoutButton=gt;exports.Copyright=mt;exports.ForgotPassword=$e;exports.Sessions=Tt;exports.SignIn=lt;exports.SignUp=ut;exports.useAuth=S;//# sourceMappingURL=react.js.map
6
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/store/token-store.ts","../../src/utils/token-utils.ts","../../src/core/env.ts","../../src/core/interceptor.ts","../../src/core/api.ts","../../src/utils/env-validator.ts","../../src/core/services.ts","../../src/react/AuthProvider.tsx","#style-inject:#style-inject","../../src/react/components/variables.css","../../src/react/components/components.css","../../src/react/components/Form/BasicInputField.tsx","../../src/react/components/Form/BasicSubmitButton.tsx","../../src/react/components/Form/CardAvatar.tsx","../../src/utils/field-validator.ts","../../src/react/components/SignIn/SignIn.tsx","../../src/react/components/SignUp/SignUp.tsx","../../src/react/components/Extra/Copyright.tsx","../../src/react/components/Logout/BasicLogoutButton.tsx","../../src/utils/icons/device-icon-map.tsx","../../src/utils/ua/parse-user-agent.ts","../../src/utils/ua/get-device-info.ts","../../src/utils/date-utils.ts","../../src/react/components/Session/SessionCard.tsx","../../src/react/components/Session/Sessions.tsx","../../src/react/components/ForgotPassword/ForgotPassword.tsx"],"names":["joinUrl","base","path","cleanBase","cleanPath","_state","_listeners","notify","l","authStore","cb","partial","event","expiry","isAuthenticated","browserStorage","key","value","sessionBrowserStorage","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","getCookieDomain","hostname","parts","decodeJwt","payload","saveAuthSession","access_token","refresh_token","claims","refreshClaims","logger","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","isExpiringSoon","thresholdSeconds","expiryStr","e","isTokenExpiringSoon","t","isRefreshSessionExpired","clearAuthTokens","getUserInfo","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","error","hasAccessToken","hasRefreshToken","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","validateProjectKey","createAuthService","apiInstance","callbacks","email","password","id","revokeAll","new_password","AuthContext","createContext","AuthProvider","children","projectId","isProjectMode","fallback","waitSession","onLogin","onForgotPassword","onRegister","onVerify","onRefresh","isRestoring","useRef","isInitializing","useSyncExternalStore","useEffect","useCallback","useMemo","auth","contextValue","jsx","useAuth","ctx","useContext","styleInject","css","insertAt","head","style","BasicInputField","label","placeholder","type","onValueChange","onBlur","autoComplete","rulesStatus","submitted","inputRef","isSecretVisible","setIsSecretVisible","useState","hasAnyFailing","r","jsxs","RiEyeCloseLine","RiEyeLine","classes","BasicSubmitButton","onSubmit","loading","CardAvatar","mainText","subText","GoPerson","evaluateRules","rules","SignIn","onSuccess","onFailed","signUpRedirect","forgotPasswordRedirect","emailRules","setEmail","setPassword","setSubmitted","loadingSubmit","setLoadingSubmit","emailRef","passwordRef","v","emailValidation","passwordValidation","emailInvalid","passwordInvalid","Fragment","SignUp","loginRedirect","passwordRules","confirmPassword","setConfirmPassword","confirmPasswordRef","confirmPasswordValidation","confirmPasswordInvalid","Copyright","size","sizeClass","BasicLogoutButton","forceLogout","setLoading","ImExit","deviceIconMap","FaMobileAlt","FaTabletAlt","FaDesktop","parseUserAgent","userAgent","device","os","browser","UAParser","getDeviceInfo","parsed","normalizeDevice","timeAgo","isoDate","diff","sec","min","hour","day","week","SessionCard","is_current","session_id","user_agent","issued_at","user_ip","onClick","deviceI","DeviceIcon","FaTrashAlt","Sessions","sessions","setSessions","fetchSessions","currentSessionId","a","b","handleRevokeASession","sessionToRemove","s","prev","ForgotPassword"],"mappings":"4WAAO,SAASA,EAAAA,CAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,UAAA,CA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ACjC+F,CAAAA,EAAU,MAAMA,CAAAA,CAAS/F,CAAAA,CAAI,OAAA,CAASA,CAAAA,CAAI,KAAK,CAAA,CAE1DuG,CAAAA,CAAiB,KAAK,EACxB,EA0B8B,OAAA,CAASD,CAAAA,CACnC,CAAA,CACCW,CAAAA,EAAiBjC,eAAAA,CAAA+B,mBAAAA,CAAA,CAChB,QAAA,CAAA,CAAA/B,eAAAA,CAAC,KAAA,CAAA,CAAI,SAAA,CAAU,sBAAA,CACb,QAAA,CAAA,CAAAxB,cAAAA,CAAC,IAAA,CAAA,EAAG,CAAA,CAAE,KAENA,cAAAA,CAAC,IAAA,CAAA,EAAG,CAAA,CAAA,CACN,CAAA,CAEAwB,eAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,oBAAA,CACb,QAAA,CAAA,CAAA,2BAAA,CACDxB,cAAAA,CAAC,MAAA,CAAA,CAAK,OAAA,CAASyD,CAAAA,CAAe,QAAA,CAAA,OAAA,CAE9B,CAAA,CAAA,CACF,CAAA,CAAA,CACF,GACF,CAEJ","file":"react.js","sourcesContent":["export function joinUrl(base: string, path: string): string {\n if (path.startsWith(\"http\")) return path;\n \n const cleanBase = base.replace(/\\/$/, \"\");\n const cleanPath = path.replace(/^\\//, \"\");\n \n return `${cleanBase}/${cleanPath}`;\n}\n","type AuthState = {\n isAuthenticated: boolean;\n isInitializing: boolean;\n};\n\nlet _state: AuthState = {\n isAuthenticated: false,\n isInitializing: true,\n};\nconst _listeners = new Set<() => void>();\n\nconst notify = () => _listeners.forEach((l) => l());\n\nexport const authStore = {\n subscribe: (cb: () => void) => {\n _listeners.add(cb);\n return () => _listeners.delete(cb);\n },\n getSnapshot: () => _state,\n getServerSnapshot: () => _state,\n set: (partial: Partial<AuthState>) => {\n _state = { ..._state, ...partial };\n notify();\n },\n reset: () => {\n _state = {\n isAuthenticated: false,\n isInitializing: false,\n };\n notify();\n },\n};\n\n// Sync between tabs\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"trieoh_access_expiry\") {\n if (!event.newValue) authStore.reset();\n else {\n const expiry = parseInt(event.newValue, 10);\n const isAuthenticated = !isNaN(expiry) && expiry > Date.now();\n authStore.set({ isAuthenticated, isInitializing: false });\n }\n }\n });\n}\n","export interface StorageAdapter {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const browserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") localStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") localStorage.removeItem(key);\n },\n};\n\nexport const sessionBrowserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? sessionStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") sessionStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") sessionStorage.removeItem(key);\n },\n};\n\nexport interface CookieOptions {\n expires?: string;\n path?: string;\n domain?: string | null;\n secure?: boolean;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n}\n\nexport const cookieStorage = {\n get: (name: string): string | null => {\n if (typeof window === \"undefined\") return null;\n const nameEQ = name + \"=\";\n const ca = document.cookie.split(\";\");\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === \" \") c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n },\n\n set: (name: string, value: string, options: CookieOptions = {}) => {\n if (typeof window === \"undefined\") return;\n\n const {\n expires,\n path = \"/\",\n domain,\n secure = window.location.protocol === \"https:\",\n sameSite = secure ? \"None\" : \"Lax\",\n } = options;\n\n const cookieParts = [\n `${name}=${value}`,\n domain ? `Domain=${domain}` : \"\",\n `Path=${path}`,\n `SameSite=${sameSite}`,\n secure ? \"Secure\" : \"\",\n expires ? `expires=${expires}` : \"\",\n ];\n\n document.cookie = cookieParts.filter(Boolean).join(\"; \");\n },\n\n remove: (name: string, domain?: string | null) => {\n cookieStorage.set(name, \"\", {\n expires: \"Thu, 01 Jan 1970 00:00:00 GMT\",\n domain,\n });\n },\n};\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, token);\n else sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n },\n clear: () => {\n sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n }\n};\n","import { authStore } from \"../store/auth-store\";\nimport { tokenStore } from \"../store/token-store\";\nimport { logger } from \"@soramux/node-fetch-sdk\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n access_token: string;\n refresh_token: string;\n}\n\nexport interface TokenClaims {\n sub: {\n id: string;\n email: string;\n session_id: string;\n user_agent: string;\n user_ip: string;\n project_id: string | null;\n verified_at: string | null;\n is_verified: boolean;\n user_type: \"client\" | \"project\";\n metadata: Record<string, unknown> | null;\n };\n iss: string;\n exp: number;\n iat: number;\n jti: string;\n}\n\nexport interface AuthTokenClaims {\n access_data: TokenClaims;\n refresh_expiry_date: string | number;\n}\n\n// Stored only in memory\nlet memoryClaims: AuthTokenClaims | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\n\nexport function getCookieDomain() {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n if (hostname === 'localhost') return null;\n if (hostname.endsWith('univents.com.br')) return 'univents.com.br';\n if (hostname.endsWith('identityx.com.br')) return 'identityx.com.br';\n\n const parts = hostname.split('.');\n if (hostname.endsWith('trieoh.com') && parts.length >= 3) {\n const appName = parts[parts.length - 3];\n return `${appName}.trieoh.com`;\n }\n\n return hostname;\n}\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n return JSON.parse(atob(payload));\n } catch {\n return null;\n }\n}\n\nexport function saveAuthSession(\n access_token: string,\n refresh_token: string,\n): void {\n const claims = decodeJwt<TokenClaims>(access_token);\n const refreshClaims = decodeJwt<{ exp: number }>(refresh_token);\n\n if (!claims || !refreshClaims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token);\n\n const refreshExpiry = refreshClaims.exp * 1000;\n const accessExpiry = claims.exp * 1000;\n\n cookieStorage.set(\"refresh_token\", refresh_token, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain: getCookieDomain()\n });\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, String(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, String(refreshExpiry));\n\n authStore.set({\n isAuthenticated: true,\n isInitializing: false,\n });\n\n logger.log(\"Auth session saved\");\n}\n\nexport function getTokenClaims(): AuthTokenClaims | null {\n if (memoryClaims) return memoryClaims;\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: parseInt(refreshExpiryStr, 10),\n };\n\n return memoryClaims;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const expiryStr = browserStorage.getItem(key);\n if (!expiryStr) return true;\n const expiry = parseInt(expiryStr, 10);\n if (isNaN(expiry)) return true;\n return (expiry - Date.now()) <= thresholdSeconds * 1000;\n } catch (e) {\n logger.warn(\"Error reading expiry:\", e);\n return true;\n }\n}\n\nexport const isTokenExpiringSoon = (t = 30) => isExpiringSoon(ACCESS_EXPIRY_KEY, t);\nexport const isRefreshSessionExpired = (t = 10) => isExpiringSoon(REFRESH_EXPIRY_KEY, t);\n\nexport function isAuthenticated(): boolean {\n if (!tokenStore.getAccessToken()) return false;\n const expiryStr = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!expiryStr) return false;\n const accessExpiryTimestamp = parseInt(expiryStr, 10);\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n memoryClaims = null;\n tokenStore.clear();\n browserStorage.removeItem(ACCESS_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_EXPIRY_KEY);\n\n const domain = getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\n\n authStore.reset();\n\n logger.log(\"Auth tokens and claims cleared\");\n}\n\nexport function getUserInfo() {\n const claims = getTokenClaims();\n if (!claims) return null;\n\n return claims.access_data.sub\n}\n\nexport function decodeJwtExp(token: string): number | null {\n const decoded = decodeJwt<{ exp: number }>(token);\n return decoded?.exp ?? null;\n}\n","export interface TrieOHEnv {\n PROJECT_ID: string;\n API_KEY: string;\n BASE_URL: string;\n}\n\nexport function resolveEnv(): TrieOHEnv {\n const isServer = typeof window === \"undefined\";\n\n const viteEnv = (\n typeof import.meta !== \"undefined\" && import.meta.env\n ? import.meta.env\n : {}\n ) as Partial<ImportMetaEnv>;\n\n const safeProcessEnv: NodeJS.ProcessEnv =\n typeof process !== \"undefined\" ? process.env : {};\n\n const resolvedProjectId =\n viteEnv.VITE_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n \"\";\n\n const resolvedApiKey = isServer\n ? (safeProcessEnv.TRIEOH_AUTH_API_KEY || \"\")\n : \"\";\n\n return {\n PROJECT_ID: resolvedProjectId,\n API_KEY: resolvedApiKey,\n BASE_URL: \"https://api.trieauth.trieoh.com\",\n };\n}\nlet memoizedEnv: TrieOHEnv | null = null;\nlet overrides: Partial<TrieOHEnv> = {};\n\n/**\n * Configure the SDK manually. This will override any environment variables.\n */\nexport function configure(config: Partial<TrieOHEnv>) {\n overrides = { ...overrides, ...config };\n memoizedEnv = null; // Reset memoization to apply new config\n}\n\nfunction getEnv(): TrieOHEnv {\n if (!memoizedEnv) {\n const resolved = resolveEnv();\n memoizedEnv = {\n ...resolved,\n ...overrides,\n };\n }\n return memoizedEnv;\n}\nexport const env: TrieOHEnv = {\n get PROJECT_ID() {\n return getEnv().PROJECT_ID;\n },\n get API_KEY() {\n return getEnv().API_KEY;\n },\n get BASE_URL() {\n return getEnv().BASE_URL;\n },\n};\n","import { joinUrl } from \"../utils/url-utils\";\nimport {\n clearAuthTokens,\n isRefreshSessionExpired,\n isTokenExpiringSoon,\n saveAuthSession,\n getTokenClaims,\n type AuthTokenClaims,\n type AuthTokens\n} from \"../utils/token-utils\";\nimport { env } from \"./env\";\nimport { logger, simpleFetch } from \"@soramux/node-fetch-sdk\";\nimport { cookieStorage } from \"../utils/storage-adapter\";\nimport { tokenStore } from \"../store/token-store\";\n\nexport interface RequestOptions extends RequestInit {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\ninterface InterceptorConfig {\n baseURL?: string;\n authBaseURL?: string;\n onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n onRefreshFailed?: (error: Error) => void;\n}\n\nexport class AuthInterceptor {\n private baseURL: string;\n private authBaseURL: string;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n private onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n private onRefreshFailed?: (error: Error) => void;\n\n constructor(config?: InterceptorConfig) {\n this.baseURL = config?.baseURL || env.BASE_URL;\n this.authBaseURL = config?.authBaseURL || this.baseURL;\n this.onTokenRefreshed = config?.onTokenRefreshed;\n this.onRefreshFailed = config?.onRefreshFailed;\n }\n\n private async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\n try {\n const res = await simpleFetch<{ code: number; data?: AuthTokens; message?: string }>(\n joinUrl(this.authBaseURL, \"/auth/refresh\"),\n { method: \"POST\", credentials: \"include\" }\n );\n\n if (res.code !== 200 || !res.data) {\n if (res.code !== 503) clearAuthTokens();\n throw new Error(res.message || \"Failed to refresh token\");\n }\n\n const { access_token, refresh_token } = res.data;\n saveAuthSession(access_token, refresh_token);\n\n const claims = getTokenClaims();\n if (claims) this.onTokenRefreshed?.(claims);\n\n logger.log(\"Token refreshed successfully\");\n } catch (error) {\n logger.warn(\"Failed to refresh token:\", error);\n clearAuthTokens();\n this.onRefreshFailed?.(error as Error);\n throw error;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n return this.refreshPromise;\n }\n\n async beforeRequest(): Promise<void> {\n if (isRefreshSessionExpired()) {\n clearAuthTokens();\n return;\n }\n\n const hasAccessToken = !!tokenStore.getAccessToken();\n const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n\n if ((!hasAccessToken && hasRefreshToken) || (hasAccessToken && isTokenExpiringSoon(30))) {\n try {\n await this.refreshToken();\n } catch (error) {\n logger.warn(\"Proactive refresh failed:\", error);\n }\n }\n }\n\n async fetch(url: string, options?: RequestOptions): Promise<Response> {\n const shouldAuth = options?.requiresAuth !== false;\n const isRefreshReq = url.includes(\"/auth/refresh\");\n\n if (shouldAuth && !isRefreshReq && !options?.skipRefresh) {\n await this.beforeRequest();\n }\n\n const finalUrl = joinUrl(this.baseURL, url);\n\n const executeFetch = async (): Promise<Response> => {\n const accessToken = tokenStore.getAccessToken();\n const headers = new Headers(options?.headers);\n\n if (shouldAuth && accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n return fetch(finalUrl, {\n ...options,\n headers,\n credentials: \"include\",\n });\n };\n\n let response = await executeFetch();\n\n if (response.status === 401 && shouldAuth && !isRefreshReq) {\n logger.log(\"401 detected, attempting one-time retry after refresh...\");\n try {\n await this.refreshToken();\n response = await executeFetch();\n } catch (e) {\n logger.error(\"Retry failed after refresh error\");\n }\n }\n\n return response;\n }\n}\n\nexport const createAuthInterceptor = (config?: InterceptorConfig) => new AuthInterceptor(config);\n\nexport const createAuthenticatedFetch = (config?: InterceptorConfig) => {\n const interceptor = new AuthInterceptor(config);\n return (url: string, options?: RequestOptions) => interceptor.fetch(url, options);\n};\n","import { AuthInterceptor, type RequestOptions as InterceptorOptions } from \"./interceptor\";\nimport type { AuthTokenClaims } from \"../utils/token-utils\";\nimport {\n createDefaultFetchClient,\n type DefaultFetchClientConfig,\n type DefaultFetchResult,\n type DefaultSuccessEnvelope,\n type DefaultFailureEnvelope,\n type FetchClient,\n type FetchClientOptions\n} from \"@soramux/node-fetch-sdk\";\n\nexport type { DefaultFetchResult as ApiResponse };\n\nexport interface ApiRequestOptions extends FetchClientOptions {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\nfunction toFetchOptions(options?: ApiRequestOptions): FetchClientOptions | undefined {\n if (!options) return undefined;\n\n const { requiresAuth, skipRefresh, ...rest } = options;\n\n const interceptorFields: Partial<InterceptorOptions> = {};\n if (requiresAuth !== undefined) interceptorFields.requiresAuth = requiresAuth;\n if (skipRefresh !== undefined) interceptorFields.skipRefresh = skipRefresh;\n\n return {\n ...rest,\n adapterInit: {\n ...rest.adapterInit,\n ...interceptorFields,\n },\n };\n}\n\nexport class Api {\n readonly interceptor: AuthInterceptor;\n private readonly client: FetchClient<DefaultSuccessEnvelope, DefaultFailureEnvelope>;\n\n constructor(\n baseURL?: string,\n authBaseURL?: string,\n onTokenRefreshed?: (claims: AuthTokenClaims) => void,\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">,\n ) {\n this.interceptor = new AuthInterceptor({\n baseURL,\n authBaseURL,\n onTokenRefreshed,\n });\n\n this.client = createDefaultFetchClient({\n ...clientConfig,\n adapter: this.interceptor.fetch.bind(this.interceptor),\n });\n }\n\n request<T>(path: string, options?: ApiRequestOptions) {\n return this.client.request<T>(path, toFetchOptions(options));\n }\n\n get<T>(path: string, options?: ApiRequestOptions) {\n return this.client.get<T>(path, toFetchOptions(options));\n }\n\n post<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.post<T>(path, body, toFetchOptions(options));\n }\n\n put<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.put<T>(path, body, toFetchOptions(options));\n }\n\n patch<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.patch<T>(path, body, toFetchOptions(options));\n }\n\n delete<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.delete<T>(path, body, toFetchOptions(options));\n }\n\n query<T>(path: string, options?: ApiRequestOptions) {\n return this.client.query<T>(path, toFetchOptions(options));\n }\n}\n\nexport function createFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return {\n request: api.request.bind(api),\n get: api.get.bind(api),\n post: api.post.bind(api),\n put: api.put.bind(api),\n patch: api.patch.bind(api),\n delete: api.delete.bind(api),\n query: api.query.bind(api),\n };\n}\n\nexport function createQueryFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return <TData>(path: string, options?: ApiRequestOptions): Promise<TData> =>\n api.query<TData>(path, options);\n}\n","import { env } from \"../core/env\";\n\nexport const validateProjectKey = () => {\n if (!env.PROJECT_ID || env.PROJECT_ID.trim() === \"\") {\n throw new Error(\n \"[TRIEOH SDK] Project ID is missing. Please set PUBLIC_TRIEOH_AUTH_PROJECT_ID, NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID or VITE_TRIEOH_AUTH_PROJECT_ID.\"\n );\n }\n};\n\nexport const validateApiKey = () => {\n if (!env.API_KEY || env.API_KEY.trim() === \"\") {\n throw new Error(\n \"[TRIEOH SDK] Private API Key is missing. This operation requires TRIEOH_AUTH_API_KEY to be set in a server-side environment.\"\n );\n }\n};\n","import type { CurrentSessionI, SessionI } from \"../types/sessions-types\";\nimport {\n clearAuthTokens,\n getUserInfo,\n saveAuthSession,\n type AuthTokens\n} from \"../utils/token-utils\";\nimport { validateProjectKey } from \"../utils/env-validator\";\nimport type { Api } from \"./api\";\nimport { env } from \"./env\";\n\nexport interface AuthCallbacks {\n onLogin?: () => void;\n onRegister?: () => void;\n onVerify?: () => void;\n onForgotPassword?: () => void;\n onRefresh?: () => void;\n}\n\nexport const createAuthService = (apiInstance: Api, callbacks?: AuthCallbacks) => ({\n login: async (email: string, password: string) => {\n if (env.PROJECT_ID) validateProjectKey();\n const url = `/auth/login${env.PROJECT_ID ? `?project_id=${env.PROJECT_ID}` : \"\"}`;\n const res = await apiInstance.post<AuthTokens>(\n url,\n { email, password },\n { requiresAuth: false }\n );\n\n if (res.success) {\n saveAuthSession(res.data.access_token, res.data.refresh_token);\n callbacks?.onLogin?.();\n }\n\n return res;\n },\n\n register: async (email: string, password: string) => {\n const options = { requiresAuth: false };\n const url = `/auth/register${env.PROJECT_ID ? `?project_id=${env.PROJECT_ID}` : \"\"}`;\n if (env.PROJECT_ID) validateProjectKey();\n\n const res = await apiInstance.post<void>(url, { email, password }, options);\n if (res.success) callbacks?.onRegister?.();\n return res;\n },\n\n logout: async (options?: { forceLogout?: boolean }) => {\n const url = `/auth/logout${env.PROJECT_ID ? `?project_id=${env.PROJECT_ID}` : \"\"}`;\n const res = await apiInstance.post<void>(url);\n if (res.success || options?.forceLogout) clearAuthTokens();\n return res;\n },\n\n refresh: async () => {\n const res = await apiInstance.post<AuthTokens>(\n \"/auth/refresh\",\n undefined,\n { skipRefresh: true }\n );\n\n if (res.success) {\n saveAuthSession(res.data.access_token, res.data.refresh_token);\n callbacks?.onRefresh?.();\n }\n\n return res;\n },\n\n sessions: async () => {\n return apiInstance.get<SessionI[]>(\"/sessions\");\n },\n\n currentSession: async () => {\n return apiInstance.get<CurrentSessionI>(\"/sessions/me\");\n },\n\n revokeASession: async (id: string) => {\n return apiInstance.delete<void>(`/sessions/${id}`);\n },\n\n revokeSessions: async (revokeAll: boolean = false) => {\n const path = revokeAll ? \"/sessions\" : \"/sessions/others\"\n return apiInstance.delete<void>(path);\n },\n\n profile: () => getUserInfo(),\n\n sendForgotPassword: async (email: string) => {\n const options = { requiresAuth: false };\n const res = await (async () => {\n if (env.PROJECT_ID) {\n validateProjectKey();\n return apiInstance.post<void>(\n \"/account/forgot-password\",\n { email, project_id: env.PROJECT_ID },\n options\n );\n }\n return apiInstance.post<void>(\"/account/forgot-password\", { email }, options);\n })();\n\n if (res.success) callbacks?.onForgotPassword?.();\n return res;\n },\n\n resetPassword: async (token: string, new_password: string) => {\n return apiInstance.post<void>(\n `/account/reset-password?token=${token}`,\n { new_password },\n { requiresAuth: false }\n );\n },\n\n verifyEmail: async () => {\n const res = await apiInstance.get<void>(\"/account/verify\", { requiresAuth: false });\n if (res.success) callbacks?.onVerify?.();\n return res;\n },\n\n resendVerifyEmail: async () => {\n return apiInstance.post<void>(\"/account/verify/resend\");\n },\n\n health: async () => {\n return apiInstance.get<{ service: string; status: string }>(\"/health\", {\n requiresAuth: false,\n });\n },\n\n authHealth: async () => {\n return apiInstance.get<{ service: string; status: string; user_id: string }>(\"/protected/health\");\n }\n\n});\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore\n} from \"react\";\nimport { Api } from \"../core/api\";\nimport { createAuthService, type AuthCallbacks } from \"../core/services\";\nimport {\n getTokenClaims,\n isRefreshSessionExpired,\n type AuthTokenClaims\n} from \"../utils/token-utils\";\nimport { validateProjectKey } from \"../utils/env-validator\";\nimport { configure } from \"../core/env\";\nimport { authStore } from \"../store/auth-store\";\nimport { logger, type DefaultFetchClientConfig } from \"@soramux/node-fetch-sdk\";\nimport { cookieStorage } from \"../utils/storage-adapter\";\n\ntype AuthContextType = {\n auth: ReturnType<typeof createAuthService>;\n isAuthenticated: boolean;\n isInitializing: boolean;\n isProjectMode?: boolean;\n};\n\nconst AuthContext = createContext<AuthContextType | null>(null);\n\nexport function AuthProvider({\n children,\n baseURL,\n projectId,\n isProjectMode = true,\n fallback,\n waitSession = true,\n clientConfig,\n onLogin,\n onForgotPassword,\n onRegister,\n onVerify,\n onRefresh,\n}: {\n children: React.ReactNode;\n baseURL?: string;\n projectId?: string;\n isProjectMode?: boolean;\n /** Component to show while initial auth check is in progress */\n fallback?: React.ReactNode;\n /** Whether to wait for the session restoration before rendering children. Defaults to true. */\n waitSession?: boolean;\n /** Extra config forwarded to the API client (e.g. timeout) */\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n} & AuthCallbacks) {\n const isRestoring = useRef(false);\n\n const { isAuthenticated, isInitializing } = useSyncExternalStore(\n authStore.subscribe,\n authStore.getSnapshot,\n authStore.getServerSnapshot,\n );\n\n useEffect(() => {\n configure({\n ...(projectId ? { PROJECT_ID: projectId } : {}),\n ...(baseURL ? { BASE_URL: baseURL } : {}),\n });\n }, [projectId, baseURL]);\n\n const onTokenRefreshed = useCallback((claims: AuthTokenClaims) => {\n authStore.set({\n isAuthenticated: !!claims.access_data,\n isInitializing: false,\n });\n onRefresh?.();\n }, [onRefresh]);\n\n const apiInstance = useMemo(() => new Api(\n baseURL,\n undefined,\n onTokenRefreshed,\n clientConfig,\n ), [baseURL, onTokenRefreshed, clientConfig]);\n\n const auth = useMemo(\n () => createAuthService(apiInstance, {\n onLogin,\n onForgotPassword,\n onRegister,\n onVerify,\n onRefresh,\n }),\n [apiInstance, onLogin, onForgotPassword, onRegister, onVerify, onRefresh],\n );\n\n useEffect(() => {\n if (isProjectMode) validateProjectKey();\n\n const restoreSession = async () => {\n if (isRestoring.current) return;\n isRestoring.current = true;\n\n if (getTokenClaims()) {\n authStore.set({ isAuthenticated: true, isInitializing: false });\n return;\n }\n\n const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n if (!hasRefreshToken || isRefreshSessionExpired()) {\n authStore.reset();\n authStore.set({ isInitializing: false });\n return;\n }\n\n logger.log(\"No cached claims, attempting silent refresh...\");\n try {\n const res = await auth.refresh();\n if (res.success) {\n authStore.set({ isAuthenticated: true, isInitializing: false });\n logger.log(\"Session restored.\");\n } else {\n authStore.reset();\n logger.warn(\"No active session.\");\n }\n } catch {\n authStore.reset();\n logger.warn(\"Could not restore session (offline?).\");\n } finally {\n authStore.set({ isInitializing: false });\n }\n };\n\n restoreSession();\n }, [auth, isProjectMode]);\n\n const contextValue = useMemo(() => ({\n auth,\n isAuthenticated,\n isInitializing,\n isProjectMode\n }), [auth, isAuthenticated, isInitializing, isProjectMode]);\n\n if (waitSession && isInitializing) return fallback ?? null;\n\n return (\n <AuthContext.Provider value={contextValue}>\n {children}\n </AuthContext.Provider>\n );\n}\n\nexport function useAuth() {\n const ctx = useContext(AuthContext);\n if (!ctx) throw new Error(\"useAuth must be used inside <AuthProvider>\");\n return ctx;\n}\n","\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\"@import\\\"https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap\\\";:root{--trieoh-primary: oklch(.1139 .0789 264.05);--trieoh-secondary: oklch(.7975 .1018 262.7);--trieoh-neutral1: oklch(.9702 0 0);--trieoh-neutral2: oklch(.1944 .0051 248.09);--trieoh-radius-full: 50%;--trieoh-text-sm: .75rem;--trieoh-text-base: .875rem;--trieoh-text-xl: 1.25rem;--trieoh-text-2xl: 1.5rem;--trieoh-text-3xl: 1.875rem;--trieoh-text-6xl: 3.75rem}\\n\")","import styleInject from '#style-inject';styleInject(\".trieoh{font-family:Inter,sans-serif}.trieoh-input{position:relative;width:100%;display:flex;flex-direction:column;gap:.25rem;color:var(--trieoh-neutral2)}.trieoh-input__label{font-size:1rem;font-weight:600}.trieoh-input__container{display:flex;justify-content:space-between;align-items:center;padding:.0625rem .625rem;gap:.625rem;border-bottom:solid .125rem var(--trieoh-neutral2)}.trieoh-input__container--error{border-color:#e53935!important}.trieoh-input__container-field{min-width:10rem;flex:1;font-size:var(--trieoh-text-base);font-weight:300;color:var(--trieoh-neutral2);-webkit-appearance:none;background:none;outline:none;border:none;box-shadow:none!important;padding:.125rem 0}.trieoh-input__container-icon{cursor:pointer;flex-shrink:0;-webkit-user-select:none;user-select:none}.trieoh-input__hint{font-size:.75rem;color:#6b7280;transition:opacity .2s ease-in-out}.trieoh-input__hint .hint-part{transition:color .12s ease,text-decoration .12s ease,opacity .12s ease;opacity:.95;margin:.125rem}.trieoh-input__hint .hint-part.passed{text-decoration:line-through;opacity:.6;color:#10b981}.trieoh-input__hint .hint-part.failed-on-submit{color:#e53935;font-weight:600;opacity:1}.trieoh-button{--trieoh-button-color: var(--trieoh-neutral2);width:100%;height:3.25rem;font-size:var(--trieoh-text-xl);font-weight:600;color:var(--trieoh-button-color);outline:none;background:none;position:relative;overflow:hidden;min-width:10rem;flex-shrink:0;border:.125rem solid var(--trieoh-button-color);cursor:pointer;padding:0 1.5rem;transition:transform .5s}.trieoh-button--all-rounded{border-radius:.25rem}.trieoh-button:hover{transform:scale(102%)}.trieoh-button:active{transform:scale(99%)}.trieoh-button[disabled],.trieoh-button--logout[disabled]{opacity:.6;cursor:not-allowed;transform:none!important}.trieoh-button--loading:after{content:\\\"\\\";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-button-color) 40%,white 15%) 40%,transparent 80%);animation:trieoh-shine 1.5s infinite}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}.trieoh-button--logout{border:none;background:none;cursor:pointer;--trieoh-button-color: oklch(.628 .2577 29.23);display:flex;align-items:end;gap:.25rem;font-size:var(--trieoh-text-base);font-weight:500;color:var(--trieoh-button-color);transition:transform .2s}.trieoh-button--logout:hover{transform:scale(1.05)}.trieoh-button--logout:active{transform:scale(.98)}.trieoh-avacard{display:flex;flex-direction:column;align-items:center}.trieoh-avacard__container{display:flex;justify-content:center;align-items:center;padding:.5rem;background-color:#d9d9d94d;border-radius:var(--trieoh-radius-full);margin-bottom:.625rem}.trieoh-avacard__content{width:64px;height:64px;padding:.625rem;background-color:var(--trieoh-neutral1);border-radius:var(--trieoh-radius-full);box-shadow:0 .25rem 1rem #00000040}.trieoh-avacard__title{text-align:center;font-size:var(--trieoh-text-xl);font-weight:500;margin:0}.trieoh-avacard__sub-title{text-align:center;font-size:.875rem;font-weight:300;opacity:.6}.trieoh-card{display:flex;flex-direction:column;width:100%;max-width:30rem;min-width:15rem;max-height:max(75dvh,32rem);overflow:hidden;gap:1.25rem;align-items:center;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.25rem 1.5rem;box-shadow:0 .25rem .25rem #00000040;transition:transform .15s ease}.trieoh-card--full-rounded{border-radius:.25rem}.trieoh-card__fields{width:100%;display:flex;flex-direction:column;gap:.625rem;flex:1 1 auto;overflow-y:auto;margin-bottom:.5rem}.trieoh-card__divider{display:flex;align-items:center;gap:.625rem;width:100%;font-size:var(--trieoh-text-base);font-weight:600;opacity:.6}.trieoh-card__divider hr{flex:1}.trieoh-card__other{font-size:var(--trieoh-text-sm);font-weight:600}.trieoh-card__other span{cursor:pointer;color:var(--trieoh-secondary);transition:color .2s}.trieoh-card__other span:hover{color:var(--trieoh-primary)}.trieoh-copyright{font-size:var(--trieoh-text-xl);font-weight:500}.trieoh-copyright--xs{font-size:var(--trieoh-text-sm)}.trieoh-copyright--sm{font-size:var(--trieoh-text-base)}.trieoh-copyright--md{font-size:var(--trieoh-text-xl)}.trieoh-copyright--lg{font-size:var(--trieoh-text-2xl)}.trieoh-copyright--xl{font-size:var(--trieoh-text-3xl)}.trieoh-copyright--2xl{font-size:var(--trieoh-text-6xl)}.trieoh-sessions{width:100%;min-width:20rem;margin:.5rem;container-type:inline-size;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.5rem .5rem;border-radius:.5rem}.trieoh-sessions__header{width:100%;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;text-align:center;gap:1rem;box-sizing:border-box;padding:0 .75rem}.trieoh-sessions__header div{flex:0 1 auto;max-width:25rem}.trieoh-sessions__header div h3{font-weight:600;font-size:var(--trieoh-text-2xl);margin:0;margin-bottom:.25rem}.trieoh-sessions__header div p{font-weight:200;font-size:var(--trieoh-text-base);margin:0}.trieoh-sessions__header button{max-width:14rem;padding:1rem 0;height:auto;font-size:var(--trieoh-text-base)}.trieoh-sessions__content{margin-top:1rem}.trieoh-sessions__empty{display:block;border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;text-align:center;font-weight:600}.trieoh-session{border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;color:var(--trieoh-neutral2)}.trieoh-session__content{position:relative;display:flex;flex-direction:column;align-items:center;gap:.5rem;flex:1;text-align:center}.trieoh-session__info{display:flex;flex-direction:column;min-width:0}.trieoh-session__meta{display:inline-flex;flex-direction:column;font-size:var(--trieoh-text-sm);font-weight:200}.trieoh-session h3{font-size:var(--trieoh-text-base);font-weight:600;margin:0}.trieoh-session span strong{color:var(--trieoh-primary);font-weight:400}.trieoh-session__content svg:last-child{position:absolute;top:0;right:0;cursor:pointer;opacity:.6;transition:opacity .2s,transform .15s}.trieoh-session__content svg:last-child:hover{opacity:1;transform:scale(1.05)}.trieoh-session__content svg:last-child:active{transform:scale(.95)}@container (min-width: 640px){.trieoh-sessions__header{justify-content:space-between;text-align:left;gap:2rem}.trieoh-session{flex-direction:row;text-align:left}.trieoh-session__content{flex-direction:row;align-items:center;gap:1rem;text-align:left}.trieoh-session__meta{flex-direction:row;gap:.5rem;align-items:center}}\\n\")","import { useState } from \"react\";\nimport { RiEyeCloseLine, RiEyeLine } from \"react-icons/ri\";\nimport type { RuleStatus } from \"../../../utils/field-validator\";\n\ninterface BasicInputFieldProps {\n /** The Input ID/Name */\n name: string;\n /** The label text (name of the field) */\n label: string;\n /** The placeholder text (a default text to help the user) */\n placeholder: string;\n /** Input Type */\n type?: \"text\" | \"email\" | \"number\" | \"password\";\n /** Current Input Value */\n value?: string;\n /** Current Input Value On Change */\n onValueChange?: (value: string) => void;\n /** OnBlur event handler */\n onBlur?: React.FocusEventHandler<HTMLInputElement>;\n /** AutoComplete */\n autoComplete?: string;\n /** Validations and their results */\n rulesStatus?: RuleStatus[];\n /** Form submission status */\n submitted?: boolean;\n /** Ref to the input element */\n inputRef?: React.Ref<HTMLInputElement>;\n}\n\nexport default function BasicInputField({\n name,\n label,\n placeholder,\n type = \"text\",\n value,\n onValueChange,\n onBlur,\n autoComplete,\n rulesStatus = [],\n submitted = false,\n inputRef,\n}: BasicInputFieldProps) {\n const [isSecretVisible, setIsSecretVisible] = useState(false);\n const hasAnyFailing = rulesStatus.some(r => !r.passed);\n\n return (\n <div className=\"trieoh trieoh-input\">\n <label htmlFor={name} className=\"trieoh-input__label\">\n {label}\n </label>\n <div \n className={\n ((hasAnyFailing && submitted) ? \"trieoh-input__container--error \" : \"\")\n + \"trieoh-input__container\"\n }\n >\n <input \n type={isSecretVisible ? \"text\" : type} \n name={name} \n id={name} \n placeholder={placeholder}\n value={value}\n onChange={(e) => onValueChange && onValueChange(e.target.value)}\n onBlur={onBlur}\n autoComplete={autoComplete}\n aria-invalid={hasAnyFailing && submitted}\n ref={inputRef}\n className=\"trieoh-input__container-field\" \n />\n {type === \"password\" && (\n isSecretVisible ?\n <RiEyeCloseLine \n className=\"trieoh-input__container-icon\"\n size={24}\n onClick={() => setIsSecretVisible(false)} \n />\n :\n <RiEyeLine \n className=\"trieoh-input__container-icon\"\n size={24}\n onClick={() => setIsSecretVisible(true)} \n />\n )\n }\n </div>\n\n <div className=\"trieoh-input__hint\">\n {rulesStatus.map((r, i) => {\n const classes = [\n \"hint-part\",\n r.passed ? \"passed\" : \"\",\n !r.passed && submitted ? \"failed-on-submit\" : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n return (\n <p key={r.id ?? i} className={classes}>\n {r.message}\n </p>\n );\n })}\n </div>\n \n </div>\n )\n}","import type { MouseEvent } from \"react\";\n\ninterface BasicSubmitButtonProps {\n /** The label text (Submit Text) */\n label: string;\n /** What will happen when the user click on the button */\n onSubmit: (e: MouseEvent<HTMLButtonElement>) => void;\n /** Is performing the submit */\n loading: boolean;\n}\n\nexport default function BasicSubmitButton({\n label,\n onSubmit,\n loading\n}: BasicSubmitButtonProps) {\n return (\n <button \n type=\"submit\"\n onClick={onSubmit}\n disabled={loading}\n className={\n `trieoh trieoh-button trieoh-button--all-rounded \n ${loading ? \"trieoh-button--loading\" : \"\"}`\n }\n >\n {label}\n </button>\n )\n}","import { GoPerson } from \"react-icons/go\";\n\n\ninterface CardAvatarProps {\n /** The main text */\n mainText: string;\n /** Sub Text that will appear below the main text */\n subText: string;\n}\n\nexport default function CardAvatar({\n mainText,\n subText,\n}: CardAvatarProps) {\n return (\n <div className=\"trieoh trieoh-avacard\">\n <div className=\"trieoh-avacard__container\">\n <GoPerson className=\"trieoh-avacard__content\" size={70} />\n </div>\n <h3 className=\"trieoh-avacard__title\">{mainText}</h3>\n <span className=\"trieoh-avacard__sub-title\">{subText}</span>\n </div>\n )\n}","export type Rule = {\n id?: string;\n message: string;\n test: (value: string) => boolean;\n};\n\nexport type RuleStatus = {\n id?: string;\n message: string;\n passed: boolean;\n};\n\nexport function evaluateRules(rules: Rule[], value: string): RuleStatus[] {\n return rules.map(r => ({ \n id: r.id,\n message: r.message,\n passed: !!r.test(value) \n }));\n}\n","import { type MouseEvent, useRef, useState } from \"react\";\nimport { useAuth } from \"../../AuthProvider\";\nimport BasicInputField from \"../Form/BasicInputField\";\nimport BasicSubmitButton from \"../Form/BasicSubmitButton\";\nimport CardAvatar from \"../Form/CardAvatar\";\nimport {\n evaluateRules,\n type Rule,\n} from \"../../../utils/field-validator\";\n\nexport interface SignInProps {\n onSuccess?: (message?: string) => Promise<void>;\n onFailed?: (message: string, trace?: string[]) => Promise<void>;\n signUpRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;\n forgotPasswordRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;\n emailRules?: Rule[];\n}\n\nexport function SignIn({\n onSuccess,\n onFailed,\n signUpRedirect,\n forgotPasswordRedirect,\n emailRules,\n}: SignInProps) {\n const [email, setEmail] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [submitted, setSubmitted] = useState(false);\n const [loadingSubmit, setLoadingSubmit] = useState(false);\n const emailRef = useRef<HTMLInputElement | null>(null);\n const passwordRef = useRef<HTMLInputElement | null>(null);\n const { auth } = useAuth();\n\n const rules: Record<string, Rule[]> = {\n email: emailRules || [\n { message: \"Digite um e-mail válido, ex: exemplo@dominio.com\", test: v => /\\S+@\\S+\\.\\S+/.test(v) },\n ],\n password: [],\n };\n\n const emailValidation = evaluateRules(rules.email, email);\n const passwordValidation = evaluateRules(rules.password, password);\n\n const handleSubmit = async (e: MouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n setSubmitted(true);\n\n const emailInvalid = emailValidation.some(r => !r.passed);\n const passwordInvalid = passwordValidation.some(r => !r.passed);\n\n if (emailInvalid) {\n emailRef.current?.focus();\n return;\n }\n if (passwordInvalid) {\n passwordRef.current?.focus();\n return;\n }\n\n setLoadingSubmit(true);\n\n const res = await auth.login(email, password);\n if (res.success) {\n if (onSuccess) await onSuccess(res.message);\n } else if (onFailed) await onFailed(res.message, res.trace);\n\n setLoadingSubmit(false);\n }\n return (\n <form className=\"trieoh trieoh-card trieoh-card--full-rounded\">\n <CardAvatar mainText=\"Faça login na sua conta\" subText=\"Insira seus dados para fazer login\" />\n <div className=\"trieoh-card__fields\">\n <BasicInputField\n label=\"Email\"\n name=\"email\"\n placeholder=\"teste@gmail.com\"\n autoComplete=\"email\"\n type=\"email\"\n value={email}\n onValueChange={setEmail}\n inputRef={emailRef}\n rulesStatus={emailValidation}\n submitted={submitted}\n />\n <BasicInputField\n label=\"Senha\"\n name=\"password\"\n placeholder=\"**********\"\n autoComplete=\"current-password\"\n type=\"password\"\n value={password}\n onValueChange={setPassword}\n inputRef={passwordRef}\n rulesStatus={passwordValidation}\n submitted={submitted}\n />\n </div>\n <BasicSubmitButton label=\"Entrar\" onSubmit={handleSubmit} loading={loadingSubmit} />\n {forgotPasswordRedirect && (\n <span className=\"trieoh-card__other\" style={{ textAlign: \"center\", cursor: \"pointer\" }}>\n <span onClick={forgotPasswordRedirect}>\n Esqueceu sua senha?\n </span>\n </span>\n )}\n {signUpRedirect && <>\n <div className=\"trieoh-card__divider\">\n <hr />\n OU\n <hr />\n </div>\n <span className=\"trieoh-card__other\">\n {\"Ainda não possui uma conta? \"}\n <span onClick={signUpRedirect}>Cadastra-se</span>\n </span>\n </>}\n </form>\n );\n}\n","import { type MouseEvent, useRef, useState } from \"react\";\nimport { useAuth } from \"../../AuthProvider\";\nimport BasicInputField from \"../Form/BasicInputField\";\nimport BasicSubmitButton from \"../Form/BasicSubmitButton\";\nimport CardAvatar from \"../Form/CardAvatar\";\nimport {\n evaluateRules,\n type Rule,\n} from \"../../../utils/field-validator\";\n\nexport interface SignUpProps {\n onSuccess?: (message?: string) => Promise<void>;\n onFailed?: (message: string, trace?: string[]) => Promise<void>;\n loginRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;\n emailRules?: Rule[];\n passwordRules?: Rule[];\n}\n\nexport function SignUp({\n onSuccess,\n onFailed,\n loginRedirect,\n emailRules,\n passwordRules,\n}: SignUpProps) {\n const [email, setEmail] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [confirmPassword, setConfirmPassword] = useState(\"\");\n const [submitted, setSubmitted] = useState(false);\n const [loadingSubmit, setLoadingSubmit] = useState(false);\n const emailRef = useRef<HTMLInputElement | null>(null);\n const passwordRef = useRef<HTMLInputElement | null>(null);\n const confirmPasswordRef = useRef<HTMLInputElement | null>(null);\n const { auth } = useAuth();\n\n const rules: Record<string, Rule[]> = {\n email: emailRules || [\n { message: \"Digite um e-mail válido, ex: exemplo@dominio.com\", test: v => /\\S+@\\S+\\.\\S+/.test(v) },\n ],\n password: passwordRules || [\n { message: \"Mínimo de 8 caracteres.\", test: v => v.length >= 8 },\n { message: \"Deve conter uma letra maiúscula.\", test: v => /[A-Z]/.test(v) },\n {\n message: \"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,\",\n test: v => /[!@#$%^&*(),.?\":{}|<>_\\-+=~`;/\\\\[\\]]/.test(v)\n },\n { message: \"Deve conter um número.\", test: v => /\\d/.test(v) },\n ],\n confirmPassword: [\n { message: \"Senhas não conferem.\", test: v => v === password },\n ],\n };\n\n const emailValidation = evaluateRules(rules.email, email);\n const passwordValidation = evaluateRules(rules.password, password);\n const confirmPasswordValidation = evaluateRules(rules.confirmPassword, confirmPassword);\n\n const handleSubmit = async (e: MouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n setSubmitted(true);\n\n const emailInvalid = emailValidation.some(r => !r.passed);\n const passwordInvalid = passwordValidation.some(r => !r.passed);\n const confirmPasswordInvalid = confirmPasswordValidation.some(r => !r.passed);\n\n if (emailInvalid) {\n emailRef.current?.focus();\n return;\n }\n if (passwordInvalid) {\n passwordRef.current?.focus();\n return;\n }\n if (confirmPasswordInvalid) {\n confirmPasswordRef.current?.focus();\n return;\n }\n\n setLoadingSubmit(true);\n\n const res = await auth.register(email, password);\n if (res.success) {\n if (onSuccess) await onSuccess(res.message);\n } else if (onFailed) await onFailed(res.message, res.trace);\n\n setLoadingSubmit(false);\n }\n return (\n <form className=\"trieoh trieoh-card trieoh-card--full-rounded\">\n <CardAvatar mainText=\"Crie sua conta\" subText=\"Insira seus dados para começar\" />\n <div className=\"trieoh-card__fields\">\n <BasicInputField\n label=\"Email\"\n name=\"email\"\n placeholder=\"teste@gmail.com\"\n autoComplete=\"email\"\n type=\"email\"\n value={email}\n onValueChange={setEmail}\n inputRef={emailRef}\n rulesStatus={emailValidation}\n submitted={submitted}\n />\n <BasicInputField\n label=\"Senha\"\n name=\"password\"\n placeholder=\"**********\"\n autoComplete=\"new-password\"\n type=\"password\"\n value={password}\n onValueChange={setPassword}\n inputRef={passwordRef}\n rulesStatus={passwordValidation}\n submitted={submitted}\n />\n <BasicInputField\n label=\"Confirme a Senha\"\n name=\"confirm-password\"\n placeholder=\"**********\"\n autoComplete=\"new-password\"\n type=\"password\"\n value={confirmPassword}\n onValueChange={setConfirmPassword}\n inputRef={confirmPasswordRef}\n rulesStatus={confirmPasswordValidation}\n submitted={submitted}\n />\n </div>\n <BasicSubmitButton label=\"Criar Conta\" onSubmit={handleSubmit} loading={loadingSubmit} />\n {loginRedirect && <>\n <div className=\"trieoh-card__divider\">\n <hr />\n OU\n <hr />\n </div>\n <span className=\"trieoh-card__other\">\n {\"Já possui uma conta? \"}\n <span onClick={loginRedirect}>Entre</span>\n </span>\n </>}\n </form>\n );\n}\n","export interface CopyrightProps {\n size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'\n}\n\nexport function Copyright({ size }: CopyrightProps) {\n const sizeClass = size ? `trieoh-copyright--${size}` : ''\n\n return (\n <span className={`trieoh trieoh-copyright ${sizeClass}`}>\n © {new Date().getFullYear()} TrieOH\n </span>\n )\n}","import { useState, type MouseEvent } from \"react\";\nimport { useAuth } from \"../../AuthProvider\";\nimport { ImExit } from \"react-icons/im\";\n\nexport interface LogoutProps {\n onSuccess?: (message?: string) => Promise<void>;\n onFailed?: (message: string, trace?: string[]) => Promise<void>;\n forceLogout?: boolean;\n}\n\nexport function BasicLogoutButton({\n onSuccess,\n onFailed,\n forceLogout\n}: LogoutProps) {\n const { auth } = useAuth();\n const [loading, setLoading] = useState(false);\n\n const handleLogout = async (e: MouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n if (loading) return;\n\n setLoading(true);\n\n const res = await auth.logout({ forceLogout });\n if (res.success) {\n if (onSuccess) await onSuccess(res.message);\n } else if (onFailed) await onFailed(res.message, res.trace);\n setLoading(false);\n }\n return (\n <button\n onClick={handleLogout}\n type=\"button\"\n disabled={loading}\n className={\"trieoh trieoh-button--logout\"}\n >\n <ImExit size={24} /> <span>Log out</span>\n </button>\n )\n}","import {\n FaMobileAlt,\n FaTabletAlt,\n FaDesktop\n} from \"react-icons/fa\";\n\nexport const deviceIconMap = {\n mobile: FaMobileAlt,\n tablet: FaTabletAlt,\n desktop: FaDesktop,\n};","import { UAParser } from \"ua-parser-js\";\n\nexport function parseUserAgent(userAgent: string) {\n const { device, os, browser } = UAParser(userAgent);\n\n return {\n deviceType: device.type ?? \"desktop\",\n os: os.name,\n browser: browser.name,\n };\n}\n","import { parseUserAgent } from \"./parse-user-agent\";\nimport type { DeviceType } from \"./device-types\";\n\nexport interface DeviceInfo {\n device: DeviceType;\n os?: string;\n browser?: string;\n}\n\nexport function getDeviceInfo(userAgent: string): DeviceInfo {\n const parsed = parseUserAgent(userAgent);\n\n return {\n device: normalizeDevice(parsed.deviceType),\n os: parsed.os,\n browser: parsed.browser,\n };\n}\n\nfunction normalizeDevice(type?: string): DeviceType {\n if (!type) return \"desktop\";\n\n switch (type) {\n case \"mobile\":\n return \"mobile\";\n case \"tablet\":\n return \"tablet\";\n default:\n return \"desktop\";\n }\n}","export function timeAgo(isoDate: string): string {\n const diff = Date.now() - new Date(isoDate).getTime();\n const sec = Math.floor(diff / 1000);\n const min = Math.floor(sec / 60);\n const hour = Math.floor(min / 60);\n const day = Math.floor(hour / 24);\n const week = Math.floor(day / 7);\n\n if (sec < 60) return \"agora mesmo\";\n if (min < 60) return `${min} minutos atrás`;\n if (hour < 24) return `${hour} horas atrás`;\n if (day < 7) return `${day} dias atrás`;\n return `${week} semanas atrás`;\n}\n","import { FaTrashAlt } from \"react-icons/fa\";\nimport { deviceIconMap } from \"../../../utils/icons/device-icon-map\";\nimport type { SessionI } from \"../../../types/sessions-types\";\nimport { getDeviceInfo } from \"../../../utils/ua/get-device-info\";\nimport type { MouseEvent } from \"react\";\nimport { timeAgo } from \"../../../utils/date-utils\";\n\ninterface SessionProps extends SessionI {\n is_current: boolean;\n onClick: (e: MouseEvent<SVGElement>, id: string) => void;\n}\n\nexport default function SessionCard({\n is_current,\n session_id,\n user_agent,\n issued_at,\n user_ip,\n onClick\n}: SessionProps) {\n const deviceI = getDeviceInfo(user_agent)\n const DeviceIcon = deviceIconMap[deviceI.device];\n return (\n <div className=\"trieoh-session\">\n <div className=\"trieoh-session__content\">\n <DeviceIcon size={40} />\n <div className=\"trieoh-session__info\">\n <h3>{deviceI.browser} - {deviceI.os}</h3>\n <span className=\"trieoh-session__meta\">\n {is_current && <strong>• Sessão Atual •</strong>}\n <span>{ `${user_ip} - ${timeAgo(issued_at)}` }</span>\n </span>\n </div>\n {!is_current && <FaTrashAlt size={20} color=\"red\" onClick={(e) => onClick(e, session_id)}/>}\n </div>\n </div>\n )\n}","import { type MouseEvent, useEffect, useState } from \"react\";\nimport SessionCard from \"./SessionCard\";\nimport { useAuth } from \"../../AuthProvider\";\nimport type { SessionI } from \"../../../types/sessions-types\";\n\nexport interface SessionsProps {\n /** If true will revoke even the current session */\n revokeAll?: boolean;\n /** What will happen when sessions are revoked */\n onSuccess?: (message?: string) => Promise<void>;\n}\n\nexport function Sessions({\n revokeAll = false,\n onSuccess,\n}: SessionsProps) {\n const { auth } = useAuth();\n const [loading, setLoading] = useState(false);\n const [sessions, setSessions] = useState<SessionI[]>([]);\n\n const fetchSessions = async () => {\n const res = await auth.sessions();\n if (res.success) {\n const currentSessionId = auth.profile()?.session_id;\n\n const sessions = (res.data).sort((a, b) => {\n if (a.session_id === currentSessionId) return -1;\n if (b.session_id === currentSessionId) return 1;\n return 0;\n });\n setSessions(sessions);\n }\n }\n\n useEffect(() => {\n fetchSessions();\n }, []);\n\n const handleRevokeASession = async (e: MouseEvent<SVGElement>, id: string) => {\n e.preventDefault();\n const sessionToRemove = sessions.find(s => s.session_id === id);\n if (!sessionToRemove) return;\n setSessions(sessions.filter(s => s.session_id !== id))\n try {\n const res = await auth.revokeASession(id);\n if (!res.success) setSessions(prev => [...prev, sessionToRemove]);\n } catch {\n setSessions(prev => [...prev, sessionToRemove]);\n }\n }\n\n const handleRevokeSessions = async (e: MouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n if (loading) return;\n setLoading(true);\n\n const res = await auth.revokeSessions(revokeAll);\n const id = auth.profile()?.session_id;\n if (res.success) {\n setSessions(revokeAll ? [] : sessions.filter(s => s.session_id === id));\n if (onSuccess) onSuccess(res.message);\n }\n setLoading(false);\n }\n\n return (\n <div className=\"trieoh trieoh-sessions\">\n <div className=\"trieoh-sessions__header\">\n <div>\n <h3>Navegadores e Dispositivos</h3>\n <p>Esses navegadores e dispositivos estão atualmente conectados à sua conta. Remova quaisquer dispositivos não autorizados.</p>\n </div>\n <button\n type=\"submit\"\n onClick={handleRevokeSessions}\n disabled={loading}\n className={\n `trieoh trieoh-button trieoh-button--all-rounded \n ${loading ? \"trieoh-button--loading\" : \"\"}`\n }\n >\n Revogar todas as sessões\n </button>\n </div>\n <div className=\"trieoh-sessions__content\">\n {sessions.length > 0 ? sessions.map(s => (\n <SessionCard\n key={s.session_id}\n {...s}\n is_current={auth.profile()?.session_id === s.session_id}\n onClick={handleRevokeASession}\n />\n )) : <span className=\"trieoh-sessions__empty\">Nenhuma Sessão Disponível</span>}\n </div>\n </div>\n )\n}","import { type MouseEvent, useRef, useState } from \"react\";\nimport { evaluateRules, type Rule } from \"../../../utils/field-validator\";\nimport CardAvatar from \"../Form/CardAvatar\";\nimport { useAuth } from \"../../AuthProvider\";\nimport BasicInputField from \"../Form/BasicInputField\";\nimport BasicSubmitButton from \"../Form/BasicSubmitButton\";\n\nexport interface ForgotPasswordProps {\n onSuccess?: (message?: string) => Promise<void>;\n onFailed?: (message: string, trace?: string[]) => Promise<void>;\n loginRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;\n emailRules?: Rule[];\n}\n\nexport default function ForgotPassword({\n onSuccess,\n onFailed,\n loginRedirect,\n emailRules,\n}: ForgotPasswordProps) {\n const [email, setEmail] = useState(\"\");\n const [submitted, setSubmitted] = useState(false);\n const [loadingSubmit, setLoadingSubmit] = useState(false);\n const emailRef = useRef<HTMLInputElement | null>(null);\n\n const { auth } = useAuth();\n\n const rules: Record<string, Rule[]> = {\n email: emailRules || [\n { message: \"Digite um e-mail válido, ex: exemplo@dominio.com\", test: v => /\\S+@\\S+\\.\\S+/.test(v) },\n ],\n };\n\n const emailValidation = evaluateRules(rules.email, email);\n\n const handleSubmit = async (e: MouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n setSubmitted(true);\n\n const emailInvalid = emailValidation.some(r => !r.passed);\n\n if (emailInvalid) {\n emailRef.current?.focus();\n return;\n }\n\n setLoadingSubmit(true);\n\n const res = await auth.sendForgotPassword(email);\n\n if (res.success) {\n if (onSuccess) await onSuccess(res.message);\n } else if (onFailed) await onFailed(res.message, res.trace);\n\n setLoadingSubmit(false);\n }\n\n return (\n <form className=\"trieoh trieoh-card trieoh-card--full-rounded\">\n <CardAvatar\n mainText=\"Esqueci a senha\"\n subText=\"Insira seu e-mail para receber um link de redefinição.\"\n />\n\n <div className=\"trieoh-card__fields\">\n <BasicInputField\n label=\"Email\"\n name=\"email\"\n placeholder=\"teste@gmail.com\"\n autoComplete=\"email\"\n type=\"email\"\n value={email}\n onValueChange={setEmail}\n inputRef={emailRef}\n rulesStatus={emailValidation}\n submitted={submitted}\n />\n </div>\n\n <BasicSubmitButton\n label={loadingSubmit ? \"Enviando...\" : \"Enviar link de redefinição\"}\n onSubmit={handleSubmit} loading={loadingSubmit}\n />\n {loginRedirect && <>\n <div className=\"trieoh-card__divider\">\n <hr />\n OU\n <hr />\n </div>\n\n <span className=\"trieoh-card__other\">\n {\"Lembrou-se da sua senha? \"}\n <span onClick={loginRedirect}>\n Login\n </span>\n </span>\n </>}\n </form>\n );\n}"]}