express-file-cluster 0.1.1 → 0.1.3
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/dist/cli/index.cjs +19 -11
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +19 -11
- package/dist/cli/index.js.map +1 -1
- package/dist/index.cjs +31 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +31 -22
- package/dist/index.js.map +1 -1
- package/package.json +3 -1
- package/src/cli/commands/start.ts +21 -11
- package/src/ignite.test.ts +193 -0
- package/src/index.ts +26 -15
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
import request from 'supertest';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import type { Server } from 'node:http';
|
|
7
|
+
import { ignite } from './index.js';
|
|
8
|
+
|
|
9
|
+
// helpers ----------------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
function tmpDir() {
|
|
12
|
+
return fs.mkdtempSync(path.join(os.tmpdir(), 'efc-ignite-'));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function writeRoute(dir: string, name: string, code: string) {
|
|
16
|
+
const file = path.join(dir, name);
|
|
17
|
+
fs.writeFileSync(file, code);
|
|
18
|
+
return file;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function closeServer(server: Server): Promise<void> {
|
|
22
|
+
return new Promise((resolve, reject) => server.close((e) => (e ? reject(e) : resolve())));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// -----------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
describe('ignite() — server integration', () => {
|
|
28
|
+
let apiDir: string;
|
|
29
|
+
let server: Server | undefined;
|
|
30
|
+
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
apiDir = tmpDir();
|
|
33
|
+
// ensure no DATABASE_URL so connectMongo is never called
|
|
34
|
+
delete process.env['DATABASE_URL'];
|
|
35
|
+
delete process.env['CORS_ORIGINS'];
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
afterEach(async () => {
|
|
39
|
+
if (server) { await closeServer(server); server = undefined; }
|
|
40
|
+
fs.rmSync(apiDir, { recursive: true, force: true });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// --- route serving ----------------------------------------------------
|
|
44
|
+
|
|
45
|
+
it('serves a GET route', async () => {
|
|
46
|
+
writeRoute(apiDir, 'health.js', `export const GET = async (_req, res) => res.json({ ok: true });`);
|
|
47
|
+
server = await ignite({ apiDir, cluster: false });
|
|
48
|
+
const res = await request(server).get('/health');
|
|
49
|
+
expect(res.status).toBe(200);
|
|
50
|
+
expect(res.body).toEqual({ ok: true });
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('serves a POST route', async () => {
|
|
54
|
+
writeRoute(apiDir, 'echo.js', `export const POST = async (req, res) => res.status(201).json(req.body);`);
|
|
55
|
+
server = await ignite({ apiDir, cluster: false });
|
|
56
|
+
const res = await request(server).post('/echo').send({ msg: 'hello' });
|
|
57
|
+
expect(res.status).toBe(201);
|
|
58
|
+
expect(res.body).toEqual({ msg: 'hello' });
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('resolves dynamic route params', async () => {
|
|
62
|
+
fs.mkdirSync(path.join(apiDir, 'users'));
|
|
63
|
+
writeRoute(
|
|
64
|
+
path.join(apiDir, 'users'), '[id].js',
|
|
65
|
+
`export const GET = async (req, res) => res.json({ id: req.params.id });`,
|
|
66
|
+
);
|
|
67
|
+
server = await ignite({ apiDir, cluster: false });
|
|
68
|
+
const res = await request(server).get('/users/42');
|
|
69
|
+
expect(res.status).toBe(200);
|
|
70
|
+
expect(res.body).toEqual({ id: '42' });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('returns 405 for an unregistered method', async () => {
|
|
74
|
+
writeRoute(apiDir, 'items.js', `export const GET = async (_req, res) => res.json([]);`);
|
|
75
|
+
server = await ignite({ apiDir, cluster: false });
|
|
76
|
+
const res = await request(server).post('/items');
|
|
77
|
+
expect(res.status).toBe(405);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// --- body parsing -----------------------------------------------------
|
|
81
|
+
|
|
82
|
+
it('parses JSON bodies automatically', async () => {
|
|
83
|
+
writeRoute(apiDir, 'body.js', `export const POST = async (req, res) => res.json(req.body);`);
|
|
84
|
+
server = await ignite({ apiDir, cluster: false });
|
|
85
|
+
const res = await request(server)
|
|
86
|
+
.post('/body')
|
|
87
|
+
.set('Content-Type', 'application/json')
|
|
88
|
+
.send(JSON.stringify({ x: 1 }));
|
|
89
|
+
expect(res.body).toEqual({ x: 1 });
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('parses URL-encoded bodies automatically', async () => {
|
|
93
|
+
writeRoute(apiDir, 'form.js', `export const POST = async (req, res) => res.json(req.body);`);
|
|
94
|
+
server = await ignite({ apiDir, cluster: false });
|
|
95
|
+
const res = await request(server)
|
|
96
|
+
.post('/form')
|
|
97
|
+
.set('Content-Type', 'application/x-www-form-urlencoded')
|
|
98
|
+
.send('name=efc&version=1');
|
|
99
|
+
expect(res.body).toEqual({ name: 'efc', version: '1' });
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// --- CORS -------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
it('allows all origins by default', async () => {
|
|
105
|
+
writeRoute(apiDir, 'ping.js', `export const GET = async (_req, res) => res.json({});`);
|
|
106
|
+
server = await ignite({ apiDir, cluster: false });
|
|
107
|
+
const res = await request(server).get('/ping').set('Origin', 'http://unknown.example');
|
|
108
|
+
expect(res.headers['access-control-allow-origin']).toBe('http://unknown.example');
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('restricts origins when CORS_ORIGINS is set', async () => {
|
|
112
|
+
process.env['CORS_ORIGINS'] = 'http://allowed.example';
|
|
113
|
+
writeRoute(apiDir, 'ping.js', `export const GET = async (_req, res) => res.json({});`);
|
|
114
|
+
server = await ignite({ apiDir, cluster: false });
|
|
115
|
+
|
|
116
|
+
const allowed = await request(server).get('/ping').set('Origin', 'http://allowed.example');
|
|
117
|
+
expect(allowed.headers['access-control-allow-origin']).toBe('http://allowed.example');
|
|
118
|
+
|
|
119
|
+
const blocked = await request(server).get('/ping').set('Origin', 'http://evil.example');
|
|
120
|
+
expect(blocked.headers['access-control-allow-origin']).toBeUndefined();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('supports multiple origins in CORS_ORIGINS', async () => {
|
|
124
|
+
process.env['CORS_ORIGINS'] = 'http://a.example, http://b.example';
|
|
125
|
+
writeRoute(apiDir, 'ping.js', `export const GET = async (_req, res) => res.json({});`);
|
|
126
|
+
server = await ignite({ apiDir, cluster: false });
|
|
127
|
+
|
|
128
|
+
const a = await request(server).get('/ping').set('Origin', 'http://a.example');
|
|
129
|
+
expect(a.headers['access-control-allow-origin']).toBe('http://a.example');
|
|
130
|
+
|
|
131
|
+
const b = await request(server).get('/ping').set('Origin', 'http://b.example');
|
|
132
|
+
expect(b.headers['access-control-allow-origin']).toBe('http://b.example');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('disables CORS when cors: false', async () => {
|
|
136
|
+
writeRoute(apiDir, 'ping.js', `export const GET = async (_req, res) => res.json({});`);
|
|
137
|
+
server = await ignite({ apiDir, cluster: false, cors: false });
|
|
138
|
+
const res = await request(server).get('/ping').set('Origin', 'http://anywhere.example');
|
|
139
|
+
expect(res.headers['access-control-allow-origin']).toBeUndefined();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// --- port & env auto-reading ------------------------------------------
|
|
143
|
+
|
|
144
|
+
it('reads PORT from env when port is not passed', async () => {
|
|
145
|
+
process.env['PORT'] = '0'; // 0 = OS assigns a free port
|
|
146
|
+
writeRoute(apiDir, 'hi.js', `export const GET = async (_req, res) => res.json({ hi: true });`);
|
|
147
|
+
server = await ignite({ apiDir, cluster: false });
|
|
148
|
+
const addr = server.address() as { port: number };
|
|
149
|
+
expect(addr.port).toBeGreaterThan(0);
|
|
150
|
+
delete process.env['PORT'];
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('falls back to port 3000 when PORT env is absent', async () => {
|
|
154
|
+
delete process.env['PORT'];
|
|
155
|
+
writeRoute(apiDir, 'hi.js', `export const GET = async (_req, res) => res.json({});`);
|
|
156
|
+
server = await ignite({ apiDir, cluster: false, port: 0 }); // 0 avoids binding 3000 in tests
|
|
157
|
+
const addr = server.address() as { port: number };
|
|
158
|
+
expect(addr.port).toBeGreaterThan(0);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('ignores NaN port and falls back to env PORT', async () => {
|
|
162
|
+
process.env['PORT'] = '0';
|
|
163
|
+
writeRoute(apiDir, 'hi.js', `export const GET = async (_req, res) => res.json({});`);
|
|
164
|
+
server = await ignite({ apiDir, cluster: false, port: Number(undefined) }); // NaN
|
|
165
|
+
const addr = server.address() as { port: number };
|
|
166
|
+
expect(addr.port).toBeGreaterThan(0);
|
|
167
|
+
delete process.env['PORT'];
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// --- error handling ---------------------------------------------------
|
|
171
|
+
|
|
172
|
+
it('returns 404 for unknown routes', async () => {
|
|
173
|
+
writeRoute(apiDir, 'exists.js', `export const GET = async (_req, res) => res.json({});`);
|
|
174
|
+
server = await ignite({ apiDir, cluster: false });
|
|
175
|
+
const res = await request(server).get('/does-not-exist');
|
|
176
|
+
expect(res.status).toBe(404);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('returns structured JSON for HttpError', async () => {
|
|
180
|
+
// Attach statusCode directly to avoid cross-module instanceof issues in tests
|
|
181
|
+
writeRoute(
|
|
182
|
+
apiDir, 'fail.js',
|
|
183
|
+
`export const GET = async (_req, _res, next) => {
|
|
184
|
+
const err = Object.assign(new Error('Invalid input'), { statusCode: 422 });
|
|
185
|
+
next(err);
|
|
186
|
+
};`,
|
|
187
|
+
);
|
|
188
|
+
server = await ignite({ apiDir, cluster: false });
|
|
189
|
+
const res = await request(server).get('/fail');
|
|
190
|
+
expect(res.status).toBe(422);
|
|
191
|
+
expect(res.body).toMatchObject({ error: 'Invalid input', statusCode: 422 });
|
|
192
|
+
});
|
|
193
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import 'dotenv/config';
|
|
2
|
+
import http from 'node:http';
|
|
2
3
|
import express from 'express';
|
|
3
4
|
import cors from 'cors';
|
|
4
5
|
import cookieParser from 'cookie-parser';
|
|
@@ -15,24 +16,32 @@ import { setDbClient } from './db/index.js';
|
|
|
15
16
|
import { scanTasks } from './tasks/scanner.js';
|
|
16
17
|
import { initBullMQ } from './tasks/bullmq-backend.js';
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
function detectDatabase(url?: string): 'mongodb' | 'postgresql' | undefined {
|
|
20
|
+
if (!url) return undefined;
|
|
21
|
+
if (url.startsWith('mongodb')) return 'mongodb';
|
|
22
|
+
if (url.startsWith('postgres')) return 'postgresql';
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function ignite(config: EFCConfig): Promise<http.Server | undefined> {
|
|
19
27
|
const {
|
|
20
28
|
port: _port,
|
|
21
|
-
cluster: clusterEnabled = true,
|
|
22
29
|
workers,
|
|
23
30
|
apiDir,
|
|
24
|
-
jwtSecret,
|
|
25
|
-
authStrategy = 'http-only',
|
|
26
31
|
globalMiddlewares = [],
|
|
27
32
|
onWorkerReady,
|
|
28
33
|
onWorkerCrash,
|
|
29
34
|
onError,
|
|
30
35
|
} = config;
|
|
31
36
|
|
|
37
|
+
// All runtime values fall back to environment variables
|
|
32
38
|
const port =
|
|
33
|
-
_port != null && !Number.isNaN(_port)
|
|
34
|
-
|
|
35
|
-
|
|
39
|
+
_port != null && !Number.isNaN(_port) ? _port : Number(process.env['PORT']) || 3000;
|
|
40
|
+
const databaseUrl = config.databaseUrl ?? process.env['DATABASE_URL'];
|
|
41
|
+
const database = config.database ?? detectDatabase(databaseUrl);
|
|
42
|
+
const jwtSecret = config.jwtSecret ?? process.env['JWT_SECRET'];
|
|
43
|
+
const authStrategy = config.authStrategy ?? 'http-only';
|
|
44
|
+
const clusterEnabled = config.cluster ?? process.env['NODE_ENV'] === 'production';
|
|
36
45
|
|
|
37
46
|
if (clusterEnabled && cluster.isPrimary) {
|
|
38
47
|
runMaster({
|
|
@@ -51,7 +60,7 @@ export async function ignite(config: EFCConfig): Promise<void> {
|
|
|
51
60
|
let origin: string | string[] | boolean;
|
|
52
61
|
if (envOrigins) {
|
|
53
62
|
const list = envOrigins.split(',').map((o) => o.trim()).filter(Boolean);
|
|
54
|
-
origin = list
|
|
63
|
+
origin = list; // always array so cors validates against the request Origin
|
|
55
64
|
} else if (typeof corsOption === 'object' && corsOption.origin !== undefined) {
|
|
56
65
|
origin = corsOption.origin;
|
|
57
66
|
} else {
|
|
@@ -70,8 +79,8 @@ export async function ignite(config: EFCConfig): Promise<void> {
|
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
// Pre-Flight step 1: Connect database
|
|
73
|
-
if (
|
|
74
|
-
const conn = await connectMongo(
|
|
82
|
+
if (database === 'mongodb' && databaseUrl) {
|
|
83
|
+
const conn = await connectMongo(databaseUrl);
|
|
75
84
|
setDbClient(conn as unknown as Record<string, unknown>);
|
|
76
85
|
}
|
|
77
86
|
|
|
@@ -115,8 +124,10 @@ export async function ignite(config: EFCConfig): Promise<void> {
|
|
|
115
124
|
res: express.Response,
|
|
116
125
|
_next: express.NextFunction,
|
|
117
126
|
) => {
|
|
118
|
-
|
|
119
|
-
|
|
127
|
+
const asHttp = err instanceof Error && 'statusCode' in err
|
|
128
|
+
? (err as HttpError) : null;
|
|
129
|
+
if (asHttp) {
|
|
130
|
+
res.status(asHttp.statusCode).json({ error: asHttp.message, statusCode: asHttp.statusCode });
|
|
120
131
|
} else {
|
|
121
132
|
console.error('[EFC] Unhandled error:', err);
|
|
122
133
|
res.status(500).json({ error: 'Internal Server Error', statusCode: 500 });
|
|
@@ -125,11 +136,11 @@ export async function ignite(config: EFCConfig): Promise<void> {
|
|
|
125
136
|
);
|
|
126
137
|
}
|
|
127
138
|
|
|
128
|
-
|
|
129
|
-
app.listen(port, () => {
|
|
139
|
+
return new Promise<http.Server>((resolve) => {
|
|
140
|
+
const server = app.listen(port, () => {
|
|
130
141
|
const wid = (cluster.worker as { id: number } | undefined)?.id ?? 'primary';
|
|
131
142
|
console.log(`[EFC] Worker ${wid} listening on :${port}`);
|
|
132
|
-
resolve();
|
|
143
|
+
resolve(server);
|
|
133
144
|
});
|
|
134
145
|
});
|
|
135
146
|
}
|