@xenterprises/fastify-xconfig 1.0.2 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -18
- package/dist/utils/randomUUID.d.ts +1 -1
- package/dist/xConfig.d.ts +1 -2
- package/dist/xConfig.js +2 -7
- package/dist/xConfig.js.map +1 -1
- package/package.json +24 -43
- package/server/app.js +78 -0
- package/src/auth/admin.js +181 -0
- package/src/auth/portal.js +177 -0
- package/src/integrations/cloudinary.js +98 -0
- package/src/integrations/geocode.js +43 -0
- package/src/integrations/prisma.js +30 -0
- package/src/integrations/sendgrid.js +58 -0
- package/src/integrations/twilio.js +146 -0
- package/src/lifecycle/xFastifyAfter.js +27 -0
- package/src/middleware/bugsnag.js +10 -0
- package/src/middleware/cors.js +10 -0
- package/src/middleware/fancyErrors.js +26 -0
- package/src/middleware/multipart.js +6 -0
- package/src/middleware/rateLimit.js +6 -0
- package/src/middleware/underPressure.js +6 -0
- package/src/utils/colorize.js +37 -0
- package/src/utils/cookie.js +5 -0
- package/src/utils/formatBytes.js +16 -0
- package/src/utils/health.js +126 -0
- package/src/utils/xEcho.js +12 -0
- package/src/utils/xSlugify.js +20 -0
- package/src/utils/xUUID.js +14 -0
- package/src/xConfig.js +117 -0
- package/test/index.js +17 -0
- package/tsconfig.json +9 -11
- package/xConfigReference.js +1526 -0
- package/xConfigWorkingList.js +720 -0
- package/.github/workflows/ci.yml +0 -19
- package/.taprc +0 -3
- package/example.ts +0 -13
- package/src/xConfig.ts +0 -20
- package/test/index.test-d.ts +0 -13
- package/test/index.test.js +0 -14
- package/test/xConfig.js +0 -115
- /package/{src → ts-reference}/integrations/cloudinary.ts +0 -0
- /package/{src → ts-reference}/integrations/prisma.ts +0 -0
- /package/{src → ts-reference}/integrations/sendgrid.ts +0 -0
- /package/{src → ts-reference}/integrations/stripe.ts +0 -0
- /package/{src → ts-reference}/integrations/twilio.ts +0 -0
- /package/{src → ts-reference}/middleware/bugsnag.ts +0 -0
- /package/{src → ts-reference}/middleware/cors.ts +0 -0
- /package/{src → ts-reference}/middleware/errorHandler.ts +0 -0
- /package/{src → ts-reference}/middleware/multipart.ts +0 -0
- /package/{src → ts-reference}/middleware/rateLimit.ts +0 -0
- /package/{src → ts-reference}/middleware/underPressure.ts +0 -0
- /package/{src → ts-reference}/utils/colorize.ts +0 -0
- /package/{src → ts-reference}/utils/formatBytes.ts +0 -0
- /package/{src → ts-reference}/utils/randomUUID.ts +0 -0
- /package/{src → ts-reference}/utils/statAsync.ts +0 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/utils/colorize.js
|
|
2
|
+
const colors = {
|
|
3
|
+
POST: 33,
|
|
4
|
+
GET: 32,
|
|
5
|
+
PUT: 34,
|
|
6
|
+
DELETE: 31,
|
|
7
|
+
PATCH: 90,
|
|
8
|
+
clear: 39,
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
// Function to colorize method and path names
|
|
13
|
+
function colorize(method, text) {
|
|
14
|
+
const colorCode = colors[method] || colors.clear;
|
|
15
|
+
return `\u001b[${colorCode}m${text}\u001b[${colors.clear}m`;
|
|
16
|
+
}
|
|
17
|
+
// Function to print the collected routes
|
|
18
|
+
function printRoutes(routes, colors = true) {
|
|
19
|
+
routes
|
|
20
|
+
.sort((a, b) => a.url.localeCompare(b.url))
|
|
21
|
+
.forEach(({ method, url }) => {
|
|
22
|
+
const methodsArray = Array.isArray(method) ? method : [method];
|
|
23
|
+
methodsArray
|
|
24
|
+
.filter((m) => m !== "HEAD")
|
|
25
|
+
.forEach((m) =>
|
|
26
|
+
console.info(
|
|
27
|
+
`${colors ? colorize(m, m) : m}\t${colors ? colorize(m, url) : url}`
|
|
28
|
+
)
|
|
29
|
+
);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export {
|
|
34
|
+
colors,
|
|
35
|
+
colorize,
|
|
36
|
+
printRoutes,
|
|
37
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import fp from "fastify-plugin";
|
|
2
|
+
|
|
3
|
+
async function formatBytesPlugin(fastify, options) {
|
|
4
|
+
fastify.decorate("formatBytes", (bytes, decimals = 2) => {
|
|
5
|
+
if (bytes === 0) return "0 Bytes";
|
|
6
|
+
|
|
7
|
+
const k = 1024;
|
|
8
|
+
const dm = decimals < 0 ? 0 : decimals;
|
|
9
|
+
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
|
|
10
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
11
|
+
|
|
12
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export default fp(formatBytesPlugin);
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Import necessary modules
|
|
2
|
+
import os from "os";
|
|
3
|
+
import process from "process";
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
import util from "util";
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
// Promisify fs functions
|
|
9
|
+
const statAsync = util.promisify(fs.stat);
|
|
10
|
+
|
|
11
|
+
// Record the server start time
|
|
12
|
+
const serverStartTime = Date.now();
|
|
13
|
+
|
|
14
|
+
// Helper function to format bytes into human-readable format
|
|
15
|
+
function formatBytes(bytes, decimals = 2) {
|
|
16
|
+
if (bytes === 0) return "0 Bytes";
|
|
17
|
+
const k = 1024;
|
|
18
|
+
const dm = decimals < 0 ? 0 : decimals;
|
|
19
|
+
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
|
|
20
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
21
|
+
const formattedNumber = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
|
|
22
|
+
return `${formattedNumber} ${sizes[i]}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function setupHealth(fastify, options) {
|
|
26
|
+
fastify.get("/health", async (request, reply) => {
|
|
27
|
+
const status = {
|
|
28
|
+
status: "healthy",
|
|
29
|
+
timestamp: new Date().toISOString(),
|
|
30
|
+
uptime: process.uptime(), // Uptime in seconds
|
|
31
|
+
version: "1.0.0", // Fetch dynamically if possible
|
|
32
|
+
environment: process.env.NODE_ENV || "development",
|
|
33
|
+
dependencies: {},
|
|
34
|
+
resources: {},
|
|
35
|
+
details: {},
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
// Database connectivity check
|
|
40
|
+
if (fastify.prisma) {
|
|
41
|
+
await fastify.prisma.$queryRaw`SELECT 1`;
|
|
42
|
+
status.dependencies.database = "up";
|
|
43
|
+
} else {
|
|
44
|
+
status.dependencies.database = "not configured";
|
|
45
|
+
}
|
|
46
|
+
} catch (error) {
|
|
47
|
+
status.dependencies.database = "down";
|
|
48
|
+
status.status = "degraded";
|
|
49
|
+
status.details.databaseError = error.message;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
// Redis connectivity check
|
|
54
|
+
if (fastify.redis) {
|
|
55
|
+
await fastify.redis.ping();
|
|
56
|
+
status.dependencies.redis = "up";
|
|
57
|
+
} else {
|
|
58
|
+
status.dependencies.redis = "not configured";
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
status.dependencies.redis = "down";
|
|
62
|
+
status.status = "degraded";
|
|
63
|
+
status.details.redisError = error.message;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Resource usage
|
|
67
|
+
const memoryUsage = process.memoryUsage();
|
|
68
|
+
const loadAverage = os.loadavg();
|
|
69
|
+
|
|
70
|
+
status.resources.memory = {
|
|
71
|
+
rss: formatBytes(memoryUsage.rss),
|
|
72
|
+
heapTotal: formatBytes(memoryUsage.heapTotal),
|
|
73
|
+
heapUsed: formatBytes(memoryUsage.heapUsed),
|
|
74
|
+
external: formatBytes(memoryUsage.external),
|
|
75
|
+
arrayBuffers: formatBytes(memoryUsage.arrayBuffers),
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
status.resources.cpu = {
|
|
79
|
+
loadAverage, // 1, 5, and 15 minute load averages
|
|
80
|
+
cpus: os.cpus().length,
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// Disk space availability
|
|
84
|
+
try {
|
|
85
|
+
// Implement disk space check using 'check-disk-space' package
|
|
86
|
+
// Install it via 'npm install check-disk-space'
|
|
87
|
+
const checkDiskSpace = (await import("check-disk-space")).default;
|
|
88
|
+
const diskSpace = await checkDiskSpace("/"); // Replace '/' with your drive or mount point
|
|
89
|
+
status.resources.disk = {
|
|
90
|
+
free: formatBytes(diskSpace.free),
|
|
91
|
+
size: formatBytes(diskSpace.size),
|
|
92
|
+
};
|
|
93
|
+
} catch (error) {
|
|
94
|
+
status.resources.disk = "unknown";
|
|
95
|
+
status.details.diskError = error.message;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Application-specific checks
|
|
99
|
+
// Example: Check if a scheduled job is running
|
|
100
|
+
if (typeof isJobRunning === "function" && !isJobRunning()) {
|
|
101
|
+
status.status = "degraded";
|
|
102
|
+
status.details.jobStatus = "Scheduled job is not running";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Configuration validation
|
|
106
|
+
const requiredEnvVars = [
|
|
107
|
+
"DATABASE_URL",
|
|
108
|
+
"ADMIN_JWT_SECRET",
|
|
109
|
+
"USER_JWT_SECRET",
|
|
110
|
+
];
|
|
111
|
+
const missingEnvVars = requiredEnvVars.filter(
|
|
112
|
+
(varName) => !process.env[varName]
|
|
113
|
+
);
|
|
114
|
+
if (missingEnvVars.length > 0) {
|
|
115
|
+
status.status = "degraded";
|
|
116
|
+
status.details.missingEnvVars = missingEnvVars;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Determine overall health
|
|
120
|
+
if (status.status === "healthy") {
|
|
121
|
+
reply.send(status);
|
|
122
|
+
} else {
|
|
123
|
+
reply.status(500).send(status);
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// src/utils/xSlugify.js
|
|
2
|
+
import fp from "fastify-plugin";
|
|
3
|
+
|
|
4
|
+
async function xSlugify(fastify, options) {
|
|
5
|
+
fastify.decorate('slugify', (string) => {
|
|
6
|
+
return string
|
|
7
|
+
.toString()
|
|
8
|
+
.toLowerCase() // Convert to lowercase
|
|
9
|
+
.trim() // Trim leading and trailing spaces
|
|
10
|
+
.replace(/\s+/g, '-') // Replace spaces with -
|
|
11
|
+
.replace(/[^\w\-]+/g, '') // Remove all non-word characters (allow only letters, numbers, and dashes)
|
|
12
|
+
.replace(/\-\-+/g, '-') // Replace multiple dashes with a single dash
|
|
13
|
+
.replace(/^-+/, '') // Trim leading dashes
|
|
14
|
+
.replace(/-+$/, ''); // Trim trailing dashes
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default fp(xSlugify, {
|
|
19
|
+
name: "xSlugify",
|
|
20
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import fp from "fastify-plugin";
|
|
2
|
+
import { randomUUID } from "uncrypto";
|
|
3
|
+
|
|
4
|
+
async function xUUID(fastify, options) {
|
|
5
|
+
fastify.decorate("generateUUID", randomUUID);
|
|
6
|
+
|
|
7
|
+
fastify.decorate('randomUUID', () => {
|
|
8
|
+
return randomUUID(); // Generate a UUID using uncrypto's randomUUID
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export default fp(xUUID, {
|
|
13
|
+
name: "xUUID",
|
|
14
|
+
});
|
package/src/xConfig.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// src/xConfig.js
|
|
2
|
+
import fp from "fastify-plugin";
|
|
3
|
+
const isProduction = process.env.NODE_ENV === 'production';
|
|
4
|
+
/*
|
|
5
|
+
* Auth
|
|
6
|
+
*/
|
|
7
|
+
import { setupAdminAuth } from "./auth/admin.js";
|
|
8
|
+
import { setupAuth } from "./auth/portal.js";
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
/*
|
|
12
|
+
* Integrations
|
|
13
|
+
*/
|
|
14
|
+
import { setupPrisma } from "./integrations/prisma.js";
|
|
15
|
+
import { setupSendgrid } from "./integrations/sendgrid.js";
|
|
16
|
+
import { setupTwilio } from "./integrations/twilio.js";
|
|
17
|
+
import { setupCloudinary } from "./integrations/cloudinary.js";
|
|
18
|
+
import { setupGeocode } from "./integrations/geocode.js";
|
|
19
|
+
|
|
20
|
+
/*
|
|
21
|
+
* Lifecycle
|
|
22
|
+
*/
|
|
23
|
+
import { xFastifyAfter } from "./lifecycle/xFastifyAfter.js";
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
/*
|
|
27
|
+
* Middleware
|
|
28
|
+
*/
|
|
29
|
+
import { setupCors } from './middleware/cors.js';
|
|
30
|
+
import { setupUnderPressure } from './middleware/underPressure.js';
|
|
31
|
+
import { setupRateLimit } from './middleware/rateLimit.js';
|
|
32
|
+
import { setupMultipart } from './middleware/multipart.js';
|
|
33
|
+
import { setupBugsnag } from './middleware/bugsnag.js';
|
|
34
|
+
import { setupFancyErrors } from './middleware/fancyErrors.js'
|
|
35
|
+
|
|
36
|
+
/*
|
|
37
|
+
* Utils
|
|
38
|
+
*/
|
|
39
|
+
import xEcho from "./utils/xEcho.js";
|
|
40
|
+
import { setupHealth } from "./utils/health.js";
|
|
41
|
+
import xSlugify from "./utils/xSlugify.js";
|
|
42
|
+
import xUUID from "./utils/xUUID.js";
|
|
43
|
+
import { setupCookie } from "./utils/cookie.js";
|
|
44
|
+
|
|
45
|
+
async function xConfig(fastify, options) {
|
|
46
|
+
const {
|
|
47
|
+
professional = false,
|
|
48
|
+
fancyErrors = true,
|
|
49
|
+
prisma: prismaOptions = {},
|
|
50
|
+
bugsnag: bugsnagOptions = {},
|
|
51
|
+
stripe: stripeOptions = {},
|
|
52
|
+
sendGrid: sendGridOptions = {},
|
|
53
|
+
twilio: twilioOptions = {},
|
|
54
|
+
cloudinary: cloudinaryOptions = {},
|
|
55
|
+
auth: authOptions = {},
|
|
56
|
+
cors: corsOptions = {},
|
|
57
|
+
underPressure: underPressureOptions = {},
|
|
58
|
+
multipart: multipartOptions = {},
|
|
59
|
+
rateLimit: rateLimitOptions = {},
|
|
60
|
+
geocode: geocodeOptions = {},
|
|
61
|
+
} = options;
|
|
62
|
+
|
|
63
|
+
// add starting console with emoji
|
|
64
|
+
console.info("\n 🌮 Starting xConfig...\n");
|
|
65
|
+
|
|
66
|
+
/*
|
|
67
|
+
===== LIST ROUTES =====
|
|
68
|
+
Moved the onRoute hook to the top to capture all routes.
|
|
69
|
+
*/
|
|
70
|
+
const routes = [];
|
|
71
|
+
fastify.addHook("onRoute", (r) => routes.push(r));
|
|
72
|
+
|
|
73
|
+
/*
|
|
74
|
+
* Integrations
|
|
75
|
+
*/
|
|
76
|
+
await setupPrisma(fastify, prismaOptions);
|
|
77
|
+
await setupSendgrid(fastify, sendGridOptions);
|
|
78
|
+
await setupTwilio(fastify, twilioOptions);
|
|
79
|
+
await setupCloudinary(fastify, cloudinaryOptions);
|
|
80
|
+
await setupGeocode(fastify, geocodeOptions);
|
|
81
|
+
|
|
82
|
+
/*
|
|
83
|
+
* Middleware
|
|
84
|
+
*/
|
|
85
|
+
await setupCors(fastify, corsOptions);
|
|
86
|
+
await setupUnderPressure(fastify, underPressureOptions);
|
|
87
|
+
await setupRateLimit(fastify, rateLimitOptions);
|
|
88
|
+
await setupMultipart(fastify, multipartOptions);
|
|
89
|
+
await setupBugsnag(fastify, bugsnagOptions);
|
|
90
|
+
await setupFancyErrors(fastify, fancyErrors);
|
|
91
|
+
fastify.register(import('@fastify/sensible'))
|
|
92
|
+
|
|
93
|
+
/*
|
|
94
|
+
* Utils
|
|
95
|
+
*/
|
|
96
|
+
|
|
97
|
+
fastify.register(xEcho);
|
|
98
|
+
fastify.register(xSlugify);
|
|
99
|
+
fastify.register(xUUID);
|
|
100
|
+
await setupHealth(fastify);
|
|
101
|
+
await setupCookie(fastify, authOptions);
|
|
102
|
+
|
|
103
|
+
/*
|
|
104
|
+
* Auth
|
|
105
|
+
*/
|
|
106
|
+
await setupAuth(fastify, authOptions);
|
|
107
|
+
await setupAdminAuth(fastify, authOptions);
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
//.after() method to ensure this runs after all plugins are registered.
|
|
111
|
+
await xFastifyAfter(fastify, { professional, routes });
|
|
112
|
+
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export default fp(xConfig, {
|
|
116
|
+
name: "xConfig",
|
|
117
|
+
});
|
package/test/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// test.js
|
|
2
|
+
const fastify = require('fastify')();
|
|
3
|
+
const myPlugin = require('../src/xConfig');
|
|
4
|
+
|
|
5
|
+
fastify.register(myPlugin);
|
|
6
|
+
|
|
7
|
+
fastify.get('/', async (request, reply) => {
|
|
8
|
+
return { message: fastify.myPluginMethod() };
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
fastify.listen(3000, (err, address) => {
|
|
12
|
+
if (err) {
|
|
13
|
+
console.error(err);
|
|
14
|
+
process.exit(1);
|
|
15
|
+
}
|
|
16
|
+
console.log(`Server running at ${address}`);
|
|
17
|
+
});
|
package/tsconfig.json
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
{
|
|
2
|
+
"extends": "fastify-tsconfig",
|
|
2
3
|
"compilerOptions": {
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
"skipLibCheck": true,
|
|
11
|
-
"forceConsistentCasingInFileNames": true,
|
|
12
|
-
"sourceMap": true
|
|
4
|
+
"outDir": "dist",
|
|
5
|
+
"sourceMap": true,
|
|
6
|
+
"moduleResolution": "node",
|
|
7
|
+
"module": "NodeNext",
|
|
8
|
+
"target": "ES2022",
|
|
9
|
+
"esModuleInterop": true,
|
|
10
|
+
"allowSyntheticDefaultImports": true
|
|
13
11
|
},
|
|
14
|
-
"include": ["src
|
|
12
|
+
"include": ["src/**/*.ts", "ts-reference/**/*.ts"],
|
|
15
13
|
"exclude": ["node_modules", "dist"]
|
|
16
14
|
}
|