@forgepack/request 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +217 -86
  2. package/dist/api/client.d.ts +17 -10
  3. package/dist/api/client.d.ts.map +1 -1
  4. package/dist/api/client.js +18 -6
  5. package/dist/hooks/AuthContext.d.ts +6 -6
  6. package/dist/hooks/AuthContext.d.ts.map +1 -1
  7. package/dist/hooks/AuthContext.js +1 -1
  8. package/dist/hooks/AuthProvider.d.ts +34 -17
  9. package/dist/hooks/AuthProvider.d.ts.map +1 -1
  10. package/dist/hooks/AuthProvider.js +26 -15
  11. package/dist/hooks/useAuth.d.ts +33 -12
  12. package/dist/hooks/useAuth.d.ts.map +1 -1
  13. package/dist/hooks/useAuth.js +30 -12
  14. package/dist/hooks/useRequest.d.ts +37 -17
  15. package/dist/hooks/useRequest.d.ts.map +1 -1
  16. package/dist/hooks/useRequest.js +36 -13
  17. package/dist/index.d.ts +159 -9
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +159 -14
  20. package/dist/services/api.d.ts +37 -15
  21. package/dist/services/api.d.ts.map +1 -1
  22. package/dist/services/api.js +40 -14
  23. package/dist/services/auth.d.ts +76 -19
  24. package/dist/services/auth.d.ts.map +1 -1
  25. package/dist/services/auth.js +94 -22
  26. package/dist/services/crud.d.ts +115 -62
  27. package/dist/services/crud.d.ts.map +1 -1
  28. package/dist/services/crud.js +132 -85
  29. package/dist/services/token.d.ts +83 -26
  30. package/dist/services/token.d.ts.map +1 -1
  31. package/dist/services/token.js +141 -52
  32. package/dist/types/auth.d.ts +20 -20
  33. package/dist/types/auth.d.ts.map +1 -1
  34. package/dist/types/error.d.ts +3 -3
  35. package/dist/types/error.d.ts.map +1 -1
  36. package/dist/types/request.d.ts +8 -8
  37. package/dist/types/request.d.ts.map +1 -1
  38. package/dist/types/response.d.ts +15 -15
  39. package/dist/types/response.d.ts.map +1 -1
  40. package/dist/types/token.d.ts +15 -15
  41. package/dist/types/token.d.ts.map +1 -1
  42. package/dist/utils/constants.d.ts +7 -7
  43. package/dist/utils/constants.js +7 -7
  44. package/package.json +15 -3
package/dist/index.js CHANGED
@@ -1,16 +1,90 @@
1
1
  "use strict";
