@trieoh/identityx-sdk-ts 0.11.6 → 0.11.9
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/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/react.js +2 -5
- package/dist/cjs/react.js.map +1 -1
- package/dist/esm/{api-DO5uH1oU.d.ts → api-DjM6jYaR.d.ts} +6 -6
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/react.d.ts +32 -10
- package/dist/esm/react.js +2 -5
- package/dist/esm/react.js.map +1 -1
- package/package.json +4 -1
package/dist/cjs/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function S(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var T={isAuthenticated:false,isInitializing:true},C=new Set,
|
|
1
|
+
'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function S(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var T={isAuthenticated:false,isInitializing:true},C=new Set,F=()=>C.forEach(t=>t()),R={subscribe:t=>(C.add(t),()=>C.delete(t)),getSnapshot:()=>T,getServerSnapshot:()=>T,set:t=>{T={...T,...t},F();},reset:()=>{T={isAuthenticated:false,isInitializing:false},F();}};typeof window<"u"&&window.addEventListener("storage",t=>{if(t.key==="trieoh_access_expiry")if(!t.newValue)R.reset();else {let e=parseInt(t.newValue,10),r=!isNaN(e)&&e>Date.now();R.set({isAuthenticated:r,isInitializing:false});}});var i={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);}},_={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);}},d={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:o=window.location.protocol==="https:",sameSite:l=o?"None":"Lax"}=r,a=window.location.hostname==="localhost",p=[`${t}=${e}`,u&&!a?`Domain=${u}`:"",`Path=${s}`,`SameSite=${l}`,o?"Secure":"",n?`expires=${n}`:""];document.cookie=p.filter(Boolean).join("; ");},remove:(t,e)=>{d.set(t,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:e});}};var k="trieoh_access_token",f={getAccessToken:()=>_.getItem(k),setAccessToken:t=>{t?_.setItem(k,t):_.removeItem(k);},clear:()=>{_.removeItem(k);}};var m=null,O="trieoh_access_expiry",y="trieoh_refresh_expiry",E="trieoh_refresh_domain";function q(t){if(typeof window>"u")return null;let e=window.location.hostname;if(t)try{let r=t;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return t}return e}function L(t){try{let e=t.split(".")[1];return JSON.parse(atob(e))}catch{return null}}function D(t){let{access_token_string:e,refresh_token_string:r,access_expires_at:n,refresh_expires_at:s}=t,u=L(e);if(!u){envoyFetchTs.logger.error("Failed to decode tokens");return}f.setAccessToken(e);let o=new Date(s).getTime(),l=new Date(n).getTime(),a=q(t.domain);d.set("refresh_token",r,{expires:new Date(o).toUTCString(),domain:a}),m={access_data:u,refresh_expiry_date:o},i.setItem(O,String(l)),i.setItem(y,String(o)),a?i.setItem(E,a):i.removeItem(E),R.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function B(){if(m)return m;let t=f.getAccessToken();if(!t)return null;let e=L(t);if(!e||e.exp*1e3<=Date.now())return null;let r=i.getItem(y);return r?(m={access_data:e,refresh_expiry_date:parseInt(r,10)},m):null}function H(t,e){try{let r=i.getItem(t);if(!r)return !0;let n=parseInt(r,10);return isNaN(n)?!0:n-Date.now()<=e*1e3}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var b=(t=30)=>H(O,t),J=(t=10)=>H(y,t);function I(){m=null,f.clear(),i.removeItem(O),i.removeItem(y);let t=i.getItem(E)||q();d.remove("refresh_token",t),i.removeItem(E),R.reset(),envoyFetchTs.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 v=null,U={};function Y(t){U={...U,...t},v=null;}function P(){return v||(v={...N(),...U}),v}var K={get BASE_URL(){return P().BASE_URL}};var g=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||K.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 envoyFetchTs.simpleFetch(S(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(e.code!==200||!e.data)throw e.code!==503&&I(),new Error(e.message||"Failed to refresh token");D(e.data);let r=B();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(e){throw envoyFetchTs.logger.warn("Failed to refresh token:",e),I(),this.onRefreshFailed?.(e),e}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(J()){I();return}let e=!!f.getAccessToken(),r=!!d.get("refresh_token");if(!e&&r||e&&b(30))try{await this.refreshToken();}catch(n){envoyFetchTs.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=S(this.baseURL,e),o=async()=>{let a=f.getAccessToken(),p=new Headers(r?.headers);return n&&a&&p.set("Authorization",`Bearer ${a}`),p.has("Content-Type")||p.set("Content-Type","application/json"),fetch(u,{...r,headers:p,credentials:"include"})},l=await o();if(l.status===401&&n&&!s&&b(30)){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),l=await o();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return l}},Te=t=>new g(t),Re=t=>{let e=new g(t);return (r,n)=>e.fetch(r,n)};function h(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 w=class{constructor(e,r,n,s){this.interceptor=new g({baseURL:e,authBaseURL:r,onTokenRefreshed:n}),this.client=envoyFetchTs.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(e,r){return this.client.request(e,h(r))}get(e,r){return this.client.get(e,h(r))}post(e,r,n){return this.client.post(e,r,h(n))}put(e,r,n){return this.client.put(e,r,h(n))}patch(e,r,n){return this.client.patch(e,r,h(n))}delete(e,r,n){return this.client.delete(e,r,h(n))}query(e,r){return this.client.query(e,h(r))}};function z(t){let e=new w(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 M(t){let e=new w(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return (r,n)=>e.query(r,n)}
|
|
2
2
|
Object.defineProperty(exports,"ApiError",{enumerable:true,get:function(){return envoyFetchTs.FetchClientError}});exports.AuthInterceptor=g;exports.configure=Y;exports.createAuthInterceptor=Te;exports.createAuthenticatedFetch=Re;exports.createFetcher=z;exports.createQueryFetcher=M;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +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","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","saveAuthSession","tokens","AccessTokenString","RefreshTokenString","AccessExpiresAt","RefreshExpiresAt","Domain","claims","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":"qJAAO,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,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAExC,OAAO,CAAA,EAAGC,CAAS,IAAIC,CAAS,CAAA,CAClC,CCFA,IAAIC,CAAAA,CAAoB,CACtB,eAAA,CAAiB,KAAA,CACjB,eAAgB,IAClB,CAAA,CACMC,EAAa,IAAI,GAAA,CAEjBC,EAAS,IAAMD,CAAAA,CAAW,OAAA,CAASE,CAAAA,EAAMA,GAAG,CAAA,CAErCC,EAAY,CACvB,SAAA,CAAYC,IACVJ,CAAAA,CAAW,GAAA,CAAII,CAAE,CAAA,CACV,IAAMJ,EAAW,MAAA,CAAOI,CAAE,GAEnC,WAAA,CAAa,IAAML,EACnB,iBAAA,CAAmB,IAAMA,EACzB,GAAA,CAAMM,CAAAA,EAAgC,CACpCN,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,GAAGM,CAAQ,CAAA,CACjCJ,CAAAA,GACF,CAAA,CACA,KAAA,CAAO,IAAM,CACXF,CAAAA,CAAS,CACP,eAAA,CAAiB,KAAA,CACjB,eAAgB,KAClB,CAAA,CACAE,CAAAA,GACF,CACF,CAAA,CAGI,OAAO,OAAW,GAAA,EACpB,MAAA,CAAO,iBAAiB,SAAA,CAAYK,CAAAA,EAAU,CAC5C,GAAIA,CAAAA,CAAM,MA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AAKA,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,CAAQtE,EAAcuB,CAAAA,GAC3BgF,CAAAA,CAAI,MAAavG,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 \"@trieoh/envoy-fetch-ts\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n AccessTokenString: string;\n RefreshTokenString: string;\n AccessExpiresAt: string;\n RefreshExpiresAt: string;\n Domain: 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\";\nconst REFRESH_DOMAIN_KEY = \"trieoh_refresh_domain\";\n\nexport function getCookieDomain(returnedDomain?: string) {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n\n // Localhost should never have a domain set for cookies to avoid issues\n if (hostname === 'localhost') return null;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n return domain;\n } catch {\n return returnedDomain;\n }\n }\n\n return hostname;\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(tokens: AuthTokens): void {\n const {\n AccessTokenString,\n RefreshTokenString,\n AccessExpiresAt,\n RefreshExpiresAt,\n Domain\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(AccessTokenString);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(AccessTokenString);\n\n const refreshExpiry = new Date(RefreshExpiresAt).getTime();\n const accessExpiry = new Date(AccessExpiresAt).getTime();\n const domain = getCookieDomain(Domain);\n\n cookieStorage.set(\"refresh_token\", RefreshTokenString, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\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 if (domain) browserStorage.setItem(REFRESH_DOMAIN_KEY, domain);\n else browserStorage.removeItem(REFRESH_DOMAIN_KEY);\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 = browserStorage.getItem(REFRESH_DOMAIN_KEY) || getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\n browserStorage.removeItem(REFRESH_DOMAIN_KEY);\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 \"@trieoh/envoy-fetch-ts\";\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 saveAuthSession(res.data);\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 \"@trieoh/envoy-fetch-ts\";\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"]}
|
|
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","isLocalhost","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","saveAuthSession","tokens","access_token_string","refresh_token_string","access_expires_at","refresh_expires_at","claims","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":"qJAAO,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,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAExC,OAAO,CAAA,EAAGC,CAAS,IAAIC,CAAS,CAAA,CAClC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A,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 isLocalhost = window.location.hostname === \"localhost\";\n\n const cookieParts = [\n `${name}=${value}`,\n domain && !isLocalhost ? `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 \"@trieoh/envoy-fetch-ts\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n access_token_string: string;\n refresh_token_string: string;\n access_expires_at: string;\n refresh_expires_at: string;\n domain: 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\";\nconst REFRESH_DOMAIN_KEY = \"trieoh_refresh_domain\";\n\nexport function getCookieDomain(returnedDomain?: string) {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n return domain;\n } catch {\n return returnedDomain;\n }\n }\n\n return hostname;\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(tokens: AuthTokens): void {\n const {\n access_token_string,\n refresh_token_string,\n access_expires_at,\n refresh_expires_at,\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(access_token_string);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token_string);\n\n const refreshExpiry = new Date(refresh_expires_at).getTime();\n const accessExpiry = new Date(access_expires_at).getTime();\n const domain = getCookieDomain(tokens.domain);\n\n cookieStorage.set(\"refresh_token\", refresh_token_string, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\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 if (domain) browserStorage.setItem(REFRESH_DOMAIN_KEY, domain);\n else browserStorage.removeItem(REFRESH_DOMAIN_KEY);\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 = browserStorage.getItem(REFRESH_DOMAIN_KEY) || getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\n browserStorage.removeItem(REFRESH_DOMAIN_KEY);\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 \"@trieoh/envoy-fetch-ts\";\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 saveAuthSession(res.data);\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 const isExpiring = isTokenExpiringSoon(30);\n\n if (isExpiring) {\n logger.log(\"401 detected and token is expiring/expired, attempting 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\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 \"@trieoh/envoy-fetch-ts\";\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"]}
|
package/dist/cjs/react.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
'use strict';var react=require('react'),envoyFetchTs=require('@trieoh/envoy-fetch-ts'),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 ge(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var V={isAuthenticated:false,isInitializing:true},ve=new Set,Ee=()=>ve.forEach(e=>e()),v={subscribe:e=>(ve.add(e),()=>ve.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 w={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);}},I={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:a=n?"None":"Lax"}=r,c=[`${e}=${t}`,i?`Domain=${i}`:"",`Path=${s}`,`SameSite=${a}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=c.filter(Boolean).join("; ");},remove:(e,t)=>{I.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",ne="trieoh_refresh_expiry",ie="trieoh_refresh_domain";function Ae(e){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost")return null;if(e)try{let r=e;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return e}return t}function Ie(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function Y(e){let{AccessTokenString:t,RefreshTokenString:r,AccessExpiresAt:o,RefreshExpiresAt:s,Domain:i}=e,n=Ie(t);if(!n){envoyFetchTs.logger.error("Failed to decode tokens");return}D.setAccessToken(t);let a=new Date(s).getTime(),c=new Date(o).getTime(),u=Ae(i);I.set("refresh_token",r,{expires:new Date(a).toUTCString(),domain:u}),F={access_data:n,refresh_expiry_date:a},w.setItem(_e,String(c)),w.setItem(ne,String(a)),u?w.setItem(ie,u):w.removeItem(ie),v.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function j(){if(F)return F;let e=D.getAccessToken();if(!e)return null;let t=Ie(e);if(!t||t.exp*1e3<=Date.now())return null;let r=w.getItem(ne);return r?(F={access_data:t,refresh_expiry_date:parseInt(r,10)},F):null}function Ce(e,t){try{let r=w.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var ke=(e=30)=>Ce(_e,e),ae=(e=10)=>Ce(ne,e);function U(){F=null,D.clear(),w.removeItem(_e),w.removeItem(ne);let e=w.getItem(ie)||Ae();I.remove("refresh_token",e),w.removeItem(ie),v.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function Pe(){let e=j();return e?e.access_data.sub:null}function je(){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 le=null,xe={};function De(e){xe={...xe,...e},le=null;}function ye(){return le||(le={...je(),...xe}),le}var _={get PROJECT_ID(){return ye().PROJECT_ID},get BASE_URL(){return ye().BASE_URL}};var ce=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 envoyFetchTs.simpleFetch(ge(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");Y(t.data);let r=j();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),U(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ae()){U();return}let t=!!D.getAccessToken(),r=!!I.get("refresh_token");if(!t&&r||t&&ke(30))try{await this.refreshToken();}catch(o){envoyFetchTs.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=ge(this.baseURL,t),n=async()=>{let c=D.getAccessToken(),u=new Headers(r?.headers);return o&&c&&u.set("Authorization",`Bearer ${c}`),u.has("Content-Type")||u.set("Content-Type","application/json"),fetch(i,{...r,headers:u,credentials:"include"})},a=await n();if(a.status===401&&o&&!s){envoyFetchTs.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),a=await n();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return a}};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 ue=class{constructor(t,r,o,s){this.interceptor=new ce({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=envoyFetchTs.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 H=()=>{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 Oe=(e,t)=>({login:async(r,o)=>{_.PROJECT_ID&&H();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),t?.onLogin?.()),i},register:async(r,o)=>{let s={requiresAuth:false},i=`/auth/register${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`;_.PROJECT_ID&&H();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),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:()=>Pe(),sendForgotPassword:async r=>{let o={requiresAuth:false},s=await(async()=>_.PROJECT_ID?(H(),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 Be=react.createContext(null);function br({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:s,waitSession:i=true,clientConfig:n,onLogin:a,onForgotPassword:c,onRegister:u,onVerify:h,onRefresh:d}){let f=react.useRef(false),{isAuthenticated:m,isInitializing:p}=react.useSyncExternalStore(v.subscribe,v.getSnapshot,v.getServerSnapshot);react.useEffect(()=>{De({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let x=react.useCallback(k=>{v.set({isAuthenticated:!!k.access_data,isInitializing:false}),d?.();},[d]),b=react.useMemo(()=>new ue(t,void 0,x,n),[t,x,n]),y=react.useMemo(()=>Oe(b,{onLogin:a,onForgotPassword:c,onRegister:u,onVerify:h,onRefresh:d}),[b,a,c,u,h,d]);react.useEffect(()=>{o&&H(),(async()=>{if(f.current)return;if(f.current=true,j()){v.set({isAuthenticated:true,isInitializing:false});return}if(!!!I.get("refresh_token")||ae()){v.reset(),v.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{(await y.refresh()).success?(v.set({isAuthenticated:!0,isInitializing:!1}),envoyFetchTs.logger.log("Session restored.")):(v.reset(),envoyFetchTs.logger.warn("No active session."));}catch{v.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{v.set({isInitializing:false});}})();},[y,o]);let A=react.useMemo(()=>({auth:y,isAuthenticated:m,isInitializing:p,isProjectMode:o}),[y,m,p,o]);return i&&p?s??null:jsxRuntime.jsx(Be.Provider,{value:A,children:e})}function R(){let e=react.useContext(Be);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function X(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));}X(`@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
|
-
`);X(`.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 S({name:e,label:t,placeholder:r,type:o="text",value:s,onValueChange:i,onBlur:n,autoComplete:a,rulesStatus:c=[],submitted:u=false,inputRef:h}){let[d,f]=react.useState(false),m=c.some(p=>!p.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:(m&&u?"trieoh-input__container--error ":"")+"trieoh-input__container",children:[jsxRuntime.jsx("input",{type:d?"text":o,name:e,id:e,placeholder:r,value:s,onChange:p=>i&&i(p.target.value),onBlur:n,autoComplete:a,"aria-invalid":m&&u,ref:h,className:"trieoh-input__container-field"}),o==="password"&&(d?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((p,x)=>{let b=["hint-part",p.passed?"passed":"",!p.passed&&u?"failed-on-submit":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:b,children:p.message},p.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 B({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 T(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function ct({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:s}){let[i,n]=react.useState(""),[a,c]=react.useState(""),[u,h]=react.useState(false),[d,f]=react.useState(false),m=react.useRef(null),p=react.useRef(null),{auth:x}=R(),b={email:s||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:P=>/\S+@\S+\.\S+/.test(P)}],password:[]},y=T(b.email,i),A=T(b.password,a);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(B,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(S,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:m,rulesStatus:y,submitted:u}),jsxRuntime.jsx(S,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:a,onValueChange:c,inputRef:p,rulesStatus:A,submitted:u})]}),jsxRuntime.jsx(L,{label:"Entrar",onSubmit:async P=>{P.preventDefault(),h(true);let q=y.some(g=>!g.passed),te=A.some(g=>!g.passed);if(q){m.current?.focus();return}if(te){p.current?.focus();return}f(true);let $=await x.login(i,a);$.success?e&&await e($.message):t&&await t($.message,$.trace),f(false);},loading:d}),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 dt({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:s}){let[i,n]=react.useState(""),[a,c]=react.useState(""),[u,h]=react.useState(""),[d,f]=react.useState(false),[m,p]=react.useState(false),x=react.useRef(null),b=react.useRef(null),y=react.useRef(null),{auth:A}=R(),k={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===a}]},P=T(k.email,i),q=T(k.password,a),te=T(k.confirmPassword,u);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(B,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(S,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:x,rulesStatus:P,submitted:d}),jsxRuntime.jsx(S,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:a,onValueChange:c,inputRef:b,rulesStatus:q,submitted:d}),jsxRuntime.jsx(S,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:u,onValueChange:h,inputRef:y,rulesStatus:te,submitted:d})]}),jsxRuntime.jsx(L,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),f(true);let Ve=P.some(J=>!J.passed),Ke=q.some(J=>!J.passed),Ye=te.some(J=>!J.passed);if(Ve){x.current?.focus();return}if(Ke){b.current?.focus();return}if(Ye){y.current?.focus();return}p(true);let re=await A.register(i,a);re.success?e&&await e(re.message):t&&await t(re.message,re.trace),p(false);},loading:m}),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 pt({size:e}){let t=e?`trieoh-copyright--${e}`:"";return jsxRuntime.jsxs("span",{className:`trieoh trieoh-copyright ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function vt({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=R(),[s,i]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async a=>{if(a.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 He={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function Me(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function ze(e){let t=Me(e);return {device:St(t.deviceType),os:t.os,browser:t.browser}}function St(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function qe(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=ze(r),a=He[n.device];return jsxRuntime.jsx("div",{className:"trieoh-session",children:jsxRuntime.jsxs("div",{className:"trieoh-session__content",children:[jsxRuntime.jsx(a,{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} - ${qe(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.FaTrashAlt,{size:20,color:"red",onClick:c=>i(c,t)})]})})}function Et({revokeAll:e=false,onSuccess:t}){let{auth:r}=R(),[o,s]=react.useState(false),[i,n]=react.useState([]),a=async()=>{let h=await r.sessions();if(h.success){let d=r.profile()?.session_id,f=h.data.sort((m,p)=>m.session_id===d?-1:p.session_id===d?1:0);n(f);}};react.useEffect(()=>{a();},[]);let c=async(h,d)=>{h.preventDefault();let f=i.find(m=>m.session_id===d);if(f){n(i.filter(m=>m.session_id!==d));try{(await r.revokeASession(d)).success||n(p=>[...p,f]);}catch{n(m=>[...m,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 h=>{if(h.preventDefault(),o)return;s(true);let d=await r.revokeSessions(e),f=r.profile()?.session_id;d.success&&(n(e?[]:i.filter(m=>m.session_id===f)),t&&t(d.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(h=>jsxRuntime.jsx(Se,{...h,is_current:r.profile()?.session_id===h.session_id,onClick:c},h.session_id)):jsxRuntime.jsx("span",{className:"trieoh-sessions__empty",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Je({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[s,i]=react.useState(""),[n,a]=react.useState(false),[c,u]=react.useState(false),h=react.useRef(null),{auth:d}=R(),m=T({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(B,{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(S,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:i,inputRef:h,rulesStatus:m,submitted:n})}),jsxRuntime.jsx(L,{label:c?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async x=>{if(x.preventDefault(),a(true),m.some(A=>!A.passed)){h.current?.focus();return}u(true);let y=await d.sendForgotPassword(s);y.success?e&&await e(y.message):t&&await t(y.message,y.trace),u(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=br;exports.BasicInputField=S;exports.BasicLogoutButton=vt;exports.Copyright=pt;exports.ForgotPassword=Je;exports.Sessions=Et;exports.SignIn=ct;exports.SignUp=dt;exports.useAuth=R;//# sourceMappingURL=react.js.map
|
|
1
|
+
'use strict';var react=require('react'),envoyFetchTs=require('@trieoh/envoy-fetch-ts'),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'),fi=require('react-icons/fi');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function we(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var K={isAuthenticated:false,isInitializing:true},xe=new Set,Le=()=>xe.forEach(e=>e()),x={subscribe:e=>(xe.add(e),()=>xe.delete(e)),getSnapshot:()=>K,getServerSnapshot:()=>K,set:e=>{K={...K,...e},Le();},reset:()=>{K={isAuthenticated:false,isInitializing:false},Le();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)x.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();x.set({isAuthenticated:r,isInitializing:false});}});var A={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);}},Y={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);}},D={get:e=>{if(typeof window>"u")return null;let t=e+"=",r=document.cookie.split(";");for(let o=0;o<r.length;o++){let i=r[o];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return i.substring(t.length,i.length)}return null},set:(e,t,r={})=>{if(typeof window>"u")return;let{expires:o,path:i="/",domain:s,secure:n=window.location.protocol==="https:",sameSite:l=n?"None":"Lax"}=r,a=window.location.hostname==="localhost",m=[`${e}=${t}`,s&&!a?`Domain=${s}`:"",`Path=${i}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=m.filter(Boolean).join("; ");},remove:(e,t)=>{D.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t});}};var ie="trieoh_access_token",B={getAccessToken:()=>Y.getItem(ie),setAccessToken:e=>{e?Y.setItem(ie,e):Y.removeItem(ie);},clear:()=>{Y.removeItem(ie);}};var z=null,be="trieoh_access_expiry",ae="trieoh_refresh_expiry",ne="trieoh_refresh_domain";function De(e){if(typeof window>"u")return null;let t=window.location.hostname;if(e)try{let r=e;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return e}return t}function Oe(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function G(e){let{access_token_string:t,refresh_token_string:r,access_expires_at:o,refresh_expires_at:i}=e,s=Oe(t);if(!s){envoyFetchTs.logger.error("Failed to decode tokens");return}B.setAccessToken(t);let n=new Date(i).getTime(),l=new Date(o).getTime(),a=De(e.domain);D.set("refresh_token",r,{expires:new Date(n).toUTCString(),domain:a}),z={access_data:s,refresh_expiry_date:n},A.setItem(be,String(l)),A.setItem(ae,String(n)),a?A.setItem(ne,a):A.removeItem(ne),x.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function X(){if(z)return z;let e=B.getAccessToken();if(!e)return null;let t=Oe(e);if(!t||t.exp*1e3<=Date.now())return null;let r=A.getItem(ae);return r?(z={access_data:t,refresh_expiry_date:parseInt(r,10)},z):null}function Me(e,t){try{let r=A.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var ye=(e=30)=>Me(be,e),le=(e=10)=>Me(ae,e);function V(){z=null,B.clear(),A.removeItem(be),A.removeItem(ae);let e=A.getItem(ne)||De();D.remove("refresh_token",e),A.removeItem(ne),x.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function Be(){let e=X();return e?e.access_data.sub:null}function ot(){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||"",i=e&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:i,BASE_URL:"https://api.trieauth.trieoh.com"}}var ce=null,Re={};function Fe(e){Re={...Re,...e},ce=null;}function Se(){return ce||(ce={...ot(),...Re}),ce}var b={get PROJECT_ID(){return Se().PROJECT_ID},get BASE_URL(){return Se().BASE_URL}};var ue=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||b.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 envoyFetchTs.simpleFetch(we(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&V(),new Error(t.message||"Failed to refresh token");G(t.data);let r=X();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),V(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(le()){V();return}let t=!!B.getAccessToken(),r=!!D.get("refresh_token");if(!t&&r||t&&ye(30))try{await this.refreshToken();}catch(o){envoyFetchTs.logger.warn("Proactive refresh failed:",o);}}async fetch(t,r){let o=r?.requiresAuth!==false,i=t.includes("/auth/refresh");o&&!i&&!r?.skipRefresh&&await this.beforeRequest();let s=we(this.baseURL,t),n=async()=>{let a=B.getAccessToken(),m=new Headers(r?.headers);return o&&a&&m.set("Authorization",`Bearer ${a}`),m.has("Content-Type")||m.set("Content-Type","application/json"),fetch(s,{...r,headers:m,credentials:"include"})},l=await n();if(l.status===401&&o&&!i&&ye(30)){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),l=await n();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return l}};function F(e){if(!e)return;let{requiresAuth:t,skipRefresh:r,...o}=e,i={};return t!==void 0&&(i.requiresAuth=t),r!==void 0&&(i.skipRefresh=r),{...o,adapterInit:{...o.adapterInit,...i}}}var me=class{constructor(t,r,o,i){this.interceptor=new ue({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=envoyFetchTs.createDefaultFetchClient({...i,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(t,r){return this.client.request(t,F(r))}get(t,r){return this.client.get(t,F(r))}post(t,r,o){return this.client.post(t,r,F(o))}put(t,r,o){return this.client.put(t,r,F(o))}patch(t,r,o){return this.client.patch(t,r,F(o))}delete(t,r,o){return this.client.delete(t,r,F(o))}query(t,r){return this.client.query(t,F(r))}};var q=()=>{if(!b.PROJECT_ID||b.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 Ue=(e,t)=>({login:async(r,o)=>{b.PROJECT_ID&&q();let i=`/auth/login${b.PROJECT_ID?`?project_id=${b.PROJECT_ID}`:""}`,s=await e.post(i,{email:r,password:o},{requiresAuth:false});return s.success&&(G(s.data),t?.onLogin?.(s)),s},register:async(r,o)=>{let i={requiresAuth:false},s=`/auth/register${b.PROJECT_ID?`?project_id=${b.PROJECT_ID}`:""}`;b.PROJECT_ID&&q();let n=await e.post(s,{email:r,password:o},i);return n.success&&t?.onRegister?.(n),n},logout:async r=>{let o=`/auth/logout${b.PROJECT_ID?`?project_id=${b.PROJECT_ID}`:""}`,i=await e.post(o);return (i.success||r?.forceLogout)&&V(),i},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(G(r.data),t?.onRefresh?.(r)),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:()=>Be(),sendForgotPassword:async r=>{let o={requiresAuth:false};return b.PROJECT_ID?(q(),e.post("/account/forgot-password",{email:r,project_id:b.PROJECT_ID},o)):e.post("/account/forgot-password",{email:r},o)},resetPassword:async(r,o)=>{let i=await e.post(`/account/reset-password?token=${r}`,{new_password:o},{requiresAuth:false});return i.success&&t?.onResetPassword?.(i),i},verifyEmail:async r=>{let o=`/account/verify?token=${r}`,i=await e.post(o);return i.success&&t?.onVerify?.(i),i},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var ze=react.createContext(null);function Hr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:i,waitSession:s=true,clientConfig:n,onLogin:l,onResetPassword:a,onRegister:m,onVerify:f,onRefresh:p}){let h=react.useRef(false),{isAuthenticated:d,isInitializing:c}=react.useSyncExternalStore(x.subscribe,x.getSnapshot,x.getServerSnapshot);react.useEffect(()=>{Fe({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let S=react.useCallback(L=>{x.set({isAuthenticated:!!L.access_data,isInitializing:false}),p?.();},[p]),R=react.useMemo(()=>new me(t,void 0,S,n),[t,S,n]),w=react.useMemo(()=>Ue(R,{onLogin:l,onResetPassword:a,onRegister:m,onVerify:f,onRefresh:p}),[R,l,a,m,f,p]);react.useEffect(()=>{o&&q(),(async()=>{if(h.current)return;if(h.current=true,X()){x.set({isAuthenticated:true,isInitializing:false});return}if(!!!D.get("refresh_token")||le()){x.reset(),x.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{(await w.refresh()).success?(x.set({isAuthenticated:!0,isInitializing:!1}),envoyFetchTs.logger.log("Session restored.")):(x.reset(),envoyFetchTs.logger.warn("No active session."));}catch{x.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{x.set({isInitializing:false});}})();},[w,o]);let C=react.useMemo(()=>({auth:w,isAuthenticated:d,isInitializing:c,isProjectMode:o}),[w,d,c,o]);return s&&c?i??null:jsxRuntime.jsx(ze.Provider,{value:C,children:e})}function y(){let e=react.useContext(ze);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Ee(e,{insertAt:t}={}){if(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));}Ee(`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--spacing: .25rem;--font-weight-extralight: 200;--font-weight-light: 300;--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--radius-lg: .5rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-trieoh-primary: oklch(.1139 .0789 264.05);--color-trieoh-secondary: oklch(.7975 .1018 262.7);--color-trieoh-neutral1: oklch(.9702 0 0);--color-trieoh-neutral2: oklch(.1944 .0051 248.09);--radius-trieoh-full: 50%;--font-inter: "Inter", sans-serif}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-font-variation-settings, normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor;@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\\@container{container-type:inline-size}.trieoh-button-loading{&:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,var(--trieoh-neutral2) 40%,transparent 80%);@supports (color: color-mix(in lab,red,red)){background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-neutral2) 40%,white 15%) 40%,transparent 80%)}animation:trieoh-shine 1.5s infinite}}.absolute{position:absolute}.relative{position:relative}.top-0{top:calc(var(--spacing) * 0)}.right-0{right:calc(var(--spacing) * 0)}.m-0{margin:calc(var(--spacing) * 0)}.m-2{margin:calc(var(--spacing) * 2)}.m-\\[0\\.125rem\\]{margin:.125rem}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-\\[0\\.625rem\\]{margin-bottom:.625rem}.box-border{box-sizing:border-box}.block{display:block}.contents{display:contents}.flex{display:flex}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-\\[3\\.25rem\\]{height:3.25rem}.h-\\[64px\\]{height:64px}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[max\\(75dvh\\,32rem\\)\\]{max-height:max(75dvh,32rem)}.min-h-screen{min-height:100vh}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-\\[64px\\]{width:64px}.w-full{width:100%}.max-w-\\[14rem\\]{max-width:14rem}.max-w-\\[25rem\\]{max-width:25rem}.max-w-\\[30rem\\]{max-width:30rem}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\\[10rem\\]{min-width:10rem}.min-w-\\[15rem\\]{min-width:15rem}.min-w-\\[20rem\\]{min-width:20rem}.flex-1{flex:1}.flex-\\[0_1_auto\\]{flex:0 1 auto}.flex-\\[1_1_auto\\]{flex:1 1 auto}.shrink-0{flex-shrink:0}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.appearance-none{appearance:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}.gap-\\[0\\.625rem\\]{gap:.625rem}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-\\[0\\.25rem\\]{border-radius:.25rem}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius-lg)}.rounded-trieoh-full{border-radius:var(--radius-trieoh-full)}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-none{--tw-border-style: none;border-style:none}.\\!border-\\[\\#e53935\\]{border-color:#e53935!important}.border-\\[rgba\\(0\\,0\\,0\\,0\\.3\\)\\]{border-color:#0000004d}.border-trieoh-neutral2{border-color:var(--color-trieoh-neutral2)}.border-trieoh-secondary{border-color:var(--color-trieoh-secondary)}.bg-\\[oklch\\(0\\.8853_0_0\\/30\\%\\)\\]{background-color:#d9d9d94d}.bg-transparent{background-color:transparent}.bg-trieoh-neutral1{background-color:var(--color-trieoh-neutral1)}.bg-trieoh-secondary\\/10{background-color:color-mix(in srgb,oklch(.7975 .1018 262.7) 10%,transparent);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-trieoh-secondary) 10%,transparent)}}.p-2{padding:calc(var(--spacing) * 2)}.p-6{padding:calc(var(--spacing) * 6)}.p-\\[0\\.625rem\\]{padding:.625rem}.p-\\[1\\.5rem_0\\.5rem\\]{padding:1.5rem .5rem}.p-\\[1\\.25rem_0\\.75rem\\]{padding:1.25rem .75rem}.p-\\[1\\.25rem_1\\.5rem\\]{padding:1.25rem 1.5rem}.p-\\[1rem_0\\]{padding:1rem 0}.px-\\[0\\.75rem\\]{padding-inline:.75rem}.px-\\[0\\.625rem\\]{padding-inline:.625rem}.px-\\[1\\.5rem\\]{padding-inline:1.5rem}.py-4{padding-block:calc(var(--spacing) * 4)}.py-\\[0\\.125rem\\]{padding-block:.125rem}.py-\\[0\\.0625rem\\]{padding-block:.0625rem}.text-center{text-align:center}.font-inter{font-family:var(--font-inter)}.text-\\[0\\.75rem\\]{font-size:.75rem}.text-\\[0\\.875rem\\]{font-size:.875rem}.text-\\[1rem\\]{font-size:1rem}.font-extralight{--tw-font-weight: var(--font-weight-extralight);font-weight:var(--font-weight-extralight)}.font-light{--tw-font-weight: var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#6b7280\\]{color:#6b7280}.text-\\[\\#10b981\\]{color:#10b981}.text-\\[\\#e53935\\]{color:#e53935}.text-\\[oklch\\(0\\.628_0\\.2577_29\\.23\\)\\]{color:red}.text-trieoh-neutral2{color:var(--color-trieoh-neutral2)}.text-trieoh-primary{color:var(--color-trieoh-primary)}.text-trieoh-secondary{color:var(--color-trieoh-secondary)}.line-through{text-decoration-line:line-through}.opacity-50{opacity:50%}.opacity-60{opacity:60%}.opacity-95{opacity:95%}.opacity-100{opacity:100%}.\\!shadow-none{--tw-shadow: 0 0 #0000 !important;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)!important}.shadow-\\[0_0\\.25rem_0\\.25rem_0_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem .25rem 0 var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[0_0\\.25rem_1rem_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem 1rem var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.transition-\\[color\\,text-decoration\\,opacity\\]{transition-property:color,text-decoration,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.duration-150{--tw-duration: .15s;transition-duration:.15s}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-500{--tw-duration: .5s;transition-duration:.5s}.duration-\\[120ms\\]{--tw-duration: .12s;transition-duration:.12s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style: none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.hover\\:scale-\\[1\\.02\\]{&:hover{@media(hover:hover){scale:1.02}}}.hover\\:scale-\\[1\\.05\\]{&:hover{@media(hover:hover){scale:1.05}}}.hover\\:text-trieoh-primary{&:hover{@media(hover:hover){color:var(--color-trieoh-primary)}}}.hover\\:opacity-100{&:hover{@media(hover:hover){opacity:100%}}}.active\\:scale-\\[0\\.95\\]{&:active{scale:.95}}.active\\:scale-\\[0\\.98\\]{&:active{scale:.98}}.active\\:scale-\\[0\\.99\\]{&:active{scale:.99}}.disabled\\:\\!transform-none{&:disabled{transform:none!important}}.disabled\\:cursor-not-allowed{&:disabled{cursor:not-allowed}}.disabled\\:opacity-60{&:disabled{opacity:60%}}.\\@\\[640px\\]\\:flex-row{@container (width >= 640px){flex-direction:row}}.\\@\\[640px\\]\\:items-center{@container (width >= 640px){align-items:center}}.\\@\\[640px\\]\\:justify-between{@container (width >= 640px){justify-content:space-between}}.\\@\\[640px\\]\\:gap-2{@container (width >= 640px){gap:calc(var(--spacing) * 2)}}.\\@\\[640px\\]\\:gap-4{@container (width >= 640px){gap:calc(var(--spacing) * 4)}}.\\@\\[640px\\]\\:gap-8{@container (width >= 640px){gap:calc(var(--spacing) * 8)}}.\\@\\[640px\\]\\:text-left{@container (width >= 640px){text-align:left}}}@import url(https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap);@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@keyframes spin{to{transform:rotate(360deg)}}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style: solid;--tw-font-weight: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-duration: initial;--tw-ease: initial}}}
|
|
2
|
+
`);function _({name:e,label:t,placeholder:r,type:o="text",value:i,onValueChange:s,onBlur:n,autoComplete:l,rulesStatus:a=[],submitted:m=false,inputRef:f}){let[p,h]=react.useState(false),d=a.some(c=>!c.passed);return jsxRuntime.jsxs("div",{className:"font-inter relative w-full flex flex-col gap-1 text-trieoh-neutral2",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"text-[1rem] font-semibold",children:t}),jsxRuntime.jsxs("div",{className:`flex justify-between items-center px-[0.625rem] py-[0.0625rem] gap-[0.625rem] border-b-2 border-trieoh-neutral2 ${d&&m?"!border-[#e53935]":""}`,children:[jsxRuntime.jsx("input",{type:p?"text":o,name:e,id:e,placeholder:r,value:i,onChange:c=>s&&s(c.target.value),onBlur:n,autoComplete:l,"aria-invalid":d&&m,ref:f,className:"min-w-[10rem] flex-1 text-trieoh-base font-light text-trieoh-neutral2 appearance-none bg-transparent outline-none border-none !shadow-none py-[0.125rem]"}),o==="password"&&(p?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(true)}))]}),jsxRuntime.jsx("div",{className:"text-[0.75rem] text-[#6b7280] transition-opacity duration-200 ease-in-out",children:a.map((c,S)=>{let R=["transition-[color,text-decoration,opacity] duration-[120ms] ease opacity-95 m-[0.125rem]",c.passed?"line-through opacity-60 text-[#10b981]":"",!c.passed&&m?"text-[#e53935] font-semibold opacity-100":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:R,children:c.message},c.id??S)})})]})}function E({label:e,onSubmit:t,loading:r}){return jsxRuntime.jsx("button",{type:"submit",onClick:t,disabled:r,className:`font-inter w-full h-[3.25rem] text-trieoh-xl font-semibold outline-none bg-transparent relative overflow-hidden min-w-[10rem] shrink-0 border-2 border-trieoh-neutral2 text-trieoh-neutral2 cursor-pointer px-[1.5rem] transition-transform duration-500 rounded-[0.25rem] hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none ${r?"trieoh-button-loading":""}`,children:e})}function k({mainText:e,subText:t}){return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col items-center",children:[jsxRuntime.jsx("div",{className:"flex justify-center items-center p-2 bg-[oklch(0.8853_0_0/30%)] rounded-trieoh-full mb-[0.625rem]",children:jsxRuntime.jsx(go.GoPerson,{className:"w-[64px] h-[64px] p-[0.625rem] bg-trieoh-neutral1 rounded-trieoh-full shadow-[0_0.25rem_1rem_rgba(0,0,0,0.25)]",size:70})}),jsxRuntime.jsx("h3",{className:"text-center text-trieoh-xl font-medium m-0",children:e}),jsxRuntime.jsx("span",{className:"text-center text-[0.875rem] font-light opacity-60",children:t})]})}function T(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function wt({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(false),[p,h]=react.useState(false),d=react.useRef(null),c=react.useRef(null),{auth:S}=y(),R={email:i||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],password:[]},w=T(R.email,s),C=T(R.password,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:m}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:C,submitted:m})]}),jsxRuntime.jsx(E,{label:"Entrar",onSubmit:async v=>{v.preventDefault(),f(true);let M=w.some(g=>!g.passed),H=C.some(g=>!g.passed);if(M){d.current?.focus();return}if(H){c.current?.focus();return}h(true);let P=await S.login(s,l);P.success?e&&await e(P.message):t&&await t(P.message,P.trace),h(false);},loading:p}),o&&jsxRuntime.jsx("span",{className:"text-trieoh-sm font-semibold text-center cursor-pointer",children:jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Cadastra-se"})]})]})]})}function bt({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(""),[p,h]=react.useState(false),[d,c]=react.useState(false),S=react.useRef(null),R=react.useRef(null),w=react.useRef(null),{auth:C}=y(),L={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:i||[{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}]},v=T(L.email,s),M=T(L.password,l),H=T(L.confirmPassword,m);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:S,rulesStatus:v,submitted:p}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:R,rulesStatus:M,submitted:p}),jsxRuntime.jsx(_,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:m,onValueChange:f,inputRef:w,rulesStatus:H,submitted:p})]}),jsxRuntime.jsx(E,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),h(true);let et=v.some(j=>!j.passed),tt=M.some(j=>!j.passed),rt=H.some(j=>!j.passed);if(et){S.current?.focus();return}if(tt){R.current?.focus();return}if(rt){w.current?.focus();return}c(true);let oe=await C.register(s,l);oe.success?e&&await e(oe.message):t&&await t(oe.message,oe.trace),c(false);},loading:d}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Entre"})]})]})]})}var St={xs:"text-trieoh-sm",sm:"text-trieoh-base",md:"text-trieoh-xl",lg:"text-trieoh-2xl",xl:"text-trieoh-3xl","2xl":"text-trieoh-6xl"};function Rt({size:e}){let t=e?St[e]:"text-trieoh-xl";return jsxRuntime.jsxs("span",{className:`font-inter font-medium ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function Tt({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=y(),[i,s]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async l=>{if(l.preventDefault(),i)return;s(true);let a=await o.logout({forceLogout:r});a.success?e&&await e(a.message):t&&await t(a.message,a.trace),s(false);},type:"button",disabled:i,className:"font-inter border-none bg-transparent cursor-pointer flex items-end gap-1 text-trieoh-base font-medium text-[oklch(0.628_0.2577_29.23)] transition-transform duration-200 hover:scale-[1.05] active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none",children:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Je={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function je(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function Ke(e){let t=je(e);return {device:Lt(t.deviceType),os:t.os,browser:t.browser}}function Lt(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Ye(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),i=Math.floor(o/60),s=Math.floor(i/24),n=Math.floor(s/7);return r<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:i<24?`${i} horas atr\xE1s`:s<7?`${s} dias atr\xE1s`:`${n} semanas atr\xE1s`}function Te({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:i,onClick:s}){let n=Ke(r),l=Je[n.device];return jsxRuntime.jsx("div",{className:"border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-trieoh-neutral2",children:jsxRuntime.jsxs("div",{className:"relative flex flex-col items-center gap-2 flex-1 text-center @[640px]:flex-row @[640px]:items-center @[640px]:gap-4 @[640px]:text-left",children:[jsxRuntime.jsx(l,{size:40}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[jsxRuntime.jsxs("h3",{className:"text-trieoh-base font-semibold m-0",children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"inline-flex flex-col text-trieoh-sm font-extralight @[640px]:flex-row @[640px]:gap-2 @[640px]:items-center",children:[e&&jsxRuntime.jsx("strong",{className:"text-trieoh-primary font-normal",children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${i} - ${Ye(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.FaTrashAlt,{size:20,color:"red",onClick:a=>s(a,t),className:"absolute top-0 right-0 cursor-pointer opacity-60 transition-[opacity,transform] duration-200 hover:opacity-100 hover:scale-[1.05] active:scale-[0.95]"})]})})}function Mt({revokeAll:e=false,onSuccess:t}){let{auth:r}=y(),[o,i]=react.useState(false),[s,n]=react.useState([]),l=async()=>{let f=await r.sessions();if(f.success){let p=r.profile()?.session_id,h=f.data.sort((d,c)=>d.session_id===p?-1:c.session_id===p?1:0);n(h);}};react.useEffect(()=>{l();},[]);let a=async(f,p)=>{f.preventDefault();let h=s.find(d=>d.session_id===p);if(h){n(s.filter(d=>d.session_id!==p));try{(await r.revokeASession(p)).success||n(c=>[...c,h]);}catch{n(d=>[...d,h]);}}};return jsxRuntime.jsxs("div",{className:"font-inter w-full min-w-[20rem] m-2 @container bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.5rem_0.5rem] rounded-lg",children:[jsxRuntime.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center text-center gap-4 box-border px-[0.75rem] @[640px]:justify-between @[640px]:text-left @[640px]:gap-8",children:[jsxRuntime.jsxs("div",{className:"flex-[0_1_auto] max-w-[25rem]",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-trieoh-2xl m-0 mb-1",children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{className:"font-extralight text-trieoh-base m-0",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 f=>{if(f.preventDefault(),o)return;i(true);let p=await r.revokeSessions(e),h=r.profile()?.session_id;p.success&&(n(e?[]:s.filter(d=>d.session_id===h)),t&&t(p.message)),i(false);},disabled:o,className:`font-inter w-full max-w-[14rem] p-[1rem_0] h-auto text-trieoh-base font-semibold outline-none bg-transparent relative overflow-hidden shrink-0 border-2 border-trieoh-neutral2 text-trieoh-neutral2 cursor-pointer transition-transform duration-500 rounded-[0.25rem] hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none ${o?"trieoh-button-loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"mt-4",children:s.length>0?s.map(f=>jsxRuntime.jsx(Te,{...f,is_current:r.profile()?.session_id===f.session_id,onClick:a},f.session_id)):jsxRuntime.jsx("span",{className:"block border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-center font-semibold",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Xe({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[i,s]=react.useState(""),[n,l]=react.useState(false),[a,m]=react.useState(false),f=react.useRef(null),{auth:p}=y(),d=T({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:S=>/\S+@\S+\.\S+/.test(S)}]}.email,i);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:f,rulesStatus:d,submitted:n})}),jsxRuntime.jsx(E,{label:a?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async S=>{if(S.preventDefault(),l(true),d.some(C=>!C.passed)){f.current?.focus();return}m(true);let w=await p.sendForgotPassword(i);w.success?e&&await e(w.message):t&&await t(w.message,w.trace),m(false);},loading:a}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Login"})]})]})]})}function Ut({token:e,onSuccess:t,onFailed:r,loginRedirect:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(false),[p,h]=react.useState(false),d=react.useRef(null),c=react.useRef(null),{auth:S}=y(),R={password:i||[{message:"M\xEDnimo de 8 caracteres.",test:v=>v.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:v=>/[A-Z]/.test(v)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:v=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(v)},{message:"Deve conter um n\xFAmero.",test:v=>/\d/.test(v)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:v=>v===s}]},w=T(R.password,s),C=T(R.confirmPassword,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Redefinir Senha",subText:"Crie uma nova senha para sua conta"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Nova Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:m}),jsxRuntime.jsx(_,{label:"Confirme a Nova Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:C,submitted:m})]}),jsxRuntime.jsx(E,{label:"Redefinir Senha",onSubmit:async v=>{v.preventDefault(),f(true);let M=w.some(g=>!g.passed),H=C.some(g=>!g.passed);if(M){d.current?.focus();return}if(H){c.current?.focus();return}h(true);let P=await S.resetPassword(e,s);P.success?t&&await t(P.message):r&&await r(P.message,P.trace),h(false);},loading:p}),o&&jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Login"})]})]})}function $t(e,t,r){let[o,i]=react.useState(true),[s,n]=react.useState("verifying"),[l,a]=react.useState("Verificando seu e-mail..."),{auth:m}=y(),f=react.useRef(false),p=async()=>{if(!f.current){f.current=true,i(true),n("verifying");try{if(m.profile()?.is_verified){n("already_verified"),a("Seu e-mail j\xE1 est\xE1 verificado."),i(!1);return}let c=await m.verifyEmail(e);c.success?(await m.refresh(),n("success"),a(c.message||"E-mail verificado com sucesso!"),t&&await t(c.message)):(n("error"),a(c.message||"Falha na verifica\xE7\xE3o do e-mail."),r&&await r(c.message,c.trace));}catch{n("error"),a("Ocorreu um erro inesperado durante a verifica\xE7\xE3o.");}finally{i(false);}}};return react.useEffect(()=>{e&&!f.current&&p();},[e]),{loading:o,status:s,message:l,onRetry:d=>{d.preventDefault(),f.current=false,p();},setStatus:n,setLoading:i,setMessage:a}}function Jt({token:e,onSuccess:t,onFailed:r}){let{loading:o,status:i,message:s,onRetry:n}=$t(e,t,r);return jsxRuntime.jsx("div",{className:"font-inter flex flex-col w-full h-full min-h-screen items-center justify-center bg-trieoh-neutral1 text-trieoh-neutral2 p-6",children:jsxRuntime.jsxs("div",{className:"w-full max-w-[30rem] flex flex-col gap-8 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:i==="verifying"?"Verificando...":i==="error"?"Ops! Falha na verifica\xE7\xE3o":"Tudo pronto!",subText:s}),i==="verifying"&&jsxRuntime.jsx("div",{className:"w-full flex justify-center py-4",children:jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-trieoh-secondary"})}),i==="error"&&jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-6 items-center",children:jsxRuntime.jsx("div",{className:"w-full mt-2",children:jsxRuntime.jsx(E,{label:"Tentar novamente",onSubmit:n,loading:o})})}),(i==="success"||i==="already_verified")&&jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 items-center",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-trieoh-secondary/10 text-trieoh-secondary",children:i==="success"?jsxRuntime.jsx(fi.FiCheck,{size:40}):jsxRuntime.jsx(fi.FiInfo,{size:40})}),jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold opacity-50 text-center",children:"Voc\xEA j\xE1 pode fechar esta janela ou continuar navegando em sua conta."})]})]})})}function jt({onSuccess:e,onFailed:t}){let[r,o]=react.useState(false),[i,s]=react.useState(false),{auth:n}=y();return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Reenviar Verifica\xE7\xE3o",subText:"N\xE3o recebeu o e-mail de verifica\xE7\xE3o? Clique no bot\xE3o abaixo para reenviar."}),jsxRuntime.jsx(E,{label:i?"E-mail Reenviado":"Reenviar E-mail de Verifica\xE7\xE3o",onSubmit:async()=>{o(true);let a=await n.resendVerifyEmail();a.success?(s(true),e&&await e(a.message)):t&&await t(a.message,a.trace),o(false);},loading:r}),i&&jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold text-trieoh-secondary",children:"Um novo link de verifica\xE7\xE3o foi enviado para seu e-mail."})]})}exports.AuthProvider=Hr;exports.BasicInputField=_;exports.BasicLogoutButton=Tt;exports.Copyright=Rt;exports.ForgotPassword=Xe;exports.ResendVerifyEmail=jt;exports.ResetPassword=Ut;exports.Sessions=Mt;exports.SignIn=wt;exports.SignUp=bt;exports.VerifyEmail=Jt;exports.useAuth=y;//# sourceMappingURL=react.js.map
|
|
6
3
|
//# sourceMappingURL=react.js.map
|