@3lineas/groovepack 0.1.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +261 -138
  2. package/dist/action-response.type-XlzII9Lr.d.ts +11 -0
  3. package/dist/api-action/index.d.ts +44 -0
  4. package/dist/api-action/index.js +105 -0
  5. package/dist/api-action/index.js.map +1 -0
  6. package/dist/api-client/index.d.ts +46 -0
  7. package/dist/api-client/index.js +142 -0
  8. package/dist/api-client/index.js.map +1 -0
  9. package/dist/api-toast/index.d.ts +58 -0
  10. package/dist/api-toast/index.js +52 -0
  11. package/dist/api-toast/index.js.map +1 -0
  12. package/dist/batch-capable-db.type-Cyybxkjc.d.ts +8 -0
  13. package/dist/chunk-PDWE3D4J.js +130 -0
  14. package/dist/chunk-PDWE3D4J.js.map +1 -0
  15. package/dist/groovepack-locale.type-CaXo9vLj.d.ts +3 -0
  16. package/dist/i18n/index.d.ts +83 -0
  17. package/dist/i18n/index.js +17 -0
  18. package/dist/i18n/index.js.map +1 -0
  19. package/dist/logger/index.d.ts +19 -0
  20. package/dist/logger/index.js +92 -0
  21. package/dist/logger/index.js.map +1 -0
  22. package/dist/pipeline/pipeline.d.ts +41 -0
  23. package/dist/pipeline/pipeline.js +64 -0
  24. package/dist/pipeline/pipeline.js.map +1 -0
  25. package/dist/pipeline/with-d1-transaction.d.ts +16 -0
  26. package/dist/pipeline/with-d1-transaction.js +17 -0
  27. package/dist/pipeline/with-d1-transaction.js.map +1 -0
  28. package/package.json +55 -16
  29. package/dist/index.js +0 -468
  30. package/dist/index.js.map +0 -1
  31. package/registry/common/api-client/files/README.md.template +0 -64
  32. package/registry/common/api-client/files/index.ts.template +0 -296
  33. package/registry/common/logger/files/README.md.template +0 -55
  34. package/registry/common/logger/files/index.ts.template +0 -194
  35. package/registry/react/api-action/files/README.md.template +0 -61
  36. package/registry/react/api-action/files/index.ts.template +0 -291
  37. package/registry/react/api-toast/files/README.md.template +0 -51
  38. package/registry/react/api-toast/files/index.ts.template +0 -169
  39. package/registry/server/pipeline/files/README.md.template +0 -205
  40. package/registry/server/pipeline/files/pipeline.ts.template +0 -134
  41. package/registry/server/pipeline/files/types.ts.template +0 -35
  42. package/registry/server/pipeline/files/with-d1-transaction.ts.template +0 -50