2
2
  /**
3
- * @fileoverview Pacote React para gerenciamento de requisições HTTP com autenticação JWT
4
- * @author Marcelo Gadelha
5
- * @version 1.0.3
3
+ * @forgepack/request - Complete HTTP client with JWT authentication for React
4
+ *
5
+ * @packageDocumentation
6
+ * @module @forgepack/request
7
+ *
8
+ * @description
9
+ * Production-ready solution for HTTP requests and JWT authentication in React applications
10
+ *
11
+ * @example
12
+ * **Quick Start**
13
+ * ```typescript
14
+ * import { createApiClient, AuthProvider, useAuth, useRequest } from '@forgepack/request'
15
+ *
16
+ * // 1. Create API client
17
+ * const api = createApiClient({
18
+ * baseURL: 'https://api.example.com',
19
+ * onUnauthorized: () => window.location.href = '/login'
20
+ * })
21
+ *
22
+ * // 2. Wrap app with AuthProvider
23
+ * function App() {
24
+ * return (
25
+ * <AuthProvider api={api}>
26
+ * <Router>
27
+ * <Routes />
28
+ * </Router>
29
+ * </AuthProvider>
30
+ * )
31
+ * }
32
+ *
33
+ * // 3. Use authentication
34
+ * function LoginPage() {
35
+ * const { loginUser } = useAuth()
36
+ *
37
+ * const handleLogin = async (credentials) => {
38
+ * const result = await loginUser(credentials)
39
+ * if (result.success) {
40
+ * navigate('/dashboard')
41
+ * }
42
+ * }
43
+ *
44
+ * return <LoginForm onSubmit={handleLogin} />
45
+ * }
46
+ *
47
+ * // 4. Fetch data with hooks
48
+ * function UsersPage() {
49
+ * const { response, loading, error } = useRequest(
50
+ * api,
51
+ * 'users',
52
+ * { page: 0, size: 10 }
53
+ * )
54
+ *
55
+ * if (loading) return <Spinner />
56
+ * if (error[0]?.message) return <Error message={error[0].message} />
57
+ *
58
+ * return <UserList users={response.content} />
59
+ * }
60
+ *
61
+ * // 5. Protect routes
62
+ * <Route path="/admin" element={<RequireAuth allowedRoles={['ADMIN']} />}>
63
+ * <Route index element={<AdminDashboard />} />
64
+ * </Route>
65
+ * ```
66
+ *
67
+ * @see {@link https://forgepack.dev/packages/request | Complete Documentation}
68
+ * @see {@link https://github.com/forgepack/request | GitHub Repository}
69
+ * @see {@link https://www.npmjs.com/package/@forgepack/request | NPM Package}
70
+ *
71
+ * @fileoverview React package for managing HTTP requests with JWT authentication
72
+ * @author Marcelo Gadelha {@link https://github.com/gadelhati}
73
+ * @version 1.0.6
6
74
  * @license Apache License 2.0
7
75
  *
8
- * Este pacote fornece uma solução completa para:
9
- * - Autenticação JWT com interceptors automáticos
10
- * - Hooks React para requisições e gerenciamento de estado
11
- * - Componentes de autenticação e autorização
12
- * - Operações CRUD padronizadas
13
- * - Gerenciamento de tokens e paginação
76
+ * @remarks
77
+ * This package requires React 16.8+ (hooks support) and axios as peer dependencies
78
+ *
79
+ * Complete solution for JWT authentication in React applications:
80
+ * - Automatic JWT authentication with Axios interceptors
81
+ * - React hooks for requests and state management (useAuth, useRequest)
82
+ * - Authentication and authorization components (AuthProvider, RequireAuth)
83
+ * - Standardized CRUD operations with error handling
84
+ * - Token management with automatic expiration checks
85
+ * - Pagination and search support for API requests
86
+ * - Request cancellation via AbortController
87
+ * - TypeScript support with comprehensive type definitions
14
88
  */
15
89
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
90
  if (k2 === undefined) k2 = k;
@@ -27,23 +101,94 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
27
101
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
28
102
  };
29
103
  Object.defineProperty(exports, "__esModule", { value: true });
30
- // API client e configurações
104
+ /**
105
+ * API client creation and configuration utilities
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * import { createApiClient } from '@forgepack/request'
110
+ *
111
+ * const api = createApiClient({
112
+ * baseURL: process.env.REACT_APP_API_URL,
113
+ * onUnauthorized: () => navigate('/login'),
114
+ * onForbidden: () => toast.error('Access denied')
115
+ * })
116
+ * ```
117
+ */
31
118
  __exportStar(require("./api/client"), exports);
32
- // Tipos e interfaces
119
+ /**
120
+ * Type definitions for authentication, errors, requests, responses and tokens
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * import type { Auth, LoginCredentials, ErrorMessage, Page } from '@forgepack/request'
125
+ *
126
+ * const credentials: LoginCredentials = {
127
+ * username: 'user@example.com',
128
+ * password: 'password123'
129
+ * }
130
+ * ```
131
+ */
33
132
  __exportStar(require("./types/auth"), exports);
34
133
  __exportStar(require("./types/error"), exports);
35
134
  __exportStar(require("./types/request"), exports);
36
135
  __exportStar(require("./types/response"), exports);
37
136
  __exportStar(require("./types/token"), exports);
