api-core-lib 5.5.4 → 6.5.5

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/index.d.mts CHANGED
@@ -1,16 +1,14 @@
1
1
  import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method } from 'axios';
2
- import * as react from 'react';
3
2
 
4
3
  /**
5
4
  * @file src/types.ts
6
- * @description
7
- * هذا الملف هو المصدر المركزي لجميع أنواع البيانات (Types) والواجهات (Interfaces)
8
- * المستخدمة في المكتبة. تعريف الأنواع هنا يضمن التناسق وسلامة الأنواع
9
- * في جميع أنحاء المشروع ويوفر واجهة واضحة للمستخدم النهائي.
5
+ * @description This file serves as the central source for all data types and interfaces
6
+ * used throughout the library. Defining types here ensures consistency, type safety,
7
+ * and provides a clear API contract for the end-user.
10
8
  */
11
9
 
12
10
  /**
13
- * يمثل بيانات الترقيم (Pagination) التي تأتي من الـ API.
11
+ * Defines the structure for pagination metadata returned by the API.
14
12
  */
15
13
  interface PaginationMeta {
16
14
  itemsPerPage: number;
@@ -19,14 +17,24 @@ interface PaginationMeta {
19
17
  totalPages: number;
20
18
  }
21
19
  /**
22
- * يمثل خطأ التحقق من صحة حقل معين.
20
+ * Represents the standard wrapper that an API might use for its responses.
21
+ * @template T The type of the core data payload.
22
+ */
23
+ interface ApiResponse<T = any> {
24
+ success?: boolean;
25
+ data: T;
26
+ message?: string;
27
+ meta?: PaginationMeta;
28
+ }
29
+ /**
30
+ * Defines the structure for a single field validation error.
23
31
  */
24
32
  interface ValidationError {
25
33
  field: string;
26
34
  message: string;
27
35
  }
28
36
  /**
29
- * يمثل كائن الخطأ الموحد الذي تنتجه المكتبة.
37
+ * Represents the unified error object produced by the library for any failed request.
30
38
  */
31
39
  interface ApiError {
32
40
  message: string;
@@ -35,34 +43,46 @@ interface ApiError {
35
43
  errors?: ValidationError[];
36
44
  requestId?: string;
37
45
  }
46
+ /**
47
+ * The standardized, final response object that every library function returns.
48
+ * This is the primary type developers will interact with.
49
+ * @template T The type of the final, unwrapped data.
50
+ */
51
+ interface StandardResponse<T> {
52
+ data: T | null;
53
+ rawResponse: any;
54
+ error: ApiError | null;
55
+ loading: boolean;
56
+ success: boolean;
57
+ message?: string;
58
+ validationErrors?: ValidationError[];
59
+ }
60
+ /**
61
+ * Represents the set of authentication tokens managed by the library.
62
+ */
38
63
  interface Tokens {
39
64
  accessToken: string | null;
40
65
  refreshToken: string | null;
41
66
  expiresAt?: number;
42
67
  tokenType?: string;
43
68
  }
69
+ /**
70
+ * An interface for a token manager, allowing the logic for token storage to be decoupled.
71
+ * Consumers of the library can provide their own implementation (e.g., LocalStorage, Cookies).
72
+ */
44
73
  interface TokenManager {
45
74
  getTokens(): Promise<Tokens>;
46
75
  setTokens(tokens: Tokens): Promise<void>;
47
76
  clearTokens(): Promise<void>;
48
77
  /**
49
- * دالة لتحديد سياق التشغيل.
50
- * true إذا كانت التوكنات في كوكيز httpOnly (الوضع الآمن).
51
- * false إذا كانت في مكان يمكن للعميل الوصول إليه (للتطبيقات غير Next.js).
78
+ * Determines the operating context.
79
+ * @returns `true` if tokens are in secure httpOnly cookies (server-side context).
80
+ * @returns `false` if tokens are accessible from the client (e.g., localStorage).
52
81
  */
53
82
  isHttpOnly(): boolean;
54
83
  }
55
84
  /**
56
- * واجهة لـ Logger مخصص. متوافقة مع `console`.
57
- */
58
- interface Logger {
59
- log(message?: any, ...optionalParams: any[]): void;
60
- info(message?: any, ...optionalParams: any[]): void;
61
- warn(message?: any, ...optionalParams: any[]): void;
62
- error(message?: any, ...optionalParams: any[]): void;
63
- }
64
- /**
65
- * سياق البرمجيات الوسيطة الذي يتم تمريره لكل دالة.
85
+ * The context object passed to each middleware function in the pipeline.
66
86
  */
67
87
  interface MiddlewareContext {
68
88
  req: InternalAxiosRequestConfig;
@@ -72,22 +92,28 @@ interface MiddlewareContext {
72
92
  custom?: Record<string, any>;
73
93
  }
74
94
  /**
75
- * دالة برمجية وسيطة (Middleware Function).
95
+ * Defines the signature for a middleware function.
76
96
  */
77
97
  type Middleware = (context: MiddlewareContext, next: () => Promise<void>) => Promise<void>;
98
+ /**
99
+ * Extends the default Axios request configuration with custom properties for the library.
100
+ */
78
101
  interface RequestConfig extends AxiosRequestConfig {
102
+ /** If true, the request will bypass the token injection logic. */
79
103
  isPublic?: boolean;
80
- }
81
- interface RequestConfig extends AxiosRequestConfig {
104
+ /** A key for managing request cancellation. */
82
105
  cancelTokenKey?: string;
106
+ /** Callback for upload progress events. */
83
107
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
108
+ /** Callback for download progress events. */
84
109
  onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
85
- isPublic?: boolean;
86
110
  }
87
111
  /**
88
- * يمثل خيارات الاستعلام للترقيم والبحث والفرز.
112
+ * Defines a flexible query options interface for pagination, sorting, filtering, and searching.
113
+ * Supports standard keys as well as any custom top-level query parameters.
114
+ * @example { page: 1, limit: 10, search: 'term', status: 'published' }
89
115
  */
90
- interface PaginateQueryOptions {
116
+ interface QueryOptions {
91
117
  page?: number;
92
118
  limit?: number;
93
119
  search?: string;
@@ -96,35 +122,58 @@ interface PaginateQueryOptions {
96
122
  direction: 'asc' | 'desc';
97
123
  }[];
98
124
  filter?: Record<string, any>;
125
+ [key: string]: any;
99
126
  }
100
127
  /**
101
- * واجهة لتخصيص عملية تجديد التوكن بشكل كامل.
128
+ * Defines additional options for action methods like create, update, or delete.
102
129
  */
103
- interface RefreshTokenConfig {
130
+ interface ActionOptions {
104
131
  /**
105
- * المسار الذي يتم استخدامه لتجديد التوكن (e.g., '/auth/refresh').
106
- * @default '/auth/refresh'
132
+ * Overrides the default endpoint for a specific action. Useful for specialized routes.
133
+ * @example update('123', { status: 'active' }, { endpoint: '/items/123/activate' })
107
134
  */
108
- path: string;
135
+ endpoint?: string;
109
136
  /**
110
- * دالة لتحديد كيفية بناء جسم (body) طلب التجديد.
111
- * @param refreshToken - التوكن المستخدم للتجديد.
112
- * @returns كائن يمثل جسم الطلب.
113
- * @default (refreshToken) => ({ refresh_token: refreshToken })
137
+ * Overrides the `refetchAfterChange` setting for a single action.
114
138
  */
139
+ refetch?: boolean;
140
+ }
141
+ /**
142
+ * The main configuration object for the `useApi` hook.
143
+ * @template T The data type the hook will manage.
144
+ */
145
+ interface UseApiConfig<T> {
146
+ /** The base API endpoint for the resource (e.g., '/users'). */
147
+ endpoint: string;
148
+ /** Initial data to populate the state before the first fetch. */
149
+ initialData?: T | T[];
150
+ /** Default query options to use for the initial fetch. */
151
+ initialQuery?: QueryOptions;
152
+ /** If false, the hook will not fetch data automatically on mount. */
153
+ enabled?: boolean;
154
+ /** If true, data will be refetched automatically after a successful create, update, or delete action. */
155
+ refetchAfterChange?: boolean;
156
+ /** A default `RequestConfig` to apply to all GET requests made by the hook. */
157
+ requestConfig?: RequestConfig;
158
+ /** Callback function executed on a successful action. */
159
+ onSuccess?: (message: string, data?: T) => void;
160
+ /** Callback function executed on a failed action. */
161
+ onError?: (message: string, error?: ApiError) => void;
162
+ }
163
+ /**
164
+ * Defines the configuration for the automatic token refresh mechanism.
165
+ */
166
+ interface RefreshTokenConfig {
167
+ /** The API path for the token refresh endpoint (e.g., '/auth/refresh'). */
168
+ path: string;
169
+ /** A function to build the request body for the refresh call. */
115
170
  buildRequestBody?: (refreshToken: string) => Record<string, any>;
116
- /**
117
- * دالة لتحديد كيفية بناء الهيدرز (headers) الخاصة بطلب التجديد.
118
- * @param currentTokens - التوكنات الحالية.
119
- * @returns كائن يمثل الهيدرز الإضافية.
120
- * @default () => ({})
121
- */
171
+ /** A function to build any custom headers for the refresh call. */
122
172
  buildRequestHeaders?: (currentTokens: Tokens) => Record<string, string>;
123
173
  /**
124
- * دالة مخصصة لاستخلاص التوكنات الجديدة من استجابة الـ API.
125
- * @param responseData - البيانات التي تم إرجاعها من الـ API.
126
- * @returns كائن من نوع Tokens.
127
- * @default (data) => ({ accessToken: data.access_token, ... })
174
+ * A function to extract the new tokens from the refresh API's response data.
175
+ * @param responseData The raw data from the refresh API response.
176
+ * @returns An object containing the new token details.
128
177
  */
129
178
  extractTokens: (responseData: any) => {
130
179
  accessToken: string;
@@ -134,106 +183,59 @@ interface RefreshTokenConfig {
134
183
  };
135
184
  }
136
185
  /**
137
- * الواجهة الرئيسية لتهيئة عميل الـ API (محدثة بالكامل).
186
+ * Defines the available levels for logging.
187
+ * 'debug': Logs everything.
188
+ * 'info': Logs standard requests and responses.
189
+ * 'warn': Logs warnings and errors.
190
+ * 'error': Logs only critical errors.
191
+ * 'silent': Disables all logging.
192
+ */
193
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
194
+ /**
195
+ * An interface for a custom logger, compatible with the standard `console` object.
196
+ * It now includes a `debug` method for more granular logging.
197
+ */
198
+ interface Logger {
199
+ /** Logs a standard message. In our wrapper, this is often an alias for `info` or `debug`. */
200
+ log(message?: any, ...optionalParams: any[]): void;
201
+ /** Logs an informational message. */
202
+ info(message?: any, ...optionalParams: any[]): void;
203
+ /** Logs a warning message. */
204
+ warn(message?: any, ...optionalParams: any[]): void;
205
+ /** Logs an error message. */
206
+ error(message?: any, ...optionalParams: any[]): void;
207
+ /**
208
+ * Logs a debug message, typically for verbose, development-only output.
209
+ */
210
+ debug(message?: any, ...optionalParams: any[]): void;
211
+ }
212
+ /**
213
+ * The main configuration object for the `createApiClient` factory function.
138
214
  */
139
215
  interface ApiClientConfig {
216
+ /** The base URL for all API requests. */
140
217
  baseURL?: string;
218
+ /** The token manager instance responsible for handling token storage. */
141
219
  tokenManager: TokenManager;
220
+ /** The request timeout in milliseconds. */
142
221
  timeout?: number;
222
+ /** Default headers to be sent with every request. */
143
223
  headers?: Record<string, string>;
224
+ /** If true, cookies will be sent with cross-origin requests. */
144
225
  withCredentials?: boolean;
226
+ /** Configuration for the automatic token refresh mechanism. */
145
227
  refreshTokenConfig?: RefreshTokenConfig;
228
+ /** A callback function executed if the token refresh process fails. */
146
229
  onRefreshError?: (error: any) => void;
147
- /**
148
- * ✨ NEW: Logger مخصص. الافتراضي هو `console`.
149
- */
230
+ /** A custom logger instance. Defaults to the browser `console`. */
150
231
  logger?: Logger;
151
- /**
152
- * ✨ NEW: مصفوفة من البرمجيات الوسيطة (Middleware) لتشغيلها مع كل طلب.
153
- */
232
+ /** An array of middleware functions to be executed with every request. */
154
233
  middleware?: Middleware[];
155
- }
156
- /**
157
- * يمثل بنية الاستجابة القياسية من الـ API.
158
- * @template T نوع البيانات الأساسية في الاستجابة.
159
- */
160
- interface ApiResponse<T = any> {
161
- data: T;
162
- message?: string;
163
- meta?: PaginationMeta;
164
- }
165
- /**
166
- * يمثل بنية الاستجابة القياسية المغلفة التي قد تأتي من بعض نقاط الـ API.
167
- * @template T نوع البيانات الأساسية في الاستجابة.
168
- */
169
- interface ApiResponse<T = any> {
170
- data: T;
171
- message?: string;
172
- meta?: PaginationMeta;
173
- success?: boolean;
174
- }
175
- /**
176
- * يمثل كائن الاستجابة الموحد والنهائي الذي يرجعه كل طلب.
177
- * هذا هو النوع الذي ستتعامل معه دائمًا.
178
- * @template T نوع البيانات النهائية التي تريد الوصول إليها.
179
- */
180
- interface StandardResponse<T> {
181
- data: T | null;
182
- rawResponse: any;
183
- error: ApiError | null;
184
- loading: boolean;
185
- success: boolean;
186
- message?: string;
187
- validationErrors?: ValidationError[];
188
- }
189
- /**
190
- * NEW: واجهة استعلام مرنة تسمح بالبارامترات القياسية (للفلترة والترقيم)
191
- * بالإضافة إلى أي بارامترات مخصصة أخرى عبر الـ index signature.
192
- * @example
193
- * { page: 1, limit: 10, search: 'term', status: 'published', authorId: 123 }
194
- */
195
- interface QueryOptions {
196
- page?: number;
197
- limit?: number;
198
- search?: string;
199
- sortBy?: {
200
- key: string;
201
- direction: 'asc' | 'desc';
202
- }[];
203
- filter?: Record<string, any>;
204
- [key: string]: any;
205
- }
206
- /**
207
- * NEW: واجهة لتمرير خيارات إضافية لدوال الأكشن (create, update, remove).
208
- */
209
- interface ActionOptions {
210
- /**
211
- * يسمح لك بتجاوز الـ endpoint الافتراضي المحدد في الهوك.
212
- * مفيد لإرسال طلبات لنقاط نهاية متخصصة.
213
- * @example
214
- * // لتحديث عنصر وتغيير حالته عبر مسار مختلف
215
- * update('123', { status: 'active' }, { endpoint: '/items/123/activate' })
216
- */
217
- endpoint?: string;
218
- refetch?: boolean;
219
- }
220
- /**
221
- * واجهة لتهيئة الهوك `useApi`.
222
- * @template T نوع البيانات التي يتعامل معها الهوك.
223
- */
224
- interface UseApiConfig<T> {
225
- endpoint: string;
226
- initialData?: T | T[];
227
- initialQuery?: QueryOptions;
228
- enabled?: boolean;
229
- refetchAfterChange?: boolean;
230
- onSuccess?: (message: string, data?: T) => void;
231
- onError?: (message: string, error?: ApiError) => void;
232
234
  /**
233
- * إعدادات Axios/Request افتراضية يتم تطبيقها على جميع طلبات الجلب (GET).
234
- * مفيدة لتمرير إعدادات مثل isPublic.
235
+ * Sets the verbosity of the internal logger.
236
+ * @default 'info'
235
237
  */
236
- requestConfig?: RequestConfig;
238
+ logLevel?: LogLevel;
237
239
  }
238
240
 
239
241
  /**
@@ -246,16 +248,6 @@ interface UseApiConfig<T> {
246
248
 
247
249
  /**
248
250
  * Creates and configures a new Axios instance with advanced features.
249
- *
250
- * This factory function is the central entry point of the library. It sets up
251
- * request and response interceptors to handle:
252
- * - Secure token management (supporting httpOnly and client-side storage).
253
- * - A flexible middleware pipeline for custom logic.
254
- * - Centralized logging for observability.
255
- * - Automatic token refresh for client-side scenarios.
256
- *
257
- * @param {ApiClientConfig} config - The configuration object for the API client.
258
- * @returns {AxiosInstance} A fully configured Axios instance ready for use.
259
251
  */
260
252
  declare function createApiClient(config: ApiClientConfig): AxiosInstance;
261
253
 
@@ -346,34 +338,84 @@ declare const cacheManager: CacheManager;
346
338
  */
347
339
  declare const processResponse: <T>(responseOrError: AxiosResponse<any> | ApiError, log?: boolean) => StandardResponse<T>;
348
340
 
341
+ /**
342
+ * @file src/hooks/useApi.types.ts
343
+ * @description This file defines the professional, publicly-facing types
344
+ * returned by the `useApi` hook, providing a clean and stable contract for consumers.
345
+ */
346
+
347
+ /**
348
+ * The primary state object managed by the `useApi` hook.
349
+ * It contains the fetched data, loading status, and any potential errors.
350
+ * @template T The type of the data entity being managed.
351
+ */
352
+ type UseApiState<T> = StandardResponse<T | T[]>;
353
+ /**
354
+ * A collection of callable functions for performing CRUD and other operations.
355
+ * These actions automatically handle state updates like loading and refetching.
356
+ * @template T The type of the data entity being managed.
357
+ */
358
+ interface UseApiActions<T> {
359
+ /** Fetches or refetches the list of data. */
360
+ fetch: (options?: QueryOptions) => Promise<void>;
361
+ /** Creates a new item. */
362
+ create: (newItem: Partial<T>, options?: ActionOptions) => Promise<StandardResponse<T>>;
363
+ /** Replaces an entire item. */
364
+ put: (id: string | number, item: T, options?: ActionOptions) => Promise<StandardResponse<T>>;
365
+ /** Partially updates an item. */
366
+ update: (id: string | number, updatedItem: Partial<T>, options?: ActionOptions) => Promise<StandardResponse<T>>;
367
+ /** Deletes an item. */
368
+ remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
369
+ /** Deletes multiple items in a single request. */
370
+ bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
371
+ /** Uploads a file, optionally with additional data. */
372
+ upload: (file: File, additionalData?: Record<string, any>, options?: ActionOptions) => Promise<StandardResponse<any>>;
373
+ }
374
+ /**
375
+ * A collection of functions and properties for controlling the query parameters
376
+ * used for fetching data, such as pagination, sorting, and filtering.
377
+ */
378
+ interface UseApiQuery {
379
+ /** The current query options state. */
380
+ options: QueryOptions;
381
+ /** A function to set the entire query options object at once. */
382
+ setOptions: React.Dispatch<React.SetStateAction<QueryOptions>>;
383
+ /** Sets the current page number and resets to the first page. */
384
+ setPage: (page: number) => void;
385
+ /** Sets the number of items per page and resets to the first page. */
386
+ setLimit: (limit: number) => void;
387
+ /** Sets the search term and resets to the first page. */
388
+ setSearchTerm: (search: string) => void;
389
+ /** Sets the sorting configuration. */
390
+ setSorting: (sortBy: {
391
+ key: string;
392
+ direction: 'asc' | 'desc';
393
+ }[]) => void;
394
+ /** Sets the filter object and resets to the first page. */
395
+ setFilters: (filter: Record<string, any>) => void;
396
+ /** Sets a single, custom query parameter and resets to the first page. */
397
+ setQueryParam: (key: string, value: any) => void;
398
+ /** Resets the query options to their initial state. */
399
+ reset: () => void;
400
+ }
401
+ /**
402
+ * The complete return type of the `useApi` hook.
403
+ * It encapsulates the state, actions, and query controls for a given API resource.
404
+ * @template T The type of the data entity being managed.
405
+ */
406
+ interface UseApiReturn<T> {
407
+ /** The current state of the API request (data, loading, error). */
408
+ state: UseApiState<T>;
409
+ /** A function to manually set the state. Use with caution. */
410
+ setState: React.Dispatch<React.SetStateAction<UseApiState<T>>>;
411
+ /** An object containing all available data manipulation actions (create, update, delete, etc.). */
412
+ actions: UseApiActions<T>;
413
+ /** An object for controlling the query parameters for data fetching. */
414
+ query: UseApiQuery;
415
+ }
416
+
349
417
  declare function useApi<T extends {
350
418
  id?: string | number;
351
- }>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): {
352
- state: StandardResponse<T | T[]>;
353
- setState: react.Dispatch<react.SetStateAction<StandardResponse<T | T[]>>>;
354
- actions: {
355
- fetch: (options?: QueryOptions) => Promise<void>;
356
- create: (newItem: Partial<T>, options?: ActionOptions) => Promise<StandardResponse<T>>;
357
- put: (id: string, item: T, options?: ActionOptions) => Promise<StandardResponse<T>>;
358
- update: (id: string, updatedItem: Partial<T>, options?: ActionOptions) => Promise<StandardResponse<T>>;
359
- remove: (id: string, options?: ActionOptions) => Promise<StandardResponse<any>>;
360
- bulkRemove: (ids: string[], options?: ActionOptions) => Promise<StandardResponse<any>>;
361
- upload: (file: File, additionalData?: Record<string, any>, options?: ActionOptions) => Promise<StandardResponse<any>>;
362
- };
363
- query: {
364
- options: QueryOptions;
365
- setOptions: react.Dispatch<react.SetStateAction<QueryOptions>>;
366
- setPage: (page: number) => void;
367
- setLimit: (limit: number) => void;
368
- setSearchTerm: (search: string) => void;
369
- setSorting: (sortBy: {
370
- key: string;
371
- direction: "asc" | "desc";
372
- }[]) => void;
373
- setFilters: (filter: Record<string, any>) => void;
374
- setQueryParam: (key: string, value: any) => void;
375
- reset: () => void;
376
- };
377
- };
419
+ }>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
378
420
 
379
- export { type ActionOptions, type ApiClientConfig, type ApiError, type ApiResponse, type Logger, type Middleware, type MiddlewareContext, type PaginateQueryOptions, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiConfig, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi };
421
+ export { type ActionOptions, type ApiClientConfig, type ApiError, type ApiResponse, type LogLevel, type Logger, type Middleware, type MiddlewareContext, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiConfig, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi };