create-charcole 2.0.4 → 2.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 (75) hide show
  1. package/CHANGELOG.md +200 -14
  2. package/README.md +137 -332
  3. package/bin/index.js +236 -55
  4. package/bin/lib/pkgManager.js +8 -25
  5. package/bin/lib/templateHandler.js +5 -42
  6. package/package.json +2 -2
  7. package/plans/V2_1_PLAN.md +20 -0
  8. package/template/js/.env.example +8 -0
  9. package/template/js/basePackage.json +11 -13
  10. package/template/js/src/app.js +4 -1
  11. package/template/js/src/modules/auth/auth.constants.js +3 -0
  12. package/template/js/src/modules/auth/auth.controller.js +29 -0
  13. package/template/js/src/modules/auth/auth.middlewares.js +19 -0
  14. package/template/js/src/modules/auth/auth.routes.js +9 -0
  15. package/template/js/src/modules/auth/auth.schemas.js +60 -0
  16. package/template/js/src/modules/auth/auth.service.js +67 -0
  17. package/template/js/src/modules/auth/package.json +6 -0
  18. package/template/js/src/repositories/user.repo.js +19 -0
  19. package/template/js/src/routes/index.js +25 -0
  20. package/template/js/src/routes/protected.js +13 -0
  21. package/template/ts/.env.example +8 -0
  22. package/template/ts/basePackage.json +19 -15
  23. package/template/ts/build.js +46 -0
  24. package/template/ts/src/app.ts +5 -4
  25. package/template/ts/src/middlewares/errorHandler.ts +15 -23
  26. package/template/ts/src/middlewares/requestLogger.ts +1 -1
  27. package/template/ts/src/middlewares/validateRequest.ts +1 -1
  28. package/template/ts/src/modules/auth/auth.constants.ts +6 -0
  29. package/template/ts/src/modules/auth/auth.controller.ts +32 -0
  30. package/template/ts/src/modules/auth/auth.middlewares.ts +46 -0
  31. package/template/ts/src/modules/auth/auth.routes.ts +9 -0
  32. package/template/ts/src/modules/auth/auth.schemas.ts +73 -0
  33. package/template/ts/src/modules/auth/auth.service.ts +106 -0
  34. package/template/ts/src/modules/auth/package.json +10 -0
  35. package/template/ts/src/modules/health/controller.ts +3 -3
  36. package/template/ts/src/repositories/user.repo.ts +33 -0
  37. package/template/ts/src/routes/index.ts +24 -0
  38. package/template/ts/src/routes/protected.ts +13 -0
  39. package/template/ts/src/server.ts +0 -1
  40. package/template/ts/src/utils/logger.ts +1 -1
  41. package/template/ts/tsconfig.json +14 -7
  42. package/template/js/ARCHITECTURE_DIAGRAMS.md +0 -283
  43. package/template/js/CHECKLIST.md +0 -279
  44. package/template/js/COMPLETE.md +0 -405
  45. package/template/js/ERROR_HANDLING.md +0 -393
  46. package/template/js/IMPLEMENTATION.md +0 -368
  47. package/template/js/IMPLEMENTATION_COMPLETE.md +0 -363
  48. package/template/js/INDEX.md +0 -290
  49. package/template/js/QUICK_REFERENCE.md +0 -270
  50. package/template/js/package.json +0 -28
  51. package/template/js/src/routes.js +0 -17
  52. package/template/js/test-api.js +0 -100
  53. package/template/ts/ARCHITECTURE_DIAGRAMS.md +0 -283
  54. package/template/ts/CHECKLIST.md +0 -279
  55. package/template/ts/COMPLETE.md +0 -405
  56. package/template/ts/ERROR_HANDLING.md +0 -393
  57. package/template/ts/IMPLEMENTATION.md +0 -368
  58. package/template/ts/IMPLEMENTATION_COMPLETE.md +0 -363
  59. package/template/ts/INDEX.md +0 -290
  60. package/template/ts/QUICK_REFERENCE.md +0 -270
  61. package/template/ts/package.json +0 -32
  62. package/template/ts/src/app.js +0 -75
  63. package/template/ts/src/config/constants.js +0 -20
  64. package/template/ts/src/config/env.js +0 -26
  65. package/template/ts/src/middlewares/errorHandler.js +0 -180
  66. package/template/ts/src/middlewares/requestLogger.js +0 -33
  67. package/template/ts/src/middlewares/validateRequest.js +0 -42
  68. package/template/ts/src/modules/health/controller.js +0 -50
  69. package/template/ts/src/routes.js +0 -17
  70. package/template/ts/src/routes.ts +0 -16
  71. package/template/ts/src/server.js +0 -38
  72. package/template/ts/src/utils/AppError.js +0 -182
  73. package/template/ts/src/utils/logger.js +0 -73
  74. package/template/ts/src/utils/response.js +0 -51
  75. package/template/ts/test-api.js +0 -100
