express-file-cluster 0.3.13 → 0.3.15
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 +163 -49
- package/dist/auth/index.cjs +4 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +4 -2
- package/dist/auth/index.d.ts +4 -2
- package/dist/auth/index.js +3 -1
- package/dist/{chunk-QOKLEPTX.cjs → chunk-6522HS2J.cjs} +22 -3
- package/dist/chunk-6522HS2J.cjs.map +1 -0
- package/dist/{chunk-YE4ORV7Z.js → chunk-VIP3PFWZ.js} +20 -1
- package/dist/chunk-VIP3PFWZ.js.map +1 -0
- package/dist/cli/index.cjs +24 -3
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +24 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/index.cjs +96 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +91 -20
- package/dist/index.js.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-CitLbYPp.d.cts → types-BusbSenn.d.cts} +44 -1
- package/dist/{types-CitLbYPp.d.ts → types-BusbSenn.d.ts} +44 -1
- package/package.json +1 -1
- package/dist/chunk-QOKLEPTX.cjs.map +0 -1
- package/dist/chunk-YE4ORV7Z.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
EFC is an opinionated backend framework built on Express. Drop files in `src/api/` and they become routes. Every CPU core serves traffic automatically. Heavy work goes to a queue-backed task subsystem so requests stay fast.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.3.
|
|
7
|
+
> **Status: v0.3.14 (Beta).** The router, clustering, auth, MongoDB adapter, and BullMQ task queue backend are all implemented.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -18,6 +18,8 @@ Most Express apps grow the same way: a working prototype, then a maze of `router
|
|
|
18
18
|
| Single-threaded Node under load | Auto-detected CPU count → worker processes |
|
|
19
19
|
| Blocking work on the request path | `enqueue()` ships it to a queue; respond immediately |
|
|
20
20
|
| Wiring auth, DB, and middleware by hand | `ignite()` — one call bootstraps everything |
|
|
21
|
+
| Scattered model definitions | `defineModel()` — typed CRUD with zero ORM ceremony |
|
|
22
|
+
| Per-request user context in nested calls | `AsyncLocalStorage`-backed `getCurrentUser()` |
|
|
21
23
|
|
|
22
24
|
---
|
|
23
25
|
|
|
@@ -49,7 +51,7 @@ my-api/
|
|
|
49
51
|
│ ├── tasks/ # Background jobs
|
|
50
52
|
│ │ ├── SendEmail.ts
|
|
51
53
|
│ │ └── ResizeImage.ts
|
|
52
|
-
│ ├──
|
|
54
|
+
│ ├── model/ # Engine-agnostic models
|
|
53
55
|
│ │ └── User.ts
|
|
54
56
|
│ └── index.ts # Framework entry point
|
|
55
57
|
├── efc.config.ts
|
|
@@ -57,6 +59,8 @@ my-api/
|
|
|
57
59
|
└── .env.example
|
|
58
60
|
```
|
|
59
61
|
|
|
62
|
+
`src/api` and `src/tasks` are resolved by convention — they are **not** `ignite()` options. EFC probes `src/api`/`src/tasks`, then `<cwd>/api`/`<cwd>/tasks`, then `dist/api`/`dist/tasks`. You only need a different layout if you're doing something unusual.
|
|
63
|
+
|
|
60
64
|
Routing rules:
|
|
61
65
|
|
|
62
66
|
| File | URL |
|
|
@@ -75,7 +79,7 @@ Export uppercase HTTP method names. Anything not exported returns **405 Method N
|
|
|
75
79
|
```ts
|
|
76
80
|
// src/api/users/index.ts
|
|
77
81
|
import type { Request, Response } from 'express';
|
|
78
|
-
import { User } from '../../
|
|
82
|
+
import { User } from '../../model/User.js';
|
|
79
83
|
|
|
80
84
|
export const GET = async (req: Request, res: Response) => {
|
|
81
85
|
const users = await User.find();
|
|
@@ -91,7 +95,7 @@ export const POST = async (req: Request, res: Response) => {
|
|
|
91
95
|
```ts
|
|
92
96
|
// src/api/users/[id].ts
|
|
93
97
|
import type { Request, Response } from 'express';
|
|
94
|
-
import { User } from '../../
|
|
98
|
+
import { User } from '../../model/User.js';
|
|
95
99
|
import { HttpError } from 'express-file-cluster';
|
|
96
100
|
|
|
97
101
|
export const GET = async (req: Request, res: Response) => {
|
|
@@ -114,7 +118,6 @@ Three tiers, each with a clear scope:
|
|
|
114
118
|
|
|
115
119
|
```ts
|
|
116
120
|
// 1. Global — applies to every request
|
|
117
|
-
// CORS is built-in — configure it via CORS_ORIGINS in .env, not a separate package
|
|
118
121
|
ignite({ globalMiddlewares: [rateLimiter()] });
|
|
119
122
|
|
|
120
123
|
// 2. Route-level — applies to every handler in this file
|
|
@@ -131,6 +134,94 @@ export const POST = compose(
|
|
|
131
134
|
|
|
132
135
|
---
|
|
133
136
|
|
|
137
|
+
## Database
|
|
138
|
+
|
|
139
|
+
### `defineModel(name, schema, options?)`
|
|
140
|
+
|
|
141
|
+
Declare a typed model with a schema. EFC compiles it to a Mongoose model and wraps it in a clean CRUD surface.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// src/model/User.ts
|
|
145
|
+
import { defineModel } from 'express-file-cluster';
|
|
146
|
+
|
|
147
|
+
interface UserDocument {
|
|
148
|
+
name: string;
|
|
149
|
+
email: string;
|
|
150
|
+
role: 'admin' | 'user';
|
|
151
|
+
verifyToken: string;
|
|
152
|
+
createdAt?: Date;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const User = defineModel<UserDocument>('User', {
|
|
156
|
+
name: { type: 'string', required: true },
|
|
157
|
+
email: { type: 'string', required: true, unique: true },
|
|
158
|
+
role: { type: 'string', enum: ['admin', 'user'], default: 'user' },
|
|
159
|
+
verifyToken: { type: 'string', default: '$uuid' }, // fresh UUID per document
|
|
160
|
+
});
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Schema default operator codes
|
|
164
|
+
|
|
165
|
+
Instead of a literal or a raw function, `default` also accepts a sentinel string — resolved to a fresh per-document value at schema-compile time, never baked in once:
|
|
166
|
+
|
|
167
|
+
| Code | Resolves to |
|
|
168
|
+
|---|---|
|
|
169
|
+
| `'$now'` | `new Date()` |
|
|
170
|
+
| `'$uuid'` | `crypto.randomUUID()` |
|
|
171
|
+
| `'$objectId'` | fresh Mongoose `ObjectId` |
|
|
172
|
+
| `'$timestamp'` | `Date.now()` (number) |
|
|
173
|
+
| `'$shortId'` | random 16-char base64url string |
|
|
174
|
+
| `'$currentUser'` | full JWT payload from the in-flight request |
|
|
175
|
+
| `'$currentUser.<key>'` | single field from that payload (e.g. `'$currentUser.id'`) |
|
|
176
|
+
|
|
177
|
+
Any other value is used as-is — only these exact strings are special-cased.
|
|
178
|
+
|
|
179
|
+
### Auto-increment (`sequence`)
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
export const Order = defineModel<OrderDocument>('Order', {
|
|
183
|
+
orderNumber: { type: 'number', sequence: true, required: true },
|
|
184
|
+
// sequence: 'global.orders' — explicit key to share a counter across models
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
`sequence` is a field option, not a `default` code — an auto-increment needs an async read-modify-write against a counters collection, but `default` resolves synchronously. It's assigned atomically in a `pre('validate')` hook, before `required` validation runs, so the field can be both `required: true` and auto-filled. Top-level fields only.
|
|
189
|
+
|
|
190
|
+
### Timestamps control
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
// Disable Mongoose's automatic createdAt/updatedAt (default: on)
|
|
194
|
+
export const Role = defineModel<RoleDocument>('Role', schema, {
|
|
195
|
+
timestamps: false,
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// Or rename them
|
|
199
|
+
export const Audit = defineModel<AuditDocument>('Audit', schema, {
|
|
200
|
+
timestamps: { createdAt: 'created_at', updatedAt: false },
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### CRUD surface
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
await User.find({ role: 'admin' }); // find all matching
|
|
208
|
+
await User.findById('66a1...'); // by _id
|
|
209
|
+
await User.findOne({ email: 'a@b.com' }); // first match
|
|
210
|
+
await User.create({ name: 'Alice', ... }); // insert
|
|
211
|
+
await User.update('66a1...', { name: 'Bob' }); // findOneAndUpdate
|
|
212
|
+
await User.delete('66a1...'); // remove
|
|
213
|
+
await User.count({ role: 'user' }); // count matching
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Populate references:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
await Post.find({}, { populate: 'author' });
|
|
220
|
+
await Post.findById(id, { populate: ['author', 'comments.user'] });
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
134
225
|
## Background Tasks
|
|
135
226
|
|
|
136
227
|
Tasks run off the request path — respond immediately, let the queue handle the work.
|
|
@@ -178,7 +269,9 @@ Task options:
|
|
|
178
269
|
| `retries` | `3` | Retry attempts before dead-lettering |
|
|
179
270
|
| `backoff` | `'exponential'` | Delay strategy between retries |
|
|
180
271
|
| `concurrency` | `tasks.concurrency` | Parallel jobs for this task |
|
|
181
|
-
| `schedule` | — | Cron expression
|
|
272
|
+
| `schedule` | — | Cron expression (accepted, not executed yet — planned) |
|
|
273
|
+
|
|
274
|
+
> `enqueue()` fails fast on an unknown task name, but currently has no timeout of its own if the queue backend (Redis) is unreachable — wrap it yourself if you need one.
|
|
182
275
|
|
|
183
276
|
---
|
|
184
277
|
|
|
@@ -215,60 +308,80 @@ export const POST = async (req, res) => {
|
|
|
215
308
|
};
|
|
216
309
|
```
|
|
217
310
|
|
|
311
|
+
### Role-gating and request context
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
// Role-gated route
|
|
315
|
+
export const middlewares = [requireAuth('admin')];
|
|
316
|
+
|
|
317
|
+
// getCurrentUser() reads the same verified JWT payload from anywhere in the
|
|
318
|
+
// async call chain — not just where `req` is in scope. This is also what
|
|
319
|
+
// powers the '$currentUser' / '$currentUser.<key>' defineModel default codes.
|
|
320
|
+
import { getCurrentUser } from 'express-file-cluster/auth';
|
|
321
|
+
|
|
322
|
+
const user = getCurrentUser(); // Record<string, unknown> | undefined
|
|
323
|
+
```
|
|
324
|
+
|
|
218
325
|
---
|
|
219
326
|
|
|
220
327
|
## Bootstrapper
|
|
221
328
|
|
|
222
|
-
|
|
223
|
-
// src/index.ts
|
|
224
|
-
import { ignite } from 'express-file-cluster';
|
|
225
|
-
import path from 'path';
|
|
226
|
-
import { fileURLToPath } from 'url';
|
|
329
|
+
Every runtime value (`PORT`, `DATABASE_URL`, `JWT_SECRET`, `CORS_ORIGINS`, ...) is read from `process.env` explicitly, once, in `efc.config.ts` — `ignite()` itself never touches `process.env` (`NODE_ENV` is the sole exception).
|
|
227
330
|
|
|
228
|
-
|
|
331
|
+
```ts
|
|
332
|
+
// efc.config.ts
|
|
333
|
+
import type { EFCConfig } from 'express-file-cluster';
|
|
229
334
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
tasksDir: path.join(__dirname, 'tasks'),
|
|
335
|
+
const corsOrigins = process.env.CORS_ORIGINS
|
|
336
|
+
? process.env.CORS_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean)
|
|
337
|
+
: undefined;
|
|
234
338
|
|
|
235
|
-
|
|
339
|
+
const config: EFCConfig = {
|
|
340
|
+
port: process.env.PORT ? Number(process.env.PORT) : undefined,
|
|
236
341
|
databaseUrl: process.env.DATABASE_URL,
|
|
237
|
-
|
|
238
|
-
authStrategy: 'http-only',
|
|
239
342
|
jwtSecret: process.env.JWT_SECRET,
|
|
343
|
+
cors: corsOrigins ? { origin: corsOrigins } : true,
|
|
344
|
+
authStrategy: 'http-only',
|
|
345
|
+
tasks: { backend: 'bullmq', concurrency: 5, redisUrl: process.env.REDIS_URL },
|
|
346
|
+
};
|
|
240
347
|
|
|
241
|
-
|
|
242
|
-
|
|
348
|
+
export default config;
|
|
349
|
+
```
|
|
243
350
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
},
|
|
351
|
+
```ts
|
|
352
|
+
// src/index.ts
|
|
353
|
+
import { ignite, gracefulShutdown } from 'express-file-cluster';
|
|
354
|
+
import config from '../efc.config.js';
|
|
249
355
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
});
|
|
356
|
+
ignite({
|
|
357
|
+
...config,
|
|
358
|
+
}).then(gracefulShutdown).catch(console.error);
|
|
254
359
|
```
|
|
255
360
|
|
|
361
|
+
> Don't hardcode `cluster: true` here. `ignite()`'s own default (`NODE_ENV === 'production'`)
|
|
362
|
+
> already gives clustering in prod and a single process in dev — an explicit boolean always
|
|
363
|
+
> wins over that default, so `cluster: true` would cluster in dev too. Only pass `cluster`
|
|
364
|
+
> to force one way regardless of `NODE_ENV`.
|
|
365
|
+
|
|
256
366
|
### `ignite()` options
|
|
257
367
|
|
|
258
368
|
| Option | Type | Default | Description |
|
|
259
369
|
|---|---|---|---|
|
|
260
370
|
| `port` | `number` | `3000` | HTTP listen port |
|
|
261
|
-
| `
|
|
262
|
-
| `
|
|
263
|
-
| `
|
|
264
|
-
| `
|
|
265
|
-
| `
|
|
266
|
-
| `
|
|
267
|
-
| `
|
|
371
|
+
| `basePath` | `string` | `'/v1/api'` | URL prefix for all routes |
|
|
372
|
+
| `database` | `'mongodb' \| 'postgresql'` | auto-detected from `databaseUrl` | Database engine |
|
|
373
|
+
| `databaseUrl` | `string` | — | Connection string — not read from env automatically, pass it explicitly |
|
|
374
|
+
| `authStrategy` | `'http-only' \| 'localStorage'` | `'http-only'` | Token delivery |
|
|
375
|
+
| `jwtSecret` | `string` | — | JWT signing secret — not read from env automatically, pass it explicitly |
|
|
376
|
+
| `jwtExpiresIn` | `string` | `'7d'` | Token lifetime |
|
|
377
|
+
| `cookieDomain` | `string` | — | Cookie domain (`http-only` only) |
|
|
378
|
+
| `cluster` | `boolean` | `true` in prod, `false` in dev | Enable multi-core clustering |
|
|
268
379
|
| `workers` | `number` | `os.cpus().length` | Worker count override |
|
|
269
380
|
| `tasks` | `TaskConfig \| false` | `false` | Background task runtime |
|
|
270
|
-
| `cors` | `boolean \| CorsConfig` | `true` | CORS —
|
|
381
|
+
| `cors` | `boolean \| CorsConfig` | `true` | CORS — pass `origin` explicitly, not auto-read from env |
|
|
382
|
+
| `requestTimeout` | `number` | — | Request timeout in ms (408 on exceed) |
|
|
271
383
|
| `globalMiddlewares` | `RequestHandler[]` | `[]` | Applied to every route |
|
|
384
|
+
| `dashboard` | `boolean` | `true` in dev | Dev route dashboard at `/` |
|
|
272
385
|
| `onWorkerReady` | `(id) => void` | — | Called when a worker boots |
|
|
273
386
|
| `onWorkerCrash` | `(id, code) => void` | — | Called before respawn |
|
|
274
387
|
| `onError` | `ErrorRequestHandler` | built-in | Override global error handler |
|
|
@@ -279,7 +392,7 @@ ignite({
|
|
|
279
392
|
|
|
280
393
|
```bash
|
|
281
394
|
# Development
|
|
282
|
-
efc start dev # Hot-reload single process
|
|
395
|
+
efc start dev # Hot-reload single process (tsx --watch), .env re-read on every restart
|
|
283
396
|
|
|
284
397
|
# Production
|
|
285
398
|
efc build prod # Type-check + compile to dist/ (tsup, dual CJS/ESM)
|
|
@@ -296,7 +409,7 @@ efc generate middleware authorize # → src/middlewares/authorize.ts
|
|
|
296
409
|
# Diagnostics
|
|
297
410
|
efc routes # Print resolved route table (path → file → methods)
|
|
298
411
|
efc tasks # List registered background tasks
|
|
299
|
-
efc doctor # Validate
|
|
412
|
+
efc doctor # Validate project setup, package.json/tsconfig, .env vars
|
|
300
413
|
```
|
|
301
414
|
|
|
302
415
|
---
|
|
@@ -312,12 +425,13 @@ efc doctor # Validate config, env vars, DB connectivity
|
|
|
312
425
|
│ │ │
|
|
313
426
|
Worker 1 Worker 2 Worker N
|
|
314
427
|
Pre-Flight lifecycle per worker:
|
|
315
|
-
1. Connect
|
|
428
|
+
1. Connect database
|
|
316
429
|
2. Configure auth
|
|
317
|
-
3. Scan
|
|
318
|
-
4.
|
|
319
|
-
5.
|
|
320
|
-
6.
|
|
430
|
+
3. Scan tasksDir → register tasks
|
|
431
|
+
4. Start BullMQ backend
|
|
432
|
+
5. Scan apiDir → build route map
|
|
433
|
+
6. Mount routes on Express
|
|
434
|
+
7. Listen (OS round-robins connections)
|
|
321
435
|
```
|
|
322
436
|
|
|
323
437
|
CPU-bound tasks fan out further into `worker_threads` — the request loop stays unblocked at every layer.
|
|
@@ -349,14 +463,14 @@ ignite({
|
|
|
349
463
|
|
|
350
464
|
## Environment Variables
|
|
351
465
|
|
|
352
|
-
`create-efc-app` generates `.env` (gitignored, `JWT_SECRET` pre-filled) and `.env.example` (committed, documented).
|
|
466
|
+
`create-efc-app` generates `.env` (gitignored, `JWT_SECRET` pre-filled) and `.env.example` (committed, documented). EFC **does not** auto-load any of these — read them yourself in `efc.config.ts` and pass them to `ignite()`.
|
|
353
467
|
|
|
354
468
|
| Variable | Required | Description |
|
|
355
469
|
|---|---|---|
|
|
356
470
|
| `PORT` | No (default `3000`) | HTTP listen port |
|
|
357
|
-
| `NODE_ENV` | No | `development \| production \| test` |
|
|
358
|
-
| `DATABASE_URL` |
|
|
359
|
-
| `JWT_SECRET` |
|
|
471
|
+
| `NODE_ENV` | No | `development \| production \| test` — the only env var EFC reads directly |
|
|
472
|
+
| `DATABASE_URL` | If using a database | MongoDB or PostgreSQL connection string |
|
|
473
|
+
| `JWT_SECRET` | If using auth | JWT signing key — auto-generated by scaffolder |
|
|
360
474
|
| `JWT_EXPIRES_IN` | No (default `7d`) | Token lifetime |
|
|
361
475
|
| `COOKIE_DOMAIN` | No | Cookie domain for `http-only` auth |
|
|
362
476
|
| `REDIS_URL` | If using BullMQ | Redis connection for the task queue |
|
package/dist/auth/index.cjs
CHANGED
|
@@ -4,12 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
var _chunkQOKLEPTXcjs = require('../chunk-QOKLEPTX.cjs');
|
|
8
7
|
|
|
8
|
+
var _chunk6522HS2Jcjs = require('../chunk-6522HS2J.cjs');
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
exports.configureAuth = _chunk6522HS2Jcjs.configureAuth; exports.getCurrentUser = _chunk6522HS2Jcjs.getCurrentUser; exports.issueToken = _chunk6522HS2Jcjs.issueToken; exports.requireAuth = _chunk6522HS2Jcjs.requireAuth; exports.revokeToken = _chunk6522HS2Jcjs.revokeToken; exports.signToken = _chunk6522HS2Jcjs.signToken;
|
|
15
17
|
//# sourceMappingURL=index.cjs.map
|
package/dist/auth/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/efc.js/efc.js/packages/core/dist/auth/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACF,
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/efc.js/efc.js/packages/core/dist/auth/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,iUAAC","file":"/home/runner/work/efc.js/efc.js/packages/core/dist/auth/index.cjs"}
|
package/dist/auth/index.d.cts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
-
import { A as AuthStrategy } from '../types-
|
|
2
|
+
import { A as AuthStrategy } from '../types-BusbSenn.cjs';
|
|
3
|
+
|
|
4
|
+
declare function getCurrentUser(): Record<string, unknown> | undefined;
|
|
3
5
|
|
|
4
6
|
interface AuthConfig {
|
|
5
7
|
secret: string;
|
|
@@ -22,4 +24,4 @@ interface RequireAuth {
|
|
|
22
24
|
}
|
|
23
25
|
declare const requireAuth: RequireAuth;
|
|
24
26
|
|
|
25
|
-
export { type RequireAuth, configureAuth, issueToken, requireAuth, revokeToken, signToken };
|
|
27
|
+
export { type RequireAuth, configureAuth, getCurrentUser, issueToken, requireAuth, revokeToken, signToken };
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
-
import { A as AuthStrategy } from '../types-
|
|
2
|
+
import { A as AuthStrategy } from '../types-BusbSenn.js';
|
|
3
|
+
|
|
4
|
+
declare function getCurrentUser(): Record<string, unknown> | undefined;
|
|
3
5
|
|
|
4
6
|
interface AuthConfig {
|
|
5
7
|
secret: string;
|
|
@@ -22,4 +24,4 @@ interface RequireAuth {
|
|
|
22
24
|
}
|
|
23
25
|
declare const requireAuth: RequireAuth;
|
|
24
26
|
|
|
25
|
-
export { type RequireAuth, configureAuth, issueToken, requireAuth, revokeToken, signToken };
|
|
27
|
+
export { type RequireAuth, configureAuth, getCurrentUser, issueToken, requireAuth, revokeToken, signToken };
|
package/dist/auth/index.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
configureAuth,
|
|
3
|
+
getCurrentUser,
|
|
3
4
|
issueToken,
|
|
4
5
|
requireAuth,
|
|
5
6
|
revokeToken,
|
|
6
7
|
signToken
|
|
7
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-VIP3PFWZ.js";
|
|
8
9
|
export {
|
|
9
10
|
configureAuth,
|
|
11
|
+
getCurrentUser,
|
|
10
12
|
issueToken,
|
|
11
13
|
requireAuth,
|
|
12
14
|
revokeToken,
|
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/auth/index.ts
|
|
2
2
|
var _jose = require('jose');
|
|
3
|
+
|
|
4
|
+
// src/context.ts
|
|
5
|
+
var _async_hooks = require('async_hooks');
|
|
6
|
+
var storage = new (0, _async_hooks.AsyncLocalStorage)();
|
|
7
|
+
function runWithContext(ctx, fn) {
|
|
8
|
+
return storage.run(ctx, fn);
|
|
9
|
+
}
|
|
10
|
+
function setCurrentUser(user) {
|
|
11
|
+
const store = storage.getStore();
|
|
12
|
+
if (store) store.user = user;
|
|
13
|
+
}
|
|
14
|
+
function getCurrentUser() {
|
|
15
|
+
return _optionalChain([storage, 'access', _ => _.getStore, 'call', _2 => _2(), 'optionalAccess', _3 => _3.user]);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/auth/index.ts
|
|
3
19
|
var _config = null;
|
|
4
20
|
function configureAuth(config) {
|
|
5
21
|
_config = config;
|
|
@@ -33,7 +49,7 @@ async function authenticate(req, res, next, roles) {
|
|
|
33
49
|
let token;
|
|
34
50
|
if (strategy === "http-only") {
|
|
35
51
|
const cookies = req.cookies;
|
|
36
|
-
token = _optionalChain([cookies, 'optionalAccess',
|
|
52
|
+
token = _optionalChain([cookies, 'optionalAccess', _4 => _4["efc_token"]]);
|
|
37
53
|
} else {
|
|
38
54
|
const auth = req.headers["authorization"];
|
|
39
55
|
if (typeof auth === "string" && auth.startsWith("Bearer ")) {
|
|
@@ -54,6 +70,7 @@ async function authenticate(req, res, next, roles) {
|
|
|
54
70
|
}
|
|
55
71
|
}
|
|
56
72
|
req.user = payload;
|
|
73
|
+
setCurrentUser(payload);
|
|
57
74
|
next();
|
|
58
75
|
} catch (e) {
|
|
59
76
|
res.status(401).json({ error: "Unauthorized" });
|
|
@@ -76,5 +93,7 @@ var requireAuth = ((...args) => {
|
|
|
76
93
|
|
|
77
94
|
|
|
78
95
|
|
|
79
|
-
|
|
80
|
-
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
exports.runWithContext = runWithContext; exports.getCurrentUser = getCurrentUser; exports.configureAuth = configureAuth; exports.issueToken = issueToken; exports.revokeToken = revokeToken; exports.signToken = signToken; exports.requireAuth = requireAuth;
|
|
99
|
+
//# sourceMappingURL=chunk-6522HS2J.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/efc.js/efc.js/packages/core/dist/chunk-6522HS2J.cjs","../src/auth/index.ts","../src/context.ts"],"names":["req","res","next"],"mappings":"AAAA;ACCA,4BAAmC;ADCnC;AACA;AEHA,0CAAkC;AAMlC,IAAM,QAAA,EAAU,IAAI,mCAAA,CAAkC,CAAA;AAM/C,SAAS,cAAA,CAAkB,GAAA,EAAqB,EAAA,EAAgB;AACrE,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAMO,SAAS,cAAA,CAAe,IAAA,EAAiD;AAC9E,EAAA,MAAM,MAAA,EAAQ,OAAA,CAAQ,QAAA,CAAS,CAAA;AAC/B,EAAA,GAAA,CAAI,KAAA,EAAO,KAAA,CAAM,KAAA,EAAO,IAAA;AAC1B;AAEO,SAAS,cAAA,CAAA,EAAsD;AACpE,EAAA,uBAAO,OAAA,mBAAQ,QAAA,mBAAS,CAAA,6BAAG,MAAA;AAC7B;AFXA;AACA;ACLA,IAAI,QAAA,EAA6B,IAAA;AAE1B,SAAS,aAAA,CAAc,MAAA,EAA0B;AACtD,EAAA,QAAA,EAAU,MAAA;AACZ;AAEA,SAAS,SAAA,CAAA,EAAwB;AAC/B,EAAA,GAAA,CAAI,CAAC,OAAA,EAAS,MAAM,IAAI,KAAA,CAAM,6DAAwD,CAAA;AACtF,EAAA,OAAO,OAAA;AACT;AAEA,MAAA,SAAsB,UAAA,CAAW,GAAA,EAAe,OAAA,EAAiD;AAC/F,EAAA,MAAM,EAAE,MAAA,EAAQ,SAAA,EAAW,aAAa,E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AAA,CAAe,OAAkC,CAAA;AACjD,IAAA,IAAA,CAAK,CAAA;AAAA,EACP,EAAA,UAAQ;AACN,IAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,eAAe,CAAC,CAAA;AAAA,EAChD;AACF;AAYO,IAAM,YAAA,EAAA,CAA4B,CAAA,GAAI,IAAA,EAAA,GAAoB;AAC/D,EAAA,GAAA,CAAI,IAAA,CAAK,OAAA,EAAS,EAAA,GAAK,OAAO,IAAA,CAAK,CAAC,EAAA,IAAM,QAAA,EAAU;AAClD,IAAA,MAAM,MAAA,EAAQ,IAAA;AACd,IAAA,OAAO,CAACA,IAAAA,EAAcC,IAAAA,EAAeC,KAAAA,EAAAA,GAAuB;AAC1D,MAAA,KAAK,YAAA,CAAaF,IAAAA,EAAKC,IAAAA,EAAKC,KAAAA,EAAM,KAAK,CAAA;AAAA,IACzC,CAAA;AAAA,EACF;AACA,EAAA,MAAM,CAAC,GAAA,EAAK,GAAA,EAAK,IAAI,EAAA,EAAI,IAAA;AACzB,EAAA,KAAK,YAAA,CAAa,GAAA,EAAK,GAAA,EAAK,IAAA,EAAM,CAAC,CAAC,CAAA;AACtC,CAAA,CAAA;AD5BA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,8PAAC","file":"/home/runner/work/efc.js/efc.js/packages/core/dist/chunk-6522HS2J.cjs","sourcesContent":[null,"import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify } from 'jose';\nimport type { AuthStrategy } from '../types.js';\nimport { setCurrentUser } from '../context.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\nexport async function issueToken(res: Response, payload: Record<string, unknown>): Promise<void> {\n const { secret, expiresIn, cookieDomain } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n const token = await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n return await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n const { secret, strategy } = getConfig();\n\n try {\n let token: string | undefined;\n\n if (strategy === 'http-only') {\n const cookies = (req as typeof req & { cookies: Record<string, string> }).cookies;\n token = cookies?.['efc_token'];\n } else {\n const auth = req.headers['authorization'];\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n token = auth.slice(7);\n }\n }\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const encodedSecret = new TextEncoder().encode(secret);\n const { payload } = await jwtVerify(token, encodedSecret);\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n setCurrentUser(payload as Record<string, unknown>);\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n\n// Reads the JWT payload requireAuth attached for the in-flight request, from\n// anywhere — not just where `req` is in scope. Returns undefined outside a\n// request, or on a request that never ran through requireAuth.\nexport { getCurrentUser } from '../context.js';\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface RequestContext {\n user?: Record<string, unknown> | undefined;\n}\n\nconst storage = new AsyncLocalStorage<RequestContext>();\n\n// Wraps one request's lifecycle in an AsyncLocalStorage context. Node propagates\n// the store through the async chain the callback initiates (awaits, .then, etc.),\n// so anything running as part of the same request — including a `$currentUser`\n// default resolved deep inside a mongoose `.create()` call — can read it back.\nexport function runWithContext<T>(ctx: RequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getRequestContext(): RequestContext | undefined {\n return storage.getStore();\n}\n\nexport function setCurrentUser(user: Record<string, unknown> | undefined): void {\n const store = storage.getStore();\n if (store) store.user = user;\n}\n\nexport function getCurrentUser(): Record<string, unknown> | undefined {\n return storage.getStore()?.user;\n}\n"]}
|
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
// src/auth/index.ts
|
|
2
2
|
import { SignJWT, jwtVerify } from "jose";
|
|
3
|
+
|
|
4
|
+
// src/context.ts
|
|
5
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
6
|
+
var storage = new AsyncLocalStorage();
|
|
7
|
+
function runWithContext(ctx, fn) {
|
|
8
|
+
return storage.run(ctx, fn);
|
|
9
|
+
}
|
|
10
|
+
function setCurrentUser(user) {
|
|
11
|
+
const store = storage.getStore();
|
|
12
|
+
if (store) store.user = user;
|
|
13
|
+
}
|
|
14
|
+
function getCurrentUser() {
|
|
15
|
+
return storage.getStore()?.user;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/auth/index.ts
|
|
3
19
|
var _config = null;
|
|
4
20
|
function configureAuth(config) {
|
|
5
21
|
_config = config;
|
|
@@ -54,6 +70,7 @@ async function authenticate(req, res, next, roles) {
|
|
|
54
70
|
}
|
|
55
71
|
}
|
|
56
72
|
req.user = payload;
|
|
73
|
+
setCurrentUser(payload);
|
|
57
74
|
next();
|
|
58
75
|
} catch {
|
|
59
76
|
res.status(401).json({ error: "Unauthorized" });
|
|
@@ -71,10 +88,12 @@ var requireAuth = ((...args) => {
|
|
|
71
88
|
});
|
|
72
89
|
|
|
73
90
|
export {
|
|
91
|
+
runWithContext,
|
|
92
|
+
getCurrentUser,
|
|
74
93
|
configureAuth,
|
|
75
94
|
issueToken,
|
|
76
95
|
revokeToken,
|
|
77
96
|
signToken,
|
|
78
97
|
requireAuth
|
|
79
98
|
};
|
|
80
|
-
//# sourceMappingURL=chunk-
|
|
99
|
+
//# sourceMappingURL=chunk-VIP3PFWZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth/index.ts","../src/context.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify } from 'jose';\nimport type { AuthStrategy } from '../types.js';\nimport { setCurrentUser } from '../context.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\nexport async function issueToken(res: Response, payload: Record<string, unknown>): Promise<void> {\n const { secret, expiresIn, cookieDomain } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n const token = await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n return await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n const { secret, strategy } = getConfig();\n\n try {\n let token: string | undefined;\n\n if (strategy === 'http-only') {\n const cookies = (req as typeof req & { cookies: Record<string, string> }).cookies;\n token = cookies?.['efc_token'];\n } else {\n const auth = req.headers['authorization'];\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n token = auth.slice(7);\n }\n }\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const encodedSecret = new TextEncoder().encode(secret);\n const { payload } = await jwtVerify(token, encodedSecret);\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n setCurrentUser(payload as Record<string, unknown>);\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n\n// Reads the JWT payload requireAuth attached for the in-flight request, from\n// anywhere — not just where `req` is in scope. Returns undefined outside a\n// request, or on a request that never ran through requireAuth.\nexport { getCurrentUser } from '../context.js';\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface RequestContext {\n user?: Record<string, unknown> | undefined;\n}\n\nconst storage = new AsyncLocalStorage<RequestContext>();\n\n// Wraps one request's lifecycle in an AsyncLocalStorage context. Node propagates\n// the store through the async chain the callback initiates (awaits, .then, etc.),\n// so anything running as part of the same request — including a `$currentUser`\n// default resolved deep inside a mongoose `.create()` call — can read it back.\nexport function runWithContext<T>(ctx: RequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getRequestContext(): RequestContext | undefined {\n return storage.getStore();\n}\n\nexport function setCurrentUser(user: Record<string, unknown> | undefined): void {\n const store = storage.getStore();\n if (store) store.user = user;\n}\n\nexport function getCurrentUser(): Record<string, unknown> | undefined {\n return storage.getStore()?.user;\n}\n"],"mappings":";AACA,SAAS,SAAS,iBAAiB;;;ACDnC,SAAS,yBAAyB;AAMlC,IAAM,UAAU,IAAI,kBAAkC;AAM/C,SAAS,eAAkB,KAAqB,IAAgB;AACrE,SAAO,QAAQ,IAAI,KAAK,EAAE;AAC5B;AAMO,SAAS,eAAe,MAAiD;AAC9E,QAAM,QAAQ,QAAQ,SAAS;AAC/B,MAAI,MAAO,OAAM,OAAO;AAC1B;AAEO,SAAS,iBAAsD;AACpE,SAAO,QAAQ,SAAS,GAAG;AAC7B;;;ADfA,IAAI,UAA6B;AAE1B,SAAS,cAAc,QAA0B;AACtD,YAAU;AACZ;AAEA,SAAS,YAAwB;AAC/B,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM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BAAgB,IAAI,YAAY,EAAE,OAAO,MAAM;AACrD,UAAM,EAAE,QAAQ,IAAI,MAAM,UAAU,OAAO,aAAa;AAExD,QAAI,MAAM,SAAS,GAAG;AACpB,YAAM,OAAQ,QAAoC,MAAM;AACxD,UAAI,OAAO,SAAS,YAAY,CAAC,MAAM,SAAS,IAAI,GAAG;AACrD,YAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,YAAY,CAAC;AAC3C;AAAA,MACF;AAAA,IACF;AAEA,IAAC,IAAuC,OAAO;AAC/C,mBAAe,OAAkC;AACjD,SAAK;AAAA,EACP,QAAQ;AACN,QAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,eAAe,CAAC;AAAA,EAChD;AACF;AAYO,IAAM,eAA4B,IAAI,SAAoB;AAC/D,MAAI,KAAK,SAAS,KAAK,OAAO,KAAK,CAAC,MAAM,UAAU;AAClD,UAAM,QAAQ;AACd,WAAO,CAACA,MAAcC,MAAeC,UAAuB;AAC1D,WAAK,aAAaF,MAAKC,MAAKC,OAAM,KAAK;AAAA,IACzC;AAAA,EACF;AACA,QAAM,CAAC,KAAK,KAAK,IAAI,IAAI;AACzB,OAAK,aAAa,KAAK,KAAK,MAAM,CAAC,CAAC;AACtC;","names":["req","res","next"]}
|
package/dist/cli/index.cjs
CHANGED
|
@@ -84,8 +84,12 @@ function startDev() {
|
|
|
84
84
|
const tsx = findTsx();
|
|
85
85
|
const preloadPath = writeDevEnvPreload(cwd);
|
|
86
86
|
const env = {
|
|
87
|
-
NODE_ENV: "development",
|
|
88
87
|
...process.env,
|
|
88
|
+
// Always last: `efc start dev` must force development mode even if the
|
|
89
|
+
// parent shell/CI already exports NODE_ENV=production, otherwise ignite()'s
|
|
90
|
+
// cluster default (`NODE_ENV === 'production'`) silently enables clustering
|
|
91
|
+
// in what's supposed to be a single-process dev server.
|
|
92
|
+
NODE_ENV: "development",
|
|
89
93
|
NODE_OPTIONS: [process.env["NODE_OPTIONS"], `--import ${preloadPath}`].filter(Boolean).join(" ")
|
|
90
94
|
};
|
|
91
95
|
const child = _child_process.spawn.call(void 0, tsx, ["watch", "--include", "src", entry], { stdio: "inherit", env });
|
|
@@ -379,9 +383,26 @@ function tasksCommand() {
|
|
|
379
383
|
console.log();
|
|
380
384
|
});
|
|
381
385
|
}
|
|
386
|
+
function readEnvFile(cwd) {
|
|
387
|
+
const envPath = _path2.default.join(cwd, ".env");
|
|
388
|
+
if (!_fs2.default.existsSync(envPath)) return {};
|
|
389
|
+
const vars = {};
|
|
390
|
+
for (const line of _fs2.default.readFileSync(envPath, "utf8").split("\n")) {
|
|
391
|
+
const trimmed = line.trim();
|
|
392
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
393
|
+
const eq = trimmed.indexOf("=");
|
|
394
|
+
if (eq === -1) continue;
|
|
395
|
+
const key = trimmed.slice(0, eq).trim();
|
|
396
|
+
const raw = trimmed.slice(eq + 1).trim();
|
|
397
|
+
vars[key] = raw.replace(/^(['"])(.*)\1$/, "$2");
|
|
398
|
+
}
|
|
399
|
+
return vars;
|
|
400
|
+
}
|
|
382
401
|
function doctorCommand() {
|
|
383
402
|
return new (0, _commander.Command)("doctor").description("Validate config, env vars, and project setup").action(() => {
|
|
384
403
|
const cwd = process.cwd();
|
|
404
|
+
const envFileVars = readEnvFile(cwd);
|
|
405
|
+
const hasEnvVar = (key) => Boolean(process.env[key]) || Boolean(envFileVars[key]);
|
|
385
406
|
const checks = [
|
|
386
407
|
{
|
|
387
408
|
label: "package.json exists",
|
|
@@ -399,12 +420,12 @@ function doctorCommand() {
|
|
|
399
420
|
},
|
|
400
421
|
{
|
|
401
422
|
label: "DATABASE_URL set",
|
|
402
|
-
ok:
|
|
423
|
+
ok: hasEnvVar("DATABASE_URL"),
|
|
403
424
|
hint: "Add DATABASE_URL to .env"
|
|
404
425
|
},
|
|
405
426
|
{
|
|
406
427
|
label: "JWT_SECRET set",
|
|
407
|
-
ok:
|
|
428
|
+
ok: hasEnvVar("JWT_SECRET"),
|
|
408
429
|
hint: "Add JWT_SECRET to .env (generate: openssl rand -hex 64)"
|
|
409
430
|
}
|
|
410
431
|
];
|