@3lineas/groovepack 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +167 -2
- package/dist/index.js +434 -0
- package/dist/index.js.map +1 -0
- package/package.json +49 -4
- package/registry/common/api-client/files/index.ts.template +296 -0
- package/registry/common/logger/files/index.ts.template +183 -0
- package/registry/react/api-action/files/index.ts.template +291 -0
- package/registry/react/api-toast/files/index.ts.template +169 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Universal API Action Wrapper for React, Next.js, and Astro.
|
|
3
|
+
* Encapsulates async operations, standardizes JSON responses, handles HTTP and business errors,
|
|
4
|
+
* provides optional polymorphic Hono RPC/Fetch compatibility, and logs exclusively on errors.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import { apiAction } from "@/lib/api-action";
|
|
9
|
+
* import { api } from "@/lib/api-client";
|
|
10
|
+
*
|
|
11
|
+
* // 1. Wrapping a REST / Fetch request
|
|
12
|
+
* export async function getCustomersAction() {
|
|
13
|
+
* return apiAction<Customer[]>({
|
|
14
|
+
* actionName: "getCustomers",
|
|
15
|
+
* apiCall: () => api.get("/customers"),
|
|
16
|
+
* onSuccess: (customers) => {
|
|
17
|
+
* console.log(`Loaded ${customers.length} customers`);
|
|
18
|
+
* },
|
|
19
|
+
* });
|
|
20
|
+
* }
|
|
21
|
+
*
|
|
22
|
+
* // 2. Wrapping a Hono RPC endpoint
|
|
23
|
+
* export async function createProductAction(data: CreateProductInput) {
|
|
24
|
+
* return apiAction<Product>({
|
|
25
|
+
* actionName: "createProduct",
|
|
26
|
+
* apiCall: () => rpc.v1.products.$post({ json: data }),
|
|
27
|
+
* });
|
|
28
|
+
* }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Standard API action response format required across frontend applications.
|
|
34
|
+
*
|
|
35
|
+
* @template T - Type of the success response data.
|
|
36
|
+
*/
|
|
37
|
+
export interface ActionResponse<T = unknown> {
|
|
38
|
+
/** Indicates whether the requested operation succeeded */
|
|
39
|
+
success: boolean;
|
|
40
|
+
/** Friendly message originating from backend or action handling */
|
|
41
|
+
message?: string | unknown;
|
|
42
|
+
/** Error code or detailed error message if operation failed */
|
|
43
|
+
error?: string;
|
|
44
|
+
/** Response payload on success */
|
|
45
|
+
data?: T;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Minimal subset of Response required by apiAction to handle HTTP/Hono RPC responses.
|
|
50
|
+
* Avoids hard dependency on hono package while supporting native Hono ClientResponse or standard fetch Response.
|
|
51
|
+
*/
|
|
52
|
+
export interface MinimalResponse {
|
|
53
|
+
/** True if HTTP status code is in 200-299 range */
|
|
54
|
+
ok: boolean;
|
|
55
|
+
/** HTTP status code number */
|
|
56
|
+
status: number;
|
|
57
|
+
/** Function returning response text */
|
|
58
|
+
text: () => Promise<string>;
|
|
59
|
+
/** Function returning parsed JSON object */
|
|
60
|
+
json: () => Promise<unknown>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Generic interface for error loggers (compatible with Logger from @/lib/logger).
|
|
65
|
+
*/
|
|
66
|
+
export interface ErrorLogger {
|
|
67
|
+
error: (message: string, context?: Record<string, unknown>, ...args: unknown[]) => void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Default internal fallback error logger when no custom Logger is injected.
|
|
72
|
+
*/
|
|
73
|
+
const defaultErrorLogger: ErrorLogger = {
|
|
74
|
+
error(message: string, context?: Record<string, unknown>, ...args: unknown[]) {
|
|
75
|
+
const timestamp = new Date().toISOString();
|
|
76
|
+
console.error(
|
|
77
|
+
`\x1b[31m[${timestamp}] [ERROR] [Web:ApiAction]\x1b[0m ${message}`,
|
|
78
|
+
context ? { ...context } : "",
|
|
79
|
+
...args,
|
|
80
|
+
);
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Types of return values accepted by apiCall.
|
|
86
|
+
* Can be an HTTP response (Hono RPC / fetch), a structured ActionResponse, or raw data T.
|
|
87
|
+
*/
|
|
88
|
+
export type ApiCallResult<T> = MinimalResponse | ActionResponse<T> | T;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Configuration options required to execute an API Action.
|
|
92
|
+
*
|
|
93
|
+
* @template T - Type of the processed success data.
|
|
94
|
+
*/
|
|
95
|
+
export interface ApiActionOptions<T> {
|
|
96
|
+
/**
|
|
97
|
+
* Asynchronous function to execute.
|
|
98
|
+
* Supports:
|
|
99
|
+
* 1. Hono RPC / Fetch call returning MinimalResponse ({ ok, status, json(), text() })
|
|
100
|
+
* 2. Direct Server Action / IPC call returning ActionResponse<T>
|
|
101
|
+
* 3. Direct async function returning data payload T
|
|
102
|
+
*/
|
|
103
|
+
apiCall: () => Promise<ApiCallResult<T>>;
|
|
104
|
+
/** Optional callback to process success data (e.g. state update, analytics) */
|
|
105
|
+
onSuccess?: (data: T) => Promise<void> | void;
|
|
106
|
+
/** Context name of the Action for targeted error logging */
|
|
107
|
+
actionName: string;
|
|
108
|
+
/** Custom logger instance (must implement error method). Defaults to internal error logger. */
|
|
109
|
+
logger?: ErrorLogger;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Type guard for MinimalResponse (Hono RPC / fetch response).
|
|
114
|
+
*/
|
|
115
|
+
function isMinimalResponse(value: unknown): value is MinimalResponse {
|
|
116
|
+
if (!value || typeof value !== "object") {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
const candidate = value as Record<string, unknown>;
|
|
120
|
+
return (
|
|
121
|
+
typeof candidate.ok === "boolean" &&
|
|
122
|
+
typeof candidate.status === "number" &&
|
|
123
|
+
typeof candidate.json === "function" &&
|
|
124
|
+
typeof candidate.text === "function"
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Type guard for ActionResponse<T>.
|
|
130
|
+
*/
|
|
131
|
+
function isActionResponse<T>(value: unknown): value is ActionResponse<T> {
|
|
132
|
+
if (!value || typeof value !== "object") {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
return "success" in value && typeof (value as { success: unknown }).success === "boolean";
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Helper to safely parse JSON from raw text without throwing exceptions.
|
|
140
|
+
*/
|
|
141
|
+
function tryParseJson(text: string): Record<string, unknown> | null {
|
|
142
|
+
try {
|
|
143
|
+
const parsed = JSON.parse(text) as unknown;
|
|
144
|
+
if (parsed && typeof parsed === "object") {
|
|
145
|
+
return parsed as Record<string, unknown>;
|
|
146
|
+
}
|
|
147
|
+
} catch {
|
|
148
|
+
// Non-JSON response text
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Handles HTTP responses originating from Hono RPC or fetch.
|
|
155
|
+
*/
|
|
156
|
+
async function handleHttpResponse<T>(
|
|
157
|
+
response: MinimalResponse,
|
|
158
|
+
actionName: string,
|
|
159
|
+
logger: ErrorLogger,
|
|
160
|
+
): Promise<ActionResponse<T>> {
|
|
161
|
+
const logContext = { actionName, status: response.status };
|
|
162
|
+
|
|
163
|
+
// 1. Check HTTP level errors (e.g. 400, 401, 404, 500)
|
|
164
|
+
if (!response.ok) {
|
|
165
|
+
const errorText = await response.text();
|
|
166
|
+
logger.error(`HTTP request failed. Status: ${response.status}`, logContext, errorText);
|
|
167
|
+
|
|
168
|
+
const errorJson = tryParseJson(errorText);
|
|
169
|
+
if (errorJson && "message" in errorJson) {
|
|
170
|
+
return {
|
|
171
|
+
success: false,
|
|
172
|
+
message: errorJson.message,
|
|
173
|
+
error: typeof errorJson.error === "string" ? errorJson.error : `HTTP ${response.status}`,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
success: false,
|
|
179
|
+
message: "No se pudo procesar la solicitud en el servidor. Por favor, intenta de nuevo.",
|
|
180
|
+
error: `HTTP ${response.status}: ${errorText}`,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 2. Parse response body safely
|
|
185
|
+
const parsedBody = (await response.json()) as unknown;
|
|
186
|
+
|
|
187
|
+
// 3. Handle structured payload with success flag
|
|
188
|
+
if (isActionResponse<T>(parsedBody)) {
|
|
189
|
+
if (!parsedBody.success) {
|
|
190
|
+
logger.error(
|
|
191
|
+
"API request failed with business error",
|
|
192
|
+
logContext,
|
|
193
|
+
parsedBody.message || parsedBody.error,
|
|
194
|
+
);
|
|
195
|
+
return {
|
|
196
|
+
success: false,
|
|
197
|
+
message: parsedBody.message || "La operación no se pudo completar.",
|
|
198
|
+
error: parsedBody.error,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
success: true,
|
|
204
|
+
message: parsedBody.message,
|
|
205
|
+
data: parsedBody.data,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// 4. Raw JSON response payload
|
|
210
|
+
return {
|
|
211
|
+
success: true,
|
|
212
|
+
data: parsedBody as T,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Universal wrapper for API calls in React and frontend applications.
|
|
218
|
+
*
|
|
219
|
+
* Features:
|
|
220
|
+
* - Polymorphic: seamlessly accepts Hono RPC responses, standard fetch responses, ActionResponses, or raw promises.
|
|
221
|
+
* - Strict Error-Only Logging: logs exclusively when errors occur (HTTP status != 2xx, business failure, or runtime crash).
|
|
222
|
+
* - Safe error message extraction with user-friendly Spanish fallbacks.
|
|
223
|
+
*
|
|
224
|
+
* @template T - Type of the success data payload returned by the action.
|
|
225
|
+
* @param options - Execution options including the API call, action name, and optional onSuccess callback.
|
|
226
|
+
* @returns Standard ActionResponse<T> with success status, message, and typed data/error details.
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* ```typescript
|
|
230
|
+
* const result = await apiAction<UserData>({
|
|
231
|
+
* actionName: "fetchUser",
|
|
232
|
+
* apiCall: () => api.get("/users/current"),
|
|
233
|
+
* onSuccess: (user) => setUser(user),
|
|
234
|
+
* });
|
|
235
|
+
*
|
|
236
|
+
* if (result.success) {
|
|
237
|
+
* console.log("User:", result.data);
|
|
238
|
+
* }
|
|
239
|
+
* ```
|
|
240
|
+
*/
|
|
241
|
+
export async function apiAction<T>(options: ApiActionOptions<T>): Promise<ActionResponse<T>> {
|
|
242
|
+
const { apiCall, onSuccess, actionName, logger = defaultErrorLogger } = options;
|
|
243
|
+
const logContext = { actionName };
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
const result = await apiCall();
|
|
247
|
+
|
|
248
|
+
let finalResponse: ActionResponse<T>;
|
|
249
|
+
|
|
250
|
+
if (isMinimalResponse(result)) {
|
|
251
|
+
finalResponse = await handleHttpResponse<T>(result, actionName, logger);
|
|
252
|
+
} else if (isActionResponse<T>(result)) {
|
|
253
|
+
if (!result.success) {
|
|
254
|
+
logger.error(
|
|
255
|
+
"Action returned failure status",
|
|
256
|
+
logContext,
|
|
257
|
+
result.message || result.error,
|
|
258
|
+
);
|
|
259
|
+
return {
|
|
260
|
+
success: false,
|
|
261
|
+
message: result.message || "La operación no se pudo completar.",
|
|
262
|
+
error: result.error,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
finalResponse = result;
|
|
266
|
+
} else {
|
|
267
|
+
finalResponse = {
|
|
268
|
+
success: true,
|
|
269
|
+
data: result,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (!finalResponse.success) {
|
|
274
|
+
return finalResponse;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (onSuccess && finalResponse.data !== undefined) {
|
|
278
|
+
await onSuccess(finalResponse.data);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return finalResponse;
|
|
282
|
+
} catch (error) {
|
|
283
|
+
logger.error("Unexpected crash during action execution", logContext, error);
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
success: false,
|
|
287
|
+
message: "Ocurrió un error inesperado al procesar la solicitud. Por favor, intenta de nuevo.",
|
|
288
|
+
error: error instanceof Error ? error.message : String(error),
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview User Feedback Toast Helper based on Sonner.
|
|
3
|
+
* Orquestates async actions and Server Actions providing automated loading,
|
|
4
|
+
* success, and error feedback toasts, returning the typed ActionResponse.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import { apiToast, toasted } from "@/lib/api-toast";
|
|
9
|
+
* import { loginAction } from "@/actions/auth";
|
|
10
|
+
*
|
|
11
|
+
* // Example in a React Form handler
|
|
12
|
+
* const handleSubmit = async (values: LoginFormValues) => {
|
|
13
|
+
* const res = await apiToast({
|
|
14
|
+
* action: () => loginAction(values),
|
|
15
|
+
* loadingMessage: "Verificando credenciales...",
|
|
16
|
+
* successMessage: (res) => `¡Bienvenido de nuevo, ${res.data?.name}!`,
|
|
17
|
+
* onSuccess: () => router.push("/dashboard"),
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* if (res.success) {
|
|
21
|
+
* // Action completed successfully
|
|
22
|
+
* }
|
|
23
|
+
* };
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { toast } from "sonner";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Standard response interface for Server Actions, API calls, and local procedures.
|
|
31
|
+
*
|
|
32
|
+
* @template T - Type of the success response data.
|
|
33
|
+
*/
|
|
34
|
+
export interface ActionResponse<T = unknown> {
|
|
35
|
+
success: boolean;
|
|
36
|
+
message?: string | unknown;
|
|
37
|
+
error?: string;
|
|
38
|
+
data?: T;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Options for configuring apiToast / toasted.
|
|
43
|
+
*
|
|
44
|
+
* @template T - Type of the data payload.
|
|
45
|
+
*/
|
|
46
|
+
export interface ApiToastOptions<T> {
|
|
47
|
+
/** The async function returning an ActionResponse to execute */
|
|
48
|
+
action: () => Promise<ActionResponse<T>>;
|
|
49
|
+
/** Message displayed while the action is in progress (default: "Procesando...") */
|
|
50
|
+
loadingMessage?: string;
|
|
51
|
+
/** Message shown on success. Can be a string or a callback taking the response */
|
|
52
|
+
successMessage?: string | ((res: ActionResponse<T>) => string);
|
|
53
|
+
/** Message shown on error. Can be a string or a callback taking the error object */
|
|
54
|
+
errorMessage?: string | ((error: Error) => string);
|
|
55
|
+
/** Callback triggered when the action succeeds */
|
|
56
|
+
onSuccess?: (res: ActionResponse<T>) => void | Promise<void>;
|
|
57
|
+
/** Callback triggered when the action fails */
|
|
58
|
+
onError?: (error: Error) => void | Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type ToastedOptions<T> = ApiToastOptions<T>;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Executes an async action with Sonner toast feedback for loading, success, and error states.
|
|
65
|
+
* Returns the final ActionResponse<T> directly to the caller.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```typescript
|
|
69
|
+
* const res = await apiToast({
|
|
70
|
+
* action: () => updateUserProfile(data),
|
|
71
|
+
* loadingMessage: "Actualizando datos...",
|
|
72
|
+
* successMessage: "Perfil guardado con éxito",
|
|
73
|
+
* onSuccess: (res) => console.log("Updated:", res.data),
|
|
74
|
+
* });
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* @template T - Type of the payload returned on success.
|
|
78
|
+
* @param options - Configuration options for feedback messages and callbacks.
|
|
79
|
+
* @returns The resolved ActionResponse<T>.
|
|
80
|
+
*/
|
|
81
|
+
export async function apiToast<T>(options: ApiToastOptions<T>): Promise<ActionResponse<T>> {
|
|
82
|
+
const {
|
|
83
|
+
action,
|
|
84
|
+
loadingMessage = "Procesando...",
|
|
85
|
+
successMessage,
|
|
86
|
+
errorMessage,
|
|
87
|
+
onSuccess,
|
|
88
|
+
onError,
|
|
89
|
+
} = options;
|
|
90
|
+
|
|
91
|
+
let capturedResponse: ActionResponse<T> | null = null;
|
|
92
|
+
|
|
93
|
+
const promise = (async (): Promise<ActionResponse<T>> => {
|
|
94
|
+
const res = await action();
|
|
95
|
+
capturedResponse = res;
|
|
96
|
+
|
|
97
|
+
if (!res.success) {
|
|
98
|
+
const errorMsg =
|
|
99
|
+
typeof res.message === "string"
|
|
100
|
+
? res.message
|
|
101
|
+
: res.error || "Ocurrió un error inesperado al procesar la solicitud.";
|
|
102
|
+
throw new Error(errorMsg);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (onSuccess) {
|
|
106
|
+
await onSuccess(res);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return res;
|
|
110
|
+
})();
|
|
111
|
+
|
|
112
|
+
toast.promise(promise, {
|
|
113
|
+
loading: loadingMessage,
|
|
114
|
+
success: (res) => {
|
|
115
|
+
if (typeof successMessage === "function") {
|
|
116
|
+
return successMessage(res);
|
|
117
|
+
}
|
|
118
|
+
if (successMessage) {
|
|
119
|
+
return successMessage;
|
|
120
|
+
}
|
|
121
|
+
return typeof res.message === "string"
|
|
122
|
+
? res.message
|
|
123
|
+
: "Operación completada con éxito.";
|
|
124
|
+
},
|
|
125
|
+
error: (err: unknown) => {
|
|
126
|
+
const errorObj = err instanceof Error ? err : new Error(String(err));
|
|
127
|
+
if (typeof errorMessage === "function") {
|
|
128
|
+
return errorMessage(errorObj);
|
|
129
|
+
}
|
|
130
|
+
if (errorMessage) {
|
|
131
|
+
return errorMessage;
|
|
132
|
+
}
|
|
133
|
+
return errorObj.message;
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const resolved = await promise;
|
|
139
|
+
return resolved;
|
|
140
|
+
} catch (error) {
|
|
141
|
+
const errorObj = error instanceof Error ? error : new Error(String(error));
|
|
142
|
+
if (onError) {
|
|
143
|
+
await onError(errorObj);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (capturedResponse) {
|
|
147
|
+
return capturedResponse;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
success: false,
|
|
152
|
+
message: errorObj.message,
|
|
153
|
+
error: errorObj.message,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Backward-compatible alias for apiToast (used across projects like socialiticos and vidriera).
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```typescript
|
|
163
|
+
* await toasted({
|
|
164
|
+
* action: () => deleteItemAction(id),
|
|
165
|
+
* loadingMessage: "Eliminando registro...",
|
|
166
|
+
* });
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export const toasted = apiToast;
|