@3lineas/groovepack 0.1.1 → 0.1.4
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 +37 -1
- package/dist/index.js +82 -48
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/registry/common/api-client/files/README.md.template +64 -0
- package/registry/common/logger/files/README.md.template +55 -0
- package/registry/common/logger/files/index.ts.template +14 -3
- package/registry/react/api-action/files/README.md.template +61 -0
- package/registry/react/api-toast/files/README.md.template +51 -0
- package/registry/server/pipeline/files/README.md.template +205 -0
- package/registry/server/pipeline/files/pipeline.ts.template +134 -0
- package/registry/server/pipeline/files/types.ts.template +35 -0
- package/registry/server/pipeline/files/with-d1-transaction.ts.template +50 -0
package/README.md
CHANGED
|
@@ -146,7 +146,43 @@ const handleSubmit = async (values: LoginFormValues) => {
|
|
|
146
146
|
---
|
|
147
147
|
|
|
148
148
|
### 3. `server`
|
|
149
|
-
|
|
149
|
+
|
|
150
|
+
#### 🚀 `pipeline`
|
|
151
|
+
Laravel-style sequential execution pipeline with preventive in-memory rollback and atomic Cloudflare D1 batching.
|
|
152
|
+
- **Drizzle & D1 Agnostic**: Works seamlessly with native Cloudflare D1 (`env.DB` / `D1PreparedStatement`), Drizzle ORM (`drizzle(env.DB)`), or pure in-memory business logic.
|
|
153
|
+
- **Strict Zero-Barrel Architecture**: Concrete modular files (`pipeline.ts`, `with-d1-transaction.ts`, `types.ts`, `README.md`) designed for direct imports.
|
|
154
|
+
- **Preventive Rollback**: If any action throws an error (e.g. domain exception), the pipeline stops immediately and zero mutations hit D1.
|
|
155
|
+
- **Atomic Batch Commit**: Staged statements (`tx.stage(...)`) are committed in a single atomic `db.batch()` call upon completion.
|
|
156
|
+
- **Default Target**: `src/lib/pipeline`
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
160
|
+
import type { D1TransactionContext } from "@/lib/pipeline/types";
|
|
161
|
+
|
|
162
|
+
// 1. Native Cloudflare D1 (env.DB)
|
|
163
|
+
const result = await Pipeline.send<UserContext>({ db: env.DB, input })
|
|
164
|
+
.transactional(env.DB)
|
|
165
|
+
.through([
|
|
166
|
+
async (ctx) => {
|
|
167
|
+
// Immediate read
|
|
168
|
+
const existing = await ctx.tx!.db.prepare("SELECT id FROM users WHERE email = ?").bind(ctx.input.email).first();
|
|
169
|
+
if (existing) throw new Error("Email already registered");
|
|
170
|
+
|
|
171
|
+
// Stage atomic mutation
|
|
172
|
+
ctx.tx!.stage(
|
|
173
|
+
ctx.tx!.db.prepare("INSERT INTO users (id, email) VALUES (?, ?)").bind(newId, ctx.input.email)
|
|
174
|
+
);
|
|
175
|
+
return ctx;
|
|
176
|
+
}
|
|
177
|
+
])
|
|
178
|
+
.thenReturn();
|
|
179
|
+
|
|
180
|
+
// 2. Drizzle ORM on D1
|
|
181
|
+
const res = await Pipeline.send<UserContext>({ db, input })
|
|
182
|
+
.transactional(db)
|
|
183
|
+
.through([validateEmailAction, stageCreateUserAction])
|
|
184
|
+
.then((ctx) => ctx.createdUser!);
|
|
185
|
+
```
|
|
150
186
|
|
|
151
187
|
---
|
|
152
188
|
|
package/dist/index.js
CHANGED
|
@@ -38,6 +38,10 @@ var REGISTRY_ITEMS = [
|
|
|
38
38
|
{
|
|
39
39
|
sourcePath: "files/index.ts.template",
|
|
40
40
|
targetRelPath: "index.ts"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
sourcePath: "files/README.md.template",
|
|
44
|
+
targetRelPath: "README.md"
|
|
41
45
|
}
|
|
42
46
|
]
|
|
43
47
|
},
|
|
@@ -52,6 +56,36 @@ var REGISTRY_ITEMS = [
|
|
|
52
56
|
{
|
|
53
57
|
sourcePath: "files/index.ts.template",
|
|
54
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"
|
|
55
89
|
}
|
|
56
90
|
]
|
|
57
91
|
},
|
|
@@ -66,6 +100,10 @@ var REGISTRY_ITEMS = [
|
|
|
66
100
|
{
|
|
67
101
|
sourcePath: "files/index.ts.template",
|
|
68
102
|
targetRelPath: "index.ts"
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
sourcePath: "files/README.md.template",
|
|
106
|
+
targetRelPath: "README.md"
|
|
69
107
|
}
|
|
70
108
|
]
|
|
71
109
|
},
|
|
@@ -80,6 +118,10 @@ var REGISTRY_ITEMS = [
|
|
|
80
118
|
{
|
|
81
119
|
sourcePath: "files/index.ts.template",
|
|
82
120
|
targetRelPath: "index.ts"
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
sourcePath: "files/README.md.template",
|
|
124
|
+
targetRelPath: "README.md"
|
|
83
125
|
}
|
|
84
126
|
]
|
|
85
127
|
}
|
|
@@ -268,62 +310,54 @@ async function hasExistingFiles(dirPath) {
|
|
|
268
310
|
}
|
|
269
311
|
async function runCli() {
|
|
270
312
|
p.intro(pc.bgCyan(pc.black(" @3lineas/groovepack ")));
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
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
|
|
288
344
|
});
|
|
289
|
-
if (p.isCancel(
|
|
345
|
+
if (p.isCancel(libChoices)) {
|
|
290
346
|
p.cancel("Operaci\xF3n cancelada por el usuario.");
|
|
291
347
|
process.exit(0);
|
|
292
348
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
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;
|
|
349
|
+
const pickedInCat = availableInCat.filter(
|
|
350
|
+
(item) => libChoices.includes(item.id)
|
|
351
|
+
);
|
|
352
|
+
selectedItems.push(...pickedInCat);
|
|
307
353
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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);
|
|
354
|
+
if (selectedItems.length === 0) {
|
|
355
|
+
p.outro(pc.yellow("No se seleccion\xF3 ninguna librer\xEDa para instalar."));
|
|
356
|
+
return;
|
|
320
357
|
}
|
|
321
|
-
const selectedItems = itemsToPresent.filter(
|
|
322
|
-
(item) => libraryChoices.includes(item.id)
|
|
323
|
-
);
|
|
324
358
|
const configuredTargets = [];
|
|
325
359
|
for (const item of selectedItems) {
|
|
326
|
-
p.log.info(pc.bold(`Configurando: ${item.name}`));
|
|
360
|
+
p.log.info(pc.bold(`Configurando: ${item.name} ${pc.dim(`[${item.category}]`)}`));
|
|
327
361
|
const targetInput = await p.text({
|
|
328
362
|
message: `Ruta de destino para "${item.name}":`,
|
|
329
363
|
initialValue: item.defaultTarget,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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,EACR;AAAA,EACA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K,EAAE,WAAW,CAAC,OAAO,GAAG,KAAK,SAAS,CAAC,KAAK,EAAE,aAAa,MAAM;AAAA,IACtG;AACA,WAAO,GAAG,GAAG,IAAI,QAAG,CAAC,IAAI,GAAG,KAAK,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;;;AKtNA,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
|
+
{"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,SA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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"]}
|
package/package.json
CHANGED
|
@@ -0,0 +1,64 @@
|
|
|
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`. |
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# 🪵 Structured Logger (`src/lib/logger`)
|
|
2
|
+
|
|
3
|
+
> **Universal, zero-dependency structured logger for Node.js, Cloudflare Workers, Next.js, and Browsers.**
|
|
4
|
+
> Human-readable ANSI color-coded formatting in development; structured JSON in production and edge runtimes.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 📖 How to Use
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
import { Logger } from "@/lib/logger";
|
|
12
|
+
|
|
13
|
+
// 1. Create a logger instance for your service or domain
|
|
14
|
+
const logger = new Logger("AuthService");
|
|
15
|
+
|
|
16
|
+
// 2. Log informational events with metadata
|
|
17
|
+
logger.info("User registered successfully", {
|
|
18
|
+
file: "auth.service.ts",
|
|
19
|
+
line: 42,
|
|
20
|
+
userId: "usr_123",
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// 3. Log warnings for non-fatal business flow anomalies
|
|
24
|
+
logger.warn("Rate limit threshold reached", { ip: "192.168.1.1" });
|
|
25
|
+
|
|
26
|
+
// 4. Log critical errors with caught exceptions
|
|
27
|
+
try {
|
|
28
|
+
await db.insert(user);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
logger.error("Failed to persist user", { file: "auth.service.ts", line: 55 }, error);
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## 📥 Inputs & Outputs
|
|
37
|
+
|
|
38
|
+
### Constructor: `new Logger(serviceName: string)`
|
|
39
|
+
- **`serviceName`**: Identifies the module or domain in log outputs (e.g. `"API:Auth"`, `"POS:Checkout"`).
|
|
40
|
+
|
|
41
|
+
### Methods: `logger.debug`, `logger.info`, `logger.warn`, `logger.error`
|
|
42
|
+
- **`message`** (`string`): Main description of the event.
|
|
43
|
+
- **`context`** (`LogContext`, optional): Key-value metadata object (e.g. `{ file, line, customerId }`).
|
|
44
|
+
- **`...args`** (`unknown[]`, optional): Extra parameters, raw objects, or caught `Error` instances.
|
|
45
|
+
- **Return Value**: `void`.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## ⚠️ Possible Errors & Troubleshooting
|
|
50
|
+
|
|
51
|
+
| Issue / Error | Cause | Solution |
|
|
52
|
+
| :--- | :--- | :--- |
|
|
53
|
+
| **`Cannot find name 'process'` (TS2580)** | Outdated logger templates referencing raw `process`. | GroovePack's logger uses safe `globalThis` detection; ensure your template is up-to-date. |
|
|
54
|
+
| **Logs printed as raw JSON during local development** | `NODE_ENV` is not set to `"development"` or `"test"`. | Ensure your dev script sets `NODE_ENV=development` or relies on default local runner flags. |
|
|
55
|
+
| **Circular reference in log context (`TypeError: Converting circular structure to JSON`)** | Passing a DOM node, active socket, or recursive object in `context` or `args`. | Pass plain serializable DTOs or extract specific properties before passing to the logger. |
|
|
@@ -65,15 +65,26 @@ export class Logger {
|
|
|
65
65
|
|
|
66
66
|
/**
|
|
67
67
|
* Evaluates if the current execution is running in development mode.
|
|
68
|
+
* Safe across Node.js, Cloudflare Workers, Edge runtimes, and browsers
|
|
69
|
+
* without requiring @types/node in the consumer project.
|
|
68
70
|
* @returns true if running in development or testing, false otherwise.
|
|
69
71
|
*/
|
|
70
72
|
private checkIsDev(): boolean {
|
|
71
|
-
|
|
73
|
+
const globalEnv = (
|
|
74
|
+
globalThis as unknown as {
|
|
75
|
+
process?: {
|
|
76
|
+
env?: Record<string, string | undefined>;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
).process?.env;
|
|
80
|
+
|
|
81
|
+
if (globalEnv?.NODE_ENV) {
|
|
72
82
|
return (
|
|
73
|
-
|
|
74
|
-
|
|
83
|
+
globalEnv.NODE_ENV === "development" ||
|
|
84
|
+
globalEnv.NODE_ENV === "test"
|
|
75
85
|
);
|
|
76
86
|
}
|
|
87
|
+
|
|
77
88
|
return true; // Fallback to dev if we can't determine
|
|
78
89
|
}
|
|
79
90
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# ⚡ API Action Wrapper (`src/lib/api-action`)
|
|
2
|
+
|
|
3
|
+
> **Universal React action wrapper for Server Actions, React hooks, and mutations with strict error-only logging.**
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 📖 How to Use
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { apiAction } from "@/lib/api-action";
|
|
11
|
+
import { api } from "@/lib/api-client";
|
|
12
|
+
|
|
13
|
+
// Wrapping a REST call
|
|
14
|
+
export async function getCustomersAction() {
|
|
15
|
+
return apiAction<Customer[]>({
|
|
16
|
+
actionName: "getCustomers",
|
|
17
|
+
apiCall: () => api.get("/customers"),
|
|
18
|
+
onSuccess: (customers) => {
|
|
19
|
+
console.log(`Loaded ${customers.length} customers`);
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Handling in a React component
|
|
25
|
+
const res = await getCustomersAction();
|
|
26
|
+
if (res.success) {
|
|
27
|
+
console.log("Data:", res.data);
|
|
28
|
+
} else {
|
|
29
|
+
console.error("Error:", res.error);
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 📥 Inputs & Outputs
|
|
36
|
+
|
|
37
|
+
### Parameters: `ApiActionOptions<T>`
|
|
38
|
+
- **`actionName`** (`string`, required): Contextual identifier used for targeted error logging.
|
|
39
|
+
- **`apiCall`** (`() => Promise<ApiCallResult<T>>`, required): Async function returning a Fetch `Response`, Hono RPC response, or `ActionResponse<T>`.
|
|
40
|
+
- **`onSuccess`** (`(data: T) => void | Promise<void>`, optional): Callback executed exclusively on successful operations.
|
|
41
|
+
- **`logger`** (`ErrorLogger`, optional): Custom logger implementing `.error()`. Defaults to ANSI colored console error.
|
|
42
|
+
|
|
43
|
+
### Return Value: `Promise<ActionResponse<T>>`
|
|
44
|
+
```typescript
|
|
45
|
+
interface ActionResponse<T> {
|
|
46
|
+
success: boolean;
|
|
47
|
+
data?: T;
|
|
48
|
+
message?: string | unknown;
|
|
49
|
+
error?: string;
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## ⚠️ Possible Errors & Troubleshooting
|
|
56
|
+
|
|
57
|
+
| Issue / Error | Cause | Solution |
|
|
58
|
+
| :--- | :--- | :--- |
|
|
59
|
+
| **`success: false` on HTTP 200** | Backend responded with a JSON body having `{ success: false }`. | `apiAction` automatically extracts business error messages from backend responses. |
|
|
60
|
+
| **No logs appearing in console on success** | By design: `apiAction` follows the **Error-Only Logging** rule. | Normal successful requests do not pollute client or server logs. Only HTTP != 2xx or crashes are logged. |
|
|
61
|
+
| **Type `T` not matching response payload** | Discrepancy between TypeScript generic and API JSON structure. | Verify your backend return type or inspect the raw response shape. |
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# 🍞 API Toast Helper (`src/lib/api-toast`)
|
|
2
|
+
|
|
3
|
+
> **Automated user feedback toasts based on Sonner for React forms, mutations, and Server Actions.**
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 📖 How to Use
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { apiToast, toasted } from "@/lib/api-toast";
|
|
11
|
+
import { updateUserProfile } from "@/actions/users";
|
|
12
|
+
|
|
13
|
+
const handleSubmit = async (values: ProfileFormValues) => {
|
|
14
|
+
const res = await apiToast({
|
|
15
|
+
action: () => updateUserProfile(values),
|
|
16
|
+
loadingMessage: "Saving changes...",
|
|
17
|
+
successMessage: (res) => `Profile updated for ${res.data?.name}!`,
|
|
18
|
+
errorMessage: (err) => `Could not save profile: ${err.message}`,
|
|
19
|
+
onSuccess: () => router.push("/profile"),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
if (res.success) {
|
|
23
|
+
// Operation succeeded
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 📥 Inputs & Outputs
|
|
31
|
+
|
|
32
|
+
### Parameters: `ApiToastOptions<T>`
|
|
33
|
+
- **`action`** (`() => Promise<ActionResponse<T>>`, required): Function returning an `ActionResponse`.
|
|
34
|
+
- **`loadingMessage`** (`string`, optional): Message shown during execution (default: `"Procesando..."`).
|
|
35
|
+
- **`successMessage`** (`string | ((res: ActionResponse<T>) => string)`, optional): Custom success text.
|
|
36
|
+
- **`errorMessage`** (`string | ((error: Error) => string)`, optional): Custom error text.
|
|
37
|
+
- **`onSuccess`** (`(res: ActionResponse<T>) => void | Promise<void>`, optional): Success callback.
|
|
38
|
+
- **`onError`** (`(error: Error) => void | Promise<void>`, optional): Failure callback.
|
|
39
|
+
|
|
40
|
+
### Return Value: `Promise<ActionResponse<T>>`
|
|
41
|
+
Returns the original `ActionResponse<T>` directly to the caller.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## ⚠️ Possible Errors & Troubleshooting
|
|
46
|
+
|
|
47
|
+
| Issue / Error | Cause | Solution |
|
|
48
|
+
| :--- | :--- | :--- |
|
|
49
|
+
| **No toasts appearing on screen** | Sonner `<Toaster />` component not mounted in React root layout. | Add `<Toaster />` from `sonner` in your root layout (`app/layout.tsx` or `App.tsx`). |
|
|
50
|
+
| **Toast stays in loading state forever** | Action promise never resolves or rejects. | Ensure the wrapped async function completes and does not hang on unhandled network calls. |
|
|
51
|
+
| **Action fails but success toast appears** | The wrapped action returned `{ success: true }` despite a failure. | Ensure your backend/action sets `success: false` when an error occurs. |
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# 🚀 Pipeline Pattern (`src/lib/pipeline`)
|
|
2
|
+
|
|
3
|
+
> **Laravel-style sequential pipeline with atomic batch transactions for Cloudflare D1 & SQLite.**
|
|
4
|
+
> 100% agnostic to **Drizzle ORM** and **Native Cloudflare D1 (`D1Database`)**.
|
|
5
|
+
> **Strict Direct Imports Rule**: No barrel files (`index.ts`). Import directly from each file.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 📖 Direct Imports Guide
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
// ✅ Correct (Direct imports)
|
|
13
|
+
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
14
|
+
import { withD1Transaction } from "@/lib/pipeline/with-d1-transaction";
|
|
15
|
+
import type { PipeAction, D1TransactionContext } from "@/lib/pipeline/types";
|
|
16
|
+
|
|
17
|
+
// ❌ Prohibited (No barrel files allowed)
|
|
18
|
+
// import { Pipeline } from "@/lib/pipeline";
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## 📖 Table of Contents
|
|
24
|
+
1. [Core Concepts](#1-core-concepts)
|
|
25
|
+
2. [How to Use](#2-how-to-use)
|
|
26
|
+
- [A. Native Cloudflare D1 (`env.DB`)](#a-native-cloudflare-d1-envdb)
|
|
27
|
+
- [B. Drizzle ORM on D1 (`db`)](#b-drizzle-orm-on-d1-db)
|
|
28
|
+
- [C. Pure In-Memory Workflows (No Database)](#c-pure-in-memory-workflows-no-database)
|
|
29
|
+
3. [Inputs, Outputs & Type Contracts](#3-inputs-outputs--type-contracts)
|
|
30
|
+
4. [Possible Errors & Troubleshooting](#4-possible-errors--troubleshooting)
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 1. Core Concepts
|
|
35
|
+
|
|
36
|
+
The Pipeline pattern solves the complexity of multi-step business logic by:
|
|
37
|
+
- **Decoupling Actions**: Each action does one thing (`(context) => context`) without nested function calls.
|
|
38
|
+
- **Atomic Cloudflare D1 Batching**: Mutating statements are staged via `tx.stage(...)` and committed together in a single `db.batch()` call upon completion.
|
|
39
|
+
- **Preventive In-Memory Rollback**: If any action throws an error (e.g. domain exception), the pipeline stops immediately. Staged mutations are discarded in memory and zero queries hit D1.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 2. How to Use
|
|
44
|
+
|
|
45
|
+
### A. Native Cloudflare D1 (`env.DB`)
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
49
|
+
import type { D1TransactionContext } from "@/lib/pipeline/types";
|
|
50
|
+
|
|
51
|
+
interface CreateUserContext {
|
|
52
|
+
db: D1Database;
|
|
53
|
+
input: { email: string; name: string };
|
|
54
|
+
tx?: D1TransactionContext<D1Database, D1PreparedStatement>;
|
|
55
|
+
userId?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// 1. Define isolated actions
|
|
59
|
+
async function ensureEmailAvailable(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
60
|
+
const existing = await ctx.tx!.db
|
|
61
|
+
.prepare("SELECT id FROM users WHERE email = ?")
|
|
62
|
+
.bind(ctx.input.email)
|
|
63
|
+
.first();
|
|
64
|
+
|
|
65
|
+
if (existing) {
|
|
66
|
+
throw new Error("Email already registered");
|
|
67
|
+
}
|
|
68
|
+
return ctx;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function stageInsertUser(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
72
|
+
const id = crypto.randomUUID();
|
|
73
|
+
|
|
74
|
+
// Stage statement for atomic batch execution
|
|
75
|
+
ctx.tx!.stage(
|
|
76
|
+
ctx.tx!.db
|
|
77
|
+
.prepare("INSERT INTO users (id, email, name) VALUES (?, ?, ?)")
|
|
78
|
+
.bind(id, ctx.input.email, ctx.input.name)
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
return { ...ctx, userId: id };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 2. Execute pipeline
|
|
85
|
+
const result = await Pipeline.send<CreateUserContext>({ db: env.DB, input })
|
|
86
|
+
.transactional(env.DB)
|
|
87
|
+
.through([ensureEmailAvailable, stageInsertUser])
|
|
88
|
+
.then((ctx) => ({ id: ctx.userId! }));
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
### B. Drizzle ORM on D1 (`db`)
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
97
|
+
import type { D1TransactionContext } from "@/lib/pipeline/types";
|
|
98
|
+
import { users } from "@/db/schema";
|
|
99
|
+
import { eq } from "drizzle-orm";
|
|
100
|
+
import type { BatchItem } from "drizzle-orm/batch";
|
|
101
|
+
|
|
102
|
+
interface CreateUserContext {
|
|
103
|
+
db: typeof db;
|
|
104
|
+
input: { email: string; name: string };
|
|
105
|
+
tx?: D1TransactionContext<typeof db, BatchItem<"sqlite">>;
|
|
106
|
+
createdId?: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function validateUniqueEmail(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
110
|
+
const [existing] = await ctx.tx!.db
|
|
111
|
+
.select({ id: users.id })
|
|
112
|
+
.from(users)
|
|
113
|
+
.where(eq(users.email, ctx.input.email));
|
|
114
|
+
|
|
115
|
+
if (existing) {
|
|
116
|
+
throw new Error("Email already registered");
|
|
117
|
+
}
|
|
118
|
+
return ctx;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function stageCreateUser(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
122
|
+
const newId = crypto.randomUUID();
|
|
123
|
+
|
|
124
|
+
// Stage Drizzle mutation
|
|
125
|
+
ctx.tx!.stage(
|
|
126
|
+
ctx.tx!.db.insert(users).values({
|
|
127
|
+
id: newId,
|
|
128
|
+
email: ctx.input.email,
|
|
129
|
+
name: ctx.input.name,
|
|
130
|
+
})
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
return { ...ctx, createdId: newId };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Execute
|
|
137
|
+
const result = await Pipeline.send<CreateUserContext>({ db, input })
|
|
138
|
+
.transactional(db)
|
|
139
|
+
.through([validateUniqueEmail, stageCreateUser])
|
|
140
|
+
.thenReturn();
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
### C. Pure In-Memory Workflows (No Database)
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
149
|
+
|
|
150
|
+
interface TransformOrderContext {
|
|
151
|
+
rawItems: Array<{ price: number; quantity: number }>;
|
|
152
|
+
discountRate: number;
|
|
153
|
+
subtotal?: number;
|
|
154
|
+
total?: number;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const finalOrder = await Pipeline.send<TransformOrderContext>({
|
|
158
|
+
rawItems: [{ price: 100, quantity: 2 }],
|
|
159
|
+
discountRate: 0.1,
|
|
160
|
+
})
|
|
161
|
+
.through([
|
|
162
|
+
(ctx) => ({ ...ctx, subtotal: ctx.rawItems.reduce((acc, i) => acc + i.price * i.quantity, 0) }),
|
|
163
|
+
(ctx) => ({ ...ctx, total: ctx.subtotal! * (1 - ctx.discountRate) }),
|
|
164
|
+
])
|
|
165
|
+
.thenReturn();
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
## 3. Inputs, Outputs & Type Contracts
|
|
171
|
+
|
|
172
|
+
### `Pipeline.send<TContext>(context: TContext)`
|
|
173
|
+
- **Input (`context`)**: Any state object representing the workflow input and accumulated outputs.
|
|
174
|
+
- **Output**: A new `Pipeline<TContext>` instance.
|
|
175
|
+
|
|
176
|
+
### `.transactional(db)`
|
|
177
|
+
- **Input (`db`)**: Any database client implementing `.batch(statements: any[])`.
|
|
178
|
+
- **Side Effect**: Injects `tx: D1TransactionContext<TDb, TStatement>` into `context.tx`.
|
|
179
|
+
- **Output**: Returns the same pipeline instance (`this`) for method chaining.
|
|
180
|
+
|
|
181
|
+
### `.through(pipes: PipeAction<TContext>[])`
|
|
182
|
+
- **Input (`pipes`)**: Array of standalone functions with signature:
|
|
183
|
+
```typescript
|
|
184
|
+
(context: TContext) => Promise<TContext> | TContext;
|
|
185
|
+
```
|
|
186
|
+
- **Rules**:
|
|
187
|
+
- Must return the updated context (or a new object spreading `...context`).
|
|
188
|
+
- To abort the flow, throw a standard error or domain exception.
|
|
189
|
+
|
|
190
|
+
### `.then(destination)` vs `.thenReturn()`
|
|
191
|
+
- **`.thenReturn()`**: Returns `Promise<TContext>` (the final accumulated state).
|
|
192
|
+
- **`.then(destination)`**: Executes `destination(finalContext)` and returns `Promise<TFinalResult>`.
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## 4. Possible Errors & Troubleshooting
|
|
197
|
+
|
|
198
|
+
| Issue / Error | Cause | Solution |
|
|
199
|
+
| :--- | :--- | :--- |
|
|
200
|
+
| **`TypeError: Cannot read properties of undefined (reading 'stage')`** | Attempting to access `ctx.tx.stage(...)` without chaining `.transactional(db)`. | Make sure you call `.transactional(db)` right after `Pipeline.send(context)`. |
|
|
201
|
+
| **Data not written to D1** | Action called `ctx.tx.db.insert(...)` or `.prepare(...)` directly instead of staging via `ctx.tx.stage(...)`. | In transactional pipelines, all writes must be passed to `ctx.tx.stage(stmt)`. Immediate writes bypass atomic batching and won't be rolled back on error. |
|
|
202
|
+
| **Unhandled Promise / Floating Promise** | Forgetting to `await` the pipeline call (`const res = Pipeline.send(...)`). | Always use `await Pipeline.send(...)...` or return the promise. |
|
|
203
|
+
| **State mutations lost between actions** | An action forgot to return `context` or returned `undefined`. | Ensure every pipe function returns `context` or `{ ...context, newProp: value }`. |
|
|
204
|
+
| **Cloudflare D1 batch size exceeded (`D1_ERROR`)** | Staging more than 100 statements or exceeding D1 payload limits in a single batch. | Split massive migrations into chunks of 50-100 items before executing the pipeline. |
|
|
205
|
+
| **Preventive Rollback behavior** | If an action throws an error, the execution immediately bubbles up the exception without calling `db.batch()`. | This is intended behavior. Handle the exception in your route middleware or `try/catch` wrapper. |
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Sequential multi-action Pipeline processor inspired by Laravel.
|
|
3
|
+
* Agnostic to Drizzle ORM and native Cloudflare D1.
|
|
4
|
+
* Strict Zero-Barrel implementation: imports types directly from ./types.
|
|
5
|
+
*/
|
|
6
|
+
import type { PipeAction, D1TransactionContext, BatchCapableDb } from "./types";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Pipeline processor inspired by the Laravel pipeline pattern.
|
|
10
|
+
*
|
|
11
|
+
* Enables sequential execution of decoupled, atomic actions over a typed context.
|
|
12
|
+
* Actions are isolated and follow the single input / single output contract:
|
|
13
|
+
* `(context: TContext) => Promise<TContext> | TContext`.
|
|
14
|
+
*
|
|
15
|
+
* Supports atomic Cloudflare D1 batching via `.transactional(db)`:
|
|
16
|
+
* - Compatible with native Cloudflare D1 (`env.DB`) and Drizzle ORM (`db`).
|
|
17
|
+
* - Automatically injects a `tx: D1TransactionContext` into `context.tx`.
|
|
18
|
+
* - Staged statements via `context.tx.stage(...)` are committed in an atomic `db.batch()`
|
|
19
|
+
* when `.then()` or `.thenReturn()` resolves.
|
|
20
|
+
* - If any action throws an error (e.g. domain exception), staged statements are discarded
|
|
21
|
+
* in memory and zero mutations are sent to D1 (preventive in-memory rollback).
|
|
22
|
+
*
|
|
23
|
+
* @template TContext - The state object that flows through and gets enriched by the pipeline.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
28
|
+
*
|
|
29
|
+
* const result = await Pipeline.send<CreateUserContext>({ db, input })
|
|
30
|
+
* .transactional(db)
|
|
31
|
+
* .through([validateEmailAction, stageCreateUserAction])
|
|
32
|
+
* .thenReturn();
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export class Pipeline<TContext> {
|
|
36
|
+
private context: TContext;
|
|
37
|
+
private pipes: PipeAction<any, any>[] = [];
|
|
38
|
+
private dbClient?: BatchCapableDb<any, any>;
|
|
39
|
+
private stagedStatements: unknown[] = [];
|
|
40
|
+
|
|
41
|
+
private constructor(context: TContext) {
|
|
42
|
+
this.context = context;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Initializes a new pipeline instance with the provided initial context.
|
|
47
|
+
*
|
|
48
|
+
* @template T - The context type of the pipeline.
|
|
49
|
+
* @param context - The initial state to be processed through the pipeline steps.
|
|
50
|
+
* @returns A new `Pipeline` instance.
|
|
51
|
+
*/
|
|
52
|
+
static send<T>(context: T): Pipeline<T> {
|
|
53
|
+
return new Pipeline<T>(context);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Enables atomic Cloudflare D1 batch transaction mode for this pipeline run.
|
|
58
|
+
*
|
|
59
|
+
* Automatically initializes `tx: D1TransactionContext` into `context.tx` and
|
|
60
|
+
* commits all staged statements atomically using `db.batch()` upon resolution.
|
|
61
|
+
* Works with both native D1 (`D1Database`) and Drizzle D1.
|
|
62
|
+
*
|
|
63
|
+
* @param db - The database client instance used to execute the final atomic batch.
|
|
64
|
+
* @returns The current pipeline instance for fluent chaining.
|
|
65
|
+
*/
|
|
66
|
+
transactional<
|
|
67
|
+
TDb extends BatchCapableDb<TStatement, any>,
|
|
68
|
+
TStatement = unknown,
|
|
69
|
+
>(db: TDb): this {
|
|
70
|
+
this.dbClient = db;
|
|
71
|
+
|
|
72
|
+
const txContext: D1TransactionContext<TDb, TStatement> = {
|
|
73
|
+
db,
|
|
74
|
+
stage: (...statements: TStatement[]) => {
|
|
75
|
+
this.stagedStatements.push(...statements);
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
if (this.context && typeof this.context === "object") {
|
|
80
|
+
this.context = {
|
|
81
|
+
...this.context,
|
|
82
|
+
tx: txContext,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return this;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Defines the sequential list of atomic pipe actions to execute.
|
|
91
|
+
*
|
|
92
|
+
* @param pipes - An array of atomic action functions.
|
|
93
|
+
* @returns The current pipeline instance for fluent method chaining.
|
|
94
|
+
*/
|
|
95
|
+
through(pipes: PipeAction<TContext, any>[]): this {
|
|
96
|
+
this.pipes = pipes;
|
|
97
|
+
return this;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Executes the pipeline sequentially, commits staged mutations atomically if transactional,
|
|
102
|
+
* and passes the final enriched context to a destination closure, returning its resolved value.
|
|
103
|
+
*
|
|
104
|
+
* @template TFinalResult - The type of value returned by the destination closure.
|
|
105
|
+
* @param destination - Callback receiving the final context.
|
|
106
|
+
* @returns A promise resolving to the result of the destination callback.
|
|
107
|
+
*/
|
|
108
|
+
async then<TFinalResult>(
|
|
109
|
+
destination: (context: TContext) => Promise<TFinalResult> | TFinalResult,
|
|
110
|
+
): Promise<TFinalResult> {
|
|
111
|
+
const finalContext = await this.thenReturn();
|
|
112
|
+
return await destination(finalContext);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Executes all pipes sequentially, executes atomic db.batch() if transactional mode is active,
|
|
117
|
+
* and returns the final context state.
|
|
118
|
+
*
|
|
119
|
+
* @returns A promise resolving to the final accumulated context object.
|
|
120
|
+
*/
|
|
121
|
+
async thenReturn(): Promise<TContext> {
|
|
122
|
+
let currentContext = this.context;
|
|
123
|
+
|
|
124
|
+
for (const pipe of this.pipes) {
|
|
125
|
+
currentContext = await pipe(currentContext);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (this.dbClient && this.stagedStatements.length > 0) {
|
|
129
|
+
await this.dbClient.batch(this.stagedStatements);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return currentContext;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Type definitions for Laravel-style Pipeline and atomic Cloudflare D1 batching.
|
|
3
|
+
* Agnostic to whether the consumer uses Drizzle ORM or native Cloudflare D1 (D1Database).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Individual action contract in the pipeline.
|
|
8
|
+
* Follows the single input / single output rule:
|
|
9
|
+
* `(context: TContext) => Promise<TContext> | TContext`.
|
|
10
|
+
*/
|
|
11
|
+
export type PipeAction<TIn, TOut = TIn> = (
|
|
12
|
+
context: TIn,
|
|
13
|
+
) => Promise<TOut> | TOut;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Generic minimal interface for database clients supporting atomic batching.
|
|
17
|
+
* Satisfied natively by Cloudflare D1 (`D1Database`) and Drizzle ORM (`DrizzleD1Database`).
|
|
18
|
+
*/
|
|
19
|
+
export interface BatchCapableDb<TStatement = unknown, TResult = unknown> {
|
|
20
|
+
batch(statements: TStatement[]): Promise<TResult[] | unknown>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Transactional context supplied to the pipeline or withD1Transaction.
|
|
25
|
+
* Allows immediate read queries via `db` and stages mutations for atomic batch execution.
|
|
26
|
+
*
|
|
27
|
+
* @template TDb - The type of database client (e.g. `D1Database` or Drizzle client).
|
|
28
|
+
* @template TStatement - The type of statement staged for batching (e.g. `D1PreparedStatement` or Drizzle `BatchItem`).
|
|
29
|
+
*/
|
|
30
|
+
export interface D1TransactionContext<TDb = unknown, TStatement = unknown> {
|
|
31
|
+
/** Database client for immediate read queries */
|
|
32
|
+
readonly db: TDb;
|
|
33
|
+
/** Enqueues one or more statements to be committed atomically in db.batch() */
|
|
34
|
+
stage: (...statements: TStatement[]) => void;
|
|
35
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Transactional wrapper that emulates Laravel's DB::transaction() pattern for Cloudflare D1.
|
|
3
|
+
* Agnostic to Drizzle ORM and native Cloudflare D1.
|
|
4
|
+
* Strict Zero-Barrel implementation: imports types directly from ./types.
|
|
5
|
+
*/
|
|
6
|
+
import type { D1TransactionContext, BatchCapableDb } from "./types";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Transactional wrapper that emulates Laravel's `DB::transaction()` pattern on Cloudflare D1.
|
|
10
|
+
*
|
|
11
|
+
* 1. Wraps the sequential execution of a Pipeline or asynchronous workflow.
|
|
12
|
+
* 2. If any Action throws an error (domain exception or unexpected error),
|
|
13
|
+
* the pipeline terminates immediately and staged mutations are discarded in memory.
|
|
14
|
+
* No queries are sent to Cloudflare D1 (Preventive in-memory rollback).
|
|
15
|
+
* 3. If the pipeline completes successfully and mutations were staged,
|
|
16
|
+
* they are dispatched together via `db.batch()`, guaranteeing ACID atomicity on SQLite/D1.
|
|
17
|
+
*
|
|
18
|
+
* Compatible with:
|
|
19
|
+
* - Native Cloudflare D1: `withD1Transaction(env.DB, async (tx) => { ... })`
|
|
20
|
+
* - Drizzle ORM: `withD1Transaction(db, async (tx) => { ... })`
|
|
21
|
+
*
|
|
22
|
+
* @param db - The database client instance (native D1 or Drizzle).
|
|
23
|
+
* @param pipelineExecution - Callback receiving the `D1TransactionContext`.
|
|
24
|
+
* @returns The resolved value of the pipeline execution callback.
|
|
25
|
+
*/
|
|
26
|
+
export async function withD1Transaction<
|
|
27
|
+
TResult,
|
|
28
|
+
TDb extends BatchCapableDb<TStatement, any> = BatchCapableDb,
|
|
29
|
+
TStatement = unknown,
|
|
30
|
+
>(
|
|
31
|
+
db: TDb,
|
|
32
|
+
pipelineExecution: (tx: D1TransactionContext<TDb, TStatement>) => Promise<TResult>,
|
|
33
|
+
): Promise<TResult> {
|
|
34
|
+
const stagedStatements: TStatement[] = [];
|
|
35
|
+
|
|
36
|
+
const tx: D1TransactionContext<TDb, TStatement> = {
|
|
37
|
+
db,
|
|
38
|
+
stage: (...statements: TStatement[]) => {
|
|
39
|
+
stagedStatements.push(...statements);
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const result = await pipelineExecution(tx);
|
|
44
|
+
|
|
45
|
+
if (stagedStatements.length > 0) {
|
|
46
|
+
await db.batch(stagedStatements);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return result;
|
|
50
|
+
}
|