express-file-cluster 0.3.15 → 0.7.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.
- package/README.md +71 -33
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-277BSYVH.js +127 -0
- package/dist/chunk-277BSYVH.js.map +1 -0
- package/dist/chunk-6OGOVV57.js +3847 -0
- package/dist/chunk-6OGOVV57.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-AZYXQU3Z.cjs +3847 -0
- package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
- package/dist/chunk-BUBXO7WU.js +170 -0
- package/dist/chunk-BUBXO7WU.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-MGH4VDV3.cjs +170 -0
- package/dist/chunk-MGH4VDV3.cjs.map +1 -0
- package/dist/chunk-R34R7QPD.cjs +116 -0
- package/dist/chunk-R34R7QPD.cjs.map +1 -0
- package/dist/chunk-RS4MXCPW.js +116 -0
- package/dist/chunk-RS4MXCPW.js.map +1 -0
- package/dist/chunk-T4OHFU5T.cjs +154 -0
- package/dist/chunk-T4OHFU5T.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-TRC4DUZB.js +438 -0
- package/dist/chunk-TRC4DUZB.js.map +1 -0
- package/dist/chunk-TYR2GZZE.cjs +196 -0
- package/dist/chunk-TYR2GZZE.cjs.map +1 -0
- package/dist/chunk-UBQYQPBU.js +154 -0
- package/dist/chunk-UBQYQPBU.js.map +1 -0
- package/dist/chunk-UTM4PEVG.js +196 -0
- package/dist/chunk-UTM4PEVG.js.map +1 -0
- package/dist/chunk-YL37D6KM.cjs +127 -0
- package/dist/chunk-YL37D6KM.cjs.map +1 -0
- package/dist/chunk-ZDM5JHVK.cjs +438 -0
- package/dist/chunk-ZDM5JHVK.cjs.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +326 -0
- package/dist/docs/api-reference/table.md +458 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +108 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +309 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +264 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +699 -7
- package/dist/index.d.ts +699 -7
- package/dist/index.js +258 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-QKBXVJ6B.js +14 -0
- package/dist/pgboss-backend-QKBXVJ6B.js.map +1 -0
- package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
- package/dist/pgboss-backend-TCHI7CHM.cjs.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-B6lVw4bj.d.cts +588 -0
- package/dist/types-B6lVw4bj.d.ts +588 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
package/dist/chunk-6522HS2J.cjs
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
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
|
-
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
|
|
19
|
-
var _config = null;
|
|
20
|
-
function configureAuth(config) {
|
|
21
|
-
_config = config;
|
|
22
|
-
}
|
|
23
|
-
function getConfig() {
|
|
24
|
-
if (!_config) throw new Error("[EFC] Auth not configured \u2014 pass jwtSecret to ignite()");
|
|
25
|
-
return _config;
|
|
26
|
-
}
|
|
27
|
-
async function issueToken(res, payload) {
|
|
28
|
-
const { secret, expiresIn, cookieDomain } = getConfig();
|
|
29
|
-
const encodedSecret = new TextEncoder().encode(secret);
|
|
30
|
-
const token = await new (0, _jose.SignJWT)(payload).setProtectedHeader({ alg: "HS256" }).setExpirationTime(expiresIn).sign(encodedSecret);
|
|
31
|
-
res.cookie("efc_token", token, {
|
|
32
|
-
httpOnly: true,
|
|
33
|
-
secure: process.env["NODE_ENV"] === "production",
|
|
34
|
-
sameSite: "strict",
|
|
35
|
-
...cookieDomain !== void 0 && { domain: cookieDomain }
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
function revokeToken(res) {
|
|
39
|
-
res.clearCookie("efc_token");
|
|
40
|
-
}
|
|
41
|
-
async function signToken(payload) {
|
|
42
|
-
const { secret, expiresIn } = getConfig();
|
|
43
|
-
const encodedSecret = new TextEncoder().encode(secret);
|
|
44
|
-
return await new (0, _jose.SignJWT)(payload).setProtectedHeader({ alg: "HS256" }).setExpirationTime(expiresIn).sign(encodedSecret);
|
|
45
|
-
}
|
|
46
|
-
async function authenticate(req, res, next, roles) {
|
|
47
|
-
const { secret, strategy } = getConfig();
|
|
48
|
-
try {
|
|
49
|
-
let token;
|
|
50
|
-
if (strategy === "http-only") {
|
|
51
|
-
const cookies = req.cookies;
|
|
52
|
-
token = _optionalChain([cookies, 'optionalAccess', _4 => _4["efc_token"]]);
|
|
53
|
-
} else {
|
|
54
|
-
const auth = req.headers["authorization"];
|
|
55
|
-
if (typeof auth === "string" && auth.startsWith("Bearer ")) {
|
|
56
|
-
token = auth.slice(7);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (!token) {
|
|
60
|
-
res.status(401).json({ error: "Unauthorized" });
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const encodedSecret = new TextEncoder().encode(secret);
|
|
64
|
-
const { payload } = await _jose.jwtVerify.call(void 0, token, encodedSecret);
|
|
65
|
-
if (roles.length > 0) {
|
|
66
|
-
const role = payload["role"];
|
|
67
|
-
if (typeof role !== "string" || !roles.includes(role)) {
|
|
68
|
-
res.status(403).json({ error: "Forbidden" });
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
req.user = payload;
|
|
73
|
-
setCurrentUser(payload);
|
|
74
|
-
next();
|
|
75
|
-
} catch (e) {
|
|
76
|
-
res.status(401).json({ error: "Unauthorized" });
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
var requireAuth = ((...args) => {
|
|
80
|
-
if (args.length > 0 && typeof args[0] === "string") {
|
|
81
|
-
const roles = args;
|
|
82
|
-
return (req2, res2, next2) => {
|
|
83
|
-
void authenticate(req2, res2, next2, roles);
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
const [req, res, next] = args;
|
|
87
|
-
void authenticate(req, res, next, []);
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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,M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;AACxD,MAAA,GAAA,CAAI,OAAO,KAAA,IAAS,SAAA,GAAY,CAAC,KAAA,CAAM,QAAA,CAAS,IAAI,CAAA,EAAG;AACrD,QAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,YAAY,CAAC,CAAA;AAC3C,QAAA,MAAA;AAAA,MACF;AAAA,IACF;AAEA,IAAC,GAAA,CAAuC,KAAA,EAAO,OAAA;AAC/C,IAAA,cAAA,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"]}
|
package/dist/chunk-DGVOJNR6.cjs
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/router/scan.ts
|
|
2
|
-
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
3
|
-
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
4
|
-
var ROUTE_FILE_RE = /\.(ts|js|mts|mjs|cts|cjs)$/;
|
|
5
|
-
var DYNAMIC_SEGMENT_RE = /\[([^\]]+)\]/g;
|
|
6
|
-
var DEFAULT_MAX_DEPTH = 10;
|
|
7
|
-
function filePathToUrlPath(relativePath) {
|
|
8
|
-
let p = relativePath.replace(ROUTE_FILE_RE, "");
|
|
9
|
-
p = p.replace(/\/index$/, "");
|
|
10
|
-
p = p.replace(DYNAMIC_SEGMENT_RE, ":$1");
|
|
11
|
-
return p === "" ? "/" : p.startsWith("/") ? p : `/${p}`;
|
|
12
|
-
}
|
|
13
|
-
function extractParams(relativePath) {
|
|
14
|
-
const params = [];
|
|
15
|
-
let match;
|
|
16
|
-
const re = new RegExp(DYNAMIC_SEGMENT_RE.source, "g");
|
|
17
|
-
while ((match = re.exec(relativePath)) !== null) {
|
|
18
|
-
if (match[1]) params.push(match[1]);
|
|
19
|
-
}
|
|
20
|
-
return params;
|
|
21
|
-
}
|
|
22
|
-
function dynamicSegmentCount(urlPath) {
|
|
23
|
-
return (_nullishCoalesce(urlPath.match(/:/g), () => ( []))).length;
|
|
24
|
-
}
|
|
25
|
-
function scanDir(dir, base = dir, maxDepth = DEFAULT_MAX_DEPTH, _depth = 0) {
|
|
26
|
-
if (!_fs2.default.existsSync(dir)) return [];
|
|
27
|
-
if (_depth > maxDepth) {
|
|
28
|
-
console.warn(`[EFC] scanDir: max depth (${maxDepth}) reached at ${dir}, skipping subtree`);
|
|
29
|
-
return [];
|
|
30
|
-
}
|
|
31
|
-
const entries = [];
|
|
32
|
-
const items = _fs2.default.readdirSync(dir, { withFileTypes: true });
|
|
33
|
-
for (const item of items) {
|
|
34
|
-
const fullPath = _path2.default.join(dir, item.name);
|
|
35
|
-
if (item.isDirectory()) {
|
|
36
|
-
entries.push(...scanDir(fullPath, base, maxDepth, _depth + 1));
|
|
37
|
-
} else if (ROUTE_FILE_RE.test(item.name)) {
|
|
38
|
-
const relative = "/" + _path2.default.relative(base, fullPath).replace(/\\/g, "/");
|
|
39
|
-
entries.push({
|
|
40
|
-
urlPath: filePathToUrlPath(relative),
|
|
41
|
-
filePath: fullPath,
|
|
42
|
-
params: extractParams(relative)
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return entries.sort((a, b) => {
|
|
47
|
-
const diff = dynamicSegmentCount(a.urlPath) - dynamicSegmentCount(b.urlPath);
|
|
48
|
-
return diff !== 0 ? diff : a.urlPath.localeCompare(b.urlPath);
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
exports.scanDir = scanDir;
|
|
55
|
-
//# sourceMappingURL=chunk-DGVOJNR6.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/efc.js/efc.js/packages/core/dist/chunk-DGVOJNR6.cjs","../src/router/scan.ts"],"names":[],"mappings":"AAAA;ACAA,gEAAe;AACf,wEAAiB;AAGjB,IAAM,cAAA,EAAgB,4BAAA;AACtB,IAAM,mBAAA,EAAqB,eAAA;AAG3B,IAAM,kBAAA,EAAoB,EAAA;AAE1B,SAAS,iBAAA,CAAkB,YAAA,EAA8B;AACvD,EAAA,IAAI,EAAA,EAAI,YAAA,CAAa,OAAA,CAAQ,aAAA,EAAe,EAAE,CAAA;AAE9C,EAAA,EAAA,EAAI,CAAA,CAAE,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA;AAE5B,EAAA,EAAA,EAAI,CAAA,CAAE,OAAA,CAAQ,kBAAA,EAAoB,KAAK,CAAA;AACvC,EAAA,OAAO,EAAA,IAAM,GAAA,EAAK,IAAA,EAAM,CAAA,CAAE,UAAA,CAAW,GAAG,EAAA,EAAI,EAAA,EAAI,CAAA,CAAA,EAAI,CAAC,CAAA,CAAA;AACvD;AAEuD;AAC3B,EAAA;AACtB,EAAA;AACgD,EAAA;AACH,EAAA;AACb,IAAA;AACpC,EAAA;AACO,EAAA;AACT;AAGsD;AACjB,EAAA;AACrC;AAgBqB;AAGc,EAAA;AACV,EAAA;AAC6B,IAAA;AAC1C,IAAA;AACV,EAAA;AAE+B,EAAA;AACoB,EAAA;AAEzB,EAAA;AACiB,IAAA;AACjB,IAAA;AAC4B,MAAA;AACV,IAAA;AACG,MAAA;AAC9B,MAAA;AACwB,QAAA;AACzB,QAAA;AACoB,QAAA;AAC/B,MAAA;AACH,IAAA;AACF,EAAA;AAG8B,EAAA;AACkB,IAAA;AACK,IAAA;AACpD,EAAA;AACH;AD7BwD;AACA;AACA;AACA","file":"/home/runner/work/efc.js/efc.js/packages/core/dist/chunk-DGVOJNR6.cjs","sourcesContent":[null,"import fs from 'node:fs';\nimport path from 'node:path';\nimport type { RouteEntry } from '../types.js';\n\nconst ROUTE_FILE_RE = /\\.(ts|js|mts|mjs|cts|cjs)$/;\nconst DYNAMIC_SEGMENT_RE = /\\[([^\\]]+)\\]/g;\n\n/** Maximum directory depth scanDir will recurse into by default. */\nconst DEFAULT_MAX_DEPTH = 10;\n\nfunction filePathToUrlPath(relativePath: string): string {\n let p = relativePath.replace(ROUTE_FILE_RE, '');\n // index files map to parent path\n p = p.replace(/\\/index$/, '');\n // [param] → :param\n p = p.replace(DYNAMIC_SEGMENT_RE, ':$1');\n return p === '' ? '/' : p.startsWith('/') ? p : `/${p}`;\n}\n\nfunction extractParams(relativePath: string): string[] {\n const params: string[] = [];\n let match: RegExpExecArray | null;\n const re = new RegExp(DYNAMIC_SEGMENT_RE.source, 'g');\n while ((match = re.exec(relativePath)) !== null) {\n if (match[1]) params.push(match[1]);\n }\n return params;\n}\n\n/** Count how many dynamic (`:param`) segments a URL path has. */\nfunction dynamicSegmentCount(urlPath: string): number {\n return (urlPath.match(/:/g) ?? []).length;\n}\n\n/**\n * Recursively scans `dir` for route files and returns a sorted list of\n * `RouteEntry` objects. Static routes are always placed before dynamic ones;\n * within the same dynamic-segment count routes are sorted alphabetically.\n *\n * @param dir - Root directory to scan (must exist).\n * @param base - Base directory used to derive relative URL paths; defaults to `dir`.\n * @param maxDepth - Maximum recursion depth (default: 10). Guards against\n * circular symlinks or unexpectedly deep directory trees.\n * @param _depth - Internal current depth counter — do not pass externally.\n */\nexport function scanDir(\n dir: string,\n base: string = dir,\n maxDepth: number = DEFAULT_MAX_DEPTH,\n _depth: number = 0,\n): RouteEntry[] {\n if (!fs.existsSync(dir)) return [];\n if (_depth > maxDepth) {\n console.warn(`[EFC] scanDir: max depth (${maxDepth}) reached at ${dir}, skipping subtree`);\n return [];\n }\n\n const entries: RouteEntry[] = [];\n const items = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dir, item.name);\n if (item.isDirectory()) {\n entries.push(...scanDir(fullPath, base, maxDepth, _depth + 1));\n } else if (ROUTE_FILE_RE.test(item.name)) {\n const relative = '/' + path.relative(base, fullPath).replace(/\\\\/g, '/');\n entries.push({\n urlPath: filePathToUrlPath(relative),\n filePath: fullPath,\n params: extractParams(relative),\n });\n }\n }\n\n // Sort: fewer dynamic segments first; ties broken alphabetically.\n return entries.sort((a, b) => {\n const diff = dynamicSegmentCount(a.urlPath) - dynamicSegmentCount(b.urlPath);\n return diff !== 0 ? diff : a.urlPath.localeCompare(b.urlPath);\n });\n}\n\nexport { filePathToUrlPath };\n"]}
|
package/dist/chunk-KOHLLUN7.js
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
// src/router/scan.ts
|
|
2
|
-
import fs from "fs";
|
|
3
|
-
import path from "path";
|
|
4
|
-
var ROUTE_FILE_RE = /\.(ts|js|mts|mjs|cts|cjs)$/;
|
|
5
|
-
var DYNAMIC_SEGMENT_RE = /\[([^\]]+)\]/g;
|
|
6
|
-
var DEFAULT_MAX_DEPTH = 10;
|
|
7
|
-
function filePathToUrlPath(relativePath) {
|
|
8
|
-
let p = relativePath.replace(ROUTE_FILE_RE, "");
|
|
9
|
-
p = p.replace(/\/index$/, "");
|
|
10
|
-
p = p.replace(DYNAMIC_SEGMENT_RE, ":$1");
|
|
11
|
-
return p === "" ? "/" : p.startsWith("/") ? p : `/${p}`;
|
|
12
|
-
}
|
|
13
|
-
function extractParams(relativePath) {
|
|
14
|
-
const params = [];
|
|
15
|
-
let match;
|
|
16
|
-
const re = new RegExp(DYNAMIC_SEGMENT_RE.source, "g");
|
|
17
|
-
while ((match = re.exec(relativePath)) !== null) {
|
|
18
|
-
if (match[1]) params.push(match[1]);
|
|
19
|
-
}
|
|
20
|
-
return params;
|
|
21
|
-
}
|
|
22
|
-
function dynamicSegmentCount(urlPath) {
|
|
23
|
-
return (urlPath.match(/:/g) ?? []).length;
|
|
24
|
-
}
|
|
25
|
-
function scanDir(dir, base = dir, maxDepth = DEFAULT_MAX_DEPTH, _depth = 0) {
|
|
26
|
-
if (!fs.existsSync(dir)) return [];
|
|
27
|
-
if (_depth > maxDepth) {
|
|
28
|
-
console.warn(`[EFC] scanDir: max depth (${maxDepth}) reached at ${dir}, skipping subtree`);
|
|
29
|
-
return [];
|
|
30
|
-
}
|
|
31
|
-
const entries = [];
|
|
32
|
-
const items = fs.readdirSync(dir, { withFileTypes: true });
|
|
33
|
-
for (const item of items) {
|
|
34
|
-
const fullPath = path.join(dir, item.name);
|
|
35
|
-
if (item.isDirectory()) {
|
|
36
|
-
entries.push(...scanDir(fullPath, base, maxDepth, _depth + 1));
|
|
37
|
-
} else if (ROUTE_FILE_RE.test(item.name)) {
|
|
38
|
-
const relative = "/" + path.relative(base, fullPath).replace(/\\/g, "/");
|
|
39
|
-
entries.push({
|
|
40
|
-
urlPath: filePathToUrlPath(relative),
|
|
41
|
-
filePath: fullPath,
|
|
42
|
-
params: extractParams(relative)
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return entries.sort((a, b) => {
|
|
47
|
-
const diff = dynamicSegmentCount(a.urlPath) - dynamicSegmentCount(b.urlPath);
|
|
48
|
-
return diff !== 0 ? diff : a.urlPath.localeCompare(b.urlPath);
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export {
|
|
53
|
-
scanDir
|
|
54
|
-
};
|
|
55
|
-
//# sourceMappingURL=chunk-KOHLLUN7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/scan.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { RouteEntry } from '../types.js';\n\nconst ROUTE_FILE_RE = /\\.(ts|js|mts|mjs|cts|cjs)$/;\nconst DYNAMIC_SEGMENT_RE = /\\[([^\\]]+)\\]/g;\n\n/** Maximum directory depth scanDir will recurse into by default. */\nconst DEFAULT_MAX_DEPTH = 10;\n\nfunction filePathToUrlPath(relativePath: string): string {\n let p = relativePath.replace(ROUTE_FILE_RE, '');\n // index files map to parent path\n p = p.replace(/\\/index$/, '');\n // [param] → :param\n p = p.replace(DYNAMIC_SEGMENT_RE, ':$1');\n return p === '' ? '/' : p.startsWith('/') ? p : `/${p}`;\n}\n\nfunction extractParams(relativePath: string): string[] {\n const params: string[] = [];\n let match: RegExpExecArray | null;\n const re = new RegExp(DYNAMIC_SEGMENT_RE.source, 'g');\n while ((match = re.exec(relativePath)) !== null) {\n if (match[1]) params.push(match[1]);\n }\n return params;\n}\n\n/** Count how many dynamic (`:param`) segments a URL path has. */\nfunction dynamicSegmentCount(urlPath: string): number {\n return (urlPath.match(/:/g) ?? []).length;\n}\n\n/**\n * Recursively scans `dir` for route files and returns a sorted list of\n * `RouteEntry` objects. Static routes are always placed before dynamic ones;\n * within the same dynamic-segment count routes are sorted alphabetically.\n *\n * @param dir - Root directory to scan (must exist).\n * @param base - Base directory used to derive relative URL paths; defaults to `dir`.\n * @param maxDepth - Maximum recursion depth (default: 10). Guards against\n * circular symlinks or unexpectedly deep directory trees.\n * @param _depth - Internal current depth counter — do not pass externally.\n */\nexport function scanDir(\n dir: string,\n base: string = dir,\n maxDepth: number = DEFAULT_MAX_DEPTH,\n _depth: number = 0,\n): RouteEntry[] {\n if (!fs.existsSync(dir)) return [];\n if (_depth > maxDepth) {\n console.warn(`[EFC] scanDir: max depth (${maxDepth}) reached at ${dir}, skipping subtree`);\n return [];\n }\n\n const entries: RouteEntry[] = [];\n const items = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dir, item.name);\n if (item.isDirectory()) {\n entries.push(...scanDir(fullPath, base, maxDepth, _depth + 1));\n } else if (ROUTE_FILE_RE.test(item.name)) {\n const relative = '/' + path.relative(base, fullPath).replace(/\\\\/g, '/');\n entries.push({\n urlPath: filePathToUrlPath(relative),\n filePath: fullPath,\n params: extractParams(relative),\n });\n }\n }\n\n // Sort: fewer dynamic segments first; ties broken alphabetically.\n return entries.sort((a, b) => {\n const diff = dynamicSegmentCount(a.urlPath) - dynamicSegmentCount(b.urlPath);\n return diff !== 0 ? diff : a.urlPath.localeCompare(b.urlPath);\n });\n}\n\nexport { filePathToUrlPath };\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAGjB,IAAM,gBAAgB;AACtB,IAAM,qBAAqB;AAG3B,IAAM,oBAAoB;AAE1B,SAAS,kBAAkB,cAA8B;AACvD,MAAI,IAAI,aAAa,QAAQ,eAAe,EAAE;AAE9C,MAAI,EAAE,QAAQ,YAAY,EAAE;AAE5B,MAAI,EAAE,QAAQ,oBAAoB,KAAK;AACvC,SAAO,MAAM,KAAK,MAAM,EAAE,WAAW,GAAG,IAAI,IAAI,IAAI,CAAC;AACvD;AAEA,SAAS,cAAc,cAAgC;AACrD,QAAM,SAA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CAAC;AACH;","names":[]}
|
package/dist/chunk-VIP3PFWZ.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
// src/auth/index.ts
|
|
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
|
|
19
|
-
var _config = null;
|
|
20
|
-
function configureAuth(config) {
|
|
21
|
-
_config = config;
|
|
22
|
-
}
|
|
23
|
-
function getConfig() {
|
|
24
|
-
if (!_config) throw new Error("[EFC] Auth not configured \u2014 pass jwtSecret to ignite()");
|
|
25
|
-
return _config;
|
|
26
|
-
}
|
|
27
|
-
async function issueToken(res, payload) {
|
|
28
|
-
const { secret, expiresIn, cookieDomain } = getConfig();
|
|
29
|
-
const encodedSecret = new TextEncoder().encode(secret);
|
|
30
|
-
const token = await new SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setExpirationTime(expiresIn).sign(encodedSecret);
|
|
31
|
-
res.cookie("efc_token", token, {
|
|
32
|
-
httpOnly: true,
|
|
33
|
-
secure: process.env["NODE_ENV"] === "production",
|
|
34
|
-
sameSite: "strict",
|
|
35
|
-
...cookieDomain !== void 0 && { domain: cookieDomain }
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
function revokeToken(res) {
|
|
39
|
-
res.clearCookie("efc_token");
|
|
40
|
-
}
|
|
41
|
-
async function signToken(payload) {
|
|
42
|
-
const { secret, expiresIn } = getConfig();
|
|
43
|
-
const encodedSecret = new TextEncoder().encode(secret);
|
|
44
|
-
return await new SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setExpirationTime(expiresIn).sign(encodedSecret);
|
|
45
|
-
}
|
|
46
|
-
async function authenticate(req, res, next, roles) {
|
|
47
|
-
const { secret, strategy } = getConfig();
|
|
48
|
-
try {
|
|
49
|
-
let token;
|
|
50
|
-
if (strategy === "http-only") {
|
|
51
|
-
const cookies = req.cookies;
|
|
52
|
-
token = cookies?.["efc_token"];
|
|
53
|
-
} else {
|
|
54
|
-
const auth = req.headers["authorization"];
|
|
55
|
-
if (typeof auth === "string" && auth.startsWith("Bearer ")) {
|
|
56
|
-
token = auth.slice(7);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (!token) {
|
|
60
|
-
res.status(401).json({ error: "Unauthorized" });
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const encodedSecret = new TextEncoder().encode(secret);
|
|
64
|
-
const { payload } = await jwtVerify(token, encodedSecret);
|
|
65
|
-
if (roles.length > 0) {
|
|
66
|
-
const role = payload["role"];
|
|
67
|
-
if (typeof role !== "string" || !roles.includes(role)) {
|
|
68
|
-
res.status(403).json({ error: "Forbidden" });
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
req.user = payload;
|
|
73
|
-
setCurrentUser(payload);
|
|
74
|
-
next();
|
|
75
|
-
} catch {
|
|
76
|
-
res.status(401).json({ error: "Unauthorized" });
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
var requireAuth = ((...args) => {
|
|
80
|
-
if (args.length > 0 && typeof args[0] === "string") {
|
|
81
|
-
const roles = args;
|
|
82
|
-
return (req2, res2, next2) => {
|
|
83
|
-
void authenticate(req2, res2, next2, roles);
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
const [req, res, next] = args;
|
|
87
|
-
void authenticate(req, res, next, []);
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
export {
|
|
91
|
-
runWithContext,
|
|
92
|
-
getCurrentUser,
|
|
93
|
-
configureAuth,
|
|
94
|
-
issueToken,
|
|
95
|
-
revokeToken,
|
|
96
|
-
signToken,
|
|
97
|
-
requireAuth
|
|
98
|
-
};
|
|
99
|
-
//# sourceMappingURL=chunk-VIP3PFWZ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,6DAAwD;AACtF,SAAO;AACT;AAEA,eAAsB,WAAW,KAAe,SAAiD;AAC/F,QAAM,EAAE,QAAQ,WAAW,aAAa,IAAI,UAAU;AACtD,QAAM,gBAAgB,IAAI,YAAY,EAAE,OAAO,MAAM;AACrD,QAAM,QAAQ,MAAM,IAAI,QAAQ,OAAO,EACpC,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,kBAAkB,SAAS,EAC3B,KAAK,aAAa;AAErB,MAAI,OAAO,aAAa,OAAO;AAAA,IAC7B,UAAU;AAAA,IACV,QAAQ,QAAQ,IAAI,UAAU,MAAM;AAAA,IACpC,UAAU;AAAA,IACV,GAAI,iBAAiB,UAAa,EAAE,QAAQ,aAAa;AAAA,EAC3D,CAAC;AACH;AAEO,SAAS,YAAY,KAAqB;AAC/C,MAAI,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,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"]}
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
import { RequestHandler, ErrorRequestHandler } from 'express';
|
|
2
|
-
|
|
3
|
-
type DatabaseEngine = 'mongodb' | 'postgresql';
|
|
4
|
-
type AuthStrategy = 'http-only' | 'localStorage';
|
|
5
|
-
type TaskBackend = 'bullmq' | 'pg-boss';
|
|
6
|
-
interface TaskConfig {
|
|
7
|
-
backend: TaskBackend;
|
|
8
|
-
redisUrl?: string;
|
|
9
|
-
concurrency?: number;
|
|
10
|
-
}
|
|
11
|
-
interface CorsConfig {
|
|
12
|
-
origin?: string | string[] | boolean;
|
|
13
|
-
methods?: string | string[];
|
|
14
|
-
allowedHeaders?: string | string[];
|
|
15
|
-
credentials?: boolean;
|
|
16
|
-
maxAge?: number;
|
|
17
|
-
}
|
|
18
|
-
interface EFCConfig {
|
|
19
|
-
port?: number;
|
|
20
|
-
basePath?: string;
|
|
21
|
-
dashboard?: boolean;
|
|
22
|
-
database?: DatabaseEngine;
|
|
23
|
-
databaseUrl?: string;
|
|
24
|
-
authStrategy?: AuthStrategy;
|
|
25
|
-
jwtSecret?: string;
|
|
26
|
-
/** JWT lifetime, e.g. '15m', '1h', '7d'. Default: '7d'. */
|
|
27
|
-
jwtExpiresIn?: string;
|
|
28
|
-
/** Cookie domain for the 'http-only' auth strategy. Default: unset (host-only cookie). */
|
|
29
|
-
cookieDomain?: string;
|
|
30
|
-
cluster?: boolean;
|
|
31
|
-
workers?: number;
|
|
32
|
-
tasks?: TaskConfig | false;
|
|
33
|
-
cors?: boolean | CorsConfig;
|
|
34
|
-
/** Request timeout in milliseconds. Requests exceeding this duration will be terminated with 408. */
|
|
35
|
-
requestTimeout?: number;
|
|
36
|
-
globalMiddlewares?: RequestHandler[];
|
|
37
|
-
onWorkerReady?: (id: number) => void;
|
|
38
|
-
onWorkerCrash?: (id: number, code: number) => void;
|
|
39
|
-
onError?: ErrorRequestHandler;
|
|
40
|
-
}
|
|
41
|
-
interface RouteEntry {
|
|
42
|
-
urlPath: string;
|
|
43
|
-
filePath: string;
|
|
44
|
-
params: string[];
|
|
45
|
-
}
|
|
46
|
-
interface RouteMethodMeta {
|
|
47
|
-
description?: string;
|
|
48
|
-
request?: {
|
|
49
|
-
headers?: Record<string, string>;
|
|
50
|
-
params?: Record<string, string>;
|
|
51
|
-
query?: Record<string, string>;
|
|
52
|
-
body?: unknown;
|
|
53
|
-
};
|
|
54
|
-
response?: {
|
|
55
|
-
status?: number;
|
|
56
|
-
body?: unknown;
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Keyed by HTTP method (`GET`, `POST`, ...) so each method implemented in a
|
|
61
|
-
* route file gets its own documentation block in the dashboard.
|
|
62
|
-
*/
|
|
63
|
-
type RouteMeta = Partial<Record<string, RouteMethodMeta>>;
|
|
64
|
-
interface TaskOptions {
|
|
65
|
-
thread?: boolean;
|
|
66
|
-
retries?: number;
|
|
67
|
-
backoff?: 'fixed' | 'exponential';
|
|
68
|
-
concurrency?: number;
|
|
69
|
-
schedule?: string;
|
|
70
|
-
}
|
|
71
|
-
interface TaskDefinition<TPayload = unknown> {
|
|
72
|
-
handler: (payload: TPayload) => Promise<void>;
|
|
73
|
-
options: TaskOptions;
|
|
74
|
-
name: string;
|
|
75
|
-
filePath?: string;
|
|
76
|
-
}
|
|
77
|
-
/** Primitive field types usable directly, or as the item type of an `array` field via `of`. */
|
|
78
|
-
type PrimitiveFieldType = 'string' | 'number' | 'boolean' | 'date' | 'object' | 'objectId';
|
|
79
|
-
/**
|
|
80
|
-
* Sentinel default-value codes, resolved at schema-compile time to a generator
|
|
81
|
-
* function so each document gets a freshly-computed value (never baked in once
|
|
82
|
-
* at schema-definition time):
|
|
83
|
-
* - `'$now'` — the current `Date` (pair with `type: 'date'`)
|
|
84
|
-
* - `'$uuid'` — a fresh `crypto.randomUUID()` string (pair with `type: 'string'`)
|
|
85
|
-
* - `'$objectId'` — a fresh Mongoose `ObjectId` (pair with `type: 'objectId'`)
|
|
86
|
-
* - `'$timestamp'` — the current epoch milliseconds as a `number` (pair with `type: 'number'`)
|
|
87
|
-
* - `'$shortId'` — a random 16-character base64url string (pair with `type: 'string'`);
|
|
88
|
-
* a shorter, non-UUID-shaped alternative to `'$uuid'` for tokens/keys
|
|
89
|
-
* - `'$currentUser'` — the JWT payload `requireAuth` attached to the in-flight request
|
|
90
|
-
* (via `getCurrentUser()`), or `undefined` outside a request / without `requireAuth`
|
|
91
|
-
* - `` `$currentUser.<key>` `` — a single field plucked from that payload, e.g.
|
|
92
|
-
* `'$currentUser.id'` (pair with a `type` matching that field's shape)
|
|
93
|
-
*
|
|
94
|
-
* `'$increment'` is intentionally NOT a `default` code — see `FieldDefinition.sequence`
|
|
95
|
-
* instead. Auto-increment needs an async read-modify-write against a counters
|
|
96
|
-
* collection; mongoose resolves `default` synchronously, so it can't live here.
|
|
97
|
-
*
|
|
98
|
-
* Any other string/value passed to `default` is used as a literal default, unchanged.
|
|
99
|
-
*/
|
|
100
|
-
type DefaultOperator = '$now' | '$uuid' | '$objectId' | '$timestamp' | '$shortId' | '$currentUser' | `$currentUser.${string}`;
|
|
101
|
-
interface FieldDefinition {
|
|
102
|
-
type: PrimitiveFieldType | 'array';
|
|
103
|
-
required?: boolean;
|
|
104
|
-
unique?: boolean;
|
|
105
|
-
/** A literal default value, or a `DefaultOperator` sentinel code (see above). */
|
|
106
|
-
default?: unknown;
|
|
107
|
-
/** Restricts the field to a fixed set of values. Valid on `string` and `number` types. */
|
|
108
|
-
enum?: readonly (string | number)[];
|
|
109
|
-
/** Mongoose model name to reference. Valid on `objectId` types (bare or as an array's `of`). */
|
|
110
|
-
ref?: string;
|
|
111
|
-
/** Item type for `array` fields, e.g. `{ type: 'array', of: 'string' }`. Omit for an untyped array. */
|
|
112
|
-
of?: PrimitiveFieldType;
|
|
113
|
-
/**
|
|
114
|
-
* Auto-increments a shared counter (stored in an internal `efc_counters` collection)
|
|
115
|
-
* and assigns it on insert, before `required` validation runs. `true` uses
|
|
116
|
-
* `'<ModelName>.<field>'` as the counter key; a string sets an explicit key so
|
|
117
|
-
* multiple fields/models can share one counter (e.g. a global order number).
|
|
118
|
-
* Only supported on top-level fields — not inside nested array sub-schemas.
|
|
119
|
-
*/
|
|
120
|
-
sequence?: boolean | string;
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* A schema field is either a `FieldDefinition`, or a one-element tuple holding a nested
|
|
124
|
-
* `ModelSchema` — the latter defines an array of embedded sub-documents, e.g.:
|
|
125
|
-
* `route_progress: [{ route_id: { type: 'string' } }]`
|
|
126
|
-
*/
|
|
127
|
-
type ModelSchema = Record<string, FieldDefinition | [ModelSchema]>;
|
|
128
|
-
interface ModelQueryOptions {
|
|
129
|
-
/** Mongoose `.populate()` path(s) to resolve on `objectId`/ref fields. */
|
|
130
|
-
populate?: string | string[];
|
|
131
|
-
}
|
|
132
|
-
interface ModelOptions {
|
|
133
|
-
/**
|
|
134
|
-
* Passed straight through to mongoose's own schema `timestamps` option.
|
|
135
|
-
* `true` (the default) adds `createdAt`/`updatedAt`; `false` disables both;
|
|
136
|
-
* an object lets you rename or selectively disable one, e.g.
|
|
137
|
-
* `{ createdAt: 'created_at', updatedAt: false }`.
|
|
138
|
-
*/
|
|
139
|
-
timestamps?: boolean | {
|
|
140
|
-
createdAt?: string | false;
|
|
141
|
-
updatedAt?: string | false;
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
interface ModelCRUD<T extends object> {
|
|
145
|
-
find(filter?: Partial<T>, options?: ModelQueryOptions): Promise<T[]>;
|
|
146
|
-
findById(id: string, options?: ModelQueryOptions): Promise<(T & {
|
|
147
|
-
id: string;
|
|
148
|
-
}) | null>;
|
|
149
|
-
findOne(filter: Partial<T>, options?: ModelQueryOptions): Promise<(T & {
|
|
150
|
-
id: string;
|
|
151
|
-
}) | null>;
|
|
152
|
-
create(data: Partial<T>): Promise<T & {
|
|
153
|
-
id: string;
|
|
154
|
-
}>;
|
|
155
|
-
update(id: string, data: Partial<T>): Promise<(T & {
|
|
156
|
-
id: string;
|
|
157
|
-
}) | null>;
|
|
158
|
-
delete(id: string): Promise<void>;
|
|
159
|
-
count(filter?: Partial<T>): Promise<number>;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
export type { AuthStrategy as A, CorsConfig as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, ModelSchema as M, RouteEntry as R, TaskOptions as T, TaskDefinition as a, ModelOptions as b, ModelCRUD as c, DefaultOperator as d, ModelQueryOptions as e, RouteMeta as f, RouteMethodMeta as g };
|