package/dist/index.js DELETED
@@ -1,468 +0,0 @@
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
- sourcePath: "files/README.md.template",
44
- targetRelPath: "README.md"
45
- }
46
- ]
47
- },
48
- {
49
- id: "api-client",
50
- name: "API Client (REST & Hono RPC)",
51
- description: "Universal HTTP client: REST methods + optional Hono RPC factory with auth token injection",
52
- category: "common",
53
- templateRelativeDir: "common/api-client",
54
- defaultTarget: "src/lib/api-client",
55
- files: [
56
- {
57
- sourcePath: "files/index.ts.template",
58
- targetRelPath: "index.ts"
59
- },
60
- {
61
- sourcePath: "files/README.md.template",
62
- targetRelPath: "README.md"
63
- }
64
- ]
65
- },
66
- {
67
- id: "pipeline",
68
- name: "Pipeline (Laravel-style)",
69
- description: "Universal sequential pipeline with atomic batch transactions (Drizzle & Native D1 agnostic)",
70
- category: "server",
71
- templateRelativeDir: "server/pipeline",
72
- defaultTarget: "src/lib/pipeline",
73
- files: [
74
- {
75
- sourcePath: "files/pipeline.ts.template",
76
- targetRelPath: "pipeline.ts"
77
- },
78
- {
79
- sourcePath: "files/with-d1-transaction.ts.template",
80
- targetRelPath: "with-d1-transaction.ts"
81
- },
82
- {
83
- sourcePath: "files/types.ts.template",
84
- targetRelPath: "types.ts"
85
- },
86
- {
87
- sourcePath: "files/README.md.template",
88
- targetRelPath: "README.md"
89
- }
90
- ]
91
- },
92
- {
93
- id: "api-action",
94
- name: "API Action Wrapper",
95
- description: "Universal React action wrapper with optional Hono RPC support and error-only logging",
96
- category: "react",
97
- templateRelativeDir: "react/api-action",
98
- defaultTarget: "src/lib/api-action",
99
- files: [
100
- {
101
- sourcePath: "files/index.ts.template",
102
- targetRelPath: "index.ts"
103
- },
104
- {
105
- sourcePath: "files/README.md.template",
106
- targetRelPath: "README.md"
107
- }
108
- ]
109
- },
110
- {
111
- id: "api-toast",
112
- name: "API Toast (Sonner)",
113
- description: "Feedback helper (apiToast / toasted) for loading, success & error states with Sonner",
114
- category: "react",
115
- templateRelativeDir: "react/api-toast",
116
- defaultTarget: "src/lib/api-toast",
117
- files: [
118
- {
119
- sourcePath: "files/index.ts.template",
120
- targetRelPath: "index.ts"
121
- },
122
- {
123
- sourcePath: "files/README.md.template",
124
- targetRelPath: "README.md"
125
- }
126
- ]
127
- }
128
- ];
129
- function getLibrariesByCategory(category) {
130
- return REGISTRY_ITEMS.filter((item) => item.category === category);
131
- }
132
-
133
- // src/installer/install-library.ts
134
- import fs2 from "fs/promises";
135
- import path2 from "path";
136
- import { fileURLToPath } from "url";
137
-
138
- // src/installer/rollback-manager.ts
139
- import fs from "fs/promises";
140
- import path from "path";
141
- var RollbackManager = class {
142
- createdDirs = [];
143
- fileBackups = /* @__PURE__ */ new Map();
144
- /**
145
- * Records a directory that was created during this transaction.
146
- * Stored in creation order.
147
- */
148
- recordCreatedDirectory(dirPath) {
149
- const normalized = path.resolve(dirPath);
150
- if (!this.createdDirs.includes(normalized)) {
151
- this.createdDirs.push(normalized);
152
- }
153
- }
154
- /**
155
- * Snapshots the current state of a target file before overwriting/creating.
156
- */
157
- async backupTargetFile(filePath) {
158
- const normalized = path.resolve(filePath);
159
- if (this.fileBackups.has(normalized)) {
160
- return;
161
- }
162
- try {
163
- const stats = await fs.stat(normalized);
164
- if (stats.isFile()) {
165
- const content = await fs.readFile(normalized);
166
- this.fileBackups.set(normalized, {
167
- path: normalized,
168
- existedBefore: true,
169
- content
170
- });
171
- return;
172
- }
173
- } catch {
174
- this.fileBackups.set(normalized, {
175
- path: normalized,
176
- existedBefore: false
177
- });
178
- }
179
- }
180
- /**
181
- * Executes rollback:
182
- * 1. Restores files that existed before with their original content.
183
- * 2. Deletes newly created files.
184
- * 3. Deletes newly created directories in reverse order if they are empty.
185
- */
186
- async rollback() {
187
- const errors = [];
188
- for (const [filePath, backup] of this.fileBackups.entries()) {
189
- try {
190
- if (backup.existedBefore && backup.content !== void 0) {
191
- await fs.writeFile(filePath, backup.content);
192
- } else {
193
- await fs.rm(filePath, { force: true });
194
- }
195
- } catch (err) {
196
- errors.push(`Failed to revert file ${filePath}: ${String(err)}`);
197
- }
198
- }
199
- const reversedDirs = [...this.createdDirs].reverse();
200
- for (const dirPath of reversedDirs) {
201
- try {
202
- const entries = await fs.readdir(dirPath);
203
- if (entries.length === 0) {
204
- await fs.rmdir(dirPath);
205
- }
206
- } catch (err) {
207
- errors.push(`Failed to clean empty dir ${dirPath}: ${String(err)}`);
208
- }
209
- }
210
- return {
211
- success: errors.length === 0,
212
- errors
213
- };
214
- }
215
- };
216
-
217
- // src/installer/install-library.ts
218
- function resolveRegistryBaseDir(explicitBase) {
219
- if (explicitBase) {
220
- return explicitBase;
221
- }
222
- const currentFile = fileURLToPath(import.meta.url);
223
- const currentDir = path2.dirname(currentFile);
224
- const candidates = [
225
- path2.resolve(currentDir, "../registry"),
226
- path2.resolve(currentDir, "../../registry"),
227
- path2.resolve(process.cwd(), "registry")
228
- ];
229
- for (const candidate of candidates) {
230
- try {
231
- const stats = fs2.stat(candidate);
232
- return candidate;
233
- } catch {
234
- }
235
- }
236
- return candidates[0] ?? path2.resolve(process.cwd(), "registry");
237
- }
238
- async function ensureDirWithRollback(dirPath, rollbackManager) {
239
- const normalized = path2.resolve(dirPath);
240
- const segmentsToCreate = [];
241
- let current = normalized;
242
- while (current !== path2.dirname(current)) {
243
- try {
244
- await fs2.stat(current);
245
- break;
246
- } catch {
247
- segmentsToCreate.push(current);
248
- current = path2.dirname(current);
249
- }
250
- }
251
- for (const seg of segmentsToCreate.reverse()) {
252
- await fs2.mkdir(seg);
253
- rollbackManager.recordCreatedDirectory(seg);
254
- }
255
- }
256
- async function installLibrary(options) {
257
- const { item, targetDir, baseRegistryDir } = options;
258
- const rollbackManager = new RollbackManager();
259
- const filesWritten = [];
260
- const registryRoot = resolveRegistryBaseDir(baseRegistryDir);
261
- const templateDir = path2.resolve(registryRoot, item.templateRelativeDir);
262
- try {
263
- try {
264
- await fs2.stat(templateDir);
265
- } catch {
266
- throw new Error(`Template directory not found: ${templateDir}`);
267
- }
268
- await ensureDirWithRollback(targetDir, rollbackManager);
269
- for (const fileDesc of item.files) {
270
- const sourceFile = path2.resolve(templateDir, fileDesc.sourcePath);
271
- const destinationFile = path2.resolve(targetDir, fileDesc.targetRelPath);
272
- const destDir = path2.dirname(destinationFile);
273
- await ensureDirWithRollback(destDir, rollbackManager);
274
- await rollbackManager.backupTargetFile(destinationFile);
275
- const content = await fs2.readFile(sourceFile);
276
- await fs2.writeFile(destinationFile, content);
277
- filesWritten.push(destinationFile);
278
- }
279
- return {
280
- libraryId: item.id,
281
- libraryName: item.name,
282
- category: item.category,
283
- status: "installed",
284
- targetPath: targetDir,
285
- filesWritten
286
- };
287
- } catch (error) {
288
- const rollbackResult = await rollbackManager.rollback();
289
- return {
290
- libraryId: item.id,
291
- libraryName: item.name,
292
- category: item.category,
293
- status: "rolled_back",
294
- targetPath: targetDir,
295
- filesWritten: [],
296
- errorMessage: error instanceof Error ? error.message : String(error),
297
- rollbackSucceeded: rollbackResult.success
298
- };
299
- }
300
- }
301
-
302
- // src/cli/run-cli.ts
303
- async function hasExistingFiles(dirPath) {
304
- try {
305
- const entries = await fs3.readdir(dirPath);
306
- return entries.length > 0;
307
- } catch {
308
- return false;
309
- }
310
- }
311
- async function runCli() {
312
- p.intro(pc.bgCyan(pc.black(" @3lineas/groovepack ")));
313
- const categoryChoices = await p.multiselect({
314
- message: "Selecciona una o m\xE1s categor\xEDas de librer\xEDas:",
315
- options: CATEGORIES.map((c) => ({
316
- value: c.id,
317
- label: c.label,
318
- hint: c.hint
319
- })),
320
- required: true
321
- });
322
- if (p.isCancel(categoryChoices)) {
323
- p.cancel("Operaci\xF3n cancelada por el usuario.");
324
- process.exit(0);
325
- }
326
- const selectedCategories = categoryChoices;
327
- const selectedItems = [];
328
- for (const catId of selectedCategories) {
329
- const categoryMeta = CATEGORIES.find((c) => c.id === catId);
330
- const catLabel = categoryMeta ? categoryMeta.label : catId;
331
- const availableInCat = getLibrariesByCategory(catId);
332
- if (availableInCat.length === 0) {
333
- p.log.warn(`No hay librer\xEDas disponibles en la categor\xEDa "${catLabel}".`);
334
- continue;
335
- }
336
- const libChoices = await p.multiselect({
337
- message: `[${pc.cyan(catLabel)}] Selecciona las librer\xEDas a incorporar:`,
338
- options: availableInCat.map((item) => ({
339
- value: item.id,
340
- label: item.name,
341
- hint: item.description
342
- })),
343
- required: false
344
- });
345
- if (p.isCancel(libChoices)) {
346
- p.cancel("Operaci\xF3n cancelada por el usuario.");
347
- process.exit(0);
348
- }
349
- const pickedInCat = availableInCat.filter(
350
- (item) => libChoices.includes(item.id)
351
- );
352
- selectedItems.push(...pickedInCat);
353
- }
354
- if (selectedItems.length === 0) {
355
- p.outro(pc.yellow("No se seleccion\xF3 ninguna librer\xEDa para instalar."));
356
- return;
357
- }
358
- const configuredTargets = [];
359
- for (const item of selectedItems) {
360
- p.log.info(pc.bold(`Configurando: ${item.name} ${pc.dim(`[${item.category}]`)}`));
361
- const targetInput = await p.text({
362
- message: `Ruta de destino para "${item.name}":`,
363
- initialValue: item.defaultTarget,
364
- validate(val) {
365
- if (!val || val.trim().length === 0) {
366
- return "La ruta no puede estar vac\xEDa.";
367
- }
368
- return void 0;
369
- }
370
- });
371
- if (p.isCancel(targetInput)) {
372
- p.cancel("Operaci\xF3n cancelada.");
373
- process.exit(0);
374
- }
375
- const resolvedTarget = path3.resolve(process.cwd(), targetInput.trim());
376
- const exists = await hasExistingFiles(resolvedTarget);
377
- if (exists) {
378
- const confirmOverwrite = await p.confirm({
379
- message: `El directorio de destino ya contiene archivos. \xBFSobrescribir si hay coincidencias?`,
380
- initialValue: true
381
- });
382
- if (p.isCancel(confirmOverwrite)) {
383
- p.cancel("Operaci\xF3n cancelada.");
384
- process.exit(0);
385
- }
386
- if (!confirmOverwrite) {
387
- p.log.warn(`Se omitir\xE1 la instalaci\xF3n de "${item.name}".`);
388
- continue;
389
- }
390
- }
391
- configuredTargets.push({
392
- item,
393
- targetDir: resolvedTarget
394
- });
395
- }
396
- if (configuredTargets.length === 0) {
397
- p.outro(pc.yellow("No se seleccion\xF3 ninguna librer\xEDa para instalar."));
398
- return;
399
- }
400
- const results = [];
401
- const s = p.spinner();
402
- for (const config of configuredTargets) {
403
- s.start(`Instalando ${config.item.name}...`);
404
- try {
405
- const result = await installLibrary({
406
- item: config.item,
407
- targetDir: config.targetDir
408
- });
409
- results.push(result);
410
- if (result.status === "installed") {
411
- s.stop(pc.green(`\u2714 ${config.item.name} instalada exitosamente.`));
412
- } else {
413
- s.stop(
414
- pc.red(
415
- `\u2716 Error al instalar ${config.item.name}. Rollback autom\xE1tico completado.`
416
- )
417
- );
418
- p.log.error(
419
- `Causa: ${result.errorMessage || "Error desconocido"}
420
- Rollback status: ${result.rollbackSucceeded ? "Completado limpiamente" : "Con advertencias"}`
421
- );
422
- }
423
- } catch (unhandledError) {
424
- s.stop(pc.red(`\u2716 Fallo cr\xEDtico aislado en ${config.item.name}.`));
425
- p.log.error(String(unhandledError));
426
- results.push({
427
- libraryId: config.item.id,
428
- libraryName: config.item.name,
429
- category: config.item.category,
430
- status: "failed",
431
- targetPath: config.targetDir,
432
- filesWritten: [],
433
- errorMessage: String(unhandledError)
434
- });
435
- }
436
- }
437
- const summaryLines = results.map((r) => {
438
- const relTarget = path3.relative(process.cwd(), r.targetPath);
439
- if (r.status === "installed") {
440
- return `${pc.green("\u2714")} ${pc.bold(r.libraryName)} -> ${pc.cyan(relTarget)} (${r.filesWritten.length} archivos)`;
441
- }
442
- return `${pc.red("\u2716")} ${pc.bold(r.libraryName)} -> ${pc.red(`Fall\xF3 (${r.errorMessage || "Rollback"})`)}`;
443
- });
444
- p.note(summaryLines.join("\n"), "Resumen de Instalaci\xF3n");
445
- const successCount = results.filter((r) => r.status === "installed").length;
446
- if (successCount === results.length) {
447
- p.outro(pc.green("\xA1Todas las librer\xEDas se incorporaron con \xE9xito!"));
448
- } else {
449
- p.outro(
450
- pc.yellow(
451
- `Finalizado: ${successCount} instaladas correctamente, ${results.length - successCount} con fallos o revertidas.`
452
- )
453
- );
454
- }
455
- }
456
-
457
- // src/index.ts
458
- process.on("unhandledRejection", (reason) => {
459
- console.error("\n[groovepack] Advertencia de excepci\xF3n no capturada:", reason);
460
- });
461
- process.on("uncaughtException", (error) => {
462
- console.error("\n[groovepack] Error cr\xEDtico capturado para evitar cierre abrupto:", error.message);
463
- });
464
- runCli().catch((err) => {
465
- console.error("\n[groovepack] Error durante la ejecuci\xF3n del CLI:", err instanceof Error ? err.message : String(err));
466
- process.exitCode = 1;
467
- });
468
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
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: Select 1 or more categories (multiselect)\n const categoryChoices = await p.multiselect<string>({\n message: \"Selecciona una o más categorías de librerías:\",\n options: CATEGORIES.map((c) => ({\n value: c.id,\n label: c.label,\n hint: c.hint,\n })),\n required: true,\n });\n\n if (p.isCancel(categoryChoices)) {\n p.cancel(\"Operación cancelada por el usuario.\");\n process.exit(0);\n }\n\n const selectedCategories = categoryChoices as LibraryCategory[];\n\n // Step 2: Iterate over selected categories to pick libraries\n const selectedItems: RegistryItem[] = [];\n\n for (const catId of selectedCategories) {\n const categoryMeta = CATEGORIES.find((c) => c.id === catId);\n const catLabel = categoryMeta ? categoryMeta.label : catId;\n const availableInCat = getLibrariesByCategory(catId);\n\n if (availableInCat.length === 0) {\n p.log.warn(`No hay librerías disponibles en la categoría \"${catLabel}\".`);\n continue;\n }\n\n const libChoices = await p.multiselect<string>({\n message: `[${pc.cyan(catLabel)}] Selecciona las librerías a incorporar:`,\n options: availableInCat.map((item) => ({\n value: item.id,\n label: item.name,\n hint: item.description,\n })),\n required: false,\n });\n\n if (p.isCancel(libChoices)) {\n p.cancel(\"Operación cancelada por el usuario.\");\n process.exit(0);\n }\n\n const pickedInCat = availableInCat.filter((item) =>\n libChoices.includes(item.id),\n );\n\n selectedItems.push(...pickedInCat);\n }\n\n if (selectedItems.length === 0) {\n p.outro(pc.yellow(\"No se seleccionó ninguna librería para instalar.\"));\n return;\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} ${pc.dim(`[${item.category}]`)}`));\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 sourcePath: \"files/README.md.template\",\n targetRelPath: \"README.md\",\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 sourcePath: \"files/README.md.template\",\n targetRelPath: \"README.md\",\n },\n ],\n },\n {\n id: \"pipeline\",\n name: \"Pipeline (Laravel-style)\",\n description: \"Universal sequential pipeline with atomic batch transactions (Drizzle & Native D1 agnostic)\",\n category: \"server\",\n templateRelativeDir: \"server/pipeline\",\n defaultTarget: \"src/lib/pipeline\",\n files: [\n {\n sourcePath: \"files/pipeline.ts.template\",\n targetRelPath: \"pipeline.ts\",\n },\n {\n sourcePath: \"files/with-d1-transaction.ts.template\",\n targetRelPath: \"with-d1-transaction.ts\",\n },\n {\n sourcePath: \"files/types.ts.template\",\n targetRelPath: \"types.ts\",\n },\n {\n sourcePath: \"files/README.md.template\",\n targetRelPath: \"README.md\",\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 sourcePath: \"files/README.md.template\",\n targetRelPath: \"README.md\",\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 sourcePath: \"files/README.md.template\",\n targetRelPath: \"README.md\",\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,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACF;;;ACtBO,IAAM,iBAA0C;AAAA,EACrD;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,qBAAqB;AAAA,IACrB,eAAe;AAAA,IACf,OAAO;AAAA,MACL;AAAA,QACE,YAAY;AAAA,QACZ,eAAe;AAAA,MACjB;AAAA,MACA;AAAA,QACE,YAAY;AAAA,QACZ,eAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,qBAAqB;AAAA,IACrB,eAAe;AAAA,IACf,OAAO;AAAA,MACL;AAAA,QACE,YAAY;AAAA,QACZ,eAAe;AAAA,MACjB;AAAA,MACA;AAAA,QACE,YAAY;AAAA,QACZ,eAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,qBAAqB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AK,EAAE,WAAW,CAAC,OAAO,GAAG,IAAI,aAAU,EAAE,gBAAgB,UAAU,GAAG,CAAC;AAAA,EACzG,CAAC;AAED,EAAE,OAAK,aAAa,KAAK,IAAI,GAAG,2BAAwB;AAExD,QAAM,eAAe,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,EAAE;AACrE,MAAI,iBAAiB,QAAQ,QAAQ;AACnC,IAAE,QAAM,GAAG,MAAM,0DAAiD,CAAC;AAAA,EACrE,OAAO;AACL,IAAE;AAAA,MACA,GAAG;AAAA,QACD,eAAe,YAAY,8BAA8B,QAAQ,SAAS,YAAY;AAAA,MACxF;AAAA,IACF;AAAA,EACF;AACF;;;AK/MA,QAAQ,GAAG,sBAAsB,CAAC,WAAW;AAC3C,UAAQ,MAAM,4DAAyD,MAAM;AAC/E,CAAC;AAED,QAAQ,GAAG,qBAAqB,CAAC,UAAU;AACzC,UAAQ,MAAM,yEAAsE,MAAM,OAAO;AACnG,CAAC;AAED,OAAO,EAAE,MAAM,CAAC,QAAQ;AACtB,UAAQ,MAAM,yDAAsD,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AACpH,UAAQ,WAAW;AACrB,CAAC;","names":["fs","path","fs","path","path","fs","fs","path"]}
@@ -1,64 +0,0 @@
1
- # 🌐 Universal API Client (`src/lib/api-client`)
2
-
3
- > **Universal REST HTTP client & Hono RPC factory with automatic Bearer token injection and BigInt-safe serialization.**
4
-
5
- ---
6
-
7
- ## 📖 How to Use
8
-
9
- ### A. REST Client
10
-
11
- ```typescript
12
- import { createApiClient } from "@/lib/api-client";
13
-
14
- export const api = createApiClient({
15
- baseUrl: "https://api.example.com",
16
- getToken: () => localStorage.getItem("auth_token"),
17
- });
18
-
19
- // GET request
20
- const response = await api.get("/users/me");
21
- const data = await response.json();
22
-
23
- // POST request with automatic JSON serialization
24
- const createRes = await api.post("/users", { name: "Alice", email: "alice@example.com" });
25
- ```
26
-
27
- ### B. Strongly-Typed Hono RPC Client
28
-
29
- ```typescript
30
- import { createHonoClient } from "@/lib/api-client";
31
- import type { AppType } from "api";
32
-
33
- export const rpc = createHonoClient<AppType>({
34
- baseUrl: "http://localhost:8787",
35
- getToken: () => localStorage.getItem("auth_token"),
36
- });
37
-
38
- // Full end-to-end typed route autocomplete
39
- const res = await rpc.v1.products.$get();
40
- ```
41
-
42
- ---
43
-
44
- ## 📥 Inputs & Outputs
45
-
46
- ### Configuration: `ApiClientConfig`
47
- - **`baseUrl`** (`string`, optional): Base URL for API requests. Defaults to empty string in browser or `http://localhost:8787` in dev.
48
- - **`getToken`** (`() => string | Promise<string>`, optional): Dynamic token resolver callback.
49
- - **`headers`** (`Record<string, string>`, optional): Static or dynamic custom headers.
50
- - **`fetch`** (`typeof fetch`, optional): Custom fetch implementation (e.g. for testing, SSR, or Cloudflare Service Bindings).
51
-
52
- ### Methods
53
- - `api.get(path, init)` / `api.post(path, body, init)` / `api.put` / `api.patch` / `api.delete` / `api.fetch`
54
- - Returns: `Promise<Response>` standard Fetch API response.
55
-
56
- ---
57
-
58
- ## ⚠️ Possible Errors & Troubleshooting
59
-
60
- | Issue / Error | Cause | Solution |
61
- | :--- | :--- | :--- |
62
- | **`Authorization` header missing** | `getToken()` returned `null`/`undefined` or was omitted. | Ensure your authentication store sets the token or pass a custom `getToken` resolver in `ApiClientConfig`. |
63
- | **`ReferenceError: window is not defined` (SSR / Edge)** | Accessing `getStoredToken()` in a server runtime. | Do not use browser `localStorage` in SSR. Pass tokens via cookies or HTTP headers. |
64
- | **`Content-Type: application/json` overriding `FormData`** | Sending files or multipart data with manual JSON header. | `createApiClient` automatically skips JSON content-type if `body` is `FormData` or `URLSearchParams`. |