@@ -1,50 +0,0 @@
1
- import { z } from "zod";
2
- import { sendSuccess } from "../../utils/response.js";
3
- import { asyncHandler } from "../../middlewares/errorHandler.js";
4
-
5
- /**
6
- * Health check endpoint
7
- * Always returns healthy status (ping endpoint)
8
- */
9
- export const getHealth = asyncHandler(async (req, res) => {
10
- sendSuccess(
11
- res,
12
- {
13
- status: "healthy",
14
- uptime: process.uptime(),
15
- timestamp: new Date().toISOString(),
16
- },
17
- 200,
18
- "Service is healthy",
19
- );
20
- });
21
-
22
- /**
23
- * Example POST endpoint with validation
24
- * Demonstrates proper error handling with Zod validation
25
- */
26
- export const createItemSchema = z.object({
27
- body: z.object({
28
- name: z.string().min(1, "Name is required").max(100),
29
- description: z.string().optional(),
30
- }),
31
- });
32
-
33
- export const createItem = asyncHandler(async (req, res) => {
34
- const { name, description } = req.validatedData.body;
35
-
36
- // Simulate some async work
37
- await new Promise((resolve) => setTimeout(resolve, 10));
38
-
39
- sendSuccess(
40
- res,
41
- {
42
- id: Math.random().toString(36).substr(2, 9),
43
- name,
44
- description: description || null,
45
- createdAt: new Date().toISOString(),
46
- },
47
- 201,
48
- "Item created successfully",
49
- );
50
- });
@@ -1,17 +0,0 @@
1
- import { Router } from "express";
2
- import {
3
- getHealth,
4
- createItem,
5
- createItemSchema,
6
- } from "./modules/health/controller.js";
7
- import { validateRequest } from "./middlewares/validateRequest.js";
8
-
9
- const router = Router();
10
-
11
- // Health check
12
- router.get("/health", getHealth);
13
-
14
- // Example: Create item with validation
15
- router.post("/items", validateRequest(createItemSchema), createItem);
16
-
17
- export default router;
@@ -1,16 +0,0 @@
1
- import { Router } from "express";
2
-
3
- import {
4
- getHealth,
5
- createItem,
6
- createItemSchema,
7
- } from "./modules/health/controller.js";
8
- import { validateRequest } from "./middlewares/validateRequest.js";
9
-
10
- const router = Router();
11
-
12
- router.get("/health", getHealth);
13
-
14
- router.post("/items", validateRequest(createItemSchema), createItem);
15
-
16
- export default router;
@@ -1,38 +0,0 @@
1
- import "dotenv/config";
2
-
3
- import { app } from "./app.js";
4
- import { env } from "./config/env.js";
5
- import { logger } from "./utils/logger.js";
6
-
7
- const PORT = env.PORT;
8
-
9
- const server = app.listen(PORT, () => {
10
- logger.info(`🔥 Server running in ${env.NODE_ENV} mode`, {
11
- url: `http://localhost:${PORT}`,
12
- port: PORT,
13
- });
14
- });
15
-
16
- // Graceful shutdown
17
- const gracefulShutdown = (signal) => {
18
- logger.warn(`${signal} signal received: closing HTTP server`);
19
- server.close(() => {
20
- logger.info("HTTP server closed");
21
- process.exit(0);
22
- });
23
- };
24
-
25
- process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
26
- process.on("SIGINT", () => gracefulShutdown("SIGINT"));
27
-
28
- // Unhandled promise rejections
29
- process.on("unhandledRejection", (reason, promise) => {
30
- logger.error("Unhandled Rejection at:", { promise, reason });
31
- process.exit(1);
32
- });
33
-
34
- // Uncaught exceptions
35
- process.on("uncaughtException", (error) => {
36
- logger.error("Uncaught Exception:", { error: error.message });
37
- process.exit(1);
38
- });
@@ -1,182 +0,0 @@
1
- /**
2
- * Operational Error Class
3
- *
4
- * Use for expected errors that can be handled gracefully
5
- * Examples: validation errors, resource not found, auth failures
6
- *
7
- * These errors are logged and sent back to client as JSON
8
- */
9
- export class AppError extends Error {
10
- constructor(
11
- message,
12
- statusCode = 500,
13
- { isOperational = true, code = null, context = null, cause = null } = {},
14
- ) {
15
- super(message);
16
-
17
- // Operational or Programmer error
18
- this.isOperational = isOperational;
19
-
20
- // HTTP status code
21
- this.statusCode = statusCode;
22
-
23
- // Error code for client handling (e.g., 'INVALID_EMAIL', 'USER_NOT_FOUND')
24
- this.code = code;
25
-
26
- // Additional context data
27
- this.context = context || {};
28
-
29
- // Original error that caused this
30
- this.cause = cause;
31
-
32
- // Timestamp
33
- this.timestamp = new Date().toISOString();
34
-
35
- // Preserve stack trace
36
- Error.captureStackTrace(this, this.constructor);
37
- }
38
-
39
- /**
40
- * Convert to JSON response format
41
- */
42
- toJSON() {
43
- return {
44
- success: false,
45
- message: this.message,
46
- code: this.code,
47
- statusCode: this.statusCode,
48
- ...(Object.keys(this.context).length > 0 && { context: this.context }),
49
- timestamp: this.timestamp,
50
- };
51
- }
52
-
53
- /**
54
- * Get full error details for logging
55
- */
56
- getFullDetails() {
57
- return {
58
- message: this.message,
59
- statusCode: this.statusCode,
60
- code: this.code,
61
- isOperational: this.isOperational,
62
- context: this.context,
63
- cause: this.cause?.message || null,
64
- stack: this.stack,
65
- timestamp: this.timestamp,
66
- };
67
- }
68
- }
69
-
70
- /**
71
- * Validation Error - extends AppError
72
- * Use for input validation failures
73
- */
74
- export class ValidationError extends AppError {
75
- constructor(message, errors = [], context = null) {
76
- super(message, 422, {
77
- isOperational: true,
78
- code: "VALIDATION_ERROR",
79
- context,
80
- });
81
- this.errors = errors;
82
- this.name = "ValidationError";
83
- }
84
-
85
- toJSON() {
86
- return {
87
- ...super.toJSON(),
88
- errors: this.errors,
89
- };
90
- }
91
- }
92
-
93
- /**
94
- * Authentication Error
95
- * Use for auth/permission failures
96
- */
97
- export class AuthenticationError extends AppError {
98
- constructor(message = "Unauthorized", context = null) {
99
- super(message, 401, {
100
- isOperational: true,
101
- code: "AUTHENTICATION_ERROR",
102
- context,
103
- });
104
- this.name = "AuthenticationError";
105
- }
106
- }
107
-
108
- /**
109
- * Authorization Error
110
- * Use for permission denied scenarios
111
- */
112
- export class AuthorizationError extends AppError {
113
- constructor(message = "Forbidden", context = null) {
114
- super(message, 403, {
115
- isOperational: true,
116
- code: "AUTHORIZATION_ERROR",
117
- context,
118
- });
119
- this.name = "AuthorizationError";
120
- }
121
- }
122
-
123
- /**
124
- * Not Found Error
125
- * Use when resource doesn't exist
126
- */
127
- export class NotFoundError extends AppError {
128
- constructor(resource = "Resource", context = null) {
129
- super(`${resource} not found`, 404, {
130
- isOperational: true,
131
- code: "NOT_FOUND",
132
- context,
133
- });
134
- this.name = "NotFoundError";
135
- }
136
- }
137
-
138
- /**
139
- * Conflict Error
140
- * Use for duplicate resources, business logic conflicts
141
- */
142
- export class ConflictError extends AppError {
143
- constructor(message, context = null) {
144
- super(message, 409, {
145
- isOperational: true,
146
- code: "CONFLICT",
147
- context,
148
- });
149
- this.name = "ConflictError";
150
- }
151
- }
152
-
153
- /**
154
- * Bad Request Error
155
- * Use for malformed requests
156
- */
157
- export class BadRequestError extends AppError {
158
- constructor(message, context = null) {
159
- super(message, 400, {
160
- isOperational: true,
161
- code: "BAD_REQUEST",
162
- context,
163
- });
164
- this.name = "BadRequestError";
165
- }
166
- }
167
-
168
- /**
169
- * Internal Server Error
170
- * Use for unexpected server-side errors (programmer errors)
171
- */
172
- export class InternalServerError extends AppError {
173
- constructor(message = "Internal server error", cause = null, context = null) {
174
- super(message, 500, {
175
- isOperational: false,
176
- code: "INTERNAL_SERVER_ERROR",
177
- cause,
178
- context,
179
- });
180
- this.name = "InternalServerError";
181
- }
182
- }
@@ -1,73 +0,0 @@
1
- import { env } from "../config/env.js";
2
-
3
- const COLORS = {
4
- reset: "\x1b[0m",
5
- red: "\x1b[31m",
6
- yellow: "\x1b[33m",
7
- green: "\x1b[32m",
8
- blue: "\x1b[36m",
9
- gray: "\x1b[90m",
10
- magenta: "\x1b[35m",
11
- };
12
-
13
- const LOG_LEVELS = {
14
- debug: 0,
15
- info: 1,
16
- warn: 2,
17
- error: 3,
18
- };
19
-
20
- const getCurrentLogLevel = () => LOG_LEVELS[env.LOG_LEVEL] || LOG_LEVELS.info;
21
-
22
- const formatLog = (level, message, data) => {
23
- const timestamp = new Date().toISOString();
24
- const dataStr = data ? ` ${JSON.stringify(data)}` : "";
25
- return `[${timestamp}] ${level}:${dataStr ? " " + message + dataStr : " " + message}`;
26
- };
27
-
28
- const formatStack = (stack) => {
29
- if (!stack) return "";
30
- return `\n${stack}`;
31
- };
32
-
33
- export const logger = {
34
- debug: (message, data) => {
35
- if (getCurrentLogLevel() <= LOG_LEVELS.debug) {
36
- console.log(
37
- `${COLORS.gray}${formatLog("DEBUG", message, data)}${COLORS.reset}`,
38
- );
39
- }
40
- },
41
-
42
- info: (message, data) => {
43
- if (getCurrentLogLevel() <= LOG_LEVELS.info) {
44
- console.log(
45
- `${COLORS.blue}${formatLog("INFO", message, data)}${COLORS.reset}`,
46
- );
47
- }
48
- },
49
-
50
- warn: (message, data) => {
51
- if (getCurrentLogLevel() <= LOG_LEVELS.warn) {
52
- console.warn(
53
- `${COLORS.yellow}${formatLog("WARN", message, data)}${COLORS.reset}`,
54
- );
55
- }
56
- },
57
-
58
- error: (message, data, stack) => {
59
- if (getCurrentLogLevel() <= LOG_LEVELS.error) {
60
- const stackTrace = formatStack(stack);
61
- console.error(
62
- `${COLORS.red}${formatLog("ERROR", message, data)}${stackTrace}${COLORS.reset}`,
63
- );
64
- }
65
- },
66
-
67
- fatal: (message, data, stack) => {
68
- const stackTrace = formatStack(stack);
69
- console.error(
70
- `${COLORS.red}${COLORS.magenta}${formatLog("FATAL", message, data)}${stackTrace}${COLORS.reset}`,
71
- );
72
- },
73
- };
@@ -1,51 +0,0 @@
1
- /**
2
- * Send success response
3
- *
4
- * @param {Response} res - Express response object
5
- * @param {*} data - Response data
6
- * @param {number} statusCode - HTTP status code (default: 200)
7
- * @param {string} message - Success message (default: 'Success')
8
- */
9
- export const sendSuccess = (
10
- res,
11
- data,
12
- statusCode = 200,
13
- message = "Success",
14
- ) => {
15
- return res.status(statusCode).json({
16
- success: true,
17
- message,
18
- data,
19
- timestamp: new Date().toISOString(),
20
- });
21
- };
22
-
23
- /**
24
- * Send error response (DEPRECATED - use AppError instead)
25
- * This is kept for backward compatibility
26
- */
27
- export const sendError = (res, message, statusCode = 500, errors = null) => {
28
- return res.status(statusCode).json({
29
- success: false,
30
- message,
31
- ...(errors && { errors }),
32
- timestamp: new Date().toISOString(),
33
- });
34
- };
35
-
36
- /**
37
- * Send validation error response (DEPRECATED - use ValidationError instead)
38
- * This is kept for backward compatibility
39
- */
40
- export const sendValidationError = (res, errors, statusCode = 422) => {
41
- return res.status(statusCode).json({
42
- success: false,
43
- message: "Validation failed",
44
- errors: errors.map((err) => ({
45
- field: err.path.join("."),
46
- message: err.message,
47
- code: err.code,
48
- })),
49
- timestamp: new Date().toISOString(),
50
- });
51
- };
@@ -1,100 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import http from "http";
4
-
5
- const tests = [
6
- {
7
- name: "Test 1: GET / (root)",
8
- method: "GET",
9
- path: "/",
10
- body: null,
11
- },
12
- {
13
- name: "Test 2: GET /api/health",
14
- method: "GET",
15
- path: "/api/health",
16
- body: null,
17
- },
18
- {
19
- name: "Test 3: POST /api/items (valid)",
20
- method: "POST",
21
- path: "/api/items",
22
- body: JSON.stringify({ name: "Test Item", description: "A test item" }),
23
- },
24
- {
25
- name: "Test 4: POST /api/items (invalid - missing name)",
26
- method: "POST",
27
- path: "/api/items",
28
- body: JSON.stringify({ description: "No name" }),
29
- },
30
- {
31
- name: "Test 5: GET /api/nonexistent (404)",
32
- method: "GET",
33
- path: "/api/nonexistent",
34
- body: null,
35
- },
36
- ];
37
-
38
- const runTest = (test) => {
39
- return new Promise((resolve) => {
40
- const options = {
41
- hostname: "localhost",
42
- port: 3000,
43
- path: test.path,
44
- method: test.method,
45
- headers: {
46
- "Content-Type": "application/json",
47
- },
48
- };
49
-
50
- const req = http.request(options, (res) => {
51
- let data = "";
52
-
53
- res.on("data", (chunk) => {
54
- data += chunk;
55
- });
56
-
57
- res.on("end", () => {
58
- try {
59
- const json = JSON.parse(data);
60
- console.log(`\n✅ ${test.name}`);
61
- console.log(` Status: ${res.statusCode}`);
62
- console.log(` Response:`, JSON.stringify(json, null, 2));
63
- } catch (error) {
64
- console.log(`\n✅ ${test.name}`);
65
- console.log(` Status: ${res.statusCode}`);
66
- console.log(` Response:`, data);
67
- }
68
- resolve();
69
- });
70
- });
71
-
72
- req.on("error", (error) => {
73
- console.error(`\n❌ ${test.name}`);
74
- console.error(` Error: ${error.message}`);
75
- resolve();
76
- });
77
-
78
- if (test.body) {
79
- req.write(test.body);
80
- }
81
- req.end();
82
- });
83
- };
84
-
85
- const runTests = async () => {
86
- console.log("🚀 Testing Charcole API Error Handling\n");
87
- console.log("=".repeat(60));
88
-
89
- for (const test of tests) {
90
- await runTest(test);
91
- await new Promise((r) => setTimeout(r, 200));
92
- }
93
-
94
- console.log("\n" + "=".repeat(60));
95
- console.log("\n✅ All tests completed!");
96
- process.exit(0);
97
- };
98
-
99
- // Wait for server to be ready
100
- setTimeout(runTests, 1000);