@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 CHANGED
@@ -1,3 +1,168 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # 📦 GroovePack (`@3lineas/groovepack`)
4
+
5
+ **A modern, zero-dependency source code registry CLI for high-performance TypeScript & React applications.**
6
+
7
+ Inspired by the `shadcn` philosophy: **don't install heavy, unmaintainable dependencies—copy battle-tested, strictly typed, adaptable source modules directly into your project.**
8
+
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
10
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue?logo=typescript)](https://www.typescriptlang.org/)
11
+ [![CLI](https://img.shields.io/badge/CLI-@clack%2Fprompts-cyan)](https://github.com/natemoo-re/clack)
12
+ [![Turborepo-free](https://img.shields.io/badge/Monorepo-Independent-green)](#)
13
+
14
+ </div>
15
+
16
+ ---
17
+
18
+ ## 🚀 Quick Start
19
+
20
+ Run the interactive CLI directly without installing anything globally:
21
+
22
+ ```bash
23
+ npx @3lineas/groovepack
24
+ ```
25
+
26
+ GroovePack will guide you through:
27
+ 1. **Selecting a Domain Category** (`Common`, `React`, `Hono / Next Server`, or `Browse all`).
28
+ 2. **Selecting Libraries** via an interactive multi-select prompt.
29
+ 3. **Choosing the Destination Path** (defaults to `src/lib/<lib>`).
30
+ 4. **Copying the Source Code** cleanly with transactional rollback guarantees.
31
+
32
+ ---
33
+
34
+ ## 💡 Why GroovePack?
35
+
36
+ Traditional npm packages often introduce:
37
+ - Dependency bloat and version conflicts across monorepos.
38
+ - Opaque abstractions that are difficult to customize for specific backend requirements.
39
+ - Overhead in CI/CD pipelines.
40
+
41
+ **GroovePack provides:**
42
+ - **Zero Package Bloat**: Code lives in your repo (`src/lib/...`). You own it, customize it, and debug it with standard breakpoints.
43
+ - **Enterprise-Grade Typing**: 100% strict TypeScript without `any` or loose casts.
44
+ - **Transactional Rollback (Zero-Crash Policy)**: If disk writing, permissions, or I/O encounters an issue, GroovePack restores prior files and cleans newly created folders automatically without terminating the process.
45
+ - **Universal Runtime Compatibility**: Node.js, Cloudflare Workers, Next.js (SSR / RSC), Astro Actions, and React Vite SPAs.
46
+
47
+ ---
48
+
49
+ ## 📚 Registry Catalog
50
+
51
+ ### 1. `common`
52
+
53
+ #### 🪵 `logger`
54
+ Universal structured logger designed for seamless local development and production observability.
55
+ - **Local Development**: Human-readable ANSI color-coded terminal output with `[file:line]` context tracing.
56
+ - **Production / Cloudflare Workers**: Fast, structured JSON serialization compatible with log aggregators (Datadog, Cloudflare Logpush, Axiom).
57
+ - **Default Target**: `src/lib/logger`
58
+
59
+ ```typescript
60
+ import { Logger } from "@/lib/logger";
61
+
62
+ const logger = new Logger("AuthService");
63
+
64
+ logger.info("User registered successfully", { userId: "usr_101" });
65
+ logger.warn("Rate limit approaching", { ip: "192.168.1.1" });
66
+ logger.error("Database connection failure", { pool: "primary" }, error);
67
+ ```
68
+
69
+ #### 🌐 `api-client`
70
+ Hybrid universal HTTP client featuring REST convenience methods, dynamic authentication header injection, and optional Hono RPC integration.
71
+ - **REST Client**: Typed `get`, `post`, `put`, `patch`, `delete`, and `fetch` with BigInt-safe JSON serialization.
72
+ - **Authentication**: Dynamic bearer token resolver (browser `localStorage`, cookies, or custom async `getToken()` callback).
73
+ - **Hono RPC Factory**: Exported `createHonoClient<AppType>()` helper to instantiate `hc<AppType>` with shared base URL and auth headers.
74
+ - **Default Target**: `src/lib/api-client`
75
+
76
+ ```typescript
77
+ import { createApiClient, createHonoClient } from "@/lib/api-client";
78
+ import type { AppType } from "api";
79
+
80
+ // 1. REST Client
81
+ export const api = createApiClient({
82
+ baseUrl: "https://api.example.com",
83
+ getToken: () => localStorage.getItem("token"),
84
+ });
85
+
86
+ const res = await api.get("/users/me");
87
+
88
+ // 2. Hono RPC Client (Optional)
89
+ export const rpc = createHonoClient<AppType>({
90
+ baseUrl: "http://localhost:8787",
91
+ });
92
+ const productRes = await rpc.v1.products.$get();
93
+ ```
94
+
95
+ ---
96
+
97
+ ### 2. `react`
98
+
99
+ #### ⚡ `api-action`
100
+ Universal async operation and API wrapper for React components, Server Actions, and custom hooks.
101
+ - **Polymorphic Compatibility**: Natively accepts Hono RPC responses, standard `fetch` (`Response`), structured `ActionResponse<T>`, or raw promises.
102
+ - **Strict Error-Only Logging**: Only logs on actual failures (`!response.ok`, `!result.success`, or unexpected runtime crashes). Does not pollute console logs on successful operations.
103
+ - **Default Target**: `src/lib/api-action`
104
+
105
+ ```typescript
106
+ import { apiAction } from "@/lib/api-action";
107
+ import { api } from "@/lib/api-client";
108
+
109
+ export async function fetchCustomersAction() {
110
+ return apiAction<Customer[]>({
111
+ actionName: "fetchCustomers",
112
+ apiCall: () => api.get("/customers"),
113
+ onSuccess: (customers) => {
114
+ console.log(`Loaded ${customers.length} customers`);
115
+ },
116
+ });
117
+ }
118
+ ```
119
+
120
+ #### 🔔 `api-toast`
121
+ User feedback utility built on top of `sonner` (`toast.promise`).
122
+ - **Tri-State Feedback**: Automates `loading`, `success`, and `error` toasts for any `apiAction` or async procedure.
123
+ - **Typed Return**: Directly returns the underlying `Promise<ActionResponse<T>>` for component state inspection.
124
+ - **Full Backward Compatibility**: Exports both `apiToast` and `toasted` aliases.
125
+ - **Default Target**: `src/lib/api-toast`
126
+
127
+ ```typescript
128
+ import { apiToast } from "@/lib/api-toast";
129
+ import { loginAction } from "@/actions/auth";
130
+
131
+ const handleSubmit = async (values: LoginFormValues) => {
132
+ const result = await apiToast({
133
+ action: () => loginAction(values),
134
+ loadingMessage: "Authenticating credentials...",
135
+ successMessage: (res) => `Welcome back, ${res.data?.name}!`,
136
+ onSuccess: () => router.push("/dashboard"),
137
+ onError: (err) => console.error("Login failed:", err),
138
+ });
139
+
140
+ if (result.success) {
141
+ // Form submission complete
142
+ }
143
+ };
144
+ ```
145
+
146
+ ---
147
+
148
+ ### 3. `server`
149
+ Reserved domain for backend adapters, micro-middleware pipelines, and Cloudflare Worker / Next.js server helpers.
150
+
151
+ ---
152
+
153
+ ## 🛡️ Fault Tolerance & Atomic Rollbacks
154
+
155
+ When installing libraries, GroovePack uses an internal `RollbackManager` that:
156
+ 1. Tracks all filesystem operations and directories created during the transaction.
157
+ 2. Backs up pre-existing destination files in memory before applying changes.
158
+ 3. If an error occurs (such as permission denials, path errors, or disk write failures):
159
+ - Restores original file contents.
160
+ - Removes newly written files.
161
+ - Cleans up empty directory segments.
162
+ - Reports the exact failure cause in the terminal **without crashing or interrupting the installation of other selected packages**.
163
+
164
+ ---
165
+
166
+ ## 📄 License
167
+
168
+ MIT © [3-Lineas](https://github.com/3-Lineas)
package/dist/index.js ADDED
@@ -0,0 +1,434 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/run-cli.ts
4
+ import fs3 from "fs/promises";
5
+ import path3 from "path";
6
+ import * as p from "@clack/prompts";
7
+ import pc from "picocolors";
8
+
9
+ // src/constants/categories.constants.ts
10
+ var CATEGORIES = [
11
+ {
12
+ id: "common",
13
+ label: "Common",
14
+ hint: "Universal agnostic utilities (Logger, formatters, pure helpers)"
15
+ },
16
+ {
17
+ id: "server",
18
+ label: "Hono / Next Server",
19
+ hint: "Backend adapters, API wrappers, RPC handlers & server errors"
20
+ },
21
+ {
22
+ id: "react",
23
+ label: "React",
24
+ hint: "Client hooks, UI wrappers, notifications & island state"
25
+ }
26
+ ];
27
+
28
+ // src/registry/registry-catalog.ts
29
+ var REGISTRY_ITEMS = [
30
+ {
31
+ id: "logger",
32
+ name: "Logger",
33
+ description: "Universal structured logger: ANSI colors in dev, JSON for Cloudflare Workers & Serverless",
34
+ category: "common",
35
+ templateRelativeDir: "common/logger",
36
+ defaultTarget: "src/lib/logger",
37
+ files: [
38
+ {
39
+ sourcePath: "files/index.ts.template",
40
+ targetRelPath: "index.ts"
41
+ }
42
+ ]
43
+ },
44
+ {
45
+ id: "api-client",
46
+ name: "API Client (REST & Hono RPC)",
47
+ description: "Universal HTTP client: REST methods + optional Hono RPC factory with auth token injection",
48
+ category: "common",
49
+ templateRelativeDir: "common/api-client",
50
+ defaultTarget: "src/lib/api-client",
51
+ files: [
52
+ {
53
+ sourcePath: "files/index.ts.template",
54
+ targetRelPath: "index.ts"
55
+ }
56
+ ]
57
+ },
58
+ {
59
+ id: "api-action",
60
+ name: "API Action Wrapper",
61
+ description: "Universal React action wrapper with optional Hono RPC support and error-only logging",
62
+ category: "react",
63
+ templateRelativeDir: "react/api-action",
64
+ defaultTarget: "src/lib/api-action",
65
+ files: [
66
+ {
67
+ sourcePath: "files/index.ts.template",
68
+ targetRelPath: "index.ts"
69
+ }
70
+ ]
71
+ },
72
+ {
73
+ id: "api-toast",
74
+ name: "API Toast (Sonner)",
75
+ description: "Feedback helper (apiToast / toasted) for loading, success & error states with Sonner",
76
+ category: "react",
77
+ templateRelativeDir: "react/api-toast",
78
+ defaultTarget: "src/lib/api-toast",
79
+ files: [
80
+ {
81
+ sourcePath: "files/index.ts.template",
82
+ targetRelPath: "index.ts"
83
+ }
84
+ ]
85
+ }
86
+ ];
87
+ function getLibrariesByCategory(category) {
88
+ return REGISTRY_ITEMS.filter((item) => item.category === category);
89
+ }
90
+
91
+ // src/installer/install-library.ts
92
+ import fs2 from "fs/promises";
93
+ import path2 from "path";
94
+ import { fileURLToPath } from "url";
95
+
96
+ // src/installer/rollback-manager.ts
97
+ import fs from "fs/promises";
98
+ import path from "path";
99
+ var RollbackManager = class {
100
+ createdDirs = [];
101
+ fileBackups = /* @__PURE__ */ new Map();
102
+ /**
103
+ * Records a directory that was created during this transaction.
104
+ * Stored in creation order.
105
+ */
106
+ recordCreatedDirectory(dirPath) {
107
+ const normalized = path.resolve(dirPath);
108
+ if (!this.createdDirs.includes(normalized)) {
109
+ this.createdDirs.push(normalized);
110
+ }
111
+ }
112
+ /**
113
+ * Snapshots the current state of a target file before overwriting/creating.
114
+ */
115
+ async backupTargetFile(filePath) {
116
+ const normalized = path.resolve(filePath);
117
+ if (this.fileBackups.has(normalized)) {
118
+ return;
119
+ }
120
+ try {
121
+ const stats = await fs.stat(normalized);
122
+ if (stats.isFile()) {
123
+ const content = await fs.readFile(normalized);
124
+ this.fileBackups.set(normalized, {
125
+ path: normalized,
126
+ existedBefore: true,
127
+ content
128
+ });
129
+ return;
130
+ }
131
+ } catch {
132
+ this.fileBackups.set(normalized, {
133
+ path: normalized,
134
+ existedBefore: false
135
+ });
136
+ }
137
+ }
138
+ /**
139
+ * Executes rollback:
140
+ * 1. Restores files that existed before with their original content.
141
+ * 2. Deletes newly created files.
142
+ * 3. Deletes newly created directories in reverse order if they are empty.
143
+ */
144
+ async rollback() {
145
+ const errors = [];
146
+ for (const [filePath, backup] of this.fileBackups.entries()) {
147
+ try {
148
+ if (backup.existedBefore && backup.content !== void 0) {
149
+ await fs.writeFile(filePath, backup.content);
150
+ } else {
151
+ await fs.rm(filePath, { force: true });
152
+ }
153
+ } catch (err) {
154
+ errors.push(`Failed to revert file ${filePath}: ${String(err)}`);
155
+ }
156
+ }
157
+ const reversedDirs = [...this.createdDirs].reverse();
158
+ for (const dirPath of reversedDirs) {
159
+ try {
160
+ const entries = await fs.readdir(dirPath);
161
+ if (entries.length === 0) {
162
+ await fs.rmdir(dirPath);
163
+ }
164
+ } catch (err) {
165
+ errors.push(`Failed to clean empty dir ${dirPath}: ${String(err)}`);
166
+ }
167
+ }
168
+ return {
169
+ success: errors.length === 0,
170
+ errors
171
+ };
172
+ }
173
+ };
174
+
175
+ // src/installer/install-library.ts
176
+ function resolveRegistryBaseDir(explicitBase) {
177
+ if (explicitBase) {
178
+ return explicitBase;
179
+ }
180
+ const currentFile = fileURLToPath(import.meta.url);
181
+ const currentDir = path2.dirname(currentFile);
182
+ const candidates = [
183
+ path2.resolve(currentDir, "../registry"),
184
+ path2.resolve(currentDir, "../../registry"),
185
+ path2.resolve(process.cwd(), "registry")
186
+ ];
187
+ for (const candidate of candidates) {
188
+ try {
189
+ const stats = fs2.stat(candidate);
190
+ return candidate;
191
+ } catch {
192
+ }
193
+ }
194
+ return candidates[0] ?? path2.resolve(process.cwd(), "registry");
195
+ }
196
+ async function ensureDirWithRollback(dirPath, rollbackManager) {
197
+ const normalized = path2.resolve(dirPath);
198
+ const segmentsToCreate = [];
199
+ let current = normalized;
200
+ while (current !== path2.dirname(current)) {
201
+ try {
202
+ await fs2.stat(current);
203
+ break;
204
+ } catch {
205
+ segmentsToCreate.push(current);
206
+ current = path2.dirname(current);
207
+ }
208
+ }
209
+ for (const seg of segmentsToCreate.reverse()) {
210
+ await fs2.mkdir(seg);
211
+ rollbackManager.recordCreatedDirectory(seg);
212
+ }
213
+ }
214
+ async function installLibrary(options) {
215
+ const { item, targetDir, baseRegistryDir } = options;
216
+ const rollbackManager = new RollbackManager();
217
+ const filesWritten = [];
218
+ const registryRoot = resolveRegistryBaseDir(baseRegistryDir);
219
+ const templateDir = path2.resolve(registryRoot, item.templateRelativeDir);
220
+ try {
221
+ try {
222
+ await fs2.stat(templateDir);
223
+ } catch {
224
+ throw new Error(`Template directory not found: ${templateDir}`);
225
+ }
226
+ await ensureDirWithRollback(targetDir, rollbackManager);
227
+ for (const fileDesc of item.files) {
228
+ const sourceFile = path2.resolve(templateDir, fileDesc.sourcePath);
229
+ const destinationFile = path2.resolve(targetDir, fileDesc.targetRelPath);
230
+ const destDir = path2.dirname(destinationFile);
231
+ await ensureDirWithRollback(destDir, rollbackManager);
232
+ await rollbackManager.backupTargetFile(destinationFile);
233
+ const content = await fs2.readFile(sourceFile);
234
+ await fs2.writeFile(destinationFile, content);
235
+ filesWritten.push(destinationFile);
236
+ }
237
+ return {
238
+ libraryId: item.id,
239
+ libraryName: item.name,
240
+ category: item.category,
241
+ status: "installed",
242
+ targetPath: targetDir,
243
+ filesWritten
244
+ };
245
+ } catch (error) {
246
+ const rollbackResult = await rollbackManager.rollback();
247
+ return {
248
+ libraryId: item.id,
249
+ libraryName: item.name,
250
+ category: item.category,
251
+ status: "rolled_back",
252
+ targetPath: targetDir,
253
+ filesWritten: [],
254
+ errorMessage: error instanceof Error ? error.message : String(error),
255
+ rollbackSucceeded: rollbackResult.success
256
+ };
257
+ }
258
+ }
259
+
260
+ // src/cli/run-cli.ts
261
+ async function hasExistingFiles(dirPath) {
262
+ try {
263
+ const entries = await fs3.readdir(dirPath);
264
+ return entries.length > 0;
265
+ } catch {
266
+ return false;
267
+ }
268
+ }
269
+ async function runCli() {
270
+ p.intro(pc.bgCyan(pc.black(" @3lineas/groovepack ")));
271
+ let selectedCategory = null;
272
+ let itemsToPresent = [];
273
+ while (true) {
274
+ const categoryChoice = await p.select({
275
+ message: "Selecciona una categor\xEDa de librer\xEDas:",
276
+ options: [
277
+ ...CATEGORIES.map((c) => ({
278
+ value: c.id,
279
+ label: c.label,
280
+ hint: c.hint
281
+ })),
282
+ {
283
+ value: "all",
284
+ label: "Ver todas agrupadas",
285
+ hint: "Muestra todo el cat\xE1logo disponible en Groovepack"
286
+ }
287
+ ]
288
+ });
289
+ if (p.isCancel(categoryChoice)) {
290
+ p.cancel("Operaci\xF3n cancelada por el usuario.");
291
+ process.exit(0);
292
+ }
293
+ selectedCategory = categoryChoice;
294
+ if (selectedCategory === "all") {
295
+ itemsToPresent = [...REGISTRY_ITEMS];
296
+ break;
297
+ }
298
+ const filtered = getLibrariesByCategory(selectedCategory);
299
+ if (filtered.length === 0) {
300
+ p.log.warn(
301
+ `A\xFAn no hay librer\xEDas disponibles en la categor\xEDa "${selectedCategory}". Selecciona otra categor\xEDa.`
302
+ );
303
+ continue;
304
+ }
305
+ itemsToPresent = filtered;
306
+ break;
307
+ }
308
+ const libraryChoices = await p.multiselect({
309
+ message: "Selecciona las librer\xEDas a incorporar:",
310
+ options: itemsToPresent.map((item) => ({
311
+ value: item.id,
312
+ label: item.name,
313
+ hint: `${pc.cyan(`[${item.category}]`)} ${item.description}`
314
+ })),
315
+ required: true
316
+ });
317
+ if (p.isCancel(libraryChoices)) {
318
+ p.cancel("Operaci\xF3n cancelada.");
319
+ process.exit(0);
320
+ }
321
+ const selectedItems = itemsToPresent.filter(
322
+ (item) => libraryChoices.includes(item.id)
323
+ );
324
+ const configuredTargets = [];
325
+ for (const item of selectedItems) {
326
+ p.log.info(pc.bold(`Configurando: ${item.name}`));
327
+ const targetInput = await p.text({
328
+ message: `Ruta de destino para "${item.name}":`,
329
+ initialValue: item.defaultTarget,
330
+ validate(val) {
331
+ if (!val || val.trim().length === 0) {
332
+ return "La ruta no puede estar vac\xEDa.";
333
+ }
334
+ return void 0;
335
+ }
336
+ });
337
+ if (p.isCancel(targetInput)) {
338
+ p.cancel("Operaci\xF3n cancelada.");
339
+ process.exit(0);
340
+ }
341
+ const resolvedTarget = path3.resolve(process.cwd(), targetInput.trim());
342
+ const exists = await hasExistingFiles(resolvedTarget);
343
+ if (exists) {
344
+ const confirmOverwrite = await p.confirm({
345
+ message: `El directorio de destino ya contiene archivos. \xBFSobrescribir si hay coincidencias?`,
346
+ initialValue: true
347
+ });
348
+ if (p.isCancel(confirmOverwrite)) {
349
+ p.cancel("Operaci\xF3n cancelada.");
350
+ process.exit(0);
351
+ }
352
+ if (!confirmOverwrite) {
353
+ p.log.warn(`Se omitir\xE1 la instalaci\xF3n de "${item.name}".`);
354
+ continue;
355
+ }
356
+ }
357
+ configuredTargets.push({
358
+ item,
359
+ targetDir: resolvedTarget
360
+ });
361
+ }
362
+ if (configuredTargets.length === 0) {
363
+ p.outro(pc.yellow("No se seleccion\xF3 ninguna librer\xEDa para instalar."));
364
+ return;
365
+ }
366
+ const results = [];
367
+ const s = p.spinner();
368
+ for (const config of configuredTargets) {
369
+ s.start(`Instalando ${config.item.name}...`);
370
+ try {
371
+ const result = await installLibrary({
372
+ item: config.item,
373
+ targetDir: config.targetDir
374
+ });
375
+ results.push(result);
376
+ if (result.status === "installed") {
377
+ s.stop(pc.green(`\u2714 ${config.item.name} instalada exitosamente.`));
378
+ } else {
379
+ s.stop(
380
+ pc.red(
381
+ `\u2716 Error al instalar ${config.item.name}. Rollback autom\xE1tico completado.`
382
+ )
383
+ );
384
+ p.log.error(
385
+ `Causa: ${result.errorMessage || "Error desconocido"}
386
+ Rollback status: ${result.rollbackSucceeded ? "Completado limpiamente" : "Con advertencias"}`
387
+ );
388
+ }
389
+ } catch (unhandledError) {
390
+ s.stop(pc.red(`\u2716 Fallo cr\xEDtico aislado en ${config.item.name}.`));
391
+ p.log.error(String(unhandledError));
392
+ results.push({
393
+ libraryId: config.item.id,
394
+ libraryName: config.item.name,
395
+ category: config.item.category,
396
+ status: "failed",
397
+ targetPath: config.targetDir,
398
+ filesWritten: [],
399
+ errorMessage: String(unhandledError)
400
+ });
401
+ }
402
+ }
403
+ const summaryLines = results.map((r) => {
404
+ const relTarget = path3.relative(process.cwd(), r.targetPath);
405
+ if (r.status === "installed") {
406
+ return `${pc.green("\u2714")} ${pc.bold(r.libraryName)} -> ${pc.cyan(relTarget)} (${r.filesWritten.length} archivos)`;
407
+ }
408
+ return `${pc.red("\u2716")} ${pc.bold(r.libraryName)} -> ${pc.red(`Fall\xF3 (${r.errorMessage || "Rollback"})`)}`;
409
+ });
410
+ p.note(summaryLines.join("\n"), "Resumen de Instalaci\xF3n");
411
+ const successCount = results.filter((r) => r.status === "installed").length;
412
+ if (successCount === results.length) {
413
+ p.outro(pc.green("\xA1Todas las librer\xEDas se incorporaron con \xE9xito!"));
414
+ } else {
415
+ p.outro(
416
+ pc.yellow(
417
+ `Finalizado: ${successCount} instaladas correctamente, ${results.length - successCount} con fallos o revertidas.`
418
+ )
419
+ );
420
+ }
421
+ }
422
+
423
+ // src/index.ts
424
+ process.on("unhandledRejection", (reason) => {
425
+ console.error("\n[groovepack] Advertencia de excepci\xF3n no capturada:", reason);
426
+ });
427
+ process.on("uncaughtException", (error) => {
428
+ console.error("\n[groovepack] Error cr\xEDtico capturado para evitar cierre abrupto:", error.message);
429
+ });
430
+ runCli().catch((err) => {
431
+ console.error("\n[groovepack] Error durante la ejecuci\xF3n del CLI:", err instanceof Error ? err.message : String(err));
432
+ process.exitCode = 1;
433
+ });
434
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/run-cli.ts","../src/constants/categories.constants.ts","../src/registry/registry-catalog.ts","../src/installer/install-library.ts","../src/installer/rollback-manager.ts","../src/index.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { CATEGORIES } from \"../constants/categories.constants.js\";\nimport {\n REGISTRY_ITEMS,\n getLibrariesByCategory,\n} from \"../registry/registry-catalog.js\";\nimport { installLibrary } from \"../installer/install-library.js\";\nimport type {\n LibraryCategory,\n RegistryItem,\n InstallOperationResult,\n} from \"../types/registry.types.js\";\n\n/**\n * Checks if target directory already has files that would conflict.\n */\nasync function hasExistingFiles(dirPath: string): Promise<boolean> {\n try {\n const entries = await fs.readdir(dirPath);\n return entries.length > 0;\n } catch {\n return false;\n }\n}\n\nexport async function runCli(): Promise<void> {\n p.intro(pc.bgCyan(pc.black(\" @3lineas/groovepack \")));\n\n // Step 1: Category selection loop\n let selectedCategory: LibraryCategory | \"all\" | null = null;\n let itemsToPresent: RegistryItem[] = [];\n\n while (true) {\n const categoryChoice = await p.select<string>({\n message: \"Selecciona una categoría de librerías:\",\n options: [\n ...CATEGORIES.map((c) => ({\n value: c.id,\n label: c.label,\n hint: c.hint,\n })),\n {\n value: \"all\",\n label: \"Ver todas agrupadas\",\n hint: \"Muestra todo el catálogo disponible en Groovepack\",\n },\n ],\n });\n\n if (p.isCancel(categoryChoice)) {\n p.cancel(\"Operación cancelada por el usuario.\");\n process.exit(0);\n }\n\n selectedCategory = categoryChoice as LibraryCategory | \"all\";\n\n if (selectedCategory === \"all\") {\n itemsToPresent = [...REGISTRY_ITEMS];\n break;\n }\n\n const filtered = getLibrariesByCategory(selectedCategory);\n if (filtered.length === 0) {\n p.log.warn(\n `Aún no hay librerías disponibles en la categoría \"${selectedCategory}\". Selecciona otra categoría.`,\n );\n continue;\n }\n\n itemsToPresent = filtered;\n break;\n }\n\n // Step 2: Multi-select libraries\n const libraryChoices = await p.multiselect<string>({\n message: \"Selecciona las librerías a incorporar:\",\n options: itemsToPresent.map((item) => ({\n value: item.id,\n label: item.name,\n hint: `${pc.cyan(`[${item.category}]`)} ${item.description}`,\n })),\n required: true,\n });\n\n if (p.isCancel(libraryChoices)) {\n p.cancel(\"Operación cancelada.\");\n process.exit(0);\n }\n\n const selectedItems = itemsToPresent.filter((item) =>\n libraryChoices.includes(item.id),\n );\n\n // Step 3: Configure destination per library\n const configuredTargets: Array<{\n item: RegistryItem;\n targetDir: string;\n }> = [];\n\n for (const item of selectedItems) {\n p.log.info(pc.bold(`Configurando: ${item.name}`));\n\n const targetInput = await p.text({\n message: `Ruta de destino para \"${item.name}\":`,\n initialValue: item.defaultTarget,\n validate(val) {\n if (!val || val.trim().length === 0) {\n return \"La ruta no puede estar vacía.\";\n }\n return undefined;\n },\n });\n\n if (p.isCancel(targetInput)) {\n p.cancel(\"Operación cancelada.\");\n process.exit(0);\n }\n\n const resolvedTarget = path.resolve(process.cwd(), targetInput.trim());\n\n // Check if files exist and ask confirmation\n const exists = await hasExistingFiles(resolvedTarget);\n if (exists) {\n const confirmOverwrite = await p.confirm({\n message: `El directorio de destino ya contiene archivos. ¿Sobrescribir si hay coincidencias?`,\n initialValue: true,\n });\n\n if (p.isCancel(confirmOverwrite)) {\n p.cancel(\"Operación cancelada.\");\n process.exit(0);\n }\n\n if (!confirmOverwrite) {\n p.log.warn(`Se omitirá la instalación de \"${item.name}\".`);\n continue;\n }\n }\n\n configuredTargets.push({\n item,\n targetDir: resolvedTarget,\n });\n }\n\n if (configuredTargets.length === 0) {\n p.outro(pc.yellow(\"No se seleccionó ninguna librería para instalar.\"));\n return;\n }\n\n // Step 4: Installation loop with spinner and isolated rollback (zero crash)\n const results: InstallOperationResult[] = [];\n const s = p.spinner();\n\n for (const config of configuredTargets) {\n s.start(`Instalando ${config.item.name}...`);\n\n try {\n const result = await installLibrary({\n item: config.item,\n targetDir: config.targetDir,\n });\n\n results.push(result);\n\n if (result.status === \"installed\") {\n s.stop(pc.green(`✔ ${config.item.name} instalada exitosamente.`));\n } else {\n s.stop(\n pc.red(\n `✖ Error al instalar ${config.item.name}. Rollback automático completado.`,\n ),\n );\n p.log.error(\n `Causa: ${result.errorMessage || \"Error desconocido\"}\\nRollback status: ${result.rollbackSucceeded ? \"Completado limpiamente\" : \"Con advertencias\"}`,\n );\n }\n } catch (unhandledError) {\n // Defensive fallback to prevent any unhandled crash\n s.stop(pc.red(`✖ Fallo crítico aislado en ${config.item.name}.`));\n p.log.error(String(unhandledError));\n results.push({\n libraryId: config.item.id,\n libraryName: config.item.name,\n category: config.item.category,\n status: \"failed\",\n targetPath: config.targetDir,\n filesWritten: [],\n errorMessage: String(unhandledError),\n });\n }\n }\n\n // Step 5: Summary Note\n const summaryLines = results.map((r) => {\n const relTarget = path.relative(process.cwd(), r.targetPath);\n if (r.status === \"installed\") {\n return `${pc.green(\"✔\")} ${pc.bold(r.libraryName)} -> ${pc.cyan(relTarget)} (${r.filesWritten.length} archivos)`;\n }\n return `${pc.red(\"✖\")} ${pc.bold(r.libraryName)} -> ${pc.red(`Falló (${r.errorMessage || \"Rollback\"})`)}`;\n });\n\n p.note(summaryLines.join(\"\\n\"), \"Resumen de Instalación\");\n\n const successCount = results.filter((r) => r.status === \"installed\").length;\n if (successCount === results.length) {\n p.outro(pc.green(\"¡Todas las librerías se incorporaron con éxito!\"));\n } else {\n p.outro(\n pc.yellow(\n `Finalizado: ${successCount} instaladas correctamente, ${results.length - successCount} con fallos o revertidas.`,\n ),\n );\n }\n}\n","import type { LibraryCategory } from \"../types/registry.types.js\";\n\nexport interface CategoryMetadata {\n id: LibraryCategory;\n label: string;\n hint: string;\n}\n\nexport const CATEGORIES: readonly CategoryMetadata[] = [\n {\n id: \"common\",\n label: \"Common\",\n hint: \"Universal agnostic utilities (Logger, formatters, pure helpers)\",\n },\n {\n id: \"server\",\n label: \"Hono / Next Server\",\n hint: \"Backend adapters, API wrappers, RPC handlers & server errors\",\n },\n {\n id: \"react\",\n label: \"React\",\n hint: \"Client hooks, UI wrappers, notifications & island state\",\n },\n] as const;\n","import type { RegistryItem, LibraryCategory } from \"../types/registry.types.js\";\n\nexport const REGISTRY_ITEMS: readonly RegistryItem[] = [\n {\n id: \"logger\",\n name: \"Logger\",\n description: \"Universal structured logger: ANSI colors in dev, JSON for Cloudflare Workers & Serverless\",\n category: \"common\",\n templateRelativeDir: \"common/logger\",\n defaultTarget: \"src/lib/logger\",\n files: [\n {\n sourcePath: \"files/index.ts.template\",\n targetRelPath: \"index.ts\",\n },\n ],\n },\n {\n id: \"api-client\",\n name: \"API Client (REST & Hono RPC)\",\n description: \"Universal HTTP client: REST methods + optional Hono RPC factory with auth token injection\",\n category: \"common\",\n templateRelativeDir: \"common/api-client\",\n defaultTarget: \"src/lib/api-client\",\n files: [\n {\n sourcePath: \"files/index.ts.template\",\n targetRelPath: \"index.ts\",\n },\n ],\n },\n {\n id: \"api-action\",\n name: \"API Action Wrapper\",\n description: \"Universal React action wrapper with optional Hono RPC support and error-only logging\",\n category: \"react\",\n templateRelativeDir: \"react/api-action\",\n defaultTarget: \"src/lib/api-action\",\n files: [\n {\n sourcePath: \"files/index.ts.template\",\n targetRelPath: \"index.ts\",\n },\n ],\n },\n {\n id: \"api-toast\",\n name: \"API Toast (Sonner)\",\n description: \"Feedback helper (apiToast / toasted) for loading, success & error states with Sonner\",\n category: \"react\",\n templateRelativeDir: \"react/api-toast\",\n defaultTarget: \"src/lib/api-toast\",\n files: [\n {\n sourcePath: \"files/index.ts.template\",\n targetRelPath: \"index.ts\",\n },\n ],\n },\n] as const;\n\nexport function getLibrariesByCategory(category: LibraryCategory): RegistryItem[] {\n return REGISTRY_ITEMS.filter((item) => item.category === category);\n}\n\nexport function getLibraryById(id: string): RegistryItem | undefined {\n return REGISTRY_ITEMS.find((item) => item.id === id);\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { RollbackManager } from \"./rollback-manager.js\";\nimport type {\n RegistryItem,\n InstallOperationResult,\n} from \"../types/registry.types.js\";\n\nexport interface InstallOptions {\n item: RegistryItem;\n targetDir: string;\n baseRegistryDir?: string;\n}\n\n/**\n * Finds the base registry directory either in development or compiled mode.\n */\nexport function resolveRegistryBaseDir(explicitBase?: string): string {\n if (explicitBase) {\n return explicitBase;\n }\n const currentFile = fileURLToPath(import.meta.url);\n const currentDir = path.dirname(currentFile);\n\n const candidates = [\n path.resolve(currentDir, \"../registry\"),\n path.resolve(currentDir, \"../../registry\"),\n path.resolve(process.cwd(), \"registry\"),\n ];\n\n for (const candidate of candidates) {\n try {\n const stats = fs.stat(candidate);\n return candidate;\n } catch {\n // Continue searching\n }\n }\n\n return candidates[0] ?? path.resolve(process.cwd(), \"registry\");\n}\n\n/**\n * Ensures a directory and all parent segments exist while tracking newly created segments in RollbackManager.\n */\nasync function ensureDirWithRollback(\n dirPath: string,\n rollbackManager: RollbackManager,\n): Promise<void> {\n const normalized = path.resolve(dirPath);\n const segmentsToCreate: string[] = [];\n\n let current = normalized;\n while (current !== path.dirname(current)) {\n try {\n await fs.stat(current);\n break;\n } catch {\n segmentsToCreate.push(current);\n current = path.dirname(current);\n }\n }\n\n for (const seg of segmentsToCreate.reverse()) {\n await fs.mkdir(seg);\n rollbackManager.recordCreatedDirectory(seg);\n }\n}\n\n/**\n * Installs a library into the target directory with transactional rollback support.\n */\nexport async function installLibrary(\n options: InstallOptions,\n): Promise<InstallOperationResult> {\n const { item, targetDir, baseRegistryDir } = options;\n const rollbackManager = new RollbackManager();\n const filesWritten: string[] = [];\n\n const registryRoot = resolveRegistryBaseDir(baseRegistryDir);\n const templateDir = path.resolve(registryRoot, item.templateRelativeDir);\n\n try {\n // 1. Validate template directory exists\n try {\n await fs.stat(templateDir);\n } catch {\n throw new Error(`Template directory not found: ${templateDir}`);\n }\n\n // 2. Ensure base target directory exists\n await ensureDirWithRollback(targetDir, rollbackManager);\n\n // 3. Process each file\n for (const fileDesc of item.files) {\n const sourceFile = path.resolve(templateDir, fileDesc.sourcePath);\n const destinationFile = path.resolve(targetDir, fileDesc.targetRelPath);\n const destDir = path.dirname(destinationFile);\n\n // Ensure subdirectory exists if nested\n await ensureDirWithRollback(destDir, rollbackManager);\n\n // Snapshot target file for rollback\n await rollbackManager.backupTargetFile(destinationFile);\n\n // Read source file content\n const content = await fs.readFile(sourceFile);\n\n // Write destination file\n await fs.writeFile(destinationFile, content);\n filesWritten.push(destinationFile);\n }\n\n return {\n libraryId: item.id,\n libraryName: item.name,\n category: item.category,\n status: \"installed\",\n targetPath: targetDir,\n filesWritten,\n };\n } catch (error) {\n const rollbackResult = await rollbackManager.rollback();\n return {\n libraryId: item.id,\n libraryName: item.name,\n category: item.category,\n status: \"rolled_back\",\n targetPath: targetDir,\n filesWritten: [],\n errorMessage: error instanceof Error ? error.message : String(error),\n rollbackSucceeded: rollbackResult.success,\n };\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\ninterface OriginalFileBackup {\n path: string;\n existedBefore: boolean;\n content?: Buffer;\n}\n\n/**\n * Manages atomic filesystem operations and guarantees rollback on failures.\n * Records directories created and file snapshots before writing.\n */\nexport class RollbackManager {\n private createdDirs: string[] = [];\n private fileBackups: Map<string, OriginalFileBackup> = new Map();\n\n /**\n * Records a directory that was created during this transaction.\n * Stored in creation order.\n */\n recordCreatedDirectory(dirPath: string): void {\n const normalized = path.resolve(dirPath);\n if (!this.createdDirs.includes(normalized)) {\n this.createdDirs.push(normalized);\n }\n }\n\n /**\n * Snapshots the current state of a target file before overwriting/creating.\n */\n async backupTargetFile(filePath: string): Promise<void> {\n const normalized = path.resolve(filePath);\n if (this.fileBackups.has(normalized)) {\n return;\n }\n\n try {\n const stats = await fs.stat(normalized);\n if (stats.isFile()) {\n const content = await fs.readFile(normalized);\n this.fileBackups.set(normalized, {\n path: normalized,\n existedBefore: true,\n content,\n });\n return;\n }\n } catch {\n // File does not exist prior to this transaction\n this.fileBackups.set(normalized, {\n path: normalized,\n existedBefore: false,\n });\n }\n }\n\n /**\n * Executes rollback:\n * 1. Restores files that existed before with their original content.\n * 2. Deletes newly created files.\n * 3. Deletes newly created directories in reverse order if they are empty.\n */\n async rollback(): Promise<{ success: boolean; errors: string[] }> {\n const errors: string[] = [];\n\n // 1 & 2. Revert files\n for (const [filePath, backup] of this.fileBackups.entries()) {\n try {\n if (backup.existedBefore && backup.content !== undefined) {\n await fs.writeFile(filePath, backup.content);\n } else {\n await fs.rm(filePath, { force: true });\n }\n } catch (err) {\n errors.push(`Failed to revert file ${filePath}: ${String(err)}`);\n }\n }\n\n // 3. Revert created directories in reverse order (deepest first)\n const reversedDirs = [...this.createdDirs].reverse();\n for (const dirPath of reversedDirs) {\n try {\n const entries = await fs.readdir(dirPath);\n if (entries.length === 0) {\n await fs.rmdir(dirPath);\n }\n } catch (err) {\n errors.push(`Failed to clean empty dir ${dirPath}: ${String(err)}`);\n }\n }\n\n return {\n success: errors.length === 0,\n errors,\n };\n }\n}\n","import { runCli } from \"./cli/run-cli.js\";\n\n// Top-level crash guard\nprocess.on(\"unhandledRejection\", (reason) => {\n console.error(\"\\n[groovepack] Advertencia de excepción no capturada:\", reason);\n});\n\nprocess.on(\"uncaughtException\", (error) => {\n console.error(\"\\n[groovepack] Error crítico capturado para evitar cierre abrupto:\", error.message);\n});\n\nrunCli().catch((err) => {\n console.error(\"\\n[groovepack] Error durante la ejecución del CLI:\", err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n});\n"],"mappings":";;;AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,YAAY,OAAO;AACnB,OAAO,QAAQ;;;ACKR,IAAM,aAA0C;AAAA,EACrD;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,EAC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