38
- // Hooks React para gerenciamento de estado
137
+ /**
138
+ * React hooks for authentication and request management
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * import { AuthProvider, useAuth, useRequest } from '@forgepack/request'
143
+ *
144
+ * // Authentication hook
145
+ * const { isAuthenticated, loginUser, logoutUser, role } = useAuth()
146
+ *
147
+ * // Request hook with pagination
148
+ * const { response, loading, error, request } = useRequest(
149
+ * api,
150
+ * 'posts',
151
+ * { page: 0, size: 20, sort: { key: 'createdAt', order: 'desc' } }
152
+ * )
153
+ * ```
154
+ */
39
155
  __exportStar(require("./hooks/AuthContext"), exports);
40
156
  __exportStar(require("./hooks/AuthProvider"), exports);
41
157
  __exportStar(require("./hooks/useAuth"), exports);
42
158
  __exportStar(require("./hooks/useRequest"), exports);
43
- // Serviços para operações de dados
159
+ /**
160
+ * Service layer for API operations, authentication, CRUD and token management
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * import { login, create, retrieve, update, remove, fetchPage } from '@forgepack/request'
165
+ *
166
+ * // Authentication
167
+ * const result = await login(api, '/auth/login', credentials)
168
+ *
169
+ * // CRUD operations
170
+ * const newUser = await create(api, 'users', userData)
171
+ * const users = await retrieve(api, 'users', { page: 0, size: 10 })
172
+ * const updated = await update(api, 'users', { id: 1, name: 'New Name' })
173
+ * await remove(api, 'users', '1')
174
+ *
175
+ * // Paginated fetch
176
+ * const page = await fetchPage(api, 'posts', { page: 0, size: 20 })
177
+ * ```
178
+ */
44
179
  __exportStar(require("./services/api"), exports);
45
180
  __exportStar(require("./services/auth"), exports);
46
181
  __exportStar(require("./services/crud"), exports);
47
182
  __exportStar(require("./services/token"), exports);
48
- // Utilitários e constantes
183
+ /**
184
+ * Utility constants and default values
185
+ *
186
+ * @example
187
+ * ```typescript
188
+ * import { initialAuth, initialPage, initialErrorMessage } from '@forgepack/request'
189
+ *
190
+ * const [auth, setAuth] = useState(initialAuth)
191
+ * const [page, setPage] = useState(initialPage)
192
+ * ```
193
+ */
49
194
  __exportStar(require("./utils/constants"), exports);
@@ -2,32 +2,54 @@ import { AxiosInstance } from 'axios';
2
2
  import { Page } from '../types/response';
3
3
  import { Search } from '../types/request';
4
4
  /**
5
- * Executa requisição paginada para um endpoint específico
5
+ * Executes a paginated GET request to a specific API endpoint with optional search and sorting
6
6
  *
7
- * Funcionalidades:
8
- * - Constrói URL com parâmetros de busca
9
- * - Adiciona parâmetros de paginação
10
- * - Suporte a ordenação
11
- * - Cancelamento de requisição via AbortSignal
7
+ * Features:
8
+ * - Builds URL with search parameters
9
+ * - Adds pagination parameters (page, size)
10
+ * - Supports sorting by field and order (asc/desc)
11
+ * - Request cancellation via AbortSignal
12
+ * - Automatic URL encoding for search values
12
13
  *
13
- * @param api - Instância configurada do Axios
14
- * @param endpoint - Endpoint da API (sem barra inicial)
15
- * @param search - Parâmetros opcionais de busca e paginação
16
- * @param signal - Signal para cancelamento da requisição
17
- * @returns Promise com dados paginados
14
+ * @param {AxiosInstance} api - Configured Axios instance with authentication and base URL
15
+ * @param {string} endpoint - API endpoint path (without leading slash, e.g., 'users' or 'posts')
16
+ * @param {Search} [search] - Optional search, pagination and sorting parameters
17
+ * @param {number} [search.page] - Page number (zero-indexed, default handled by backend)
18
+ * @param {number} [search.size] - Number of items per page (default handled by backend)
19
+ * @param {string} [search.value] - Search term for filtering results (URL encoded automatically)
20
+ * @param {Object} [search.sort] - Sorting configuration
21
+ * @param {string} [search.sort.key] - Field name to sort by (e.g., 'name', 'createdAt')
22
+ * @param {'asc'|'desc'} [search.sort.order] - Sort order (ascending or descending)
23
+ * @param {AbortSignal} [signal] - Signal for request cancellation (from AbortController)
24
+ * @returns {Promise<Page>} Promise resolving to paginated response data
18
25
  *
19
- * @throws {Error} Lança erro se a requisição falhar
26
+ * @throws {AxiosError} When the HTTP request fails
27
+ * @throws {Error} When request is aborted via signal
20
28
  *
21
29
  * @example
22
30
  * ```typescript
23
- * const controller = new AbortController()
24
- * const result = await fetchPage(
31
+ * // Most basic usage
32
+ * const result = await fetchPage(api, 'articles')
33
+ *
34
+ * // With sorting
35
+ * const promise = fetchPage(
25
36
  * api,
26
37
  * 'users',
38
+ * { page: 0, size: 10, sort: { key: 'createdAt', order: 'desc' } },
39
+ * controller.signal
40
+ * )
41
+ *
42
+ * // With cancellation support
43
+ * const controller = new AbortController()
44
+ * const promise = fetchPage(
45
+ * api,
46
+ * 'posts',
27
47
  * { page: 0, size: 10, value: 'search term' },
28
48
  * controller.signal
29
49
  * )
50
+ * // Cancel if needed
51
+ * controller.abort()
30
52
  * ```
31
53
  */
