@soramux/node-auth-sdk 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Base structure shared by all API responses.
3
+ */
4
+ interface BaseResponse {
5
+ module: string;
6
+ message: string;
7
+ timestamp: string;
8
+ code: number;
9
+ }
10
+ /**
11
+ * Standardized API Response.
12
+ * Use 'success' to narrow down to the data or error details.
13
+ */
14
+ type ApiResponse<T> = (BaseResponse & {
15
+ success: true;
16
+ data: T;
17
+ }) | (BaseResponse & {
18
+ success: false;
19
+ error_id: string;
20
+ trace?: string[];
21
+ });
22
+ /**
23
+ * Custom error class for API failures.
24
+ * Provides access to the full standardized response.
25
+ */
26
+ declare class ApiError extends Error {
27
+ code: number;
28
+ trace?: string[];
29
+ response: ApiResponse<unknown>;
30
+ constructor(response: ApiResponse<unknown>);
31
+ }
32
+ declare class Api {
33
+ private baseURL;
34
+ private authInterceptor;
35
+ constructor(baseURL?: string, authBaseURL?: string);
36
+ private get headers();
37
+ request<T = unknown>(path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
38
+ get<T = unknown>(path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
39
+ post<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
40
+ put<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
41
+ patch<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
42
+ delete<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
43
+ }
44
+ /**
45
+ * Creates a fetcher object with all HTTP methods returning standardized ApiResponse.
46
+ *
47
+ * @param config - Optional configuration for the fetcher (baseURL, authBaseURL, etc.)
48
+ * @returns An object with get, post, put, patch, delete, and request methods.
49
+ */
50
+ declare const createFetcher: (config?: {
51
+ baseURL?: string;
52
+ authBaseURL?: string;
53
+ }) => {
54
+ request: <T = unknown>(path: string, options?: RequestOptions) => Promise<ApiResponse<T>>;
55
+ get: <T = unknown>(path: string, options?: RequestOptions) => Promise<ApiResponse<T>>;
56
+ post: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<ApiResponse<T>>;
57
+ put: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<ApiResponse<T>>;
58
+ patch: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<ApiResponse<T>>;
59
+ delete: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<ApiResponse<T>>;
60
+ };
61
+ /**
62
+ * Creates a simple fetcher function that returns data directly or throws an ApiError on failure.
63
+ * Ideal for Query libraries like TanStack Query.
64
+ *
65
+ * @param config - Optional configuration for the fetcher (baseURL, authBaseURL, etc.)
66
+ * @returns A single fetcher function that returns a Promise of TData.
67
+ */
68
+ declare const createQueryFetcher: (config?: {
69
+ baseURL?: string;
70
+ authBaseURL?: string;
71
+ }) => <TData>(path: string, init?: RequestOptions) => Promise<TData>;
72
+
73
+ interface TokenClaims {
74
+ sub: {
75
+ id: string;
76
+ email: string;
77
+ session_id: string;
78
+ user_agent: string;
79
+ user_ip: string;
80
+ };
81
+ iss: string;
82
+ exp: number;
83
+ iat: number;
84
+ jti: string;
85
+ }
86
+ interface AuthTokenClaims {
87
+ access: TokenClaims;
88
+ refresh_expire_date: number;
89
+ }
90
+
91
+ interface RequestOptions extends RequestInit {
92
+ requiresAuth?: boolean;
93
+ skipRefresh?: boolean;
94
+ }
95
+ interface InterceptorConfig {
96
+ baseURL?: string;
97
+ authBaseURL?: string;
98
+ onTokenRefreshed?: (claims: AuthTokenClaims) => void;
99
+ onRefreshFailed?: (error: Error) => void;
100
+ }
101
+ declare class AuthInterceptor {
102
+ private baseURL;
103
+ private authBaseURL;
104
+ private isRefreshing;
105
+ private refreshPromise;
106
+ private onTokenRefreshed?;
107
+ private onRefreshFailed?;
108
+ constructor(config?: InterceptorConfig);
109
+ private fetchClaimsAndSave;
110
+ private refreshToken;
111
+ beforeRequest(): Promise<void>;
112
+ fetch(url: string, options?: RequestOptions): Promise<Response>;
113
+ }
114
+ declare const createAuthInterceptor: (config?: InterceptorConfig) => AuthInterceptor;
115
+ declare const createAuthenticatedFetch: (config?: InterceptorConfig) => (url: string, options?: RequestOptions) => Promise<Response>;
116
+
117
+ export { ApiError as A, type BaseResponse as B, type RequestOptions as R, type ApiResponse as a, createQueryFetcher as b, createFetcher as c, AuthInterceptor as d, createAuthInterceptor as e, createAuthenticatedFetch as f, Api as g, type AuthTokenClaims as h };
@@ -0,0 +1,201 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { g as Api, B as BaseResponse, a as ApiResponse, h as AuthTokenClaims } from './interceptor-CbsDF_WC.mjs';
3
+ import { F as FieldValue, P as ProjectFieldDefinitionResultI, a as FieldDefinitionResultI } from './fields-types-BawiMTEP.mjs';
4
+ import { MouseEvent } from 'react';
5
+
6
+ interface SessionI {
7
+ session_id: string;
8
+ user_agent: string;
9
+ user_ip: string;
10
+ issued_at: string;
11
+ }
12
+
13
+ declare const createAuthService: (apiInstance: Api) => {
14
+ login: (email: string, password: string) => Promise<(BaseResponse & {
15
+ success: false;
16
+ error_id: string;
17
+ trace?: string[];
18
+ }) | (BaseResponse & {
19
+ success: true;
20
+ data: {
21
+ is_up_to_date: boolean;
22
+ };
23
+ })>;
24
+ register: (email: string, password: string, flow_id?: string, custom?: Record<string, FieldValue>) => Promise<ApiResponse<string>>;
25
+ logout: () => Promise<ApiResponse<string>>;
26
+ refresh: () => Promise<ApiResponse<{
27
+ is_up_to_date: boolean;
28
+ }>>;
29
+ sessions: () => Promise<ApiResponse<SessionI[]>>;
30
+ revokeASession: (id: string) => Promise<ApiResponse<string>>;
31
+ revokeSessions: (revokeAll?: boolean) => Promise<ApiResponse<string>>;
32
+ refreshProfileInfo: () => Promise<BaseResponse & {
33
+ success: true;
34
+ data: AuthTokenClaims;
35
+ }>;
36
+ profile: () => {
37
+ id: string;
38
+ email: string;
39
+ session_id: string;
40
+ user_agent: string;
41
+ user_ip: string;
42
+ } | null;
43
+ getProfileUpgradeForms: () => Promise<ApiResponse<ProjectFieldDefinitionResultI>>;
44
+ updateProfile: (custom: Record<string, FieldValue>) => Promise<ApiResponse<string>>;
45
+ sendForgotPassword: (email: string) => Promise<ApiResponse<string>>;
46
+ resetPassword: (token: string, new_password: string) => Promise<ApiResponse<string>>;
47
+ resendVerifyEmail: () => Promise<ApiResponse<string>>;
48
+ verifyEmail: () => Promise<ApiResponse<string>>;
49
+ addSubContext: (user_id: string, data: Record<string, unknown>) => Promise<ApiResponse<void>>;
50
+ removeSubContext: (user_id: string, keys: string[]) => Promise<ApiResponse<void>>;
51
+ };
52
+
53
+ type AuthContextType = {
54
+ auth: ReturnType<typeof createAuthService>;
55
+ isAuthenticated: boolean;
56
+ isClient?: boolean;
57
+ };
58
+ declare function AuthProvider({ children, baseURL, projectId, isClient, }: {
59
+ children: React.ReactNode;
60
+ baseURL?: string;
61
+ projectId?: string;
62
+ isClient?: boolean;
63
+ }): react_jsx_runtime.JSX.Element | null;
64
+ declare function useAuth(): AuthContextType;
65
+
66
+ type Rule = {
67
+ id?: string;
68
+ message: string;
69
+ test: (value: string) => boolean;
70
+ };
71
+ type RuleStatus = {
72
+ id?: string;
73
+ message: string;
74
+ passed: boolean;
75
+ };
76
+
77
+ interface SignInProps {
78
+ onSuccess?: (is_up_to_date: boolean) => Promise<void>;
79
+ onFailed?: (message: string) => Promise<void>;
80
+ signUpRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;
81
+ forgotPasswordRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;
82
+ emailRules?: Rule[];
83
+ }
84
+ declare function SignIn({ onSuccess, onFailed, signUpRedirect, forgotPasswordRedirect, emailRules, }: SignInProps): react_jsx_runtime.JSX.Element;
85
+
86
+ interface SignUpProps {
87
+ onSuccess?: () => Promise<void>;
88
+ onFailed?: (message: string, trace?: string[]) => Promise<void>;
89
+ loginRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;
90
+ emailRules?: Rule[];
91
+ passwordRules?: Rule[];
92
+ flow_id?: string;
93
+ fields?: FieldDefinitionResultI[];
94
+ }
95
+ declare function SignUp({ onSuccess, onFailed, loginRedirect, emailRules, passwordRules, flow_id, fields, }: SignUpProps): react_jsx_runtime.JSX.Element;
96
+
97
+ interface TabbedFlowI {
98
+ label: string;
99
+ value: string;
100
+ fields: FieldDefinitionResultI[];
101
+ }
102
+ interface TabbedSignUpProps extends Omit<SignUpProps, 'flow_id' | 'fields'> {
103
+ flowIds: TabbedFlowI[];
104
+ }
105
+ declare function TabbedSignUp({ flowIds, ...rest }: TabbedSignUpProps): react_jsx_runtime.JSX.Element | null;
106
+
107
+ interface CopyrightProps {
108
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
109
+ }
110
+ declare function Copyright({ size }: CopyrightProps): react_jsx_runtime.JSX.Element;
111
+
112
+ interface LogoutProps {
113
+ onSuccess?: () => Promise<void>;
114
+ onFailed?: (message: string) => Promise<void>;
115
+ }
116
+ declare function BasicLogoutButton({ onSuccess, onFailed }: LogoutProps): react_jsx_runtime.JSX.Element;
117
+
118
+ interface SessionsProps {
119
+ /** If true will revoke even the current session */
120
+ revokeAll?: boolean;
121
+ /** What will happen when sessions are revoked */
122
+ onSuccess?: () => Promise<void>;
123
+ }
124
+ declare function Sessions({ revokeAll, onSuccess, }: SessionsProps): react_jsx_runtime.JSX.Element;
125
+
126
+ interface UpdateProfileProps {
127
+ fields: FieldDefinitionResultI[];
128
+ initialValues?: Record<string, FieldValue>;
129
+ onSuccess?: () => Promise<void>;
130
+ onFailed?: (message: string, trace?: string[]) => Promise<void>;
131
+ submitLabel?: string;
132
+ }
133
+ declare function UpdateProfile({ fields, initialValues, onSuccess, onFailed, submitLabel, }: UpdateProfileProps): react_jsx_runtime.JSX.Element;
134
+
135
+ interface EditorFormProps {
136
+ fields: FieldDefinitionResultI[];
137
+ submitted?: boolean;
138
+ title?: string;
139
+ description?: string;
140
+ noFieldsMessage?: string;
141
+ }
142
+ declare function EditorForm({ fields, submitted, title, description, noFieldsMessage, }: EditorFormProps): react_jsx_runtime.JSX.Element;
143
+
144
+ interface BasicInputFieldProps {
145
+ /** The Input ID/Name */
146
+ name: string;
147
+ /** The label text (name of the field) */
148
+ label: string;
149
+ /** The placeholder text (a default text to help the user) */
150
+ placeholder: string;
151
+ /** Input Type */
152
+ type?: "text" | "email" | "number" | "password";
153
+ /** Current Input Value */
154
+ value?: string;
155
+ /** Current Input Value On Change */
156
+ onValueChange?: (value: string) => void;
157
+ /** OnBlur event handler */
158
+ onBlur?: React.FocusEventHandler<HTMLInputElement>;
159
+ /** AutoComplete */
160
+ autoComplete?: string;
161
+ /** Validations and their results */
162
+ rulesStatus?: RuleStatus[];
163
+ /** Form submission status */
164
+ submitted?: boolean;
165
+ /** Ref to the input element */
166
+ inputRef?: React.Ref<HTMLInputElement>;
167
+ }
168
+ declare function BasicInputField({ name, label, placeholder, type, value, onValueChange, onBlur, autoComplete, rulesStatus, submitted, inputRef, }: BasicInputFieldProps): react_jsx_runtime.JSX.Element;
169
+
170
+ interface Option {
171
+ id: string | number;
172
+ value: string;
173
+ label: string;
174
+ }
175
+ interface CustomSelectProps {
176
+ /** The Input ID/Name */
177
+ name: string;
178
+ /** The label text (name of the field) */
179
+ label: string;
180
+ /** The placeholder text (a default text to help the user) */
181
+ placeholder?: string;
182
+ /** Current selected value */
183
+ value?: string;
184
+ /** Available options */
185
+ options: Option[];
186
+ /** Current Value On Change */
187
+ onValueChange?: (value: string) => void;
188
+ /** OnBlur event handler */
189
+ onBlur?: React.FocusEventHandler<HTMLDivElement>;
190
+ /** Validations and their results */
191
+ rulesStatus?: RuleStatus[];
192
+ /** Form submission status */
193
+ submitted?: boolean;
194
+ /** Ref to the trigger element */
195
+ triggerRef?: React.Ref<HTMLDivElement>;
196
+ /** Disabled state */
197
+ disabled?: boolean;
198
+ }
199
+ declare function BasicSelectField({ name, label, placeholder, value, options, onValueChange, onBlur, rulesStatus, submitted, triggerRef, disabled, }: CustomSelectProps): react_jsx_runtime.JSX.Element;
200
+
201
+ export { AuthProvider, BasicInputField, BasicLogoutButton, BasicSelectField, Copyright, EditorForm, Sessions, SignIn, SignUp, TabbedSignUp, UpdateProfile, useAuth };
@@ -0,0 +1,6 @@
1
+ import {createContext,useState,useMemo,useEffect,useContext,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {RiEyeCloseLine,RiEyeLine,RiArrowDownSLine}from'react-icons/ri';import {GoPerson}from'react-icons/go';import {ImExit}from'react-icons/im';import {FaDesktop,FaTabletAlt,FaMobileAlt,FaTrashAlt}from'react-icons/fa';import {UAParser}from'ua-parser-js';function We(){let e=typeof window>"u",t=typeof import.meta<"u"&&import.meta.env?import.meta.env:{},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.default.com"}}var Z=null,de={};function Ce(e){de={...de,...e},Z=null;}function ue(){return Z||(Z={...We(),...de}),Z}var x={get PROJECT_ID(){return ue().PROJECT_ID},get BASE_URL(){return ue().BASE_URL}};function ee(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var pe="trieoh_access_expiry",me="trieoh_refresh_expiry",he=null;function fe(e){he=e,localStorage.setItem(me,String(e.refresh_expire_date)),localStorage.setItem(pe,String(e.access.exp)),console.log("[TRIEOH SDK] Token claims saved");}function ge(){return he}function Ae(e=30){try{let t=localStorage.getItem(pe);if(!t)return !0;let r=parseInt(t,10),o=Math.floor(Date.now()/1e3);return r-o<=e}catch(t){return console.warn("[TRIEOH SDK] Error reading access expiry date:",t),true}}function De(){try{let e=localStorage.getItem(me);if(!e)return !0;let t=parseInt(e,10),r=Math.floor(Date.now()/1e3);return t<=r}catch(e){return console.warn("[TRIEOH SDK] Error reading refresh expiry date:",e),true}}function B(){he=null,localStorage.removeItem(pe),localStorage.removeItem(me),console.log("[TRIEOH SDK] Auth tokens and claims cleared");}function Oe(){let e=ge();return e?e.access.sub:null}var j=async e=>{try{let t=await e.get("/sessions/me",{requiresAuth:!0});if(t.success)return fe(t.data),t;throw new Error(t.message||"Failed to fetch session claims")}catch(t){throw console.warn("[TRIEOH SDK] fetch claims failed (network/server)",t),t}};var te=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.authBaseURL=t?.authBaseURL||x.BASE_URL,this.baseURL=t?.baseURL||this.authBaseURL,this.onTokenRefreshed=t?.onTokenRefreshed,this.onRefreshFailed=t?.onRefreshFailed;}async fetchClaimsAndSave(){let r=await(await fetch(ee(this.authBaseURL,"/sessions/me"),{method:"GET",headers:{"Content-Type":"application/json"},credentials:"include"})).json();if(r.code!==200||!r.data)throw B(),new Error(r.message||"Failed to fetch session claims after refresh");let o=r.data;return fe(o),o}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{let t;try{let o=await(await fetch(ee(this.authBaseURL,"/auth/refresh"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include"})).json();if(o.code!==200)throw o.code!==503&&B(),new Error(o.message||"Failed to refresh token");t=await this.fetchClaimsAndSave(),this.onTokenRefreshed?.(t),console.log("[TRIEOH SDK] Token refreshed successfully");}catch(r){throw console.warn("[TRIEOH SDK] Failed to refresh token:",r),B(),this.onRefreshFailed?.(r),r}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(De()){B();return}if(Ae(30)){console.log("[TRIEOH SDK] Token expiring soon, refreshing...");try{await this.refreshToken();}catch(t){console.warn("[TRIEOH SDK] Refresh interceptor failed:",t);}}}async fetch(t,r){let o=r?.requiresAuth!==false,s=!r?.skipRefresh;o&&s&&await this.beforeRequest();let n=ee(this.baseURL,t);return fetch(n,{...r,credentials:"include",headers:{"Content-Type":"application/json",...r?.headers}})}};var re=class{constructor(t,r){this.baseURL=t||x.BASE_URL,this.authInterceptor=new te({baseURL:this.baseURL,authBaseURL:r});}get headers(){return {"Content-Type":"application/json"}}async request(t,r){try{let o=await this.authInterceptor.fetch(t,{...r,headers:{...this.headers,...r?.headers??{}}}),s=await o.json().catch(()=>({module:"Client",message:o.statusText||"Unknown error",timestamp:new Date().toISOString(),code:o.status,error_id:"CLIENT_PARSE_ERROR",trace:["Failed to parse API response as JSON"]}));return o.ok?{success:!0,module:s.module,message:s.message,timestamp:s.timestamp,code:s.code,data:s.data}:{success:!1,module:s.module||"Unknown",message:s.message||o.statusText||"An unknown error occurred",timestamp:s.timestamp||new Date().toISOString(),code:s.code||o.status,error_id:s.error_id||"UNKNOWN_ERROR",trace:s.trace}}catch(o){let s=o instanceof Error?o.message:"A network or unknown error occurred.";return {success:false,module:"Network",message:s,timestamp:new Date().toISOString(),code:503,error_id:"CLIENT_NETWORK_ERROR",trace:o instanceof Error?[o.stack||s]:[s]}}}get(t,r){return this.request(t,{...r,method:"GET"})}post(t,r,o){return this.request(t,{...o,method:"POST",body:r?JSON.stringify(r):void 0})}put(t,r,o){return this.request(t,{...o,method:"PUT",body:r?JSON.stringify(r):void 0})}patch(t,r,o){return this.request(t,{...o,method:"PATCH",body:r?JSON.stringify(r):void 0})}delete(t,r,o){return this.request(t,{...o,method:"DELETE",body:r?JSON.stringify(r):void 0})}};var P=()=>{if(!x.PROJECT_ID||x.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 Fe=e=>({login:async(t,r)=>{let o={requiresAuth:false};if(x.PROJECT_ID){P();let n=`/projects/${x.PROJECT_ID}/login`,i=await e.post(n,{email:t,password:r},o);return i.success&&await j(e),i}let s=await e.post("/auth/login",{email:t,password:r},o);return s.success&&await j(e),s},register:(t,r,o,s={})=>{let n={requiresAuth:false};if(x.PROJECT_ID){P();let i=new URLSearchParams;o&&(i.append("flow_id",o),i.append("schema_type","context"),i.append("version","1"));let a={email:t,password:r,...o&&{custom_fields:s}},p=i.toString()?`?${i.toString()}`:"",d=`/projects/${x.PROJECT_ID}/register${p}`;return e.post(d,a,n)}return e.post("/auth/register",{email:t,password:r},n)},logout:async()=>{let t=await e.post("/auth/logout");return t.success&&B(),t},refresh:async()=>{let t=await e.post("/auth/refresh",void 0,{skipRefresh:true});return t.success&&await j(e),t},sessions:async()=>e.get("/sessions"),revokeASession:async t=>e.delete(`/sessions/${t}`),revokeSessions:async(t=false)=>{let r=t?"/sessions":"/sessions/others";return e.delete(r)},refreshProfileInfo:async()=>j(e),profile:()=>Oe(),getProfileUpgradeForms:async()=>{P();let t=`/projects/${x.PROJECT_ID}/upgrade-form`;return e.get(t)},updateProfile:async t=>{P();let r=`/projects/${x.PROJECT_ID}/metadata`;return e.post(r,{custom_fields:t})},sendForgotPassword:async t=>{let r={requiresAuth:false};return x.PROJECT_ID?(P(),e.post("/auth/forgot-password",{email:t,project_id:x.PROJECT_ID},r)):e.post("/auth/forgot-password",{email:t},r)},resetPassword:async(t,r)=>e.post(`/auth/reset-password?token=${t}`,{new_password:r},{requiresAuth:false}),resendVerifyEmail:async()=>e.post("/auth/verify/resend"),verifyEmail:async()=>e.get("/auth/verify",{requiresAuth:false}),addSubContext:async(t,r)=>(P(),e.post(`/projects/${x.PROJECT_ID}/sub-context`,{data:r,user_id:t})),removeSubContext:async(t,r)=>(P(),e.delete(`/projects/${x.PROJECT_ID}/sub-context`,{keys:r,user_id:t}))});var Le=createContext(null);function fr({children:e,baseURL:t,projectId:r,isClient:o=true}){let[s,n]=useState(false),[i,a]=useState(false);useMemo(()=>{(r||t)&&Ce({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let p=useMemo(()=>new re(t),[t]),d=useMemo(()=>Fe(p),[p]);return useEffect(()=>{o&&P(),(async()=>{if(ge()){a(true),n(true);return}console.log("[TRIEOH SDK] Attempting to refresh session...");try{(await d.refreshProfileInfo()).success?(a(!0),console.log("[TRIEOH SDK] Session restored successfully.")):(a(!1),console.warn("[TRIEOH SDK] Session restoration failed/no session."));}catch{console.warn("[TRIEOH SDK] Unable to verify session (offline?)"),a(false);}finally{n(true);}})();},[d,o]),s?jsx(Le.Provider,{value:{auth:d,isAuthenticated:i,isClient:o},children:e}):null}function I(){let e=useContext(Le);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Y(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));}Y(`@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
+ `);Y(`.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-custom-select__wrapper{position:relative;width:100%}.trieoh-custom-select{cursor:pointer;user-select:none;box-sizing:border-box}.trieoh-custom-select.is-disabled{opacity:.5;cursor:not-allowed}.trieoh-custom-select:focus-visible{outline:2px solid var(--trieoh-primary);outline-offset:2px}.trieoh-custom-select__trigger{display:flex;align-items:center;width:100%}.trieoh-custom-select__trigger.placeholder{opacity:.6}.trieoh-custom-select__arrow{transition:transform .2s ease;flex-shrink:0}.trieoh-custom-select__arrow.is-open{transform:rotate(180deg)}.trieoh-custom-select__dropdown{position:absolute;top:calc(100% + .25rem);left:0;right:0;width:100%;box-sizing:border-box;background:var(--trieoh-neutral1);border:solid .125rem var(--trieoh-neutral2);border-radius:.25rem;box-shadow:0 4px 12px #00000026;z-index:1000;max-height:15rem;overflow-y:auto;animation:dropdownSlide .15s ease-out}@keyframes dropdownSlide{0%{opacity:0;transform:translateY(-.5rem)}to{opacity:1;transform:translateY(0)}}.trieoh-custom-select__options{padding:.25rem 0}.trieoh-custom-select__option{padding:.5rem .625rem;font-size:var(--trieoh-text-base);font-weight:300;color:var(--trieoh-neutral2);cursor:pointer;transition:background-color .15s ease,color .15s ease;outline:none}.trieoh-custom-select__option:hover,.trieoh-custom-select__option:focus-visible{background-color:var(--trieoh-secondary);color:var(--trieoh-neutral2)}.trieoh-custom-select__option.is-selected{background-color:var(--trieoh-secondary);color:var(--trieoh-neutral2);font-weight:500}.trieoh-custom-select.is-open{border-color:var(--trieoh-primary, var(--trieoh-neutral2))}.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-card__empty{display:block;padding:1.25rem .75rem;text-align:center;font-weight:400;opacity:.6}.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}}.trieoh-tabbed-signup{width:100%;max-width:30rem;min-width:15rem;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);box-shadow:0 .25rem .25rem #00000040;transition:transform .15s ease}.trieoh-tabbed-signup__header{width:100%;display:flex;justify-content:space-between;gap:.25rem;overflow-x:auto;overflow-y:hidden;padding:.25rem 0;position:relative;-webkit-overflow-scrolling:touch;scrollbar-width:thin;scrollbar-color:transparent}.trieoh-tabbed-signup__tab{flex-shrink:0;padding:.875rem 1.5rem;border:none;background:transparent;color:var(--trieoh-neutral2);opacity:.8;font-size:.8125rem;font-weight:500;letter-spacing:.01em;cursor:pointer;position:relative;white-space:nowrap;transition:color .2s ease,opacity .2s ease;border-radius:.375rem .375rem 0 0}.trieoh-tabbed-signup__tab:hover{color:var(--trieoh-primary);opacity:1}.trieoh-tabbed-signup__tab.active{color:var(--trieoh-primary);background:transparent}.trieoh-tabbed-signup__tab.active:after{content:"";position:absolute;bottom:4px;left:1rem;right:1rem;height:2px;background:var(--trieoh-primary);border-radius:2px}.trieoh-tabbed-signup__tab:focus-visible{outline:none;color:var(--trieoh-primary)}.trieoh-tabbed-signup hr{opacity:.5;border-top:1px solid var(--trieoh-primary);margin:0 .5rem;border-radius:1rem}.trieoh-tabbed-signup .trieoh-card{box-shadow:none;background:none;overflow-y:auto;box-sizing:border-box}.trieoh-tabbed-signup__content{width:100%}
3
+ `);function T({name:e,label:t,placeholder:r,type:o="text",value:s,onValueChange:n,onBlur:i,autoComplete:a,rulesStatus:p=[],submitted:d=false,inputRef:l}){let[c,g]=useState(false),f=p.some(b=>!b.passed);return jsxs("div",{className:"trieoh trieoh-input",children:[jsx("label",{htmlFor:e,className:"trieoh-input__label",children:t}),jsxs("div",{className:(f&&d?"trieoh-input__container--error ":"")+"trieoh-input__container",children:[jsx("input",{type:c?"text":o,name:e,id:e,placeholder:r,value:s,onChange:b=>n&&n(b.target.value),onBlur:i,autoComplete:a,"aria-invalid":f&&d,ref:l,className:"trieoh-input__container-field"}),o==="password"&&(c?jsx(RiEyeCloseLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>g(false)}):jsx(RiEyeLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>g(true)}))]}),jsx("div",{className:"trieoh-input__hint",children:p.map((b,_)=>{let u=["hint-part",b.passed?"passed":"",!b.passed&&d?"failed-on-submit":""].filter(Boolean).join(" ");return jsx("p",{className:u,children:b.message},b.id??_)})})]})}function H({label:e,onSubmit:t,loading:r}){return jsx("button",{type:"submit",onClick:t,disabled:r,className:`trieoh trieoh-button trieoh-button--all-rounded
4
+ ${r?"trieoh-button--loading":""}`,children:e})}function G({mainText:e,subText:t}){return jsxs("div",{className:"trieoh trieoh-avacard",children:[jsx("div",{className:"trieoh-avacard__container",children:jsx(GoPerson,{className:"trieoh-avacard__content",size:70})}),jsx("h3",{className:"trieoh-avacard__title",children:e}),jsx("span",{className:"trieoh-avacard__sub-title",children:t})]})}function $(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function at({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:s}){let[n,i]=useState(""),[a,p]=useState(""),[d,l]=useState(false),[c,g]=useState(false),f=useRef(null),b=useRef(null),{auth:_}=I(),u={email:s||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:k=>/\S+@\S+\.\S+/.test(k)}],password:[]},y=$(u.email,n),E=$(u.password,a);return jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsx(G,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxs("div",{className:"trieoh-card__fields",children:[jsx(T,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:n,onValueChange:i,inputRef:f,rulesStatus:y,submitted:d}),jsx(T,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:a,onValueChange:p,inputRef:b,rulesStatus:E,submitted:d})]}),jsx(H,{label:"Entrar",onSubmit:async k=>{k.preventDefault(),l(true);let v=y.some(U=>!U.passed),S=E.some(U=>!U.passed);if(v){f.current?.focus();return}if(S){b.current?.focus();return}g(true);let L=await _.login(n,a);L.success&&e?await e(L.data.is_up_to_date||true):t&&await t(L.message),g(false);},loading:c}),o&&jsx("span",{className:"trieoh-card__other",style:{textAlign:"center",cursor:"pointer"},children:jsx("span",{onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"trieoh-card__divider",children:[jsx("hr",{}),"OU",jsx("hr",{})]}),jsxs("span",{className:"trieoh-card__other",children:["Ainda n\xE3o possui uma conta? ",jsx("span",{onClick:r,children:"Cadastra-se"})]})]})]})}function ie({name:e,label:t,placeholder:r="Selecione uma op\xE7\xE3o",value:o,options:s,onValueChange:n,onBlur:i,rulesStatus:a=[],submitted:p=false,triggerRef:d,disabled:l=false}){let[c,g]=useState(false),[f,b]=useState(""),_=useRef(null),u=a.some(v=>!v.passed);useEffect(()=>{let v=s.find(S=>S.value===o);b(v?v.label:"");},[o,s]),useEffect(()=>{let v=S=>{_.current&&!_.current.contains(S.target)&&g(false);};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);let y=v=>{n&&n(v),g(false);},E=()=>{l||g(!c);},N=v=>{_.current?.contains(v.relatedTarget)||i&&i(v);},k=f||r;return jsxs("div",{className:"trieoh trieoh-input",children:[jsx("label",{htmlFor:e,className:"trieoh-input__label",children:t}),jsxs("div",{className:"trieoh-custom-select__wrapper",ref:_,children:[jsxs("div",{className:(u&&p?"trieoh-input__container--error ":"")+"trieoh-input__container trieoh-custom-select "+(c?"is-open ":"")+(l?"is-disabled ":""),onClick:E,onBlur:N,ref:d,id:e,role:"combobox","aria-expanded":c,"aria-haspopup":"listbox","aria-disabled":l,tabIndex:l?-1:0,children:[jsx("div",{className:"trieoh-input__container-field trieoh-custom-select__trigger "+(f?"":"placeholder"),children:k}),jsx(RiArrowDownSLine,{className:`trieoh-input__container-icon trieoh-custom-select__arrow ${c?"is-open":""}`,size:24})]}),c&&jsx("div",{className:"trieoh-custom-select__dropdown",role:"listbox","aria-label":`Op\xE7\xF5es para ${t}`,children:jsx("div",{className:"trieoh-custom-select__options",children:s.map(v=>jsx("div",{className:`trieoh-custom-select__option ${v.value===o?"is-selected":""}`,onClick:()=>y(v.value),role:"option","aria-selected":v.value===o,tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),y(v.value));},children:v.label},v.id))})})]}),jsx("div",{className:"trieoh-input__hint",children:a.map((v,S)=>{let L=["hint-part",v.passed?"passed":"",!v.passed&&p?"failed-on-submit":""].filter(Boolean).join(" ");return jsx("p",{className:L,children:v.message},v.id??S)})})]})}function ye(e,t,r){return useMemo(()=>{if(!e||e.length===0)return {satisfied:true,statuses:[]};let o=e.map(n=>pt(n,t,r));return {satisfied:o.every(n=>n.passed),statuses:o}},[e,t,r])}function pt(e,t,r){let o=r[e.depends_on_field_id];if(!o)return {id:e.id,message:"Campo dependente n\xE3o encontrado.",passed:false};let s=t[o.key],n=e.operator,i=e.value,a=o.title,p,d,l=c=>c==null?"":String(c);switch(n){case "exists":{p=s!=null&&s!=="",d=`O campo "${a}" deve estar preenchido.`;break}case "not_exists":{p=s==null||s==="",d=`O campo "${a}" deve estar vazio.`;break}case "equals":{p=l(s)===l(i),d=`O campo "${a}" deve ser igual a "${l(i)}".`;break}case "not_equals":{p=l(s)!==l(i),d=`O campo "${a}" deve ser diferente de "${l(i)}".`;break}case "contains":{p=l(s).includes(l(i)),d=`O campo "${a}" deve conter "${l(i)}".`;break}case "greater_than":{p=Number(s)>Number(i),d=`O campo "${a}" deve ser maior que ${l(i)}.`;break}case "greater_than_equal":{p=Number(s)>=Number(i),d=`O campo "${a}" deve ser maior ou igual a ${l(i)}.`;break}case "lower_than":{p=Number(s)<Number(i),d=`O campo "${a}" deve ser menor que ${l(i)}.`;break}case "lower_than_equal":{p=Number(s)<=Number(i),d=`O campo "${a}" deve ser menor ou igual a ${l(i)}.`;break}case "in":{let c=l(i).split(",").map(f=>f.trim());p=c.includes(l(s));let g=c.join(", ");d=`O campo "${a}" deve ser um dos seguintes: ${g}.`;break}case "not_in":{let c=l(i).split(",").map(f=>f.trim());p=!c.includes(l(s));let g=c.join(", ");d=`O campo "${a}" n\xE3o pode ser um dos seguintes: ${g}.`;break}default:p=false,d=`Operador "${n}" desconhecido.`;}return {passed:p,id:e.id,message:d}}function M({fields:e,values:t,onValueChange:r,submitted:o=false}){if(!e||e.length===0)return null;let s=useMemo(()=>e.reduce((i,a)=>(i[a.id]={key:a.key,title:a.title},a.object_id&&(i[a.object_id]={key:a.key,title:a.title}),i),{}),[e]),n=useMemo(()=>[...e].sort((i,a)=>i.position-a.position),[e]);return jsx(Fragment,{children:n.map(i=>jsx(mt,{field:i,values:t,onValueChange:r,submitted:o,fieldsMap:s},i.id))})}function mt({field:e,values:t,onValueChange:r,submitted:o,fieldsMap:s}){let n=ye(e.visibility_rules,t,s),a=!(e.visibility_rules&&e.visibility_rules.length>0)||n.satisfied,p=ye(e.required_rules,t,s),l=e.required_rules&&e.required_rules.length>0&&p.satisfied,c=e.required||l,g=t[e.key]??e.default_value??"",f=g===""||g===void 0||g===null,b=useMemo(()=>{let u=[];return c&&u.push({message:`${e.title} \xE9 obrigat\xF3rio.`,passed:!f}),u},[e.title,c,f]);if(!a)return null;let _={name:e.key,label:e.title,placeholder:e.placeholder,value:String(g),submitted:o,rulesStatus:b,required:c};switch(e.type){case "string":case "email":return jsx(T,{..._,type:e.type==="email"?"email":"text",onValueChange:u=>r(e.key,u)});case "int":return jsx(T,{..._,type:"number",onValueChange:u=>r(e.key,u)});case "radio":return jsxs("div",{className:"trieoh trieoh-input",children:[jsxs("label",{className:"trieoh-input__label",children:[e.title,c&&jsx("span",{style:{color:"#e74c3c",marginLeft:"4px"},children:"*"})]}),jsx("div",{className:"trieoh-radio-group",style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.options?.map(u=>jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},children:[jsx("input",{type:"radio",name:e.key,value:u.value,checked:g===u.value,onChange:y=>r(e.key,y.target.value)}),jsx("span",{children:u.label})]},u.id))}),o&&b.filter(u=>!u.passed).map((u,y)=>jsx("span",{style:{color:"#e74c3c",fontSize:"12px",marginTop:"4px",display:"block"},children:u.message},y))]});case "select":return jsx(ie,{..._,options:e.options||[],onValueChange:u=>r(e.key,u)});case "checkbox":{let u=Array.isArray(t[e.key])?t[e.key]:[];return jsxs("div",{className:"trieoh trieoh-input",children:[jsxs("label",{className:"trieoh-input__label",children:[e.title,c&&jsx("span",{style:{color:"#e74c3c",marginLeft:"4px"},children:"*"})]}),jsx("div",{className:"trieoh-checkbox-group",style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.options?.map(y=>jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},children:[jsx("input",{type:"checkbox",name:e.key,value:y.value,checked:u.includes(y.value),onChange:E=>{let N=E.target.checked?[...u,y.value]:u.filter(k=>k!==y.value);r(e.key,N);}}),jsx("span",{children:y.label})]},y.id))}),o&&b.filter(y=>!y.passed).map((y,E)=>jsx("span",{style:{color:"#e74c3c",fontSize:"12px",marginTop:"4px",display:"block"},children:y.message},E))]})}case "bool":return jsxs("div",{className:"trieoh trieoh-input",style:{flexDirection:"row",alignItems:"center",gap:"8px"},children:[jsx("input",{type:"checkbox",id:e.key,name:e.key,checked:!!t[e.key],onChange:u=>r(e.key,u.target.checked)}),jsxs("label",{htmlFor:e.key,className:"trieoh-input__label",style:{marginBottom:0},children:[e.title,c&&jsx("span",{style:{color:"#e74c3c",marginLeft:"4px"},children:"*"})]}),o&&b.filter(u=>!u.passed).map((u,y)=>jsx("span",{style:{color:"#e74c3c",fontSize:"12px",marginLeft:"8px"},children:u.message},y))]});default:return null}}function Re({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:s,flow_id:n,fields:i=[]}){let[a,p]=useState(""),[d,l]=useState(""),[c,g]=useState(""),[f,b]=useState({}),[_,u]=useState(false),[y,E]=useState(false),N=useRef(null),k=useRef(null),v=useRef(null),{auth:S}=I(),L=(w,ae)=>{b(le=>({...le,[w]:ae}));},U={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:w=>/\S+@\S+\.\S+/.test(w)}],password:s||[{message:"M\xEDnimo de 8 caracteres.",test:w=>w.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:w=>/[A-Z]/.test(w)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:w=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(w)},{message:"Deve conter um n\xFAmero.",test:w=>/\d/.test(w)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:w=>w===d}]},ke=$(U.email,a),Pe=$(U.password,d),Ie=$(U.confirmPassword,c);return jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsx(G,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxs("div",{className:"trieoh-card__fields",children:[jsx(T,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:a,onValueChange:p,inputRef:N,rulesStatus:ke,submitted:_}),jsx(T,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:d,onValueChange:l,inputRef:k,rulesStatus:Pe,submitted:_}),jsx(T,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:c,onValueChange:g,inputRef:v,rulesStatus:Ie,submitted:_}),jsx(M,{fields:i,values:f,onValueChange:L,submitted:_})]}),jsx(H,{label:"Criar Conta",onSubmit:async w=>{w.preventDefault(),u(true);let ae=ke.some(D=>!D.passed),le=Pe.some(D=>!D.passed),Ye=Ie.some(D=>!D.passed),Ge=i.some(D=>D.required&&!f[D.key]);if(ae){N.current?.focus();return}if(le){k.current?.focus();return}if(Ye){v.current?.focus();return}if(Ge)return;E(true);let ce=await S.register(a,d,n,f);ce.success?e&&await e():t&&await t(ce.message,ce.trace),E(false);},loading:y}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"trieoh-card__divider",children:[jsx("hr",{}),"OU",jsx("hr",{})]}),jsxs("span",{className:"trieoh-card__other",children:["J\xE1 possui uma conta? ",jsx("span",{onClick:r,children:"Entre"})]})]})]})}function vt({flowIds:e,...t}){let[r,o]=useState(e[0]?.value||"");if(!e||e.length===0)return null;let s=e.find(n=>n.value===r);return jsxs("div",{className:"trieoh-tabbed-signup",children:[jsx("div",{className:"trieoh-tabbed-signup__header",children:e.map(n=>jsx("button",{className:`trieoh-tabbed-signup__tab ${r===n.value?"active":""}`,onClick:()=>o(n.value),type:"button","aria-selected":r===n.value,role:"tab",children:jsx("span",{className:"trieoh-tabbed-signup__tab-text",children:n.label})},n.value))}),jsx("hr",{}),jsx("div",{className:"trieoh-tabbed-signup__content",children:jsx(Re,{flow_id:r,...t,fields:s?.fields},r)})]})}function yt({size:e}){let t=e?`trieoh-copyright--${e}`:"";return jsxs("span",{className:`trieoh trieoh-copyright ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function wt({onSuccess:e,onFailed:t}){let{auth:r}=I(),[o,s]=useState(false);return jsxs("button",{onClick:async i=>{if(i.preventDefault(),o)return;s(true);let a=await r.logout();a.success&&e?await e():t&&await t(a.message),s(false);},type:"button",disabled:o,className:"trieoh trieoh-button--logout",children:[jsx(ImExit,{size:24})," ",jsx("span",{children:"Log out"})]})}var Ve={mobile:FaMobileAlt,tablet:FaTabletAlt,desktop:FaDesktop};function ze(e){let{device:t,os:r,browser:o}=UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function qe(e){let t=ze(e);return {device:It(t.deviceType),os:t.os,browser:t.browser}}function It(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Ke(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),s=Math.floor(o/60),n=Math.floor(s/24),i=Math.floor(n/7);return r<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:s<24?`${s} horas atr\xE1s`:n<7?`${n} dias atr\xE1s`:`${i} semanas atr\xE1s`}function we({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:s,onClick:n}){let i=qe(r),a=Ve[i.device];return jsx("div",{className:"trieoh-session",children:jsxs("div",{className:"trieoh-session__content",children:[jsx(a,{size:40}),jsxs("div",{className:"trieoh-session__info",children:[jsxs("h3",{children:[i.browser," - ",i.os]}),jsxs("span",{className:"trieoh-session__meta",children:[e&&jsx("strong",{children:"\u2022 Sess\xE3o Atual \u2022"}),jsx("span",{children:`${s} - ${Ke(o)}`})]})]}),!e&&jsx(FaTrashAlt,{size:20,color:"red",onClick:p=>n(p,t)})]})})}function Dt({revokeAll:e=false,onSuccess:t}){let{auth:r}=I(),[o,s]=useState(false),[n,i]=useState([]),a=async()=>{let l=await r.sessions();if(l.success){let c=r.profile()?.session_id,g=l.data.sort((f,b)=>f.session_id===c?-1:b.session_id===c?1:0);i(g);}};useEffect(()=>{a();},[]);let p=async(l,c)=>{l.preventDefault();let g=n.find(f=>f.session_id===c);if(g){i(n.filter(f=>f.session_id!==c));try{(await r.revokeASession(c)).success||i(b=>[...b,g]);}catch{i(f=>[...f,g]);}}};return jsxs("div",{className:"trieoh trieoh-sessions",children:[jsxs("div",{className:"trieoh-sessions__header",children:[jsxs("div",{children:[jsx("h3",{children:"Navegadores e Dispositivos"}),jsx("p",{children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsx("button",{type:"submit",onClick:async l=>{if(l.preventDefault(),o)return;s(true);let c=await r.revokeSessions(e),g=r.profile()?.session_id;c.success&&(i(e?[]:n.filter(f=>f.session_id===g)),t&&t()),s(false);},disabled:o,className:`trieoh trieoh-button trieoh-button--all-rounded
5
+ ${o?"trieoh-button--loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsx("div",{className:"trieoh-sessions__content",children:n.length>0?n.map(l=>jsx(we,{...l,is_current:r.profile()?.session_id===l.session_id,onClick:p},l.session_id)):jsx("span",{className:"trieoh-sessions__empty",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Ft({fields:e,initialValues:t,onSuccess:r,onFailed:o,submitLabel:s="Atualizar Dados"}){let[n,i]=useState(t||{}),[a,p]=useState(false),[d,l]=useState(false),{auth:c}=I();return useEffect(()=>{t&&i(t);},[t]),jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsx("div",{className:"trieoh-card__fields",children:jsx(M,{fields:e,values:n,onValueChange:(b,_)=>{i(u=>({...u,[b]:_}));},submitted:a})}),jsx(H,{label:s,onSubmit:async b=>{if(b.preventDefault(),p(true),e.some(y=>y.required&&!n[y.key]))return;l(true);let u=await c.updateProfile(n);u.success?r&&await r():o&&await o(u.message,u.trace),l(false);},loading:d})]})}function Ut({fields:e,submitted:t=false,title:r,description:o,noFieldsMessage:s="No fields available"}){let[n,i]=useState({}),a=(p,d)=>{i(l=>({...l,[p]:d}));};return jsxs("div",{className:"trieoh trieoh-card trieoh-card--full-rounded",style:{gap:"0.25rem"},children:[(r||o)&&jsxs("div",{style:{width:"100%",textAlign:"center"},children:[r&&jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600},children:r}),o&&jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.875rem",opacity:.7},children:o}),jsx("hr",{style:{marginTop:"1rem",border:0,borderTop:"1px solid rgba(0,0,0,0.1)",marginBottom:"0.5rem"}})]}),jsx("div",{className:"trieoh-card__fields",children:e&&e.length>0?jsx(M,{fields:e,values:n,onValueChange:a,submitted:t}):jsx("div",{className:"trieoh-card__empty",children:s})})]})}export{fr as AuthProvider,T as BasicInputField,wt as BasicLogoutButton,ie as BasicSelectField,yt as Copyright,Ut as EditorForm,Dt as Sessions,at as SignIn,Re as SignUp,vt as TabbedSignUp,Ft as UpdateProfile,I as useAuth};//# sourceMappingURL=react.js.map
6
+ //# sourceMappingURL=react.js.map