32
- export declare const fetchPage: (api: AxiosInstance, endpoint: string, search?: Search, signal?: AbortSignal) => Promise<Page>;
54
+ export declare const fetchPage: <T>(api: AxiosInstance, endpoint: string, search?: Search, signal?: AbortSignal) => Promise<Page<T>>;
33
55
  //# sourceMappingURL=api.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/services/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,SAAS,GAAU,KAAK,aAAa,EAAE,UAAU,MAAM,EAAE,SAAS,MAAM,EAAE,SAAS,WAAW,KAAG,OAAO,CAAC,IAAI,CAkBzH,CAAA"}
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/services/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,eAAO,MAAM,SAAS,GAAU,CAAC,EAAG,KAAK,aAAa,EAAE,UAAU,MAAM,EAAE,SAAS,MAAM,EAAE,SAAS,WAAW,KAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAqBhI,CAAA"}
@@ -2,45 +2,71 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.fetchPage = void 0;
4
4
  /**
5
- * Executa requisição paginada para um endpoint específico
5
+ * Executes a paginated GET request to a specific API endpoint with optional search and sorting
6
6
  *
7
- * Funcionalidades:
8
- * - Constrói URL com parâmetros de busca
9
- * - Adiciona parâmetros de paginação
10
- * - Suporte a ordenação
11
- * - Cancelamento de requisição via AbortSignal
7
+ * Features:
8
+ * - Builds URL with search parameters
9
+ * - Adds pagination parameters (page, size)
10
+ * - Supports sorting by field and order (asc/desc)
11
+ * - Request cancellation via AbortSignal
12
+ * - Automatic URL encoding for search values
12
13
  *
13
- * @param api - Instância configurada do Axios
14
- * @param endpoint - Endpoint da API (sem barra inicial)
15
- * @param search - Parâmetros opcionais de busca e paginação
16
- * @param signal - Signal para cancelamento da requisição
17
- * @returns Promise com dados paginados
14
+ * @param {AxiosInstance} api - Configured Axios instance with authentication and base URL
15
+ * @param {string} endpoint - API endpoint path (without leading slash, e.g., 'users' or 'posts')
16
+ * @param {Search} [search] - Optional search, pagination and sorting parameters
17
+ * @param {number} [search.page] - Page number (zero-indexed, default handled by backend)
18
+ * @param {number} [search.size] - Number of items per page (default handled by backend)
19
+ * @param {string} [search.value] - Search term for filtering results (URL encoded automatically)
20
+ * @param {Object} [search.sort] - Sorting configuration
21
+ * @param {string} [search.sort.key] - Field name to sort by (e.g., 'name', 'createdAt')
22
+ * @param {'asc'|'desc'} [search.sort.order] - Sort order (ascending or descending)
23
+ * @param {AbortSignal} [signal] - Signal for request cancellation (from AbortController)
24
+ * @returns {Promise<Page>} Promise resolving to paginated response data
18
25
  *
19
- * @throws {Error} Lança erro se a requisição falhar
26
+ * @throws {AxiosError} When the HTTP request fails
27
+ * @throws {Error} When request is aborted via signal
20
28
  *
21
29
  * @example
22
30
  * ```typescript
23
- * const controller = new AbortController()
24
- * const result = await fetchPage(
31
+ * // Most basic usage
32
+ * const result = await fetchPage(api, 'articles')
33
+ *
34
+ * // With sorting
35
+ * const promise = fetchPage(
25
36
  * api,
26
37
  * 'users',
38
+ * { page: 0, size: 10, sort: { key: 'createdAt', order: 'desc' } },
39
+ * controller.signal
40
+ * )
41
+ *
42
+ * // With cancellation support
43
+ * const controller = new AbortController()
44
+ * const promise = fetchPage(
45
+ * api,
46
+ * 'posts',
27
47
  * { page: 0, size: 10, value: 'search term' },
28
48
  * controller.signal
29
49
  * )
50
+ * // Cancel if needed
51
+ * controller.abort()
30
52
  * ```
31
53
  */
32
54
  const fetchPage = async (api, endpoint, search, signal) => {
33
55
  var _a, _b, _c;
56
+ /** Build base URI with optional search query */
34
57
  const uri = ((_a = search === null || search === void 0 ? void 0 : search.value) === null || _a === void 0 ? void 0 : _a.trim())
35
58
  ? `/${endpoint}?value=${encodeURIComponent(search.value)}`
36
59
  : `/${endpoint}`;
60
+ /** Build request parameters */
37
61
  const params = {
38
62
  page: search === null || search === void 0 ? void 0 : search.page,
39
63
  size: search === null || search === void 0 ? void 0 : search.size
40
64
  };
65
+ /** Add sorting parameter if provided */
41
66
  if (((_b = search === null || search === void 0 ? void 0 : search.sort) === null || _b === void 0 ? void 0 : _b.order) && ((_c = search === null || search === void 0 ? void 0 : search.sort) === null || _c === void 0 ? void 0 : _c.key)) {
42
67
  params.sort = `${search.sort.key},${search.sort.order}`;
43
68
  }
69
+ /** Execute GET request with parameters and cancellation signal */
44
70
  const { data } = await api.get(uri, {
45
71
  params: Object.keys(params).length > 0 ? params : undefined,
46
72
  signal
@@ -2,47 +2,104 @@ import { AxiosInstance } from 'axios';
2
2
  import { ErrorMessage } from '../types/error';
3
3
  import { LoginCredentials, LoginResponse, ChangePasswordData, ResetPasswordData } from '../types/auth';
4
4
  /**
5
- * Realiza login do usuário e armazena o token retornado
5
+ * Performs user login and stores the returned token
6
6
  *
7
- * @param api - Instância do Axios configurada
8
- * @param url - Endpoint de login
9
- * @param credentials - Credenciais do usuário
10
- * @returns Promise com resposta de login formatada
7
+ * @param {AxiosInstance} api - Configured Axios instance with base URL
8
+ * @param {string} url - Login endpoint path (e.g., '/auth/login')
9
+ * @param {LoginCredentials} credentials - User login credentials
10
+ * @param {string} credentials.username - Username or email
11
+ * @param {string} credentials.password - User password
12
+ * @returns {Promise<LoginResponse>} Promise resolving to login response with success flag and data/errors
13
+ *
14
+ * @throws {never} Never throws - all errors are caught and returned in response
11
15
  *
12
16
  * @example
13
17
  * ```typescript
18
+ * // Successful login
14
19
  * const result = await login(api, '/auth/login', {
15
- * username: 'user',
16
- * password: 'pass'
20
+ * username: 'john@snow.com',
21
+ * password: 'SecurePass123!'
17
22
  * })
18
23
  *
19
24
  * if (result.success) {
20
- * console.log('Logado!', result.data)
25
+ * // Navigate to dashboard
26
+ * console.log('Logged in!', result.data)
21
27
  * } else {
22
- * console.error('Erros:', result.errors)
28
+ * // Display errors to user
29
+ * result.errors?.forEach(error => {
30
+ * console.log(`${error.field}: ${error.message}`)
31
+ * })
23
32
  * }
24
33
  * ```
25
34
  */
26
35
  export declare const login: (api: AxiosInstance, url: string, credentials: LoginCredentials) => Promise<LoginResponse>;
27
36
  /**
28
- * Realiza reset de senha do usuário e atualiza o token
37
+ * Performs password reset using a reset token and updates authentication
38
+ *
39
+ * @param {AxiosInstance} api - Configured Axios instance
40
+ * @param {string} url - Password reset endpoint path (e.g., '/auth/reset-password')
41
+ * @param {ResetPasswordData} data - Password reset data
42
+ * @param {string} data.token - Password reset token (from email)
43
+ * @param {string} data.newPassword - New password to set
44
+ * @returns {Promise<LoginResponse>} Promise with auth data on success or errors on failure
45
+ *
46
+ * @throws {never} Never throws - all errors are caught and returned in response
29
47
  *
30
- * @param api - Instância do Axios configurada
31
- * @param url - Endpoint de reset de senha
32
- * @param data - Dados para reset da senha
33
- * @returns Promise com dados de auth ou array de erros
48
+ * @example
49
+ * ```typescript
50
+ * ```
34
51
  */
35
52
  export declare const reset: (api: AxiosInstance, url: string, data: ResetPasswordData) => Promise<LoginResponse>;
36
53
  /**
37
- * Remove o token do localStorage e desloga o usuário
54
+ * Logs out the current user by removing authentication data from localStorage
55
+ *
56
+ * This function only clears local storage. For complete logout:
57
+ * - Call this function to clear local data
58
+ * - Redirect user to login page
59
+ *
60
+ * @returns {void}
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * logout()
65
+ * window.location.href = '/login'
66
+ * ```
38
67
  */
39
68
  export declare const logout: () => void;
40
69
  /**
41
- * Altera a senha do usuário autenticado
70
+ * Changes the password for an authenticated user
71
+ *
72
+ * Requires user to be authenticated (valid token in localStorage).
73
+ * User must provide current password for verification.
74
+ *
75
+ * @param {AxiosInstance} api - Configured Axios instance with authentication
76
+ * @param {ChangePasswordData} data - Password change data
77
+ * @param {string} data.currentPassword - Current password for verification
78
+ * @param {string} data.newPassword - New password to set
79
+ * @param {string} data.confirmPassword - Confirm password to set
80
+ * @returns {Promise<{success: boolean; errors?: ErrorMessage[]}>} Promise with success status and optional errors
42
81
  *
43
- * @param api - Instância do Axios configurada
44
- * @param data - Dados para alteração da senha
45
- * @returns Promise com resposta de sucesso ou erros
82
+ * @throws {never} Never throws - all errors are caught and returned in response
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * // Password change in user settings
87
+ * const result = await changePassword(api, {
88
+ * currentPassword: 'OldPass123!',
89
+ * newPassword: 'NewSecurePass456!',
90
+ * confirmPassword: 'NewSecurePass456!'
91
+ * })
92
+ * if (result.success) {
93
+ * alert('Password changed successfully')
94
+ * } else {
95
+ * // Display errors
96
+ * result.errors?.forEach(err => {
97
+ * if (err.field === 'currentPassword') {
98
+ * console.error('Current password is incorrect')
99
+ * }
100
+ * })
101
+ * }
102
+ * ```
46
103
  */
47
104
  export declare const changePassword: (api: AxiosInstance, data: ChangePasswordData) => Promise<{
48
105
  success: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/services/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAQ,gBAAgB,EAAE,aAAa,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAwB5G;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,KAAK,GAAU,KAAK,aAAa,EAAE,KAAK,MAAM,EAAE,aAAa,gBAAgB,KAAG,OAAO,CAAC,aAAa,CAcjH,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,GAAU,KAAK,aAAa,EAAE,KAAK,MAAM,EAAE,MAAM,iBAAiB,KAAG,OAAO,CAAC,aAAa,CAc3G,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,MAAM,YAElB,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAU,KAAK,aAAa,EAAE,MAAM,kBAAkB,KAAG,OAAO,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,YAAY,EAAE,CAAA;CAAE,CAUxI,CAAA"}
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/services/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAQ,gBAAgB,EAAE,aAAa,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAuC5G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,eAAO,MAAM,KAAK,GAAU,KAAK,aAAa,EAAE,KAAK,MAAM,EAAE,aAAa,gBAAgB,KAAG,OAAO,CAAC,aAAa,CAcjH,CAAA;AAED;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,KAAK,GAAU,KAAK,aAAa,EAAE,KAAK,MAAM,EAAE,MAAM,iBAAiB,KAAG,OAAO,CAAC,aAAa,CAc3G,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,MAAM,YAElB,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,cAAc,GAAU,KAAK,aAAa,EAAE,MAAM,kBAAkB,KAAG,OAAO,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,YAAY,EAAE,CAAA;CAAE,CAUxI,CAAA"}
@@ -3,20 +3,35 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.changePassword = exports.logout = exports.reset = exports.login = void 0;
4
4
  const token_1 = require("./token");
5
5
  /**
6
- * Processa erros de resposta da API e converte em formato padronizado
6
+ * Processes API response errors and converts them to standardized format
7
7
  *
8
- * @param error - Objeto de erro do Axios
9
- * @returns Array de mensagens de erro formatadas
8
+ * @param {any} error - Axios error object
9
+ * @returns {ErrorMessage[]} Array of formatted error messages with field and message properties
10
+ *
11
+ * @internal This is a utility function used internally by auth service methods
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * // Validation errors response
16
+ * {
17
+ * validationErrors: [
18
+ * { field: 'email', message: 'Invalid email format' },
19
+ * { field: 'password', message: 'Password too short' }
20
+ * ]
21
+ * }
22
+ * ```
10
23
  */
11
24
  const addError = (error) => {
12
25
  var _a, _b, _c, _d;
13
26
  let errorMessage = [];
27
+ /** Check for validation errors in the response */
14
28
  if ((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.validationErrors) {
15
29
  error.response.data.validationErrors.forEach((element) => {
16
30
  errorMessage.push({ field: element.field, message: element.message });
17
31
  });
18
32
  }
19
33
  else {
34
+ /** General errors */
20
35
  errorMessage.push({
21
36
  field: 'Error',
22
37
  message: ((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.message) || 'Internal Error'
@@ -25,24 +40,33 @@ const addError = (error) => {
25
40
  return errorMessage;
26
41
  };
27
42
  /**
28
- * Realiza login do usuário e armazena o token retornado
43
+ * Performs user login and stores the returned token
44
+ *
45
+ * @param {AxiosInstance} api - Configured Axios instance with base URL
46
+ * @param {string} url - Login endpoint path (e.g., '/auth/login')
47
+ * @param {LoginCredentials} credentials - User login credentials
48
+ * @param {string} credentials.username - Username or email
49
+ * @param {string} credentials.password - User password
50
+ * @returns {Promise<LoginResponse>} Promise resolving to login response with success flag and data/errors
29
51
  *
30
- * @param api - Instância do Axios configurada
31
- * @param url - Endpoint de login
32
- * @param credentials - Credenciais do usuário
33
- * @returns Promise com resposta de login formatada
52
+ * @throws {never} Never throws - all errors are caught and returned in response
34
53
  *
35
54
  * @example
36
55
  * ```typescript
56
+ * // Successful login
37
57
  * const result = await login(api, '/auth/login', {
38
- * username: 'user',
39
- * password: 'pass'
58
+ * username: 'john@snow.com',
59
+ * password: 'SecurePass123!'
40
60
  * })
41
61
  *
42
62
  * if (result.success) {
43
- * console.log('Logado!', result.data)
63
+ * // Navigate to dashboard
64
+ * console.log('Logged in!', result.data)
44
65
  * } else {
45
- * console.error('Erros:', result.errors)
66
+ * // Display errors to user
67
+ * result.errors?.forEach(error => {
68
+ * console.log(`${error.field}: ${error.message}`)
69
+ * })
46
70
  * }
47
71
  * ```
48
72
  */
@@ -64,12 +88,20 @@ const login = async (api, url, credentials) => {
64
88
  };
65
89
  exports.login = login;
66
90
  /**
67
- * Realiza reset de senha do usuário e atualiza o token
91
+ * Performs password reset using a reset token and updates authentication
68
92
  *
69
- * @param api - Instância do Axios configurada
70
- * @param url - Endpoint de reset de senha
71
- * @param data - Dados para reset da senha
72
- * @returns Promise com dados de auth ou array de erros
93
+ * @param {AxiosInstance} api - Configured Axios instance
94
+ * @param {string} url - Password reset endpoint path (e.g., '/auth/reset-password')
95
+ * @param {ResetPasswordData} data - Password reset data
96
+ * @param {string} data.token - Password reset token (from email)
97
+ * @param {string} data.newPassword - New password to set
98
+ * @returns {Promise<LoginResponse>} Promise with auth data on success or errors on failure
99
+ *
100
+ * @throws {never} Never throws - all errors are caught and returned in response
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * ```
73
105
  */
74
106
  const reset = async (api, url, data) => {
75
107
  try {
@@ -89,18 +121,58 @@ const reset = async (api, url, data) => {
89
121
  };
90
122
  exports.reset = reset;
91
123
  /**
92
- * Remove o token do localStorage e desloga o usuário
124
+ * Logs out the current user by removing authentication data from localStorage
125
+ *
126
+ * This function only clears local storage. For complete logout:
127
+ * - Call this function to clear local data
128
+ * - Redirect user to login page
129
+ *
130
+ * @returns {void}
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * logout()
135
+ * window.location.href = '/login'
136
+ * ```
93
137
  */
94
138
  const logout = () => {
95
139
  (0, token_1.removeToken)();
96
140
  };
97
141
  exports.logout = logout;
98
142
  /**
99
- * Altera a senha do usuário autenticado
143
+ * Changes the password for an authenticated user
144
+ *
145
+ * Requires user to be authenticated (valid token in localStorage).
146
+ * User must provide current password for verification.
147
+ *
148
+ * @param {AxiosInstance} api - Configured Axios instance with authentication
149
+ * @param {ChangePasswordData} data - Password change data
150
+ * @param {string} data.currentPassword - Current password for verification
151
+ * @param {string} data.newPassword - New password to set
152
+ * @param {string} data.confirmPassword - Confirm password to set
153
+ * @returns {Promise<{success: boolean; errors?: ErrorMessage[]}>} Promise with success status and optional errors
154
+ *
155
+ * @throws {never} Never throws - all errors are caught and returned in response
100
156
  *
101
- * @param api - Instância do Axios configurada
102
- * @param data - Dados para alteração da senha
103
- * @returns Promise com resposta de sucesso ou erros
157
+ * @example
158
+ * ```typescript
159
+ * // Password change in user settings
160
+ * const result = await changePassword(api, {
161
+ * currentPassword: 'OldPass123!',
162
+ * newPassword: 'NewSecurePass456!',
163
+ * confirmPassword: 'NewSecurePass456!'
164
+ * })
165
+ * if (result.success) {
166
+ * alert('Password changed successfully')
167
+ * } else {
168
+ * // Display errors
169
+ * result.errors?.forEach(err => {
170
+ * if (err.field === 'currentPassword') {
171
+ * console.error('Current password is incorrect')
172
+ * }
173
+ * })
174
+ * }
175
+ * ```
104
176
  */
105
177
  const changePassword = async (api, data) => {
106
178
  try {